1 / 58

Advanced Compiler Techniques

Advanced Compiler Techniques. Course Introduction. LIU Xianhua School of EECS, Peking University. Outline. Course Overview Course Topics Course Requirements Grading Preparation Materials Compiler Review. Course Overview. Graduate level compiler course

lieu
Télécharger la présentation

Advanced Compiler Techniques

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Advanced Compiler Techniques Course Introduction LIU Xianhua School of EECS, Peking University

  2. Outline • Course Overview • Course Topics • Course Requirements • Grading • Preparation Materials • Compiler Review “Advanced Compiler Techniques”

  3. Course Overview • Graduate level compiler course • Focusing on advanced materials on program analysis and optimization. • Assuming that you have basic knowledge & techniques on compiler construction. • Gain hands-on experience through a programming project to implement a specific program analysis or optimization technique. • Course website: • http://mprc.pku.edu.cn/~liuxianhua/ACT13 “Advanced Compiler Techniques”

  4. Administrivia • Time: 10-12 (6:40pm-) every Thursday • Location: 2-420 • TA: WANG Wei, DONG Yin • Email: act13 [at] mprc.pku.edu.cn • Office Hour: 4-5:30pm Tuesdays • or by appointment via email • Contact: • Phone: 62765828-809, 62759129 • Room 1818, 1st Science Building • Email: lxh [at] mprc.pku.edu.cn • Include [ACT13] in the subject “Advanced Compiler Techniques”

  5. Course Materials • Dragon Book • Aho, Lam, Sethi, Ullman, “Compilers: Principles, Techniques, and Tools”, 2nd Edition, Addison 2007 • Related Papers • Class website “Advanced Compiler Techniques”

  6. Requirements • Basic Requirements • Read materials before/after class. • Work on your homework individually. • Discussions are encouraged but don’t copy others’ work. • Get you hands dirty! • Experiment with ideas presented in class and gain first-hand knowledge! • Come to class and DON’T hesitate to speak if you have any questions/comments/suggestions! • Student participation is important! “Advanced Compiler Techniques”

  7. Grading • Grading based on • Homework: 20% • ~5 homework assignments • Midterm: 30% • Week 11 or 12 (Nov 21st or 28th) • Final Project: 40% • Class participation: 10% “Advanced Compiler Techniques”

  8. Final Project • Groups of 2-3 students • Pair Programming recommended! • Topic • Problem of your choice (recommend project list will be provided) • Should be an interesting enough (non-trivial) problem • Suggested environment • LLVM(UIUC), • SUIF(Stanford), gcc(GNU), Soot (McGill Univ.), JoeQ, Jikes(IBM), OpenJDK, Dalvik, V8… “Advanced Compiler Techniques”

  9. Project Req. • Week 5: Introduction • Week 7: Proposal due • Week 8: Proposal Presentation • Week 12: Progress Report due • Week 16: Final Presentation • Week 17: Final Report due “Advanced Compiler Techniques”

  10. Course Topics • Basic analysis & optimizations • Data flow analysis & implementation • Control flow analysis • SSA form & its application • Loops/Instruction scheduling • Pointer analysis • Localization & Parallelization optimization • Selected topics (TBD) • Architecture-based optimization • Program slicing, program testing • Power-aware compilation “Advanced Compiler Techniques”

  11. Advanced Compiler Techniques Compiler Review LIU Xianhua School of EECS, Peking University

  12. What Is a Compiler? • A program that translates a program in one language to another language • The essential interface between applications & architectures • Typically lowers the level of abstraction • analyzes and reasons about the program & architecture • We expect the program to be optimized, i.e., better than the original • ideally exploiting architectural strengths and hiding weaknesses “Advanced Compiler Techniques”

  13. Why Study Compilers? (1) • Become a better programmer(!) • Insight into interaction between languages, compilers, and hardware • Understanding of implementation techniques • What is all that stuff in the debugger anyway? • Better intuition about what your code does

  14. Why Study Compilers? (2) • Compiler techniques are everywhere • Parsing (little languages, interpreters, XML) • Software tools (verifiers, checkers, …) • Database engines, query languages • AI, etc. : domain-specific languages • Text processing • Tex/LaTex -> dvi -> Postscript -> PDF • Hardware: VHDL; model-checking tools • Mathematics (Mathematica, Matlab)

  15. Why Study Compilers? (3) • Fascinating blend of theory and engineering • Direct applications of theory to practice • Parsing, scanning, static analysis • Some very difficult problems (NPH or worse) • Resource allocation, “optimization”, etc. • Need to come up with good-enough approximations/heuristics “Advanced Compiler Techniques”

  16. Why Study Compilers? (4) • Ideas from many parts of CSE • AI: Greedy algorithms, heuristic search • Algorithms: graph algorithms, union-find, dynamic programming, approximation algorithms • Theory: Grammars, DFAs and PDAs, pattern matching, fixed-point algorithms, lattice theory for analysis • Systems: Allocation & naming, synchronization, locality • Architecture: pipelines, instruction set use, memory hierarchy management “Advanced Compiler Techniques”

  17. Why Study Advanced Compilers? • An opportunity to explore compiler techniques in both breadth and depth • Parallelization? Functional? • Optimizations with more details • Compiler optimizations rely on both program analysis and transformation, which are useful in many related areas • Software engineering: program understanding / reverse engineering / debugging • Run-time support and improvement • Open problems • Engineering effort: limits and issues • Motivate research topics “Advanced Compiler Techniques”

  18. Compiler vs. Interpreter • Compilers: Translate a source (human-writable) program to an executable (machine-readable) program • Interpreters: Convert a source program and execute it at the same time. “Advanced Compiler Techniques”

  19. Compiler vs. Interpreter Ideal concept: Source code Executable Compiler Input data Executable Output data Source code Interpreter Output data Input data “Advanced Compiler Techniques”

  20. Compiler vs. Interpreter • Most languages are usually thought of as using either one or the other: • Compilers: FORTRAN, C, C++, Pascal, COBOL, PL/1 • Interpreters: Lisp, Scheme, BASIC, APL, Perl, Python, Smalltalk, Javascript, RUBY, Shellscripts/awk/sed… • BUT: not always implemented this way • Virtual Machines (think Java) • Linking of executables at runtime • JIT (Just-in-time) compiling “Advanced Compiler Techniques”

  21. Compiler vs. Interpreter • Actually, no sharp boundary between them • General situation is a combo: Translator Intermed. code Source code Intermed. code Virtual machine Output Input Data “Advanced Compiler Techniques”

  22. Hybrid Approaches • Classic example: Java • Compile Java source to byte codes – Java Virtual Machine language (.class files) • Execution • Interpret byte codes directly, or • Compile some or all byte codes to native code • Just-In-Time compiler (JIT) – detect hot spots & compile on the fly to native code – standard these days • Variations used for .NET (compile always) & in high-performance compilers for dynamic languages, e.g., JavaScript “Advanced Compiler Techniques”

  23. Compiler vs. Interpreter Compiler • Pros • Less space • Fast execution • Cons • Slow processing • Partly Solved(Separate compilation) • Debugging • Improved thru IDEs Interpreter • Pros • Easy debugging • Fast Development • Interaction • Cons • Not for large projects • Exceptions: Perl, Python • Requires more space • Slower execution • Interpreter in memory all the time TRADE OFF “Advanced Compiler Techniques”

  24. Traditional Compiler IR Syntactic structure Scanner (lexical analysis) tokens Parser (syntax analysis) Semantic Analysis (IR generator) IR Code Optimizer IR Code Generator Source program Target program Symbol Table • intermediate representation (IR) • front end maps legal code into IR • back end maps IR onto target machine • simplify retargeting • allows multiple front ends • multiple passes  better code

  25. Fallacy • Front-end, IR and back-end must encode knowledge needed for all nm combinations! “Advanced Compiler Techniques”

  26. Optimizer (Middle End) • Modern optimizers are usually built as a set of passes • constant propagation and folding • code motion • reduction of operator strength • common sub-expression elimination • redundant store elimination • dead code elimination

  27. Phase of Compilations “Advanced Compiler Techniques”

  28. Scanning/Lexical Analysis identifier operator number index := start + step * 20 Input: index:=start+step*20 After scanning: • Break program down into its smallest meaningful symbols (tokens, atoms) • Tools for this include lex, flex • Tokens include e.g.: • Reserved words: do if float while • Special characters: ( { , + - = ! / • Names & numbers:myValue 3.07e02 • Start symbol table with new symbols found “Advanced Compiler Techniques”

  29. Parsing • Construct a parse tree from symbols • A pattern-matching problem • Language grammar defined by set of rules that identify legal (meaningful) combinations of symbols • Each application of a rule results in a node in the parse tree • Parser applies these rules repeatedly to the program until leaves of parse tree are “atoms” • If no pattern matches, it’s a syntax error • yacc, bison are tools for this (generate c code that parses specified language) “Advanced Compiler Techniques”

  30. Parse Tree • Output of parsing • Top-down description of program syntax • Root node is entire program • Constructed by repeated application of rules in Context Free Grammar (CFG) • Leaves are tokens that were identified during lexical analysis “Advanced Compiler Techniques”

  31. Example: Parsing Rules for Pascal These are like the following: • program ----> PROGRAM identifier (identifier more_identifiers) ; block • more_identifiers ----> , identifier more_identifiers | ε • block ----> variables BEGIN statement more_statements END • statement ----> do_statement | if_statement | assignment | … • if_statement ----> IF logical_expressionTHEN statement ELSE … “Advanced Compiler Techniques”

  32. Pascal Code Example program gcd (input, output) vari, j : integer begin read (i , j) while i <> j do if i>j then i := i – j; else j := j – i ; writeln (i); end . “Advanced Compiler Techniques”

  33. Example: Parse Tree “Advanced Compiler Techniques”

  34. Semantic Analysis • Discovery of meaning in a program using the symbol table • Do static semantics check • Simplify the structure of the parse tree ( from parse tree to abstract syntax tree (AST) ) • Static semantics check • Making sure identifiers are declared before use • Type checking for assignments and operators • Checking types and number of parameters to subroutines • Making sure functions contain return statements • … “Advanced Compiler Techniques”

  35. Example: AST “Advanced Compiler Techniques”

  36. (Intermediate) Code Generation • Go through the parse tree from bottom up, turning rules into code. • e.g. • A sum expression results in the code that computes the sum and saves the result • Result: inefficient code in a machine-independent language “Advanced Compiler Techniques”

  37. Target Code Generation • Convert intermediate code to machine instructions on intended target machine • Determine storage addresses for entries in symbol table “Advanced Compiler Techniques”

  38. Types of Code Optimizations • Machine-independent optimizations • Eliminate redundant computation • Eliminate dead code • Perform computation at compile time if possible • Execute code less frequently • Machine-dependent optimizations • Hide latency • Parallelize computation • Replace expensive computations with cheaper ones • Improve memory performance “Advanced Compiler Techniques”

  39. Scopes of Code Optimizations • Peephole optimizations • Consider a small window of instructions • Local optimizations • Consider instruction sequences within a basic block • Intra-procedural(global) optimizations • Consider multiple basic blocks within a procedure • Need support from control flow analysis • Branches, loops, merging of flows • Inter-procedural optimizations • Consider the whole program w/ multiple procedures • Need to analyze calls/returns “Advanced Compiler Techniques”

  40. Sample Optimizations • Redundant loads and stores elimination MOV R0, a MOV R0, a MOV a, R0 • Unreachable code elimination GOTO L2 x := x + 1  unreachable • Algebraic identities x := x + 0  can eliminate x := x * 1 • Reduction in strength x := x * 2 x := x + x • Constant folding p = 2 * 3.14  p = 6.2.8 • Constant propagation p = 6.28 p=6.28 x = x * p  x = x * 6.28 “Advanced Compiler Techniques”

  41. Sample Optimizations t:=d+e a:=t t:=d+e b:=t a:=d+e b:=d+e c:=d+e c:=t t:=d+e a:=t t:=d+e a:=d+e c:=d+e c:=t • Common sub-expression elimination • Local m = 2 * y * z t = 2 * y o = 2 * y - z  m = t * z o = t - z • Global • Global partial “Advanced Compiler Techniques”

  42. Sample Optimizations • Loop optimizations • Code motion while (i <= limit - 2) { … }  t = limit - 2 while (i <= t) { … } • Loop unrolling do i=1 to n by 4 a(i) = a(i)+b(i) a(i+1) = a(i+1)+b(i+1) a(i+2) = a(i+2)+b(i+2) a(i+3) = a(i+3)+b(i+3) end … //process tail part do i=1 to n by 1 a(i) = a(i)+b(i)  end “Advanced Compiler Techniques”

  43. When Should We Compile? • Ahead-of-time: before you run the program • Offline profiling: compile several times compile/run/profile.... then run again • Just-in-time: while you run the program required for dynamic class loading, i.e., Java, Python, etc. “Advanced Compiler Techniques”

  44. Aren’t Compilers a Solved Problem? “Optimization for scalar machines is a problem that was solved ten years ago.” -- David Kuck, Fall 1990 • Architectures keep changing • New features pose new problems • Changing costs lead to different concerns • Old solutions need re-engineering • Languages keep changing • Applications keep changing - SPEC CPU? • When to compile keeps changing • And compiling options/parameters? • Desired target properties keep changing • Code size, running time, power consumption, security • Design flow also may change “Advanced Compiler Techniques”

  45. Role of compilers • Bridge complexity and evolution in architecture, languages, & applications • Help programs with correctness, reliability, program understanding • Compiler optimizations can significantly improve performance • 1 to 10x on conventional processors • Performance stability:one line change can dramatically alter performance • unfortunate, but true “Advanced Compiler Techniques”

  46. Performance Anxiety • But does performance reallymatter? • Computers are really fast • Moore’s law (roughly):hardware performance doubles every 18 months • Real bottlenecks lie elsewhere: • Memory & storage access • Communications in bus and network • Human! (think interactive apps) • Human typing avg. 8 cps (max 25 cps) • Waste time “thinking” “Advanced Compiler Techniques”

  47. Compilers Don’t Help Much • Do compilers improve performance anyway? • Proebsting’s law(Todd Proebsting, Microsoft Research): • Difference between optimizing and non-optimizing compiler ~ 4x • Assume compiler technology represents 36 years of progress (actually more) • Compilers double program performance every 18 years! • Not quite Moore’s Law… “Advanced Compiler Techniques”

  48. A Big BUT • Why use high-level languages anyway? • Easier to write & maintain • Safer (think Java) • More convenient (think libraries, GC…) • But: people will not accept massive performance hit for these gains • Compile with optimization! • Still use C and C++!! • Hand-optimize their code!!! • Even write assembler code (gasp)!!!! • Apparently performance does matter… “Advanced Compiler Techniques”

  49. Why Compilers Matter • Key part of compiler’s job:make the costs of abstraction reasonable • Remove performance penalty for: • Using objects • Safety checks (e.g., array-bounds) • Writing clean code (e.g., recursion) • Use program analysis to transform code primary topic of this course “Advanced Compiler Techniques”

  50. Program Analysis • Source code analysisis the process of extracting information about a program from its source code or artifacts (e.g., from Java byte code or execution traces) generated from the source code using automatic tools. • Source code is any static, textual, human readable, fully executable description of a computer program that can be compiled automatically into an executable form. • To support dynamic analysis the description can include documents needed to execute or compile the program, such as program inputs. Source: Dave Binkely-”Source Code Analysis – A Roadmap”, FOSE’07 “Advanced Compiler Techniques”

More Related