the gamedesigninitiative at cornell university Lecture 9 Memory Management

Similar documents
Memory Management: The Details

the gamedesigninitiative at cornell university Lecture 10 Memory Management

Memory Management: High-Level Overview

CS 345. Garbage Collection. Vitaly Shmatikov. slide 1

Mobile Application Development

Run-time Environments - 3

CMSC 330: Organization of Programming Languages

Run-time Environments -Part 3

Memory management COSC346

Lecture Notes on Garbage Collection

Motivation for Dynamic Memory. Dynamic Memory Allocation. Stack Organization. Stack Discussion. Questions answered in this lecture:

CS 241 Honors Memory

Habanero Extreme Scale Software Research Project

CMSC 330: Organization of Programming Languages

Managed runtimes & garbage collection. CSE 6341 Some slides by Kathryn McKinley

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

Managed runtimes & garbage collection

CPSC 213. Introduction to Computer Systems. Winter Session 2017, Term 2. Unit 1c Jan 24, 26, 29, 31, and Feb 2

Design Issues. Subroutines and Control Abstraction. Subroutines and Control Abstraction. CSC 4101: Programming Languages 1. Textbook, Chapter 8

Compilers. 8. Run-time Support. Laszlo Böszörmenyi Compilers Run-time - 1

Reference Counting. Reference counting: a way to know whether a record has other users

Shenandoah: An ultra-low pause time garbage collector for OpenJDK. Christine Flood Roman Kennke Principal Software Engineers Red Hat

CMSC 330: Organization of Programming Languages. Memory Management and Garbage Collection

Programming Language Implementation

Project. there are a couple of 3 person teams. a new drop with new type checking is coming. regroup or see me or forever hold your peace

Compiler Construction

CS577 Modern Language Processors. Spring 2018 Lecture Garbage Collection

Reference Counting. Reference counting: a way to know whether a record has other users

Sustainable Memory Use Allocation & (Implicit) Deallocation (mostly in Java)

a data type is Types

Compiler Construction

Manual Allocation. CS 1622: Garbage Collection. Example 1. Memory Leaks. Example 3. Example 2 11/26/2012. Jonathan Misurda

Intermediate Programming, Spring 2017*

CS 11 C track: lecture 5

ITP 342 Advanced Mobile App Dev. Memory

Exception Namespaces C Interoperability Templates. More C++ David Chisnall. March 17, 2011

CA341 - Comparative Programming Languages

CPSC 213. Introduction to Computer Systems. Instance Variables and Dynamic Allocation. Unit 1c

CS 536 Introduction to Programming Languages and Compilers Charles N. Fischer Lecture 11

Q1: /8 Q2: /30 Q3: /30 Q4: /32. Total: /100

StackVsHeap SPL/2010 SPL/20

Acknowledgements These slides are based on Kathryn McKinley s slides on garbage collection as well as E Christopher Lewis s slides

Garbage Collection. CS 351: Systems Programming Michael Saelee

the gamedesigninitiative at cornell university Lecture 13 Memory Management

Class Destructors constant member functions

Runtime. The optimized program is ready to run What sorts of facilities are available at runtime

Advances in Programming Languages: Regions

Advanced Programming & C++ Language

Heap Management. Heap Allocation

Object-Oriented Programming for Scientific Computing

Lecture 7 More Memory Management Slab Allocator. Slab Allocator

Deallocation Mechanisms. User-controlled Deallocation. Automatic Garbage Collection

CS193E Lecture #3 Categories and Protocols Cocoa Memory Management


Older geometric based addressing is called CHS for cylinder-head-sector. This triple value uniquely identifies every sector.

Run-Time Environments/Garbage Collection

