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