compilation - cs.tau.ac.il · translation into c 4. compiling simple classes §fields are handled...

113
Compilation 0368-3133 Lecture 12 Compiling Object-Oriented Programs Noam Rinetzky 1

Upload: others

Post on 11-Jul-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

Compilation0368-3133Lecture12

CompilingObject-OrientedPrograms

NoamRinetzky

1

Page 2: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

ObjectOrientedPrograms

§ C++,Java,C#,Python,…

§ Mainabstraction:Objects (usuallyoftypecalledclass)§ Code§ Data

§ NaturallysupportsAbstractDataTypeimplementations§ Informationhiding§ Evolution&reusability

§ Importantcharacteristic:Extension/Inheritance 2

Page 3: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

ASimpleExample

3

Object

Vehicleint posmove(..)

Carint passengers

move(..)

Truckawait(..)

Page 4: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

TranslationintoC

4

Page 5: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

CompilingSimpleClasses

§ Fieldsarehandledasrecords§ Methodshaveuniquenames

5

classA{fielda1;fielda2;methodm1(){…}methodm2(int i){…}

}

a1a2

Runtimeobject

m1Am2A

Compile-TimeTable

voidm2A(classA *this,int i){//Bodyofm2withanyobject//object-fielda1asthisà a1…

}

Page 6: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

CompilingSimpleClasses

§ Fieldsarehandledasrecords§ Methodshaveuniquenames

6

classA{fielda1;fielda2;methodm1(){…}methodm2(int i){…}

}

a1a2

Runtimeobject

m1Am2A

Compile-TimeTable

voidm2A(classA *this,int i){//Bodyofm2withany//object-fielda1asthisà a1…

}a.m2(5)

m2A(a,5)

Page 7: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

FeaturesofOOlanguages

§ Inheritance§ Subclass gets(inherits)propertiesofsuperclass

§ Methodoverloading§ Multiplemethodswiththesamenameanddifferentsignatures(insameclass)

§ Abstract (akavirtual)methods§ Methodoverriding§ Multiplemethodswiththesamename&signaturebutwithdifferentimplementations(acrossclasses)

§ Dynamicdispatch§ Lookupmethodsby(runtime)typeoftargetobject

7

Page 8: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

CompilingOOlanguages

§ “TranslationintoC”§ Powerfulruntimeenvironment

§ Adding“gluing”code

8

Page 9: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

RuntimeEnvironment

§ MediatesbetweentheOSandtheprogramminglanguage

§ Hidesdetailsofthemachinefromtheprogrammer§ Rangesfromsimplesupportfunctionsallthewaytoafull-fledgedvirtualmachine

§ Handlescommontasks§ Runtimestack(activationrecords)§ Memorymanagement

§ Runtimetypeinformation§ Methodinvocation§ Typeconversions

9

Page 10: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

MemoryLayout

10

stackgrowsdown(towardsloweraddresses)

heapgrowsup(towardshigher

addresses)

Heap

stack

code

staticdata

Page 11: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

MemoryLayout

11

stackgrowsdown(towardsloweraddresses)

heapgrowsup(towardshigher

addresses)

Heap

stack

code

staticdata

Runtimetypeinformation

Page 12: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

HandlingSingleInheritance

§ Simpletypeextension

12

class A {field a1;field a2;method m1() {…}method m2() {…}

}

class B extends A {field b1;method m3() {…}

}

Page 13: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

AddingfieldsFieldsakaDatamembers,instancevariables

§ Addsmoreinformationtotheinheritedclass§ “Prefixing”fieldsensuresconsistency

13

class A {field a1;field a2;method m1() {…}method m2() {…}

}

class B extends A {field b1;method m2() {…}method m3() {…}

}

typedef struct {field a1;field a2;

} A;

void m1A_A(A* this){…}void m2A_A(A* this){…}

typedef struct {field a1;field a2;field b1;

} B;

void m2A_B(B* this) {…}void m3B_B(B* this) {…}

Page 14: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

MethodOverriding

§ Redefinesfunctionality§ Morespecific§ Canaccessadditionalfields

14

class A {field a1;field a2;method m1() {…}method m2() {…}

}

class B extends A {field b1;method m2() {

… b1 …}method m3() {…}

}

Page 15: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

MethodOverriding

§ Redefinesfunctionality§ Morespecific§ Canaccessadditionalfields

15

class A {field a1;field a2;method m1() {…}method m2() {…}

}

class B extends A {field b1;method m2() {

… b1 …}method m3() {…}

}m2isdeclaredanddefined

m2isredefined

Page 16: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

MethodOverriding

§ Redefinesfunctionality§ Affectssemanticanalysis

16

a1a2

Runtimeobject

m1A_Am2A_A

Compile-TimeTable a1a2

Runtimeobject

b1

m1A_Am2A_B

Compile-TimeTable

m3B_B