6.172 Performance Engineering of Software Systems Spring Lecture 9. P after. Figure 1: A diagram of the stack (Image by MIT OpenCourseWare.

Lecture Conservative Garbage Collection. 3.2 Precise Garbage Collectors. 3.3 Other Garbage Collection Techniques

Pointers. Developed By Ms. K.M.Sanghavi

Limitations of the stack

Engineering Robust Server Software

the gamedesigninitiative at cornell university Lecture 6 C++: Basics

Smart Pointers. Some slides from Internet

A.Arpaci-Dusseau. Mapping from logical address space to physical address space. CS 537:Operating Systems lecture12.fm.2

Dynamic Storage Allocation

Memory Management. Didactic Module 14 Programming Languages - EEL670 1

Memory Management. Chapter Fourteen Modern Programming Languages, 2nd ed. 1

Pointers and References

Last week. Data on the stack is allocated automatically when we do a function call, and removed when we return

Robust Memory Management Schemes

Short Notes of CS201

Lecture 14 Notes. Brent Edmunds

CS201 - Introduction to Programming Glossary By

Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst

CSCI-1200 Data Structures Fall 2011 Lecture 24 Garbage Collection & Smart Pointers

Lecture 13: Garbage Collection

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

CSCI-1200 Data Structures Fall 2017 Lecture 5 Pointers, Arrays, & Pointer Arithmetic

Ironclad C++ A Library-Augmented Type-Safe Subset of C++

Lecture Notes on Advanced Garbage Collection

Structure of Programming Languages Lecture 10

Objective-C ICT/7421ICTNathan. René Hexel. School of Information and Communication Technology Griffith University.

Name, Scope, and Binding. Outline [1]

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

Memory management has always involved tradeoffs between numerous optimization possibilities: Schemes to manage problem fall into roughly two camps

CS61C : Machine Structures

A new Mono GC. Paolo Molaro October 25, 2006

Lecture 7: Binding Time and Storage

Profiling & Optimization

Exploiting the Behavior of Generational Garbage Collector

Consider the program...

Automatic Memory Management

Lecture 15a Persistent Memory & Shared Pointers

CS61C : Machine Structures

JAVA PERFORMANCE. PR SW2 S18 Dr. Prähofer DI Leopoldseder

Quantifying the Performance of Garbage Collection vs. Explicit Memory Management

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

CMSC 330: Organization of Programming Languages. Ownership, References, and Lifetimes in Rust

Processes. Johan Montelius KTH

Process s Address Space. Dynamic Memory. Backing the Heap. Dynamic memory allocation 3/29/2013. When a process starts the heap is empty

Transcription:

Lecture 9

Gaming Memory Constraints Redux Wii-U Playstation 4 2GB of RAM 1GB dedicated to OS Shared with GPGPU 8GB of RAM Shared GPU, 8-core CPU OS footprint unknown 2

Two Main Concerns with Memory Getting rid of memory you no longer want Doing it yourself: deallocation Runtime support: garbage collection Having enough memory to function Reserved memory: memory pools Spatial locality: dynamic loading 3

Manual Deletion in C/C++ Depends on allocation malloc: free new: delete What does deletion do? Marks memory as available Does not erase contents Does not reset pointer int main() { cout << "Program started" << endl; int* a = new int[length]; delete a; for(int ii = 0; ii < LENGTH; ii++) { cout << "a[" << ii << "]=" << a[ii] << endl; Only crashes if pointer bad Pointer is currently NULL Pointer is illegal address cout << "Program done" << endl; 4

Memory Leaks Leak: Cannot release memory Object allocated on heap Only reference is moved No way to reference object Consumes memory fast! Can even happen in Java memoryarea = newarea; JNI supports native libraries Method may allocate memory Need anor method to free Example: dispose() in JOGL 5

A Question of Ownership void foo() { MyObject* o = " new MyObject(); o.dosomething(); o = null; return; Memory Leak void foo(int key) { MyObject* o =" table.get(key); o.dosomething(); o = null; return; Not a Leak 6

A Question of Ownership void foo() { MyObject* o =" table.get(key); table.remove(key); o = null; return; Memory Leak? void foo(int key) { MyObject* o =" table.get(key); table.remove(key); ntable.put(key,o); o = null; return; Not a Leak 7

A Question of Ownership Thread 1 Thread 2 Owners of obj void run() { o.dosomething1(); void run() { o.dosomething2(); Who deletes obj? 8

Understanding Ownership Function-Based Object owned by a function Function allocated object Can delete when function done Ownership never transferred May pass to or functions But always returns to owner Really a stack-based object Active as long as allocator is But allocated on heap (why?) Object-Based Owned by anor object Referenced by a field Stored in a data structure Allows multiple ownership No guaranteed relationship between owning objects Call each owner a reference When can we deallocate? No more references References unimportant 9

Understanding Ownership Function-Based Object owned by a function Function allocated object Can delete when function done Ownership never transferred May pass to or functions But always returns to owner Easy: Will ignore Really a stack-based object Active as long as allocator is But allocated on heap (why?) Object-Based Owned by anor object Referenced by a field Stored in a data structure Allows multiple ownership No guaranteed relationship between owning objects Call each owner a reference When can we deallocate? No more references References unimportant 10

Reference Strength Strong Reference Reference asserts ownership Cannot delete referred object Assign to NULL to release Else assign to anor object Can use reference directly No need to copy reference Treat like a normal object Standard type of reference Weak Reference Reference!= ownership Object can be deleted anytime Often for performance caching Only use indirect references Copy to local variable first Compute on local variable Be prepared for NULL Reconstruct object? Abort computation? 11

Weak Reference Example in Java public class CombatComponent { WeakReference<NPC> target; public void attacktarget(aicontroller ai) { NPC Target = target.get(); if (Target == null) { // Be prepared for NULL Target = ai.pickcombattargetfor(this); target = new WeakReference<NPC>(Target); // Do stuff with Target Class in package java.lang.ref 12

Weak Reference Example in Java public class CombatComponent { WeakReference<NPC> target; public void attacktarget(aicontroller ai) { NPC Target = target.get(); if (Target == null) { // Be prepared for NULL WeakReference Target = ai.pickcombattargetfor(this); GC if no standard references left target = new WeakReference<NPC>(Target); Encourages eager GC policies // Do stuff with Target Class in package java.lang.ref Reference Managers in Java SoftReference GC possible if no references left But only if space is needed 13

Reference Counting Every object has a counter Tracks number of owners No owners = memory leak Increment when assign reference Can be explicit method call can we do it automatically? Decrement when remove reference Can be explicit or automatic If makes count 0, delete it Ref 1 Ref 2 Object Count = 12 14

When to Adjust Count? On object allocation Initial allocator is an owner Even if in a local variable When added to an object Often handled by setter Part of class invariant When removed from object Also handled by setter Release before reassign Any or time? public class Container { RCObject object; public Container() { // Initial allocation; ownership Object = new RCObject(); public void setobject(rcobject o) { if (object!= null) { object.decrement(); o.increment(); object = o; 15

Reference Counting in Obj-C // create a new instance" Fraction *frac = [[Fraction alloc] init];! [frac retain]; Reference count 2 // set values and print " [frac setnumerator: 1]; " [frac setdenominator: 3]; Reference count 1 printf( "The fraction is: " ); " [frac print]; " printf( "\n" ); 16 // free memory " [frac release];! [frac release]; Reference count 1 Reference count 0 frac is deleted

Reference Counting in Classic Obj-C // create a new instance" Fraction *frac = [[Fraction alloc] init];! [frac retain]; Reference count 2 // set values and print " [frac setnumerator: 1]; " [frac setdenominator: 3]; Reference count 1 printf( "The fraction is: " ); " [frac print]; " printf( "\n" ); // free memory " [frac release];! Reference count 1 Memory Leak! 17

Which Is Correct? Fraction* foo(int n, int d) { // create a new instance" Fraction *frac =" [[Fraction alloc] init]; // set values " [frac setnumerator: n]; " [frac setdenominator: d]; // free memory " [frac release]; // return it " return frac; Fraction* foo(int n, int d) { // create a new instance" Fraction *frac =" [[Fraction alloc] init]; // set values " [frac setnumerator: n]; " [frac setdenominator: d]; // Do nothing" // return it " return frac; 18

Which Is Correct? Fraction* foo(int n, int d) { // create a new instance" Fraction *frac =" [[Fraction alloc] init]; Fraction* foo(int n, int d) { // create a new instance" Fraction *frac =" [[Fraction alloc] init]; // set values " [frac setnumerator: n]; " [frac setdenominator: d]; // free memory " [frac release]; Trick Question! // set values " [frac setnumerator: n]; " [frac setdenominator: d]; // Do nothing" // return it " return frac; // return it " return frac; 19

Neir is Optimal Fraction* foo(int n, int d) { // create a new instance" Fraction *frac =" [[Fraction alloc] init]; // set values " [frac setnumerator: n]; " [frac setdenominator: d]; Fraction* foo(int n, int d) { // create a new instance" Fraction One *frac possibility: =" [[Fraction alloc] init]; make ownership transfer part of // set values " [frac setnumerator: specification n]; " [frac setdenominator: d]; // free memory " [frac release]; // return it " return frac; Object freed. Nothing left to return. // Do nothing" // return it " return frac; Reference kept. Who will release this reference? 20

Objective-C: An Alternate Solution Fraction* foo(int n, int d) { Autorelease // create a new instance" Fraction *frac =" [[Fraction alloc] init]; // set values " [frac setnumerator: n]; " [frac setdenominator: d]; // free memory " [frac autorelease]; // return it " return frac; Delay release until later. Handled by OS. Places object in a pool OS releases all in pool At end of event handler Games are not event driven! Game loop runs continuously Pool is not released You can release it manually At end of loop iteration? 21

Objective-C: An Alternate Solution Fraction* foo(int n, int d) { // create a new instance" Fraction *frac =" [[Fraction alloc] init]; // set values " [frac setnumerator: n]; " [frac setdenominator: d]; // free memory " [frac autorelease]; // return it " return frac; Delay release until later. Handled by OS. Autorelease Al Demers sez: Places object in a pool This is a hack. OS releases Bad Apple, all in bad. pool At end of event handler Games are not event driven! Game loop runs continuously Pool is not released You can release it manually At end of loop iteration? 22

Reference Counting in ios 5 // create a new instance" Fraction *frac = [[Fraction alloc] init];! [frac retain]; // set values and print " [frac setnumerator: 1]; " [frac setdenominator: 3]; printf( "The fraction is: " ); " [frac print]; " printf( "\n" ); // free memory " [frac release];! No-op (does nothing) No-op (does nothing) Automated Reference Counting Handled by compiler Inserts retain/release for you Still reference counting, not GC Old methods are deprecated Backwards compatibility only No-ops if ARC is turned on 23

C++ Analogue: Smart Pointers C++ can override anything Assignment operator = Dereference operator -> Use special object as pointer A field to reference object Also a reference counter Assignment increments What about decrementing? When smart pointer deleted Delete object if count is 0 void foo(){ // Create smart pointer" smart_ptr<myobject> p(); // Allocate & assign it" p = new MyObject(); p->dosomething(); // NO LEAK 24

C++ Analogue: Smart Pointers C++ can override anything Assignment operator = Dereference operator -> Use special object as pointer Stack object; not in heap. A field to reference object Also a reference counter Assignment increments void foo(){ // Create smart pointer" smart_ptr<myobject> p(); // Allocate & assign it" p = new MyObject(); p->dosomething(); What about decrementing? 25 When smart pointer deleted Delete object if count is 0 // NO LEAK Stack released; Smart pointer is disposed.

Where Does Count Go? Non-Intruisive Pointers Count inside smart pointer Advantage: Works with any class Disadvantage: Combining with raw pointers (and hence any stdlib code) Intruisive Pointers Count inside referred object Advantage: Easy to mix with raw pointers Disadvantage: Requires custom base object [Images courtesy of Kosmas Karadimitriou] 26

References vs. Garbage Collectors Reference Counting Advantages Deallocation is immediate Works on non-memory objects Ideal for real-time systems Disadvantages Overhead on every assignment Cannot easily handle cycles (e.g. object points to itself) Requires training to use Mark-and-Sweep Advantages No assignment overhead Can handle reference cycles No specialized training to use Disadvantages Collection can be expensive Hurts performance when runs Usually triggered whenever memory is close to full 27

Incremental Mark-and-Sweep Objects have multiple colors Indicate where in GC process At GC, change some colors Free objects of certain color Natural for game loops Give GC a time budget Do at end of game loop Stop when done or time up See online reading for more Lua 3.0: Quad-Color M&S 28

Incremental Mark-and-Sweep Objects have multiple colors Indicate where in GC process At GC, change some colors Free objects of certain color Natural for game loops Give GC a time budget Al Demers sez: Unless memory is always close to full, incremental mark and sweep is better than all or options (even manual deallocation) Do at end of game loop Stop when done or time up See online reading for more Lua 3.0: Quad-Color M&S 29

Incremental Mark-and-Sweep Problem is availability Not available in Java Objective-C uses ARC No good C/C++ libraries You need to implement! Create a singleton allocator Has (weak) references to all objects that it allocates Popular interview question Insomniac uses this to test gameplay programmers Lua 3.0: Quad-Color M&S 30

Two Main Concerns with Memory Getting rid of memory you no longer want Doing it yourself: deallocation Runtime support: garbage collection Having enough memory to function Reserved memory: memory pools Spatial locality: dynamic loading 31

Custom Allocators Subdivide memory into functional units Physics memory, AI memory, etc If area is full, that function must cut back Works as a form of budgeting (hard or soft) Enforce budgets with a custom allocator Objects allocated for a function go in that region C++ and Objective-C support this functionality Example: [[Fraction alloc] init] 32 Allocation Initialization

Custom Allocators Subdivide memory into functional units Physics memory, AI memory, etc If area is full, that function must cut back Works as a form of budgeting (hard or soft) Enforce budgets with a custom allocator Objects allocated for a function go in that region C++ and Objective-C support this functionality Example: [[Fraction alloc] init] Advanced and Difficult to Write 33 Allocation Initialization

Dynamic Loading Most game data is spatial Only load if player nearby Loading Radius Unload as player moves away Minimizes memory used Arrange memory in cells Different from a memory pool Track player visibility radius Load/unload via outer radius Alternative: loading zones Visibility Radius Elevators in Mass Effect 34

Dynamic Loading in Assassin s Creed 35

Implementing Dynamic Loading Part of serialization model Level/save file has cells Cell addresses in memory Load/page on demand On Disk Sort of like virtual memory But paging strategy is spatial In RAM 36

Dynamic Loading Challenges Not same as virtual memory Objects unloaded do not exist Do not save state when unload Objects loaded are new created Can lead to unexpected states Forgetful NPCs Creative Assassin s Creed kills Workaround: Global State Track major game conditions Example: Guards Alerted Use to load objects in standard, but appropriate, configurations See Piazza for There is No Spoon 37

Summary Memory management can be a major challenge Manual deallocation is difficult Garbage collection is better on paper But not all techniques easily available Custom allocators common in AAA games Organize memory in pools and budget use Could oretically support GC as well Dynamic loading most relevant to you 38