1 .. 2 If Passes.html is up to date, the following "one-liner" should print 3 an empty diff. 4 5 egrep -e '^<tr><td><a href="#.*">-.*</a></td><td>.*</td></tr>$' \ 6 -e '^ <a name=".*">.*</a>$' < Passes.html >html; \ 7 perl >help <<'EOT' && diff -u help html; rm -f help html 8 open HTML, "<Passes.html" or die "open: Passes.html: $!\n"; 9 while (<HTML>) { 10 m:^<tr><td><a href="#(.*)">-.*</a></td><td>.*</td></tr>$: or next; 11 $order{$1} = sprintf("%03d", 1 + int %order); 12 } 13 open HELP, "../Release/bin/opt -help|" or die "open: opt -help: $!\n"; 14 while (<HELP>) { 15 m:^ -([^ ]+) +- (.*)$: or next; 16 my $o = $order{$1}; 17 $o = "000" unless defined $o; 18 push @x, "$o<tr><td><a href=\"#$1\">-$1</a></td><td>$2</td></tr>\n"; 19 push @y, "$o <a name=\"$1\">-$1: $2</a>\n"; 20 } 21 @x = map { s/^\d\d\d//; $_ } sort @x; 22 @y = map { s/^\d\d\d//; $_ } sort @y; 23 print @x, @y; 24 EOT 25 26 This (real) one-liner can also be helpful when converting comments to HTML: 27 28 perl -e '$/ = undef; for (split(/\n/, <>)) { s:^ *///? ?::; print " <p>\n" if !$on && $_ =~ /\S/; print " </p>\n" if $on && $_ =~ /^\s*$/; print " $_\n"; $on = ($_ =~ /\S/); } print " </p>\n" if $on' 29 30 ==================================== 31 LLVM's Analysis and Transform Passes 32 ==================================== 33 34 .. contents:: 35 :local: 36 37 Introduction 38 ============ 39 40 This document serves as a high level summary of the optimization features that 41 LLVM provides. Optimizations are implemented as Passes that traverse some 42 portion of a program to either collect information or transform the program. 43 The table below divides the passes that LLVM provides into three categories. 44 Analysis passes compute information that other passes can use or for debugging 45 or program visualization purposes. Transform passes can use (or invalidate) 46 the analysis passes. Transform passes all mutate the program in some way. 47 Utility passes provides some utility but don't otherwise fit categorization. 48 For example passes to extract functions to bitcode or write a module to bitcode 49 are neither analysis nor transform passes. The table of contents above 50 provides a quick summary of each pass and links to the more complete pass 51 description later in the document. 52 53 Analysis Passes 54 =============== 55 56 This section describes the LLVM Analysis Passes. 57 58 ``-aa-eval``: Exhaustive Alias Analysis Precision Evaluator 59 ----------------------------------------------------------- 60 61 This is a simple N^2 alias analysis accuracy evaluator. Basically, for each 62 function in the program, it simply queries to see how the alias analysis 63 implementation answers alias queries between each pair of pointers in the 64 function. 65 66 This is inspired and adapted from code by: Naveen Neelakantam, Francesco 67 Spadini, and Wojciech Stryjewski. 68 69 ``-basicaa``: Basic Alias Analysis (stateless AA impl) 70 ------------------------------------------------------ 71 72 A basic alias analysis pass that implements identities (two different globals 73 cannot alias, etc), but does no stateful analysis. 74 75 ``-basiccg``: Basic CallGraph Construction 76 ------------------------------------------ 77 78 Yet to be written. 79 80 ``-count-aa``: Count Alias Analysis Query Responses 81 --------------------------------------------------- 82 83 A pass which can be used to count how many alias queries are being made and how 84 the alias analysis implementation being used responds. 85 86 ``-da``: Dependence Analysis 87 ---------------------------- 88 89 Dependence analysis framework, which is used to detect dependences in memory 90 accesses. 91 92 ``-debug-aa``: AA use debugger 93 ------------------------------ 94 95 This simple pass checks alias analysis users to ensure that if they create a 96 new value, they do not query AA without informing it of the value. It acts as 97 a shim over any other AA pass you want. 98 99 Yes keeping track of every value in the program is expensive, but this is a 100 debugging pass. 101 102 ``-domfrontier``: Dominance Frontier Construction 103 ------------------------------------------------- 104 105 This pass is a simple dominator construction algorithm for finding forward 106 dominator frontiers. 107 108 ``-domtree``: Dominator Tree Construction 109 ----------------------------------------- 110 111 This pass is a simple dominator construction algorithm for finding forward 112 dominators. 113 114 115 ``-dot-callgraph``: Print Call Graph to "dot" file 116 -------------------------------------------------- 117 118 This pass, only available in ``opt``, prints the call graph into a ``.dot`` 119 graph. This graph can then be processed with the "dot" tool to convert it to 120 postscript or some other suitable format. 121 122 ``-dot-cfg``: Print CFG of function to "dot" file 123 ------------------------------------------------- 124 125 This pass, only available in ``opt``, prints the control flow graph into a 126 ``.dot`` graph. This graph can then be processed with the :program:`dot` tool 127 to convert it to postscript or some other suitable format. 128 129 ``-dot-cfg-only``: Print CFG of function to "dot" file (with no function bodies) 130 -------------------------------------------------------------------------------- 131 132 This pass, only available in ``opt``, prints the control flow graph into a 133 ``.dot`` graph, omitting the function bodies. This graph can then be processed 134 with the :program:`dot` tool to convert it to postscript or some other suitable 135 format. 136 137 ``-dot-dom``: Print dominance tree of function to "dot" file 138 ------------------------------------------------------------ 139 140 This pass, only available in ``opt``, prints the dominator tree into a ``.dot`` 141 graph. This graph can then be processed with the :program:`dot` tool to 142 convert it to postscript or some other suitable format. 143 144 ``-dot-dom-only``: Print dominance tree of function to "dot" file (with no function bodies) 145 ------------------------------------------------------------------------------------------- 146 147 This pass, only available in ``opt``, prints the dominator tree into a ``.dot`` 148 graph, omitting the function bodies. This graph can then be processed with the 149 :program:`dot` tool to convert it to postscript or some other suitable format. 150 151 ``-dot-postdom``: Print postdominance tree of function to "dot" file 152 -------------------------------------------------------------------- 153 154 This pass, only available in ``opt``, prints the post dominator tree into a 155 ``.dot`` graph. This graph can then be processed with the :program:`dot` tool 156 to convert it to postscript or some other suitable format. 157 158 ``-dot-postdom-only``: Print postdominance tree of function to "dot" file (with no function bodies) 159 --------------------------------------------------------------------------------------------------- 160 161 This pass, only available in ``opt``, prints the post dominator tree into a 162 ``.dot`` graph, omitting the function bodies. This graph can then be processed 163 with the :program:`dot` tool to convert it to postscript or some other suitable 164 format. 165 166 ``-globalsmodref-aa``: Simple mod/ref analysis for globals 167 ---------------------------------------------------------- 168 169 This simple pass provides alias and mod/ref information for global values that 170 do not have their address taken, and keeps track of whether functions read or 171 write memory (are "pure"). For this simple (but very common) case, we can 172 provide pretty accurate and useful information. 173 174 ``-instcount``: Counts the various types of ``Instruction``\ s 175 -------------------------------------------------------------- 176 177 This pass collects the count of all instructions and reports them. 178 179 ``-intervals``: Interval Partition Construction 180 ----------------------------------------------- 181 182 This analysis calculates and represents the interval partition of a function, 183 or a preexisting interval partition. 184 185 In this way, the interval partition may be used to reduce a flow graph down to 186 its degenerate single node interval partition (unless it is irreducible). 187 188 ``-iv-users``: Induction Variable Users 189 --------------------------------------- 190 191 Bookkeeping for "interesting" users of expressions computed from induction 192 variables. 193 194 ``-lazy-value-info``: Lazy Value Information Analysis 195 ----------------------------------------------------- 196 197 Interface for lazy computation of value constraint information. 198 199 ``-libcall-aa``: LibCall Alias Analysis 200 --------------------------------------- 201 202 LibCall Alias Analysis. 203 204 ``-lint``: Statically lint-checks LLVM IR 205 ----------------------------------------- 206 207 This pass statically checks for common and easily-identified constructs which 208 produce undefined or likely unintended behavior in LLVM IR. 209 210 It is not a guarantee of correctness, in two ways. First, it isn't 211 comprehensive. There are checks which could be done statically which are not 212 yet implemented. Some of these are indicated by TODO comments, but those 213 aren't comprehensive either. Second, many conditions cannot be checked 214 statically. This pass does no dynamic instrumentation, so it can't check for 215 all possible problems. 216 217 Another limitation is that it assumes all code will be executed. A store 218 through a null pointer in a basic block which is never reached is harmless, but 219 this pass will warn about it anyway. 220 221 Optimization passes may make conditions that this pass checks for more or less 222 obvious. If an optimization pass appears to be introducing a warning, it may 223 be that the optimization pass is merely exposing an existing condition in the 224 code. 225 226 This code may be run before :ref:`instcombine <passes-instcombine>`. In many 227 cases, instcombine checks for the same kinds of things and turns instructions 228 with undefined behavior into unreachable (or equivalent). Because of this, 229 this pass makes some effort to look through bitcasts and so on. 230 231 ``-loops``: Natural Loop Information 232 ------------------------------------ 233 234 This analysis is used to identify natural loops and determine the loop depth of 235 various nodes of the CFG. Note that the loops identified may actually be 236 several natural loops that share the same header node... not just a single 237 natural loop. 238 239 ``-memdep``: Memory Dependence Analysis 240 --------------------------------------- 241 242 An analysis that determines, for a given memory operation, what preceding 243 memory operations it depends on. It builds on alias analysis information, and 244 tries to provide a lazy, caching interface to a common kind of alias 245 information query. 246 247 ``-module-debuginfo``: Decodes module-level debug info 248 ------------------------------------------------------ 249 250 This pass decodes the debug info metadata in a module and prints in a 251 (sufficiently-prepared-) human-readable form. 252 253 For example, run this pass from ``opt`` along with the ``-analyze`` option, and 254 it'll print to standard output. 255 256 ``-postdomfrontier``: Post-Dominance Frontier Construction 257 ---------------------------------------------------------- 258 259 This pass is a simple post-dominator construction algorithm for finding 260 post-dominator frontiers. 261 262 ``-postdomtree``: Post-Dominator Tree Construction 263 -------------------------------------------------- 264 265 This pass is a simple post-dominator construction algorithm for finding 266 post-dominators. 267 268 ``-print-alias-sets``: Alias Set Printer 269 ---------------------------------------- 270 271 Yet to be written. 272 273 ``-print-callgraph``: Print a call graph 274 ---------------------------------------- 275 276 This pass, only available in ``opt``, prints the call graph to standard error 277 in a human-readable form. 278 279 ``-print-callgraph-sccs``: Print SCCs of the Call Graph 280 ------------------------------------------------------- 281 282 This pass, only available in ``opt``, prints the SCCs of the call graph to 283 standard error in a human-readable form. 284 285 ``-print-cfg-sccs``: Print SCCs of each function CFG 286 ---------------------------------------------------- 287 288 This pass, only available in ``opt``, printsthe SCCs of each function CFG to 289 standard error in a human-readable fom. 290 291 ``-print-dom-info``: Dominator Info Printer 292 ------------------------------------------- 293 294 Dominator Info Printer. 295 296 ``-print-externalfnconstants``: Print external fn callsites passed constants 297 ---------------------------------------------------------------------------- 298 299 This pass, only available in ``opt``, prints out call sites to external 300 functions that are called with constant arguments. This can be useful when 301 looking for standard library functions we should constant fold or handle in 302 alias analyses. 303 304 ``-print-function``: Print function to stderr 305 --------------------------------------------- 306 307 The ``PrintFunctionPass`` class is designed to be pipelined with other 308 ``FunctionPasses``, and prints out the functions of the module as they are 309 processed. 310 311 ``-print-module``: Print module to stderr 312 ----------------------------------------- 313 314 This pass simply prints out the entire module when it is executed. 315 316 .. _passes-print-used-types: 317 318 ``-print-used-types``: Find Used Types 319 -------------------------------------- 320 321 This pass is used to seek out all of the types in use by the program. Note 322 that this analysis explicitly does not include types only used by the symbol 323 table. 324 325 ``-regions``: Detect single entry single exit regions 326 ----------------------------------------------------- 327 328 The ``RegionInfo`` pass detects single entry single exit regions in a function, 329 where a region is defined as any subgraph that is connected to the remaining 330 graph at only two spots. Furthermore, an hierarchical region tree is built. 331 332 ``-scalar-evolution``: Scalar Evolution Analysis 333 ------------------------------------------------ 334 335 The ``ScalarEvolution`` analysis can be used to analyze and catagorize scalar 336 expressions in loops. It specializes in recognizing general induction 337 variables, representing them with the abstract and opaque ``SCEV`` class. 338 Given this analysis, trip counts of loops and other important properties can be 339 obtained. 340 341 This analysis is primarily useful for induction variable substitution and 342 strength reduction. 343 344 ``-scev-aa``: ScalarEvolution-based Alias Analysis 345 -------------------------------------------------- 346 347 Simple alias analysis implemented in terms of ``ScalarEvolution`` queries. 348 349 This differs from traditional loop dependence analysis in that it tests for 350 dependencies within a single iteration of a loop, rather than dependencies 351 between different iterations. 352 353 ``ScalarEvolution`` has a more complete understanding of pointer arithmetic 354 than ``BasicAliasAnalysis``' collection of ad-hoc analyses. 355 356 ``-targetdata``: Target Data Layout 357 ----------------------------------- 358 359 Provides other passes access to information on how the size and alignment 360 required by the target ABI for various data types. 361 362 Transform Passes 363 ================ 364 365 This section describes the LLVM Transform Passes. 366 367 ``-adce``: Aggressive Dead Code Elimination 368 ------------------------------------------- 369 370 ADCE aggressively tries to eliminate code. This pass is similar to :ref:`DCE 371 <passes-dce>` but it assumes that values are dead until proven otherwise. This 372 is similar to :ref:`SCCP <passes-sccp>`, except applied to the liveness of 373 values. 374 375 ``-always-inline``: Inliner for ``always_inline`` functions 376 ----------------------------------------------------------- 377 378 A custom inliner that handles only functions that are marked as "always 379 inline". 380 381 ``-argpromotion``: Promote 'by reference' arguments to scalars 382 -------------------------------------------------------------- 383 384 This pass promotes "by reference" arguments to be "by value" arguments. In 385 practice, this means looking for internal functions that have pointer 386 arguments. If it can prove, through the use of alias analysis, that an 387 argument is *only* loaded, then it can pass the value into the function instead 388 of the address of the value. This can cause recursive simplification of code 389 and lead to the elimination of allocas (especially in C++ template code like 390 the STL). 391 392 This pass also handles aggregate arguments that are passed into a function, 393 scalarizing them if the elements of the aggregate are only loaded. Note that 394 it refuses to scalarize aggregates which would require passing in more than 395 three operands to the function, because passing thousands of operands for a 396 large array or structure is unprofitable! 397 398 Note that this transformation could also be done for arguments that are only 399 stored to (returning the value instead), but does not currently. This case 400 would be best handled when and if LLVM starts supporting multiple return values 401 from functions. 402 403 ``-bb-vectorize``: Basic-Block Vectorization 404 -------------------------------------------- 405 406 This pass combines instructions inside basic blocks to form vector 407 instructions. It iterates over each basic block, attempting to pair compatible 408 instructions, repeating this process until no additional pairs are selected for 409 vectorization. When the outputs of some pair of compatible instructions are 410 used as inputs by some other pair of compatible instructions, those pairs are 411 part of a potential vectorization chain. Instruction pairs are only fused into 412 vector instructions when they are part of a chain longer than some threshold 413 length. Moreover, the pass attempts to find the best possible chain for each 414 pair of compatible instructions. These heuristics are intended to prevent 415 vectorization in cases where it would not yield a performance increase of the 416 resulting code. 417 418 ``-block-placement``: Profile Guided Basic Block Placement 419 ---------------------------------------------------------- 420 421 This pass is a very simple profile guided basic block placement algorithm. The 422 idea is to put frequently executed blocks together at the start of the function 423 and hopefully increase the number of fall-through conditional branches. If 424 there is no profile information for a particular function, this pass basically 425 orders blocks in depth-first order. 426 427 ``-break-crit-edges``: Break critical edges in CFG 428 -------------------------------------------------- 429 430 Break all of the critical edges in the CFG by inserting a dummy basic block. 431 It may be "required" by passes that cannot deal with critical edges. This 432 transformation obviously invalidates the CFG, but can update forward dominator 433 (set, immediate dominators, tree, and frontier) information. 434 435 ``-codegenprepare``: Optimize for code generation 436 ------------------------------------------------- 437 438 This pass munges the code in the input function to better prepare it for 439 SelectionDAG-based code generation. This works around limitations in its 440 basic-block-at-a-time approach. It should eventually be removed. 441 442 ``-constmerge``: Merge Duplicate Global Constants 443 ------------------------------------------------- 444 445 Merges duplicate global constants together into a single constant that is 446 shared. This is useful because some passes (i.e., TraceValues) insert a lot of 447 string constants into the program, regardless of whether or not an existing 448 string is available. 449 450 ``-constprop``: Simple constant propagation 451 ------------------------------------------- 452 453 This pass implements constant propagation and merging. It looks for 454 instructions involving only constant operands and replaces them with a constant 455 value instead of an instruction. For example: 456 457 .. code-block:: llvm 458 459 add i32 1, 2 460 461 becomes 462 463 .. code-block:: llvm 464 465 i32 3 466 467 NOTE: this pass has a habit of making definitions be dead. It is a good idea 468 to run a :ref:`Dead Instruction Elimination <passes-die>` pass sometime after 469 running this pass. 470 471 .. _passes-dce: 472 473 ``-dce``: Dead Code Elimination 474 ------------------------------- 475 476 Dead code elimination is similar to :ref:`dead instruction elimination 477 <passes-die>`, but it rechecks instructions that were used by removed 478 instructions to see if they are newly dead. 479 480 ``-deadargelim``: Dead Argument Elimination 481 ------------------------------------------- 482 483 This pass deletes dead arguments from internal functions. Dead argument 484 elimination removes arguments which are directly dead, as well as arguments 485 only passed into function calls as dead arguments of other functions. This 486 pass also deletes dead arguments in a similar way. 487 488 This pass is often useful as a cleanup pass to run after aggressive 489 interprocedural passes, which add possibly-dead arguments. 490 491 ``-deadtypeelim``: Dead Type Elimination 492 ---------------------------------------- 493 494 This pass is used to cleanup the output of GCC. It eliminate names for types 495 that are unused in the entire translation unit, using the :ref:`find used types 496 <passes-print-used-types>` pass. 497 498 .. _passes-die: 499 500 ``-die``: Dead Instruction Elimination 501 -------------------------------------- 502 503 Dead instruction elimination performs a single pass over the function, removing 504 instructions that are obviously dead. 505 506 ``-dse``: Dead Store Elimination 507 -------------------------------- 508 509 A trivial dead store elimination that only considers basic-block local 510 redundant stores. 511 512 .. _passes-functionattrs: 513 514 ``-functionattrs``: Deduce function attributes 515 ---------------------------------------------- 516 517 A simple interprocedural pass which walks the call-graph, looking for functions 518 which do not access or only read non-local memory, and marking them 519 ``readnone``/``readonly``. In addition, it marks function arguments (of 520 pointer type) "``nocapture``" if a call to the function does not create any 521 copies of the pointer value that outlive the call. This more or less means 522 that the pointer is only dereferenced, and not returned from the function or 523 stored in a global. This pass is implemented as a bottom-up traversal of the 524 call-graph. 525 526 ``-globaldce``: Dead Global Elimination 527 --------------------------------------- 528 529 This transform is designed to eliminate unreachable internal globals from the 530 program. It uses an aggressive algorithm, searching out globals that are known 531 to be alive. After it finds all of the globals which are needed, it deletes 532 whatever is left over. This allows it to delete recursive chunks of the 533 program which are unreachable. 534 535 ``-globalopt``: Global Variable Optimizer 536 ----------------------------------------- 537 538 This pass transforms simple global variables that never have their address 539 taken. If obviously true, it marks read/write globals as constant, deletes 540 variables only stored to, etc. 541 542 ``-gvn``: Global Value Numbering 543 -------------------------------- 544 545 This pass performs global value numbering to eliminate fully and partially 546 redundant instructions. It also performs redundant load elimination. 547 548 .. _passes-indvars: 549 550 ``-indvars``: Canonicalize Induction Variables 551 ---------------------------------------------- 552 553 This transformation analyzes and transforms the induction variables (and 554 computations derived from them) into simpler forms suitable for subsequent 555 analysis and transformation. 556 557 This transformation makes the following changes to each loop with an 558 identifiable induction variable: 559 560 * All loops are transformed to have a *single* canonical induction variable 561 which starts at zero and steps by one. 562 * The canonical induction variable is guaranteed to be the first PHI node in 563 the loop header block. 564 * Any pointer arithmetic recurrences are raised to use array subscripts. 565 566 If the trip count of a loop is computable, this pass also makes the following 567 changes: 568 569 * The exit condition for the loop is canonicalized to compare the induction 570 value against the exit value. This turns loops like: 571 572 .. code-block:: c++ 573 574 for (i = 7; i*i < 1000; ++i) 575 576 into 577 578 .. code-block:: c++ 579 580 for (i = 0; i != 25; ++i) 581 582 * Any use outside of the loop of an expression derived from the indvar is 583 changed to compute the derived value outside of the loop, eliminating the 584 dependence on the exit value of the induction variable. If the only purpose 585 of the loop is to compute the exit value of some derived expression, this 586 transformation will make the loop dead. 587 588 This transformation should be followed by strength reduction after all of the 589 desired loop transformations have been performed. Additionally, on targets 590 where it is profitable, the loop could be transformed to count down to zero 591 (the "do loop" optimization). 592 593 ``-inline``: Function Integration/Inlining 594 ------------------------------------------ 595 596 Bottom-up inlining of functions into callees. 597 598 .. _passes-instcombine: 599 600 ``-instcombine``: Combine redundant instructions 601 ------------------------------------------------ 602 603 Combine instructions to form fewer, simple instructions. This pass does not 604 modify the CFG. This pass is where algebraic simplification happens. 605 606 This pass combines things like: 607 608 .. code-block:: llvm 609 610 %Y = add i32 %X, 1 611 %Z = add i32 %Y, 1 612 613 into: 614 615 .. code-block:: llvm 616 617 %Z = add i32 %X, 2 618 619 This is a simple worklist driven algorithm. 620 621 This pass guarantees that the following canonicalizations are performed on the 622 program: 623 624 #. If a binary operator has a constant operand, it is moved to the right-hand 625 side. 626 #. Bitwise operators with constant operands are always grouped so that shifts 627 are performed first, then ``or``\ s, then ``and``\ s, then ``xor``\ s. 628 #. Compare instructions are converted from ``<``, ``>``, ````, or ```` to 629 ``=`` or ```` if possible. 630 #. All ``cmp`` instructions on boolean values are replaced with logical 631 operations. 632 #. ``add X, X`` is represented as ``mul X, 2`` ``shl X, 1`` 633 #. Multiplies with a constant power-of-two argument are transformed into 634 shifts. 635 #. etc. 636 637 This pass can also simplify calls to specific well-known function calls (e.g. 638 runtime library functions). For example, a call ``exit(3)`` that occurs within 639 the ``main()`` function can be transformed into simply ``return 3``. Whether or 640 not library calls are simplified is controlled by the 641 :ref:`-functionattrs <passes-functionattrs>` pass and LLVM's knowledge of 642 library calls on different targets. 643 644 ``-internalize``: Internalize Global Symbols 645 -------------------------------------------- 646 647 This pass loops over all of the functions in the input module, looking for a 648 main function. If a main function is found, all other functions and all global 649 variables with initializers are marked as internal. 650 651 ``-ipconstprop``: Interprocedural constant propagation 652 ------------------------------------------------------ 653 654 This pass implements an *extremely* simple interprocedural constant propagation 655 pass. It could certainly be improved in many different ways, like using a 656 worklist. This pass makes arguments dead, but does not remove them. The 657 existing dead argument elimination pass should be run after this to clean up 658 the mess. 659 660 ``-ipsccp``: Interprocedural Sparse Conditional Constant Propagation 661 -------------------------------------------------------------------- 662 663 An interprocedural variant of :ref:`Sparse Conditional Constant Propagation 664 <passes-sccp>`. 665 666 ``-jump-threading``: Jump Threading 667 ----------------------------------- 668 669 Jump threading tries to find distinct threads of control flow running through a 670 basic block. This pass looks at blocks that have multiple predecessors and 671 multiple successors. If one or more of the predecessors of the block can be 672 proven to always cause a jump to one of the successors, we forward the edge 673 from the predecessor to the successor by duplicating the contents of this 674 block. 675 676 An example of when this can occur is code like this: 677 678 .. code-block:: c++ 679 680 if () { ... 681 X = 4; 682 } 683 if (X < 3) { 684 685 In this case, the unconditional branch at the end of the first if can be 686 revectored to the false side of the second if. 687 688 ``-lcssa``: Loop-Closed SSA Form Pass 689 ------------------------------------- 690 691 This pass transforms loops by placing phi nodes at the end of the loops for all 692 values that are live across the loop boundary. For example, it turns the left 693 into the right code: 694 695 .. code-block:: c++ 696 697 for (...) for (...) 698 if (c) if (c) 699 X1 = ... X1 = ... 700 else else 701 X2 = ... X2 = ... 702 X3 = phi(X1, X2) X3 = phi(X1, X2) 703 ... = X3 + 4 X4 = phi(X3) 704 ... = X4 + 4 705 706 This is still valid LLVM; the extra phi nodes are purely redundant, and will be 707 trivially eliminated by ``InstCombine``. The major benefit of this 708 transformation is that it makes many other loop optimizations, such as 709 ``LoopUnswitch``\ ing, simpler. 710 711 .. _passes-licm: 712 713 ``-licm``: Loop Invariant Code Motion 714 ------------------------------------- 715 716 This pass performs loop invariant code motion, attempting to remove as much 717 code from the body of a loop as possible. It does this by either hoisting code 718 into the preheader block, or by sinking code to the exit blocks if it is safe. 719 This pass also promotes must-aliased memory locations in the loop to live in 720 registers, thus hoisting and sinking "invariant" loads and stores. 721 722 This pass uses alias analysis for two purposes: 723 724 #. Moving loop invariant loads and calls out of loops. If we can determine 725 that a load or call inside of a loop never aliases anything stored to, we 726 can hoist it or sink it like any other instruction. 727 728 #. Scalar Promotion of Memory. If there is a store instruction inside of the 729 loop, we try to move the store to happen AFTER the loop instead of inside of 730 the loop. This can only happen if a few conditions are true: 731 732 #. The pointer stored through is loop invariant. 733 #. There are no stores or loads in the loop which *may* alias the pointer. 734 There are no calls in the loop which mod/ref the pointer. 735 736 If these conditions are true, we can promote the loads and stores in the 737 loop of the pointer to use a temporary alloca'd variable. We then use the 738 :ref:`mem2reg <passes-mem2reg>` functionality to construct the appropriate 739 SSA form for the variable. 740 741 ``-loop-deletion``: Delete dead loops 742 ------------------------------------- 743 744 This file implements the Dead Loop Deletion Pass. This pass is responsible for 745 eliminating loops with non-infinite computable trip counts that have no side 746 effects or volatile instructions, and do not contribute to the computation of 747 the function's return value. 748 749 .. _passes-loop-extract: 750 751 ``-loop-extract``: Extract loops into new functions 752 --------------------------------------------------- 753 754 A pass wrapper around the ``ExtractLoop()`` scalar transformation to extract 755 each top-level loop into its own new function. If the loop is the *only* loop 756 in a given function, it is not touched. This is a pass most useful for 757 debugging via bugpoint. 758 759 ``-loop-extract-single``: Extract at most one loop into a new function 760 ---------------------------------------------------------------------- 761 762 Similar to :ref:`Extract loops into new functions <passes-loop-extract>`, this 763 pass extracts one natural loop from the program into a function if it can. 764 This is used by :program:`bugpoint`. 765 766 ``-loop-reduce``: Loop Strength Reduction 767 ----------------------------------------- 768 769 This pass performs a strength reduction on array references inside loops that 770 have as one or more of their components the loop induction variable. This is 771 accomplished by creating a new value to hold the initial value of the array 772 access for the first iteration, and then creating a new GEP instruction in the 773 loop to increment the value by the appropriate amount. 774 775 ``-loop-rotate``: Rotate Loops 776 ------------------------------ 777 778 A simple loop rotation transformation. 779 780 ``-loop-simplify``: Canonicalize natural loops 781 ---------------------------------------------- 782 783 This pass performs several transformations to transform natural loops into a 784 simpler form, which makes subsequent analyses and transformations simpler and 785 more effective. 786 787 Loop pre-header insertion guarantees that there is a single, non-critical entry 788 edge from outside of the loop to the loop header. This simplifies a number of 789 analyses and transformations, such as :ref:`LICM <passes-licm>`. 790 791 Loop exit-block insertion guarantees that all exit blocks from the loop (blocks 792 which are outside of the loop that have predecessors inside of the loop) only 793 have predecessors from inside of the loop (and are thus dominated by the loop 794 header). This simplifies transformations such as store-sinking that are built 795 into LICM. 796 797 This pass also guarantees that loops will have exactly one backedge. 798 799 Note that the :ref:`simplifycfg <passes-simplifycfg>` pass will clean up blocks 800 which are split out but end up being unnecessary, so usage of this pass should 801 not pessimize generated code. 802 803 This pass obviously modifies the CFG, but updates loop information and 804 dominator information. 805 806 ``-loop-unroll``: Unroll loops 807 ------------------------------ 808 809 This pass implements a simple loop unroller. It works best when loops have 810 been canonicalized by the :ref:`indvars <passes-indvars>` pass, allowing it to 811 determine the trip counts of loops easily. 812 813 ``-loop-unswitch``: Unswitch loops 814 ---------------------------------- 815 816 This pass transforms loops that contain branches on loop-invariant conditions 817 to have multiple loops. For example, it turns the left into the right code: 818 819 .. code-block:: c++ 820 821 for (...) if (lic) 822 A for (...) 823 if (lic) A; B; C 824 B else 825 C for (...) 826 A; C 827 828 This can increase the size of the code exponentially (doubling it every time a 829 loop is unswitched) so we only unswitch if the resultant code will be smaller 830 than a threshold. 831 832 This pass expects :ref:`LICM <passes-licm>` to be run before it to hoist 833 invariant conditions out of the loop, to make the unswitching opportunity 834 obvious. 835 836 ``-loweratomic``: Lower atomic intrinsics to non-atomic form 837 ------------------------------------------------------------ 838 839 This pass lowers atomic intrinsics to non-atomic form for use in a known 840 non-preemptible environment. 841 842 The pass does not verify that the environment is non-preemptible (in general 843 this would require knowledge of the entire call graph of the program including 844 any libraries which may not be available in bitcode form); it simply lowers 845 every atomic intrinsic. 846 847 ``-lowerinvoke``: Lower invokes to calls, for unwindless code generators 848 ------------------------------------------------------------------------ 849 850 This transformation is designed for use by code generators which do not yet 851 support stack unwinding. This pass converts ``invoke`` instructions to 852 ``call`` instructions, so that any exception-handling ``landingpad`` blocks 853 become dead code (which can be removed by running the ``-simplifycfg`` pass 854 afterwards). 855 856 ``-lowerswitch``: Lower ``SwitchInst``\ s to branches 857 ----------------------------------------------------- 858 859 Rewrites switch instructions with a sequence of branches, which allows targets 860 to get away with not implementing the switch instruction until it is 861 convenient. 862 863 .. _passes-mem2reg: 864 865 ``-mem2reg``: Promote Memory to Register 866 ---------------------------------------- 867 868 This file promotes memory references to be register references. It promotes 869 alloca instructions which only have loads and stores as uses. An ``alloca`` is 870 transformed by using dominator frontiers to place phi nodes, then traversing 871 the function in depth-first order to rewrite loads and stores as appropriate. 872 This is just the standard SSA construction algorithm to construct "pruned" SSA 873 form. 874 875 ``-memcpyopt``: MemCpy Optimization 876 ----------------------------------- 877 878 This pass performs various transformations related to eliminating ``memcpy`` 879 calls, or transforming sets of stores into ``memset``\ s. 880 881 ``-mergefunc``: Merge Functions 882 ------------------------------- 883 884 This pass looks for equivalent functions that are mergable and folds them. 885 886 Total-ordering is introduced among the functions set: we define comparison 887 that answers for every two functions which of them is greater. It allows to 888 arrange functions into the binary tree. 889 890 For every new function we check for equivalent in tree. 891 892 If equivalent exists we fold such functions. If both functions are overridable, 893 we move the functionality into a new internal function and leave two 894 overridable thunks to it. 895 896 If there is no equivalent, then we add this function to tree. 897 898 Lookup routine has O(log(n)) complexity, while whole merging process has 899 complexity of O(n*log(n)). 900 901 Read 902 :doc:`this <MergeFunctions>` 903 article for more details. 904 905 ``-mergereturn``: Unify function exit nodes 906 ------------------------------------------- 907 908 Ensure that functions have at most one ``ret`` instruction in them. 909 Additionally, it keeps track of which node is the new exit node of the CFG. 910 911 ``-partial-inliner``: Partial Inliner 912 ------------------------------------- 913 914 This pass performs partial inlining, typically by inlining an ``if`` statement 915 that surrounds the body of the function. 916 917 ``-prune-eh``: Remove unused exception handling info 918 ---------------------------------------------------- 919 920 This file implements a simple interprocedural pass which walks the call-graph, 921 turning invoke instructions into call instructions if and only if the callee 922 cannot throw an exception. It implements this as a bottom-up traversal of the 923 call-graph. 924 925 ``-reassociate``: Reassociate expressions 926 ----------------------------------------- 927 928 This pass reassociates commutative expressions in an order that is designed to 929 promote better constant propagation, GCSE, :ref:`LICM <passes-licm>`, PRE, etc. 930 931 For example: 4 + (x + 5) x + (4 + 5) 932 933 In the implementation of this algorithm, constants are assigned rank = 0, 934 function arguments are rank = 1, and other values are assigned ranks 935 corresponding to the reverse post order traversal of current function (starting 936 at 2), which effectively gives values in deep loops higher rank than values not 937 in loops. 938 939 ``-reg2mem``: Demote all values to stack slots 940 ---------------------------------------------- 941 942 This file demotes all registers to memory references. It is intended to be the 943 inverse of :ref:`mem2reg <passes-mem2reg>`. By converting to ``load`` 944 instructions, the only values live across basic blocks are ``alloca`` 945 instructions and ``load`` instructions before ``phi`` nodes. It is intended 946 that this should make CFG hacking much easier. To make later hacking easier, 947 the entry block is split into two, such that all introduced ``alloca`` 948 instructions (and nothing else) are in the entry block. 949 950 ``-sroa``: Scalar Replacement of Aggregates 951 ------------------------------------------------------ 952 953 The well-known scalar replacement of aggregates transformation. This transform 954 breaks up ``alloca`` instructions of aggregate type (structure or array) into 955 individual ``alloca`` instructions for each member if possible. Then, if 956 possible, it transforms the individual ``alloca`` instructions into nice clean 957 scalar SSA form. 958 959 .. _passes-sccp: 960 961 ``-sccp``: Sparse Conditional Constant Propagation 962 -------------------------------------------------- 963 964 Sparse conditional constant propagation and merging, which can be summarized 965 as: 966 967 * Assumes values are constant unless proven otherwise 968 * Assumes BasicBlocks are dead unless proven otherwise 969 * Proves values to be constant, and replaces them with constants 970 * Proves conditional branches to be unconditional 971 972 Note that this pass has a habit of making definitions be dead. It is a good 973 idea to run a :ref:`DCE <passes-dce>` pass sometime after running this pass. 974 975 .. _passes-simplifycfg: 976 977 ``-simplifycfg``: Simplify the CFG 978 ---------------------------------- 979 980 Performs dead code elimination and basic block merging. Specifically: 981 982 * Removes basic blocks with no predecessors. 983 * Merges a basic block into its predecessor if there is only one and the 984 predecessor only has one successor. 985 * Eliminates PHI nodes for basic blocks with a single predecessor. 986 * Eliminates a basic block that only contains an unconditional branch. 987 988 ``-sink``: Code sinking 989 ----------------------- 990 991 This pass moves instructions into successor blocks, when possible, so that they 992 aren't executed on paths where their results aren't needed. 993 994 ``-strip``: Strip all symbols from a module 995 ------------------------------------------- 996 997 Performs code stripping. This transformation can delete: 998 999 * names for virtual registers 1000 * symbols for internal globals and functions 1001 * debug information 1002 1003 Note that this transformation makes code much less readable, so it should only 1004 be used in situations where the strip utility would be used, such as reducing 1005 code size or making it harder to reverse engineer code. 1006 1007 ``-strip-dead-debug-info``: Strip debug info for unused symbols 1008 --------------------------------------------------------------- 1009 1010 .. FIXME: this description is the same as for -strip 1011 1012 performs code stripping. this transformation can delete: 1013 1014 * names for virtual registers 1015 * symbols for internal globals and functions 1016 * debug information 1017 1018 note that this transformation makes code much less readable, so it should only 1019 be used in situations where the strip utility would be used, such as reducing 1020 code size or making it harder to reverse engineer code. 1021 1022 ``-strip-dead-prototypes``: Strip Unused Function Prototypes 1023 ------------------------------------------------------------ 1024 1025 This pass loops over all of the functions in the input module, looking for dead 1026 declarations and removes them. Dead declarations are declarations of functions 1027 for which no implementation is available (i.e., declarations for unused library 1028 functions). 1029 1030 ``-strip-debug-declare``: Strip all ``llvm.dbg.declare`` intrinsics 1031 ------------------------------------------------------------------- 1032 1033 .. FIXME: this description is the same as for -strip 1034 1035 This pass implements code stripping. Specifically, it can delete: 1036 1037 #. names for virtual registers 1038 #. symbols for internal globals and functions 1039 #. debug information 1040 1041 Note that this transformation makes code much less readable, so it should only 1042 be used in situations where the 'strip' utility would be used, such as reducing 1043 code size or making it harder to reverse engineer code. 1044 1045 ``-strip-nondebug``: Strip all symbols, except dbg symbols, from a module 1046 ------------------------------------------------------------------------- 1047 1048 .. FIXME: this description is the same as for -strip 1049 1050 This pass implements code stripping. Specifically, it can delete: 1051 1052 #. names for virtual registers 1053 #. symbols for internal globals and functions 1054 #. debug information 1055 1056 Note that this transformation makes code much less readable, so it should only 1057 be used in situations where the 'strip' utility would be used, such as reducing 1058 code size or making it harder to reverse engineer code. 1059 1060 ``-tailcallelim``: Tail Call Elimination 1061 ---------------------------------------- 1062 1063 This file transforms calls of the current function (self recursion) followed by 1064 a return instruction with a branch to the entry of the function, creating a 1065 loop. This pass also implements the following extensions to the basic 1066 algorithm: 1067 1068 #. Trivial instructions between the call and return do not prevent the 1069 transformation from taking place, though currently the analysis cannot 1070 support moving any really useful instructions (only dead ones). 1071 #. This pass transforms functions that are prevented from being tail recursive 1072 by an associative expression to use an accumulator variable, thus compiling 1073 the typical naive factorial or fib implementation into efficient code. 1074 #. TRE is performed if the function returns void, if the return returns the 1075 result returned by the call, or if the function returns a run-time constant 1076 on all exits from the function. It is possible, though unlikely, that the 1077 return returns something else (like constant 0), and can still be TRE'd. It 1078 can be TRE'd if *all other* return instructions in the function return the 1079 exact same value. 1080 #. If it can prove that callees do not access theier caller stack frame, they 1081 are marked as eligible for tail call elimination (by the code generator). 1082 1083 Utility Passes 1084 ============== 1085 1086 This section describes the LLVM Utility Passes. 1087 1088 ``-deadarghaX0r``: Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE) 1089 ------------------------------------------------------------------------ 1090 1091 Same as dead argument elimination, but deletes arguments to functions which are 1092 external. This is only for use by :doc:`bugpoint <Bugpoint>`. 1093 1094 ``-extract-blocks``: Extract Basic Blocks From Module (for bugpoint use) 1095 ------------------------------------------------------------------------ 1096 1097 This pass is used by bugpoint to extract all blocks from the module into their 1098 own functions. 1099 1100 ``-instnamer``: Assign names to anonymous instructions 1101 ------------------------------------------------------ 1102 1103 This is a little utility pass that gives instructions names, this is mostly 1104 useful when diffing the effect of an optimization because deleting an unnamed 1105 instruction can change all other instruction numbering, making the diff very 1106 noisy. 1107 1108 .. _passes-verify: 1109 1110 ``-verify``: Module Verifier 1111 ---------------------------- 1112 1113 Verifies an LLVM IR code. This is useful to run after an optimization which is 1114 undergoing testing. Note that llvm-as verifies its input before emitting 1115 bitcode, and also that malformed bitcode is likely to make LLVM crash. All 1116 language front-ends are therefore encouraged to verify their output before 1117 performing optimizing transformations. 1118 1119 #. Both of a binary operator's parameters are of the same type. 1120 #. Verify that the indices of mem access instructions match other operands. 1121 #. Verify that arithmetic and other things are only performed on first-class 1122 types. Verify that shifts and logicals only happen on integrals f.e. 1123 #. All of the constants in a switch statement are of the correct type. 1124 #. The code is in valid SSA form. 1125 #. It is illegal to put a label into any other type (like a structure) or to 1126 return one. 1127 #. Only phi nodes can be self referential: ``%x = add i32 %x``, ``%x`` is 1128 invalid. 1129 #. PHI nodes must have an entry for each predecessor, with no extras. 1130 #. PHI nodes must be the first thing in a basic block, all grouped together. 1131 #. PHI nodes must have at least one entry. 1132 #. All basic blocks should only end with terminator insts, not contain them. 1133 #. The entry node to a function must not have predecessors. 1134 #. All Instructions must be embedded into a basic block. 1135 #. Functions cannot take a void-typed parameter. 1136 #. Verify that a function's argument list agrees with its declared type. 1137 #. It is illegal to specify a name for a void value. 1138 #. It is illegal to have an internal global value with no initializer. 1139 #. It is illegal to have a ``ret`` instruction that returns a value that does 1140 not agree with the function return value type. 1141 #. Function call argument types match the function prototype. 1142 #. All other things that are tested by asserts spread about the code. 1143 1144 Note that this does not provide full security verification (like Java), but 1145 instead just tries to ensure that code is well-formed. 1146 1147 ``-view-cfg``: View CFG of function 1148 ----------------------------------- 1149 1150 Displays the control flow graph using the GraphViz tool. 1151 1152 ``-view-cfg-only``: View CFG of function (with no function bodies) 1153 ------------------------------------------------------------------ 1154 1155 Displays the control flow graph using the GraphViz tool, but omitting function 1156 bodies. 1157 1158 ``-view-dom``: View dominance tree of function 1159 ---------------------------------------------- 1160 1161 Displays the dominator tree using the GraphViz tool. 1162 1163 ``-view-dom-only``: View dominance tree of function (with no function bodies) 1164 ----------------------------------------------------------------------------- 1165 1166 Displays the dominator tree using the GraphViz tool, but omitting function 1167 bodies. 1168 1169 ``-view-postdom``: View postdominance tree of function 1170 ------------------------------------------------------ 1171 1172 Displays the post dominator tree using the GraphViz tool. 1173 1174 ``-view-postdom-only``: View postdominance tree of function (with no function bodies) 1175 ------------------------------------------------------------------------------------- 1176 1177 Displays the post dominator tree using the GraphViz tool, but omitting function 1178 bodies. 1179 1180