class A {field a1;field a2;method m1() {…}method m2() {…}

}

class B extends A {field b1;method m2() {

… b1 …}method m3() {…}

}

Page 17: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

MethodOverriding

§ Redefinesfunctionality§ Affectssemanticanalysis

17

a1a2

Runtimeobject

m1A_Am2A_A

Compile-TimeTable a1a2

Runtimeobject

b1

m1A_Am2A_B

Compile-TimeTable

m3B_B

class A {field a1;field a2;method m1() {…}method m2() {…}

}

class B extends A {field b1;method m2() {

… b1 …}method m3() {…}

}

declared defined

Page 18: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

18

MethodOverriding

a1a2

Runtimeobject

m1A_Am2A_A

Compile-TimeTable a1a2

Runtimeobject

b1

m1A_Am2A_B

Compile-TimeTable

m3B_B

class A {field a1;field a2;method m1() {…}method m2() {…}

}

class B extends A {field b1;method m2() {

… b1 …}method m3() {…}

}

a.m2(5) // class(a) = A

m2A_A(a, 5)

b.m2(5) // class(b) = B

m2A_B(b, 5)

Page 19: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

19

MethodOverriding

a1a2

Runtimeobject

m1A_Am2A_A

Compile-TimeTable a1a2

Runtimeobject

b1

m1A_Am2A_B

Compile-TimeTable

m3B_B

class A {field a1;field a2;method m1() {…}method m2() {…}

}

class B extends A {field b1;method m2() { … b1 …

}method m3() {…}

}typedef struct {

field a1;field a2;

} A;

void m1A_A(A* this){…}void m2A_A(A* this){…}

typedef struct {field a1;field a2;field b1;

} B;

void m2A_B(B* this) {…}void m3B_B(B* this) {…}

Page 20: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

20

MethodOverriding

a1a2

Runtimeobject

m1A_Am2A_A

Compile-TimeTable a1a2

Runtimeobject

b1

m1A_Am2A_B

Compile-TimeTable

m3B_B

a.m2(5)//class(a)=A

m2A_A(a,5)

b.m2(5)//class(b)=B

m2A_B(b,5)

typedef struct {field a1;field a2;

} A;

void m1A_A(A* this){…}void m2A_A(A* this){…}

typedef struct {field a1;field a2;field b1;

} B;

void m2A_B(B* this) {…}void m3B_B(B* this) {…}

Page 21: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

Abstractmethods&classes

§ Abstractmethods§ Declaredseparately,definedinchildclasses§ E.g.,C++purevirtualmethods,abstractmethodsinJava

§ Abstractclasses=classmayhaveabstractmethods§ E.G.,Java/C++abstractclasses§ Abstractclassescannotbeinstantiated

§ Abstractaka“virtual”

§ Inheritingabstractclasshandledlikeregularinheritance§ Compilerchecksabstractclassesarenotallocated 21

Page 22: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

HandlingPolymorphism

§ WhenaclassBextendsaclassA§ variableoftypepointertoAmayactuallyrefertoobjectoftypeB

§ Upcasting fromasubclasstoasuperclass§ Prefixingfieldsguaranteesvalidity

22

classB*b=…;

classA*a=b;

a1a2b1

PointertoBPointertoAinsideB

(also)

classA *a=convert_ptr_to_B_to_ptr_A(b);

AB

Page 23: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

DynamicBinding

§ Anobject(“pointer”)odeclaredtobeofclassAcanactuallybe(“refer”)toaclassB

§ Whatdoes‘o.m()’mean?§ Staticbinding§ Dynamicbinding

§ Dependsontheprogramminglanguagerules

§ Howtoimplementdynamicbinding?§ Theinvokedfunctionisnotknownatcompiletime§ NeedtooperateondataoftheBandAinconsistentway

23

Page 24: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

ConceptualImpl.ofDynamicBinding

24

a1a2

Runtimeobject

m1A_Am2A_A

Compile-TimeTable a1a2

Runtimeobject

b1

m1A_Am2A_B

Compile-TimeTable

m3B_B

class A {field a1;field a2;method m1() {…}method m2() {…}

}

class B extends A {field b1;method m2() { … a3 …

}method m3() {…}

}typedef struct {

field a1;field a2;

} A;

void m1A_A(A* this){…}void m2A_A(A* this){…}

typedef struct {field a1;field a2;field b1;

} B;

void m2A_B(B* this) {…}void m3B_B(B* this) {…}

Page 25: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

ConceptualImpl.ofDynamicBinding

25

a1a2

Runtimeobject

m1A_Am2A_A

Compile-TimeTable a1a2

Runtimeobject

b1

m1A_Am2A_B

Compile-TimeTable

m3B_B

switch(dynamic_type(p)){caseDynamic_class_A:m2_A_A(p,3);caseDynamic_class_B:m2_A_B(convert_ptr_to_A_to_ptr_B(p),3);

}

