Date post: | 25-Dec-2015 |
Category: |
Documents |
Upload: | stella-patrick |
View: | 257 times |
Download: | 1 times |
2
In the construction of large programs, In the construction of large programs, we need to design and implement new we need to design and implement new data types.data types.• Designing the specification of the abstract Designing the specification of the abstract
data type (attributes and operations).data type (attributes and operations).• Implementing it.Implementing it.
Like aLike a section section in a university registration in a university registration system.system.
3
Basic mechanisms providing the Basic mechanisms providing the programmer ability of creating new programmer ability of creating new data types and operations on that type:data types and operations on that type:• SubprogramsSubprograms
– correct use of the new type is the programmer correct use of the new type is the programmer responsibility.responsibility.
• Type declarationsType declarations– the programming language partly support the the programming language partly support the
correct use of the new type.correct use of the new type.
• InheritanceInheritance
4
5.1. 5.1. Abstract Data TypesAbstract Data Types
Early languages (FORTRAN,COBOL)Early languages (FORTRAN,COBOL)• subprogram definitionsubprogram definition
Ada and C++ Ada and C++ • package and classpackage and class
data typedata type• a set of data objectsa set of data objects• valid operations on them (early 1970s)valid operations on them (early 1970s)
5
Data AbstractionData Abstraction
A set of A set of data objects,data objects, ordinarily using ordinarily using one or more type definitions,one or more type definitions,
A set of A set of abstract operations abstract operations on those on those data objects, anddata objects, and
EncapsulationEncapsulation of the whole in such a of the whole in such a way that the user of the new type way that the user of the new type cannot manipulate data objects of the cannot manipulate data objects of the type except by the operations defined.type except by the operations defined.
6
Information HidingInformation Hiding
Each program component should Each program component should hide as much information as hide as much information as possible from the users of the possible from the users of the component.component.
Program designProgram design
7
EncapsulationEncapsulation
The user of the abstractionThe user of the abstraction• Does not need to know the hidden Does not need to know the hidden
information in order to use the information in order to use the abstraction, andabstraction, and
• Is not permitted to directly use or Is not permitted to directly use or manipulate the hidden information manipulate the hidden information even if desiring to do so.even if desiring to do so.
Language designLanguage design
8
5.2. Encapsulation By 5.2. Encapsulation By SubprogramsSubprograms
An abstract operation defined by An abstract operation defined by the programmer.the programmer.
A subprogram definition:A subprogram definition:• specificationspecification• implementationimplementation
9
Specification of a Specification of a SubprogramSubprogram
The The name name of the subprogram.of the subprogram. The The signaturesignature (prototype) of the (prototype) of the
subprogram (number, order and subprogram (number, order and data type of arguments and data type of arguments and results).results).
The The action action performed by the performed by the subprogram, (a description of the subprogram, (a description of the function it computes).function it computes).
10
In C :In C :• void Sub(float X, int Y, float *Z, int *W);void Sub(float X, int Y, float *Z, int *W);
In Ada :In Ada :• procedure Sub(X: in REAL; Y: in integer; Z: procedure Sub(X: in REAL; Y: in integer; Z:
in out REAL; W: out BOOLEAN)in out REAL; W: out BOOLEAN)
• Sub : real1* integer * real2 --> real3 * Sub : real1* integer * real2 --> real3 * BooleanBoolean
11
Implementation of a Implementation of a SubprogramSubprogram
Subprogram body:Subprogram body:• local data declarationslocal data declarations• statementsstatements
float FN(float X, int Y)float FN(float X, int Y) signaturesignature
{float M(10); int N;{float M(10); int N; dcldcl
… … statementsstatements
}} subprograms are like primitive operations, subprograms are like primitive operations,
but the programmer must explicitly declare but the programmer must explicitly declare the arguments and results types.the arguments and results types.
12
Subprogram Definition and Subprogram Definition and InvocationInvocation
Definitions and activationsDefinitions and activations• Programmer writes a subprogram Programmer writes a subprogram
definition as a static property of a definition as a static property of a program.program.
The definition serves as a template for The definition serves as a template for creating activations during execution.creating activations during execution.
• During execution, if the subprogram During execution, if the subprogram is called (or invoked), an activation of is called (or invoked), an activation of it is created. it is created.
13
SubprogramSubprogram definition definition is like a is like a type definitiontype definition
and subprogram and subprogram activationactivation is like is like a data object of that type.a data object of that type.
14
Subprogram ActivationSubprogram Activation
Is a type of data object,Is a type of data object, as a block of storage that contains as a block of storage that contains
certain component data items,certain component data items, storage allocated when it is created, storage allocated when it is created,
freed when it is destroyed,freed when it is destroyed, has a has a lifetimelifetime (between (between callcall and and returnreturn),), it is executed, reference and modify it is executed, reference and modify
other data objects during execution. other data objects during execution. (these are the differences with other data objects)(these are the differences with other data objects)
15
Implementation of Implementation of Subprogram Definition and Subprogram Definition and invocationinvocation
Float FN(float X, int Y) Float FN(float X, int Y)
{const initval=2;{const initval=2;
#define finalval 10#define finalval 10
float M(10);int N;float M(10);int N;
……
N = initval;N = initval;
if (n<finalval){…}if (n<finalval){…}
return (20*X+M(N));}return (20*X+M(N));}
16
Components needed for Components needed for an activation of the an activation of the subprogramsubprogram
FN’s signature: storage for FN’s signature: storage for parametersparameters and and resultresult
DCLs: storage for DCLs: storage for local variableslocal variables storage for storage for literalsliterals and and defined defined
constantsconstants statements: storage for statements: storage for executable codeexecutable code
fig. 5.1. fig. 5.1. Page 205Page 205
17
Structure of a subprogram Structure of a subprogram activationactivation
Split the template into two parts:Split the template into two parts:• A static part, A static part, code segment. code segment.
– Constants and executable code. Constants and executable code. – Invariant during execution.Invariant during execution.– Shared by all activations.Shared by all activations.
• A dynamic part, A dynamic part, activation record.activation record.– Parameters,function results, local data , Parameters,function results, local data ,
housekeeping data (temporary storage areas, housekeeping data (temporary storage areas, return points, linkages for referencing non-local return points, linkages for referencing non-local variables).variables).
– A copy for each activation. A copy for each activation. (fig. 5.2. P.206)(fig. 5.2. P.206)
18
Storage ManagementStorage Management
Access to the components: using Access to the components: using the base-address-plus-offset the base-address-plus-offset calculation.calculation.
Allocation of a block of Allocation of a block of appropriate size on a subprogram appropriate size on a subprogram call, freeing the block on return.call, freeing the block on return.
19
Generic SubprogramsGeneric Subprograms
A generic subprogram name is A generic subprogram name is overloaded .overloaded .
p.207, p.208p.207, p.208
20
Type DefinitionsType Definitions
Type definition: definition of a Type definition: definition of a class of data objects.class of data objects.• A type nameA type name• declaration of the structure of a class declaration of the structure of a class
of data objects.of data objects.
p. 209,210p. 209,210
21
Advantages of type Advantages of type definitionsdefinitions
Simplifying program structure,Simplifying program structure, Simplifying the program Simplifying the program
modification,modification, as an argument to a subprogram.as an argument to a subprogram.
A kind of encapsulation and A kind of encapsulation and information hiding.information hiding.
22
implementationimplementation
A type definition is used only during A type definition is used only during translation.translation.• Enters the information from a type Enters the information from a type
definition into a table during definition into a table during translation,translation,
• using it during execution.using it during execution.
(storage representation: storage (storage representation: storage management, type checking)management, type checking)
23
Type EquivalenceType Equivalence
What does it mean to say that two What does it mean to say that two types are “the same”?types are “the same”? (a data type issue)(a data type issue)
What does it mean to say that two What does it mean to say that two data objects of the same type are data objects of the same type are “equal”?“equal”? (a semantic issue, r-value of a data (a semantic issue, r-value of a data
object)object)
24
Type EqualityType Equality
ProgramProgram main(input, output); main(input, output);
typetype Vect1: Vect1: arrayarray[1..10] [1..10] ofof real; real;
Vect2: Vect2: arrayarray[1..10] [1..10] ofof real; real;
var var X,Z: Vect1; Y:Vect2;X,Z: Vect1; Y:Vect2;
procedure procedure Sub(A: Vect1); Sub(A: Vect1);
… …
end;end;
begin -begin -main programmain program
X:= Y;X:= Y;
Sub(y)Sub(y)
end.end.
25
Type EqualityType Equality
Name equivalenceName equivalence• only if they have the same only if they have the same namename..• in Ada, C++, subprogram parameters in Pascalin Ada, C++, subprogram parameters in Pascal
Structural equivalenceStructural equivalence• if they define data objects that have the same if they define data objects that have the same
internal components. internal components. ( the same storage ( the same storage representation so the same accessing formulas representation so the same accessing formulas and the same run-time implementation)and the same run-time implementation)
• older languages (FORTRAN, COBOL, PL/1), C, older languages (FORTRAN, COBOL, PL/1), C, PascalPascal
26
Name Equivalence Name Equivalence DisadvantagesDisadvantages
There can be no There can be no anonymous types.anonymous types.• If we have If we have
var W: array[1..10] of real;var W: array[1..10] of real;
W can’t be used as an argument, its type has W can’t be used as an argument, its type has no name.no name.
A single global type definition must be A single global type definition must be used. A single type definition must be used. A single type definition must be used in all or large parts of a program used in all or large parts of a program (transmitting as an argument through a (transmitting as an argument through a chain of subprograms).chain of subprograms).
27
Structural Equivalence Structural Equivalence DisadvantagesDisadvantages
Several questions arise when two types are Several questions arise when two types are structurally equivalent.structurally equivalent.• For records, must the component names be identical?For records, must the component names be identical?• Or does it suffice to have the same number and type of Or does it suffice to have the same number and type of
components in the same order?components in the same order?• If record component names must be identical, then If record component names must be identical, then
must the components be in the same order?must the components be in the same order?• Must array subscript ranges be identical?Must array subscript ranges be identical?• Or is it sufficient to have the same number of Or is it sufficient to have the same number of
components?components?• Must the literals in two enumeration types be the same Must the literals in two enumeration types be the same
and in the same order? and in the same order?
28
Structural Equivalence Structural Equivalence DisadvantagesDisadvantages(cont.)(cont.)
Two variables may be structurally Two variables may be structurally equivalent, even though the equivalent, even though the programmer declares them as programmer declares them as separate types.separate types.• For example: type Meters = integer;For example: type Meters = integer;
liters = integer;liters = integer;
var Len: Meters;var Len: Meters;
Vol: Liters;Vol: Liters;
many type errors may go undetected.many type errors may go undetected.
29
Structural Equivalence Structural Equivalence DisadvantagesDisadvantages(cont.)(cont.)
Determining whether two complex Determining whether two complex type definition are structurally type definition are structurally equivalent, if done frequently, may equivalent, if done frequently, may be a costly part of translation.be a costly part of translation.
30
Data Object EqualityData Object Equality
Once the compiler determines that Once the compiler determines that two objects are the same type, are the two objects are the same type, are the two objects equal?two objects equal?
• Stack equality.Stack equality.• Set equality.Set equality.
Programmer-defined data, separate Programmer-defined data, separate operation for equaloperation for equal
P. 214P. 214
31
Type Definitions with Type Definitions with ParametersParameters
Parameterizing the type definition Parameterizing the type definition to be used repeatedly with to be used repeatedly with different substitutions for the different substitutions for the parameters.parameters.
Parameters likeParameters like• class size in Adaclass size in Ada• a type in MLa type in ML• no parameterized types in Pascalno parameterized types in Pascal
32
5.4. Storage Management5.4. Storage Management
Different features in a language causes Different features in a language causes different storage management techniques different storage management techniques to be used.to be used.• FORTRAN: no recursive calls, no dynamic FORTRAN: no recursive calls, no dynamic
storage management.storage management.• Pascal: stack-based storage management.Pascal: stack-based storage management.• LISP: garbage collection. LISP: garbage collection.
Language implementers decide about the Language implementers decide about the details. details.
Programmers don’t know about it.Programmers don’t know about it.
33
Major Run-Time Elements Major Run-Time Elements Requiring StorageRequiring Storage
DataData operationsoperations
34
Data and program Data and program Requiring StorageRequiring Storage
Code segments for translated user Code segments for translated user programs.programs.
System run-time programs.System run-time programs.• Supporting user programs.Supporting user programs.• Like library routines, software interpreters or Like library routines, software interpreters or
translator, storage management routines.translator, storage management routines. User-defined data structures and User-defined data structures and
constants.constants. Subprogram return points.Subprogram return points.
35
Referencing environments.Referencing environments.• Identifier associations (LISP A-list)Identifier associations (LISP A-list)
Temporaries in expression evaluation.Temporaries in expression evaluation.• Recursive function calls make it a lot.Recursive function calls make it a lot.
Temporaries in parameter Temporaries in parameter transmission.transmission.• Resulting values for evaluation of actual Resulting values for evaluation of actual
parameters are stored in temporaries until parameters are stored in temporaries until the total evaluation is completed.the total evaluation is completed.
36
Input-output buffers.Input-output buffers.• Temporary storage areas used between Temporary storage areas used between
the time of the actual physical transfer the time of the actual physical transfer of the data to or from external storage of the data to or from external storage and the program-initiated input / output and the program-initiated input / output operation.operation.
Miscellaneous system data.Miscellaneous system data.• System data like tables, status System data like tables, status
information for input-output, ...information for input-output, ...
37
Major operations requiring Major operations requiring storagestorage
Subprogram call and return operations.Subprogram call and return operations.• Activation record,Activation record,• local referencing environment, …local referencing environment, …
Data structure creation and destruction Data structure creation and destruction operations.operations.• new - dispose in Pascal.new - dispose in Pascal.• malloc - free in Cmalloc - free in C
Component insertion and deletion operations.Component insertion and deletion operations.• ML and Lisp list operations, inserting a ML and Lisp list operations, inserting a
component into a list.component into a list.
38
Programmer- and System- Programmer- and System- Controlled Storage Controlled Storage ManagementManagement
Programmer control of storage Programmer control of storage managementmanagement• place a large and often undesirable place a large and often undesirable
burden on the programmer,burden on the programmer,• may interfere with the necessary may interfere with the necessary
system-controlled storage system-controlled storage management.management.
Programmer can cause dangling Programmer can cause dangling references and garbage.references and garbage.
39
What language?What language?• Protection for the programmer by using a Protection for the programmer by using a
language with strong typing and language with strong typing and effective storage management features,effective storage management features,
• decrease in performancedecrease in performance
OROR• performanceperformance• more risk in having errors and fail during more risk in having errors and fail during
execution.execution.
40
Storage Management Storage Management PhasesPhases
Initial allocationInitial allocation RecoveryRecovery Compaction and reuseCompaction and reuse
41
Static Storage Static Storage ManagementManagement
SimplestSimplest static allocationstatic allocation no run-time storage managementno run-time storage management no concern for recovery and reuseno concern for recovery and reuse efficientefficient in COBOL and FORTRANin COBOL and FORTRAN
42
In FORTRANIn FORTRAN• each subprogram is compiled each subprogram is compiled
separately,separately,• the code segment includes an the code segment includes an
activation recordactivation record– compiled program,compiled program,– its data areas,its data areas,– return point location,return point location,– miscellaneous items of system data.miscellaneous items of system data.
43
Stack-Based Storage Stack-Based Storage ManagementManagement
Simplest run-time storage management Simplest run-time storage management technique.technique.
Based on the nested last in first out Based on the nested last in first out structure in subprograms calls and structure in subprograms calls and returns.returns.
Automatic compaction.Automatic compaction. In Pascal : a single central stack of activation records, In Pascal : a single central stack of activation records,
and a statically allocated area for subprogram code and a statically allocated area for subprogram code segments and system programs.segments and system programs.
P.222, fig. 5.5P.222, fig. 5.5
44
Heap Storage Heap Storage Management: Fixed-Size Management: Fixed-Size ElementsElements
A heap is a block of storage within A heap is a block of storage within which pieces are allocated and freed in which pieces are allocated and freed in some relatively unstructured manner.some relatively unstructured manner.
Need for heap , when a language Need for heap , when a language permits storage to be allocated and permits storage to be allocated and freed at execution time.freed at execution time.
Fixed size elements allocated => no Fixed size elements allocated => no need for compaction.need for compaction.
Page 224, fig. 5.7.Page 224, fig. 5.7.
45
RecoveryRecovery
The problem: identification of reusable The problem: identification of reusable element, solutions:element, solutions:
Explicit return by programmer or system.Explicit return by programmer or system.• Natural, but cause garbage and dangling Natural, but cause garbage and dangling
reference. P.226reference. P.226 Reference counts.Reference counts.
• Cost of maintaining. P.227Cost of maintaining. P.227• popular with parallel processing systems.popular with parallel processing systems.
Garbage collection.Garbage collection.
46
Garbage CollectionGarbage Collection
Dangling references more dangorousDangling references more dangorous
Two stagesTwo stages• MarkMark
– garbage collection bit, set off if it is active.garbage collection bit, set off if it is active.
• SweepSweep– links the “on” elements to the free list.links the “on” elements to the free list.
When is a heap element active?When is a heap element active?– There is a pointer to it from There is a pointer to it from
– outside the heapoutside the heap– another active heap elementanother active heap element
47
Three critical assumptionsThree critical assumptions• any active element must be reachable by a any active element must be reachable by a
chain of pointers beginning outside the heap.chain of pointers beginning outside the heap.• It must be possible to identify every pointer It must be possible to identify every pointer
outside the heap that points to an element outside the heap that points to an element inside the heap.inside the heap.
• It must be possible to identify within any It must be possible to identify within any active heap element the fields that contain active heap element the fields that contain pointers to other heap elements.pointers to other heap elements.
P. 231P. 231
48
Heap Storage Heap Storage Management:Management:Variable-Size ElementsVariable-Size Elements
More difficultMore difficult if space for programmer defined if space for programmer defined
data structures is sequential, like data structures is sequential, like arrays or activation records.arrays or activation records.
Major difficulty : reuse of Major difficulty : reuse of recovered space.recovered space.
49
Initial allocation and reuse.Initial allocation and reuse. reuse directly from a free-space list.reuse directly from a free-space list.
• First-fit methodFirst-fit method• best-fit methodbest-fit method
keeping free-space list in size order.keeping free-space list in size order. Recovery with variable-size blocks.Recovery with variable-size blocks.
• In first word of each block: a length indicator.In first word of each block: a length indicator. Compaction and memory fragmentation Compaction and memory fragmentation
problem.problem.
50
Compaction approaches:Compaction approaches:• Partial compactionPartial compaction
– only adjacent free blocksonly adjacent free blocks
• Full compactionFull compaction– active blocks may be shiftedactive blocks may be shifted