typedef struct {field a1;field a2;

} A;

void m1A_A(A* this){…}void m2A_A(A* this){…}

typedef struct {field a1;field a2;field b1;

} B;

void m2A_B(B* this) {…}void m3B_B(B* this) {…}

”p.m2(3)”

Page 26: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

ConceptualImpl.ofDynamicBinding

26

a1a2

Runtimeobject

m1A_Am2A_A

Compile-TimeTable a1a2

Runtimeobject

b1

m1A_Am2A_B

Compile-TimeTable

m3B_B

switch(dynamic_type(p)){caseDynamic_class_A:m2_A_A(p,3);caseDynamic_class_B:m2_A_B(convert_ptr_to_A_to_ptr_B(p),3);

}

?

typedef struct {field a1;field a2;

} A;

void m1A_A(A* this){…}void m2A_A(A* this){…}

typedef struct {field a1;field a2;field b1;

} B;

void m2A_B(B* this) {…}void m3B_B(B* this) {…}

”p.m2(3)”

Page 27: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

Moreefficientimplementation

§ Applypointerconversioninsublasses§ Usedispatchtabletoinvokefunctions§ Similartotableimplementationofcase

27

voidm2A_B(classA *this_A){Class_B *this=convert_ptr_to_A_ptr_to_A_B(this_A);…

}

Page 28: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

Moreefficientimplementation

28

typedef struct {field a1;field a2;

} A;

void m1A_A(A* this){…}void m2A_A(A* this, int x){…}

typedef struct {field a1;field a2;field b1;

} B;

void m2A_B(A* thisA, int x){Class_B *this =

convert_ptr_to_A_to_ptr_to_B(thisA);…

}

void m3B_B(B* this){…}

Page 29: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

Moreefficientimplementation

29

typedef struct {field a1;field a2;

} A;

void m1A_A(A* this){…}void m2A_A(A* this, int x){…}

typedef struct {field a1;field a2;field b1;

} B;

void m2A_B(A* thisA, int x){Class_B *this =

convert_ptr_to_A_to_ptr_to_B(thisA);…

}

void m3B_B(B* this){…}

a1

a2

Runtimeobjectm1A_A

m2A_A

(Runtime)DispatchTable

vtablep

classA *p;

Page 30: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

Moreefficientimplementation

30

typedef struct {field a1;field a2;

} A;

void m1A_A(A* this){…}void m2A_A(A* this, int x){…}

typedef struct {field a1;field a2;field b1;

} B;

void m2A_B(A* thisA, int x){Class_B *this =

convert_ptr_to_A_to_ptr_to_B(thisA);…

}

void m3B_B(B* this){…}

a1

a2

Runtimeobjectm1A

m2A

(Runtime)DispatchTable

vtablep

classA *p;

m1A_A

m2A_A

Code

Page 31: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

Moreefficientimplementation

31

typedef struct {field a1;field a2;

} A;

void m1A_A(A* this){…}void m2A_A(A* this, int x){…}

typedef struct {field a1;field a2;field b1;

} B;

void m2A_B(A* thisA, int x){Class_B *this =

convert_ptr_to_A_to_ptr_to_B(thisA);…

}

void m3B_B(B* this){…}

p.m2(3); p®dispatch_table®m2A(p,3);

a1

a2

Runtimeobjectm1A_A

m2A_A

(Runtime)DispatchTable

vtablep

classA *p;

Page 32: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

Moreefficientimplementation

32

typedef struct {field a1;field a2;

} A;

void m1A_A(A* this){…}void m2A_A(A* this, int x){…}

typedef struct {field a1;field a2;field b1;

} B;

void m2A_B(A* thisA, int x){Class_B *this =

convert_ptr_to_A_to_ptr_to_B(thisA);…

}

void m3B_B(B* this){…}

p.m2(3); p®dispatch_table®m2A(p,3);

a1

a2

Runtimeobject

b1

vtablep m1A_A

m2A_B

(Runtime)DispatchTable

m3B_B

Page 33: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

Moreefficientimplementation

33

typedef struct {field a1;field a2;

} A;

void m1A_A(A* this){…}void m2A_A(A* this, int x){…}

typedef struct {field a1;field a2;field b1;

} B;

void m2A_B(A* thisA, int x){Class_B *this =

convert_ptr_to_A_to_ptr_to_B(thisA);…

}

void m3B_B(B* this){…}

p.m2(3); p®dispatch_table®m2A(,3);

a1

a2

Runtimeobject

b1

vtablep

convert_ptr_to_B_to_ptr_to_A(p)

m1A_A

m2A_B

(Runtime)DispatchTable

m3B_B

Page 34: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

Allocatingobjects(runtime)

§ x=newA()

§ AllocatememoryforA’sfields+pointertovtable§ Initializevtable topointtoA’svtable§ initializeA’sfields(callconstructor)§ returnobject

34

Page 35: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

Executinga.m2(5)

§ Fetchtheclassdescriptoratoffset0froma§ Fetchthemethod-instancepointerpfromtheconstantm2offsetofa

§ callm2(jumptoaddressp)

35

Page 36: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

MultipleInheritance

36

class C {field c1;field c2;method m1(){…}method m2(){…}

}

class D {field d1;

method m3() {…}method m4(){…}

}

class E extends C, D {field e1;

method m2() {…} method m4() {…}method m5(){…}

}

Page 37: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

MultipleInheritance

§ Allowsunifyingbehaviors§ Butraisessemanticdifficulties§ Ambiguityofclasses§ Repeatedinheritance

§ Hardtoimplement§ Semanticanalysis§ Codegeneration

§ Prefixingnolongerwork§ Needtogeneratecodefordowncasts

§ Hardtouse

37

Page 38: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

Asimpleimplementation

§ Mergedispatchtablesofsuperclases§ Generatecodeforupcastsanddowncasts

38

Page 39: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

Asimpleimplementation

39

class C {field c1;field c2;method m1(){…}method m2(){…}

}

class D {field d1;

method m3() {…}method m4(){…}

}

class E extends C, D {field e1;

method m2() {…} method m4() {…}method m5(){…}

}

d1

e1

Runtimeobject

m3D_D

m4D_E

(Runtime)DispatchTable

m5E_E

vtable

c1

c2

vtable

Pointerto- E- CinsideE

Pointerto- DinsideE

m1C_C

m2C_E

Page 40: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

Downcasting(EàC,D)

40

class C {field c1;field c2;method m1(){…}method m2(){…}

}

class D {field d1;

method m3() {…}method m4(){…}

}

class E extends C, D {field e1;

method m2() {…} method m4() {…}method m5(){…}

}

d1

e1

Runtimeobject

vtable

c1

c2

vtable

Pointerto- E- CinsideE

Pointerto- DinsideE

convert_ptr_to_E_to_ptr_to_C(e)=e;

convert_ptr_to_E_to_ptr_to_D(e)=e+sizeof(C);

m3D_D

m4D_E

(Runtime)DispatchTable

m5E_E

m1C_C

m2C_E

Page 41: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

Upcasting(C,DàE)

41

class C {field c1;field c2;method m1(){…}method m2(){…}

}

class D {field d1;

method m3() {…}method m4(){…}

}

class E extends C, D {field e1;

method m2() {…} method m4() {…}method m5(){…}

}

d1

e1

Runtimeobject

vtable

c1

c2

vtable

Pointerto- E- CinsideE

Pointerto- DinsideE

convert_ptr_to_C_to_ptr_to_E(c)=c;

convert_ptr_to_D_to_ptr_to_E(d)=d- sizeof(C);

m3D_D

m4D_E

(Runtime)DispatchTable

m5E_E

m1C_C

m2C_E

Page 42: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

IndependentmultipleInheritance

42

class C extends A {field c1;field c2;method m1(){…}method m2(){…}

}

class D extends A {field d1;

method m3(){…}method m4(){…}

}

class E extends C, D {field e1;

method m2() {…} method m4() {…}method m5(){…}

}

class A{field a1;field a2;method m1(){…}method m3(){…}

}

class A{field a1;field a2;method m1(){…}method m3(){…}

}

Page 43: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

IndependentmultipleInheritance

43

class C extends A {field c1;field c2;method m1(){…}method m2(){…}

}

class D extends A {field d1;

method m3(){…}method m4(){…}

}

class E extends C, D {field e1;

method m2() {…} method m4() {…}method m5(){…}

}

class A{field a1;field a2;method m1(){…}method m3(){…}

}

class A{field a1;field a2;method m1(){…}method m3(){…}

}

Page 44: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

IndependentmultipleInheritance

44

class C extends A {field c1;field c2;method m1(){…}method m2(){…}

}

class D extends A {field d1;

method m3(){…}method m4(){…}

}

class E extends C, D {field e1;

method m2() {…} method m4() {…}method m5(){…}

}

class A{field a1;field a2;method m1(){…}method m3(){…}

}

class A{field a1;field a2;method m1(){…}method m3(){…}

}

Page 45: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

IndependentmultipleInheritance

45

class C extends A {field c1;field c2;method m1(){…}method m2(){…}

}

class D extends A {field d1;

method m3(){…}method m4(){…}

}

class E extends C, D {field e1;method m3(){…} //altexplicitqualificationmethod m2() {…} method m4() {…}method m5(){…}

}

class A{field a1;field a2;method m1(){…}method m3(){…}

}

class A{field a1;field a2;method m1(){…}method m3(){…}

}

Page 46: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

class A{field a1;field a2;method m1(){…}method m3(){…}

}

IndependentInheritance

46

class C extends A{

field c1;field c2;method m1(){…}method m2(){…}

}

class D extends A{

field d1;

method m3(){…}method m4(){…}

}

class E extends C,D{

field e1;

method m2() {…} method m4() {…}method m5(){…}

}

e1

RuntimeEobject

m2C_E

m1A_A

(Runtime)DispatchTable

m3A_D

d1

Pointerto- E- CinsideE

Pointerto- DinsideE

m1A_C

m3A_A

a2

a2

c1

a1

vtable

c2

a1 m4D_E

m5E_E

vtable

Page 47: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

Dependentmultipleinheritance

§ Superclasses sharetheirownsuperclass

§ Thesimplesolutiondoesnotwork§ Thepositionsofnestedfieldsdonotagree

47

Page 48: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

DependentmultipleInheritance

48

class C extends A {field c1;field c2;method m1(){…}method m2(){…}

}

class D extends A {field d1;

method m3(){…}method m4(){…}

}

class E extends C, D {field e1;

method m2() {…} method m4() {…}method m5(){…}

}

class A{field a1;field a2;method m1(){…}method m3(){…}

}

Page 49: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

DependentmultipleInheritance

49

class C extends A {field c1;field c2;method m1(){…}method m2(){…}

}

class D extends A {field d1;

method m3(){…}method m4(){…}

}

class E extends C, D {field e1;

method m2() {…} method m4() {…}method m5(){…}

}

class A{field a1;field a2;method m1(){…}method m3(){…}

}

Page 50: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

DependentmultipleInheritance

50

class C extends A {field c1;field c2;method m1(){…}method m2(){…}

}

class D extends A {field d1;

method m3(){…}method m4(){…}

}

class E extends C, D {field e1;

method m2() {…} method m4() {…}method m5(){…}

}

class A{field a1;field a2;method m1(){…}method m3(){…}

}

Page 51: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

DependentInheritance

§ Superclasses sharetheirownsuperclass

§ Thesimplesolutiondoesnotwork§ Thepositionsofnestedfieldsdonotagree

51

Page 52: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

Implementation

§ Useanindextabletoaccessfields§ Accessoffsetsindirectly

52

Page 53: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

Implementationclass C

extends A{field c1;field c2;method m1(){…}method m2(){…}

}

class D extends A{

field d1;

method m3(){…}method m4(){…}

}

class E extends C,D{

field e1;

method m2() {…} method m4() {…}method m5(){…}

}

class A{field a1;field a2;method m1(){…}method m3(){…}

}

53

d1

e1

RuntimeEobject

m2C_E

m1A_A

(Runtime)DispatchTable

m3A_D

Indextab

Pointerto- E- CinsideE

Pointerto- DinsideE

m1A_C

m3A_A

vtable

a1

a2

Indextab

vtable

c1

c2

2 3 4 5 8 9 -4 -3 2

m4D_E

m5E_EIndextables

Page 54: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

ClassDescriptors

§ Runtimeinformationassociatedwithinstances§ Dispatchtables§ Invokedmethods

§ Indextables§ Sharedbetweeninstancesofthesameclass

§ Canhavemore(reflection)

54

Page 55: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

InterfaceTypes

§ Javasupportslimitedformofmultipleinheritance§ Interfaceconsistsofseveralmethodsbutnofields

§ AclasscanimplementmultipleinterfacesSimplertoimplement/understand/use

55

publicinterfaceComparable{publicint compare(Comparableo);

}

Page 56: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

InterfaceTypes

§ Implementation:recordwith2pointers:§ Aseparatedispatchtableperinterface§ Apointertotheobject

56

a1

a2

interfacetablevtable

i.table

object

vtable

field1

field2

a1

b1

a2

Page 57: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

DynamicClassLoading

§ SupportedbysomeOOlanguages(Java)§ Atcompiletime§ theactualclassofagivenobjectatagivenprogrampointmaynotbeknown

§ Someaddresseshavetoberesolvedatruntime§ problemwhenmultipleinheritanceisallowed

§ Canusehashtabletomapfieldsnametopointerstofunctions

57

Page 58: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

OtherOOFeatures

§ Informationhiding§ private/public/protectedfields§ Semanticanalysis(contexthandling)

§ Testingclassmembership§ Singleinheritance:lookupthechainof“supers”§ Ifinheritanceisbounded

§ Allocateparentarrayateveryclassdescriptors§ lookupat“depth-of-inheritance”index

§ Upcasting:(Possibly)runtimechecks§ Bx=(B)a//BextendsA 58

Page 59: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

OptimizingOOlanguages

§ Hideadditionalcosts§ Eliminateruntimechecks

Ax=newB()//BextendsABy=(B)x

§ Eliminatedeadfields

§ Replacedynamicbystaticbindingwhenpossiblex=newB()//BextendsAandoverridesfx.f()//invokeB_f(x)§ Typepropagationanalysis~reachingdefinitions

59

Page 60: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

OptimizingOOlanguages

§ Simultaneouslygeneratecodeformultipleclasses

§ GeneratecodeB_f()andC_f()§ Codespaceisanissue

60

classA{g(){}f(){g()}

}

classBextendsA{g(){}}

classCextendsA{g()}

Page 61: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

Summary

§ OOisaprogramming/designparadigm§ OOfeaturescomplicatescompilation§ Semanticanalysis§ Codegeneration§ Runtime§ Memorymanagement

§ UnderstandingcompilationofOOcanbeusefulforprogrammers

61

Page 62: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

62

Page 63: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

Compilation0368-3133Lecture12b

MemoryManagement

NoamRinetzky

63

Page 64: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

AST+Sym.Tab.

StagesofcompilationSourcecode

(program)

LexicalAnalysis

SyntaxAnalysis

Parsing

ContextAnalysis

Portable/Retargetable codegeneration

Targetcode

(executable)

Assembly

IRText

Tokenstream

AST

CodeGeneration

Page 65: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

Compilationè Execution

AST+Sym.Tab.

Sourcecode

(program)

LexicalAnalysis

SyntaxAnalysis

Parsing

ContextAnalysis

Portable/Retargetable codegeneration

Targetcode

(executable)

IRText

Tokenstream

AST

CodeGeneration

Linker

Assembler

Loader

Symbo

licAdd

r

ObjectF

ile

ExecutableFile

image

Executingprogram

Runtim

eSystem

Page 66: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

RuntimeEnvironment

§ MediatesbetweentheOSandtheprogramminglanguage§ Hidesdetailsofthemachinefromtheprogrammer

§ Rangesfromsimplesupportfunctionsallthewaytoafull-fledgedvirtualmachine

§ Handlescommontasks§ Runtimestack(activationrecords)§ Memorymanagement§ Dynamicoptimization§ Debugging§ …

66

Page 67: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

Wheredoweallocatedata?

§ Activationrecords§ Lifetimeofallocateddatalimitedbyprocedurelifetime§ Stackframedeallocated (popped)whenprocedurereturn

§ Dynamicmemoryallocationontheheap

67

Page 68: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

MemoryLayout

stackgrowsdown(towardsloweraddresses)

heapgrowsup(towardshigher

addresses)

heap

stack

code

staticdata

68

Page 69: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

Alignment

§ Typically,canonlyaccessmemoryatalignedaddresses§ Either4-bytesor8-bytes

§ Whathappensifyouallocatedataofsize5bytes?§ Padding – thespaceuntilthenextalignedaddressesiskeptempty

§ (sidenote:x86,ismorecomplicated,asusual,andalsoallowsunalignedaccesses,butnotrecommended)

69

Page 70: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

Allocatingmemory

§ InC- malloc§ void *malloc(size_t size)

§ Whydoesmalloc returnvoid*?§ Itjustallocatesachunkofmemory,withoutregardtoitstype

§ Howdoesmalloc guaranteealignment?§ Afterall,youdon’tknowwhattypeitisallocatingfor§ Ithastoalignforthelargestprimitivetype§ Inpracticeoptimizedfor8bytealignment(glibc-2.17)

70

Page 71: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

MemoryManagement

§ Manualmemorymanagement§ Automaticmemorymanagement

71

Page 72: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

Manualmemorymanagement

§ malloc§ free

a = malloc(…) ;// do something with afree(a);

72

Page 73: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

malloc

§ whereismalloc implemented?§ howdoesitwork?

73

Page 74: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

§ Adatastructurerecordsthelocationandsizeoffreecellsofmemory.

§ Theallocatorconsiderseachfreecellinturn,andaccordingtosomepolicy,choosesonetoallocate.

§ Threebasictypesoffree-listallocation:§ First-fit§ Next-fit§ Best-fit

Free-listAllocation

Page 75: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

Memorychunks

75

Page 76: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

Freelist

76

Page 77: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

First-Fit

150KB 100KB 170KB 300KB 50KB

Allocated Free

120KB allocation request

30KB 100KB 170KB 300KB 50KB

Page 78: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

30KB 100KB 170KB 300KB 50KB

50KB allocation request

30KB 50KB 170KB 300KB 50KB

First-Fit

Page 79: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

30KB 50KB 170KB 300KB 50KB

200KB allocation request

30KB 50KB 170KB 100KB 50KB

First-Fit

Page 80: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

§ Dispersaloffreememoryacrossapossiblylargenumberofsmallfreecells.

§ Negativeeffects:§ Canpreventallocationfromsucceeding§ Maycauseaprogramtousemoreaddressspace,moreresidentpagesandmorecachelines.

§ Fragmentationisimpracticaltoavoid:§ Usuallytheallocatorcannotknowwhatthefuturerequestsequencewillbe.

§ Evengivenaknownrequestsequence,doinganoptimalallocationisNP-hard.

§ UsuallyThereisatrade-offbetweenallocationspeedandfragmentation.

Fragmentation

Page 81: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

§ Idea– usemultiplefree-listwhosemembersaresegregatedbysizeinordertospeedallocation.

§ Usuallyafixednumberk ofsizevaluess0 <s1<…<sk-1§ k+1freelistsf0,…,fk§ Forafreecell,b,onlistfi,

size b =𝑠2∀1 ≤ 𝑖 ≤ 𝑘 − 1size(b)>sk-1ifi=k

§ Whenrequestingacellofsizeb≤sk-1,theallocatorroundstherequestsizeuptothesmallestsi suchthatb ≤si.

§ Siiscalledasizeclass

Segregated-fitsAllocation

Page 82: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

SegregatedFitAllocate(j):

result ← remove(freeLists[j])

if result = nulllarge ← allocateBlock()

if large = nullreturn null

initialize(large, sizes[j])

result ← remove(freeList[j])

return result

§ Listfk,forcellslargerthansk,isorganizedtouseoneofthebasicsingle-listalgorithm.

§ Per-celloverheadsforlargecellareabithigherbutintotalitisnegligible.

§ Themainadvantage:forsizeclassesotherthansk,allocationtypicallyrequiresconstanttime.

Segregated-fitsAllocation

Page 83: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

fk-1

fk

f1

f0

s0

s1

sk-1

>sk-1 >sk-1

Page 84: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

RuntimesupportforMM

§ C’sstandardlibraryprovidesbasicmemorymanagement§ GetsmemorypagesfromtheOS§ Maintainsinventoryoffreememorycells

§ mmap(),brk()

84

Page 85: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

free

§ Freetoolate– wastememory(memoryleak)§ Freetooearly– danglingpointers/crashes§ Freetwice– error

85

Page 86: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

Whencanwefreeanobject?

a = malloc(…) ;b = a;// free (a); ? c = malloc (…);if (b == c)

printf(“unexpected equality”);

Cannotfreeanobjectifithasareferencewithafutureuse!

86

Page 87: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

Whencanfreexbeinsertedafterp?

pcannotfreex

xreferencesanobjectl

somereferencetolisused

Onallexecutionpathsafterptherearenousesofreferencestotheobjectreferencedbyxè insertingfreexafterpisvalid

87

Page 88: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

AutomaticMemoryManagement

§ automaticallyfreememorywhenitisnolongerneeded

§ notlimitedtoOOlanguages§ prevalentinOOlanguagessuchasJava§ alsoinfunctionallanguages

88

Page 89: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

Garbagecollection

§ approximatereasoningaboutobjectliveness§ usereachabilitytoapproximateliveness§ assumereachableobjectsarelive§ non-reachableobjectsaredead

89

Page 90: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

GarbageCollection– ClassicalTechniques

§ referencecounting§ markandsweep§ copying

90

Page 91: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

GCusingReferenceCounting

§ addareference-countfieldtoeveryobject§ howmanyreferencespointtoit

§ when(rc==0)theobjectisnonreachable§ nonreachable=>dead§ canbecollected(deallocated)

91

Page 92: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

ManagingReferenceCounts§ Eachobjecthasareferencecounto.RC§ Anewlyallocatedobjectogetso.RC =1§ why?

§ write-barrierforreferenceupdatesupdate(x,old,new){old.RC--;new.RC++;if(old.RC ==0)collect(old);

}

§ collect(old)willdecrementRCforallchildrenandrecursivelycollectobjectswhoseRCreached0.

92

Page 93: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

Cycles!

§ cannotidentifynon-reachablecycles§ referencecountsfornodesonthecyclewillneverdecrementto0

§ severalapproachesfordealingwithcycles§ ignore§ periodicallyinvokeatracingalgorithmtocollectcycles§ specializedalgorithmsforcollectingcycles

93

Page 94: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

TheMark-and-SweepAlgorithm[McCarthy1960]

§ Markingphase§ markroots§ traceallobjectstransitivelyreachablefromroots§ markeverytraversedobject

§ Sweepphase§ scanallobjectsintheheap§ collectallunmarkedobjects

94

Page 95: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

The Mark-Sweep algorithm

§ Traverseliveobjects&markblack.§ Whiteobjectscanbereclaimed.

stackHeap

registers

Roots

Note!Thisisnottheheap datastructure!

95

Page 96: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

Triggering

New(A)=iffree_list isempty

mark_sweep()iffree_list isempty

return(“out-of-memory”)pointer=allocate(A)return(pointer)

Garbagecollectionistriggeredbyallocation

96

Page 97: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

BasicAlgorithm

mark_sweep()=forPtr inRoots

mark(Ptr)sweep()

mark(Obj)=ifmark_bit(Obj)==unmarked

mark_bit(Obj)=markedforCinChildren(Obj)

mark(C)

Sweep()=p=Heap_bottomwhile(p<Heap_top)

if(mark_bit(p)==unmarked)thenfree(p)elsemark_bit(p)=unmarked;p=p+size(p)

97

Page 98: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

Mark&Sweep Example

r1

r2

98

Page 99: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

Mark&Sweep inDepth

mark(Obj)=ifmark_bit(Obj)==unmarked

mark_bit(Obj)=markedforCinChildren(Obj)

mark(C)

§ Howmuchmemorydoesitconsume?§ Recursiondepth?§ Canyoutraversetheheapwithoutworst-caseO(n)stack?

§ Deutch-Schorr-Waitealgorithmforgraphmarkingwithoutrecursionorstack(worksbyreversingpointers)

99

Page 100: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

PropertiesofMark&Sweep

• Mostpopularmethodtoday• Simple• Doesnotmoveobjects,andsoheapmayfragment• Complexity

JMarkphase:liveobjects(dominantphase)L Sweepphase:heapsize

• Termination:eachpointertraversedonce• Engineeringtricksusedtoimproveperformance

100

Page 101: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

Mark-Compact

§ Duringtherunobjectsareallocatedandreclaimed§ Gradually,theheapgetsfragmented§ Whenspaceistoofragmentedtoallocate,acompactionalgorithmisused

§ Moveallliveobjectstothebeginningoftheheapandupdateallpointerstoreferencethenewlocations

§ Compactionisverycostlyandweattempttorunitinfrequently,oronlypartially

101

The Heap

Page 102: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

MarkCompact

§ Importantparametersofacompactionalgorithm

§ Keeporderofobjects?§ Useextraspaceforcompactordatastructures?§ Howmanyheappasses?§ Canitruninparallelonamulti-processor?

§ Wedonotelaborateinthisintro

102

Page 103: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

CopyingGC

§ partitiontheheapintotwoparts§ oldspace§ newspace

§ CopyingGCalgorithm§ copyallreachable objectsfromoldspacetonewspace§ swaprolesofold/newspace

103

Page 104: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

Example

old new

Roots

A

D

C

B

E

104

Page 105: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

Example

old new

Roots

A

D

C

B

E

A

C

105

Page 106: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

PropertiesofCopyingCollection

§ Compactionforfree§ Majordisadvantage:halfoftheheapisnotused§ “Touch”onlytheliveobjects

§ Goodwhenmostobjectsaredead§ Usuallymostnewobjectsaredead

§ Somemethodsuseasmallspaceforyoungobjectsandcollectthisspaceusingcopyinggarbagecollection

106

Page 107: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

Averysimplisticcomparison

CopyingMark&sweepReferenceCounting

LiveobjectsMark=liveobjectsSweep=Sizeofheap

Pointerupdates+deadobjects

Complexity

Halfheapwasted

Bit/object+stackforDFS

Count/object+stackforDFS

Spaceoverhead

ForfreeAdditionalworkAdditionalworkCompaction

longlongMostlyshortPausetime

CyclecollectionMoreissues

107

Page 108: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

ParallelMark&Sweep GC

r1

r2

Thread1Thread2

ParallelGC:mutator isstopped,GCthreadsruninparallel

108

Page 109: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

ConcurrentMark&Sweep Example

r1

r2

X

X

ConcurrentGC:mutator andGCthreadsruninparallel,noneedtostopmutator

109

Page 110: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

ConservativeGC

§ HowdoyoutrackpointersinlanguagessuchasC?§ Anyvaluecanbecastdowntoapointer

§ Howcanyoufollowpointersinastructure?

§ Easy– beconservative,consideranythingthatcanbeapointertobeapointer

§ Practical!(e.g.,Boehmcollector)

110

Page 111: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

ConservativeGC

§ Canyouimplementaconservativecopying GC?

§ Whatistheproblem?

§ Cannotupdatepointerstothenewaddress…youdon’tknowwhetherthevalueisapointer,cannotupdateit

111

Page 112: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

ModernMemoryManagement

§ Considersstandardprogramproperties§ Handleparallelism§ Stoptheprogramandcollectinparallelonallavailableprocessors

§ Runcollectionconcurrentlywiththeprogramrun

§ Cacheconsciousness§ Real-time

112

Page 113: Compilation - cs.tau.ac.il · Translation into C 4. Compiling Simple Classes §Fields are handled as records §Methods have unique names 5 class A {field a1; field a2; method m1()

TerminologyRecap

§ Heap,objects

§ Allocate,free(deallocate,delete,reclaim)

§ Reachable,live,dead,unreachable

§ Roots§ Referencecounting,markandsweep,copying,

compaction,tracingalgorithms

§ Fragmentation

113