Remove documentation for a deleted pass.
[oota-llvm.git] / docs / Passes.rst
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 ``-no-aa``: No Alias Analysis (always returns 'may' alias)
257 ----------------------------------------------------------
258
259 This is the default implementation of the Alias Analysis interface.  It always
260 returns "I don't know" for alias queries.  NoAA is unlike other alias analysis
261 implementations, in that it does not chain to a previous analysis.  As such it
262 doesn't follow many of the rules that other alias analyses must.
263
264 ``-no-profile``: No Profile Information
265 ---------------------------------------
266
267 The default "no profile" implementation of the abstract ``ProfileInfo``
268 interface.
269
270 ``-postdomfrontier``: Post-Dominance Frontier Construction
271 ----------------------------------------------------------
272
273 This pass is a simple post-dominator construction algorithm for finding
274 post-dominator frontiers.
275
276 ``-postdomtree``: Post-Dominator Tree Construction
277 --------------------------------------------------
278
279 This pass is a simple post-dominator construction algorithm for finding
280 post-dominators.
281
282 ``-print-alias-sets``: Alias Set Printer
283 ----------------------------------------
284
285 Yet to be written.
286
287 ``-print-callgraph``: Print a call graph
288 ----------------------------------------
289
290 This pass, only available in ``opt``, prints the call graph to standard error
291 in a human-readable form.
292
293 ``-print-callgraph-sccs``: Print SCCs of the Call Graph
294 -------------------------------------------------------
295
296 This pass, only available in ``opt``, prints the SCCs of the call graph to
297 standard error in a human-readable form.
298
299 ``-print-cfg-sccs``: Print SCCs of each function CFG
300 ----------------------------------------------------
301
302 This pass, only available in ``opt``, printsthe SCCs of each function CFG to
303 standard error in a human-readable fom.
304
305 ``-print-dom-info``: Dominator Info Printer
306 -------------------------------------------
307
308 Dominator Info Printer.
309
310 ``-print-externalfnconstants``: Print external fn callsites passed constants
311 ----------------------------------------------------------------------------
312
313 This pass, only available in ``opt``, prints out call sites to external
314 functions that are called with constant arguments.  This can be useful when
315 looking for standard library functions we should constant fold or handle in
316 alias analyses.
317
318 ``-print-function``: Print function to stderr
319 ---------------------------------------------
320
321 The ``PrintFunctionPass`` class is designed to be pipelined with other
322 ``FunctionPasses``, and prints out the functions of the module as they are
323 processed.
324
325 ``-print-module``: Print module to stderr
326 -----------------------------------------
327
328 This pass simply prints out the entire module when it is executed.
329
330 .. _passes-print-used-types:
331
332 ``-print-used-types``: Find Used Types
333 --------------------------------------
334
335 This pass is used to seek out all of the types in use by the program.  Note
336 that this analysis explicitly does not include types only used by the symbol
337 table.
338
339 ``-profile-estimator``: Estimate profiling information
340 ------------------------------------------------------
341
342 Profiling information that estimates the profiling information in a very crude
343 and unimaginative way.
344
345 ``-profile-loader``: Load profile information from ``llvmprof.out``
346 -------------------------------------------------------------------
347
348 A concrete implementation of profiling information that loads the information
349 from a profile dump file.
350
351 ``-profile-verifier``: Verify profiling information
352 ---------------------------------------------------
353
354 Pass that checks profiling information for plausibility.
355
356 ``-regions``: Detect single entry single exit regions
357 -----------------------------------------------------
358
359 The ``RegionInfo`` pass detects single entry single exit regions in a function,
360 where a region is defined as any subgraph that is connected to the remaining
361 graph at only two spots.  Furthermore, an hierarchical region tree is built.
362
363 ``-scalar-evolution``: Scalar Evolution Analysis
364 ------------------------------------------------
365
366 The ``ScalarEvolution`` analysis can be used to analyze and catagorize scalar
367 expressions in loops.  It specializes in recognizing general induction
368 variables, representing them with the abstract and opaque ``SCEV`` class.
369 Given this analysis, trip counts of loops and other important properties can be
370 obtained.
371
372 This analysis is primarily useful for induction variable substitution and
373 strength reduction.
374
375 ``-scev-aa``: ScalarEvolution-based Alias Analysis
376 --------------------------------------------------
377
378 Simple alias analysis implemented in terms of ``ScalarEvolution`` queries.
379
380 This differs from traditional loop dependence analysis in that it tests for
381 dependencies within a single iteration of a loop, rather than dependencies
382 between different iterations.
383
384 ``ScalarEvolution`` has a more complete understanding of pointer arithmetic
385 than ``BasicAliasAnalysis``' collection of ad-hoc analyses.
386
387 ``-targetdata``: Target Data Layout
388 -----------------------------------
389
390 Provides other passes access to information on how the size and alignment
391 required by the target ABI for various data types.
392
393 Transform Passes
394 ================
395
396 This section describes the LLVM Transform Passes.
397
398 ``-adce``: Aggressive Dead Code Elimination
399 -------------------------------------------
400
401 ADCE aggressively tries to eliminate code.  This pass is similar to :ref:`DCE
402 <passes-dce>` but it assumes that values are dead until proven otherwise.  This
403 is similar to :ref:`SCCP <passes-sccp>`, except applied to the liveness of
404 values.
405
406 ``-always-inline``: Inliner for ``always_inline`` functions
407 -----------------------------------------------------------
408
409 A custom inliner that handles only functions that are marked as "always
410 inline".
411
412 ``-argpromotion``: Promote 'by reference' arguments to scalars
413 --------------------------------------------------------------
414
415 This pass promotes "by reference" arguments to be "by value" arguments.  In
416 practice, this means looking for internal functions that have pointer
417 arguments.  If it can prove, through the use of alias analysis, that an
418 argument is *only* loaded, then it can pass the value into the function instead
419 of the address of the value.  This can cause recursive simplification of code
420 and lead to the elimination of allocas (especially in C++ template code like
421 the STL).
422
423 This pass also handles aggregate arguments that are passed into a function,
424 scalarizing them if the elements of the aggregate are only loaded.  Note that
425 it refuses to scalarize aggregates which would require passing in more than
426 three operands to the function, because passing thousands of operands for a
427 large array or structure is unprofitable!
428
429 Note that this transformation could also be done for arguments that are only
430 stored to (returning the value instead), but does not currently.  This case
431 would be best handled when and if LLVM starts supporting multiple return values
432 from functions.
433
434 ``-bb-vectorize``: Basic-Block Vectorization
435 --------------------------------------------
436
437 This pass combines instructions inside basic blocks to form vector
438 instructions.  It iterates over each basic block, attempting to pair compatible
439 instructions, repeating this process until no additional pairs are selected for
440 vectorization.  When the outputs of some pair of compatible instructions are
441 used as inputs by some other pair of compatible instructions, those pairs are
442 part of a potential vectorization chain.  Instruction pairs are only fused into
443 vector instructions when they are part of a chain longer than some threshold
444 length.  Moreover, the pass attempts to find the best possible chain for each
445 pair of compatible instructions.  These heuristics are intended to prevent
446 vectorization in cases where it would not yield a performance increase of the
447 resulting code.
448
449 ``-block-placement``: Profile Guided Basic Block Placement
450 ----------------------------------------------------------
451
452 This pass is a very simple profile guided basic block placement algorithm.  The
453 idea is to put frequently executed blocks together at the start of the function
454 and hopefully increase the number of fall-through conditional branches.  If
455 there is no profile information for a particular function, this pass basically
456 orders blocks in depth-first order.
457
458 ``-break-crit-edges``: Break critical edges in CFG
459 --------------------------------------------------
460
461 Break all of the critical edges in the CFG by inserting a dummy basic block.
462 It may be "required" by passes that cannot deal with critical edges.  This
463 transformation obviously invalidates the CFG, but can update forward dominator
464 (set, immediate dominators, tree, and frontier) information.
465
466 ``-codegenprepare``: Optimize for code generation
467 -------------------------------------------------
468
469 This pass munges the code in the input function to better prepare it for
470 SelectionDAG-based code generation.  This works around limitations in its
471 basic-block-at-a-time approach.  It should eventually be removed.
472
473 ``-constmerge``: Merge Duplicate Global Constants
474 -------------------------------------------------
475
476 Merges duplicate global constants together into a single constant that is
477 shared.  This is useful because some passes (i.e., TraceValues) insert a lot of
478 string constants into the program, regardless of whether or not an existing
479 string is available.
480
481 ``-constprop``: Simple constant propagation
482 -------------------------------------------
483
484 This pass implements constant propagation and merging.  It looks for
485 instructions involving only constant operands and replaces them with a constant
486 value instead of an instruction.  For example:
487
488 .. code-block:: llvm
489
490   add i32 1, 2
491
492 becomes
493
494 .. code-block:: llvm
495
496   i32 3
497
498 NOTE: this pass has a habit of making definitions be dead.  It is a good idea
499 to run a :ref:`Dead Instruction Elimination <passes-die>` pass sometime after
500 running this pass.
501
502 .. _passes-dce:
503
504 ``-dce``: Dead Code Elimination
505 -------------------------------
506
507 Dead code elimination is similar to :ref:`dead instruction elimination
508 <passes-die>`, but it rechecks instructions that were used by removed
509 instructions to see if they are newly dead.
510
511 ``-deadargelim``: Dead Argument Elimination
512 -------------------------------------------
513
514 This pass deletes dead arguments from internal functions.  Dead argument
515 elimination removes arguments which are directly dead, as well as arguments
516 only passed into function calls as dead arguments of other functions.  This
517 pass also deletes dead arguments in a similar way.
518
519 This pass is often useful as a cleanup pass to run after aggressive
520 interprocedural passes, which add possibly-dead arguments.
521
522 ``-deadtypeelim``: Dead Type Elimination
523 ----------------------------------------
524
525 This pass is used to cleanup the output of GCC.  It eliminate names for types
526 that are unused in the entire translation unit, using the :ref:`find used types
527 <passes-print-used-types>` pass.
528
529 .. _passes-die:
530
531 ``-die``: Dead Instruction Elimination
532 --------------------------------------
533
534 Dead instruction elimination performs a single pass over the function, removing
535 instructions that are obviously dead.
536
537 ``-dse``: Dead Store Elimination
538 --------------------------------
539
540 A trivial dead store elimination that only considers basic-block local
541 redundant stores.
542
543 ``-functionattrs``: Deduce function attributes
544 ----------------------------------------------
545
546 A simple interprocedural pass which walks the call-graph, looking for functions
547 which do not access or only read non-local memory, and marking them
548 ``readnone``/``readonly``.  In addition, it marks function arguments (of
549 pointer type) "``nocapture``" if a call to the function does not create any
550 copies of the pointer value that outlive the call.  This more or less means
551 that the pointer is only dereferenced, and not returned from the function or
552 stored in a global.  This pass is implemented as a bottom-up traversal of the
553 call-graph.
554
555 ``-globaldce``: Dead Global Elimination
556 ---------------------------------------
557
558 This transform is designed to eliminate unreachable internal globals from the
559 program.  It uses an aggressive algorithm, searching out globals that are known
560 to be alive.  After it finds all of the globals which are needed, it deletes
561 whatever is left over.  This allows it to delete recursive chunks of the
562 program which are unreachable.
563
564 ``-globalopt``: Global Variable Optimizer
565 -----------------------------------------
566
567 This pass transforms simple global variables that never have their address
568 taken.  If obviously true, it marks read/write globals as constant, deletes
569 variables only stored to, etc.
570
571 ``-gvn``: Global Value Numbering
572 --------------------------------
573
574 This pass performs global value numbering to eliminate fully and partially
575 redundant instructions.  It also performs redundant load elimination.
576
577 .. _passes-indvars:
578
579 ``-indvars``: Canonicalize Induction Variables
580 ----------------------------------------------
581
582 This transformation analyzes and transforms the induction variables (and
583 computations derived from them) into simpler forms suitable for subsequent
584 analysis and transformation.
585
586 This transformation makes the following changes to each loop with an
587 identifiable induction variable:
588
589 * All loops are transformed to have a *single* canonical induction variable
590   which starts at zero and steps by one.
591 * The canonical induction variable is guaranteed to be the first PHI node in
592   the loop header block.
593 * Any pointer arithmetic recurrences are raised to use array subscripts.
594
595 If the trip count of a loop is computable, this pass also makes the following
596 changes:
597
598 * The exit condition for the loop is canonicalized to compare the induction
599   value against the exit value.  This turns loops like:
600
601   .. code-block:: c++
602
603     for (i = 7; i*i < 1000; ++i)
604
605     into
606
607   .. code-block:: c++
608
609     for (i = 0; i != 25; ++i)
610
611 * Any use outside of the loop of an expression derived from the indvar is
612   changed to compute the derived value outside of the loop, eliminating the
613   dependence on the exit value of the induction variable.  If the only purpose
614   of the loop is to compute the exit value of some derived expression, this
615   transformation will make the loop dead.
616
617 This transformation should be followed by strength reduction after all of the
618 desired loop transformations have been performed.  Additionally, on targets
619 where it is profitable, the loop could be transformed to count down to zero
620 (the "do loop" optimization).
621
622 ``-inline``: Function Integration/Inlining
623 ------------------------------------------
624
625 Bottom-up inlining of functions into callees.
626
627 ``-insert-edge-profiling``: Insert instrumentation for edge profiling
628 ---------------------------------------------------------------------
629
630 This pass instruments the specified program with counters for edge profiling.
631 Edge profiling can give a reasonable approximation of the hot paths through a
632 program, and is used for a wide variety of program transformations.
633
634 Note that this implementation is very naïve.  It inserts a counter for *every*
635 edge in the program, instead of using control flow information to prune the
636 number of counters inserted.
637
638 ``-insert-optimal-edge-profiling``: Insert optimal instrumentation for edge profiling
639 -------------------------------------------------------------------------------------
640
641 This pass instruments the specified program with counters for edge profiling.
642 Edge profiling can give a reasonable approximation of the hot paths through a
643 program, and is used for a wide variety of program transformations.
644
645 .. _passes-instcombine:
646
647 ``-instcombine``: Combine redundant instructions
648 ------------------------------------------------
649
650 Combine instructions to form fewer, simple instructions.  This pass does not
651 modify the CFG This pass is where algebraic simplification happens.
652
653 This pass combines things like:
654
655 .. code-block:: llvm
656
657   %Y = add i32 %X, 1
658   %Z = add i32 %Y, 1
659
660 into:
661
662 .. code-block:: llvm
663
664   %Z = add i32 %X, 2
665
666 This is a simple worklist driven algorithm.
667
668 This pass guarantees that the following canonicalizations are performed on the
669 program:
670
671 #. If a binary operator has a constant operand, it is moved to the right-hand
672    side.
673 #. Bitwise operators with constant operands are always grouped so that shifts
674    are performed first, then ``or``\ s, then ``and``\ s, then ``xor``\ s.
675 #. Compare instructions are converted from ``<``, ``>``, ``≤``, or ``≥`` to
676    ``=`` or ``≠`` if possible.
677 #. All ``cmp`` instructions on boolean values are replaced with logical
678    operations.
679 #. ``add X, X`` is represented as ``mul X, 2`` ⇒ ``shl X, 1``
680 #. Multiplies with a constant power-of-two argument are transformed into
681    shifts.
682 #. … etc.
683
684 ``-internalize``: Internalize Global Symbols
685 --------------------------------------------
686
687 This pass loops over all of the functions in the input module, looking for a
688 main function.  If a main function is found, all other functions and all global
689 variables with initializers are marked as internal.
690
691 ``-ipconstprop``: Interprocedural constant propagation
692 ------------------------------------------------------
693
694 This pass implements an *extremely* simple interprocedural constant propagation
695 pass.  It could certainly be improved in many different ways, like using a
696 worklist.  This pass makes arguments dead, but does not remove them.  The
697 existing dead argument elimination pass should be run after this to clean up
698 the mess.
699
700 ``-ipsccp``: Interprocedural Sparse Conditional Constant Propagation
701 --------------------------------------------------------------------
702
703 An interprocedural variant of :ref:`Sparse Conditional Constant Propagation
704 <passes-sccp>`.
705
706 ``-jump-threading``: Jump Threading
707 -----------------------------------
708
709 Jump threading tries to find distinct threads of control flow running through a
710 basic block.  This pass looks at blocks that have multiple predecessors and
711 multiple successors.  If one or more of the predecessors of the block can be
712 proven to always cause a jump to one of the successors, we forward the edge
713 from the predecessor to the successor by duplicating the contents of this
714 block.
715
716 An example of when this can occur is code like this:
717
718 .. code-block:: c++
719
720   if () { ...
721     X = 4;
722   }
723   if (X < 3) {
724
725 In this case, the unconditional branch at the end of the first if can be
726 revectored to the false side of the second if.
727
728 ``-lcssa``: Loop-Closed SSA Form Pass
729 -------------------------------------
730
731 This pass transforms loops by placing phi nodes at the end of the loops for all
732 values that are live across the loop boundary.  For example, it turns the left
733 into the right code:
734
735 .. code-block:: c++
736
737   for (...)                for (...)
738       if (c)                   if (c)
739           X1 = ...                 X1 = ...
740       else                     else
741           X2 = ...                 X2 = ...
742       X3 = phi(X1, X2)         X3 = phi(X1, X2)
743   ... = X3 + 4              X4 = phi(X3)
744                               ... = X4 + 4
745
746 This is still valid LLVM; the extra phi nodes are purely redundant, and will be
747 trivially eliminated by ``InstCombine``.  The major benefit of this
748 transformation is that it makes many other loop optimizations, such as
749 ``LoopUnswitch``\ ing, simpler.
750
751 .. _passes-licm:
752
753 ``-licm``: Loop Invariant Code Motion
754 -------------------------------------
755
756 This pass performs loop invariant code motion, attempting to remove as much
757 code from the body of a loop as possible.  It does this by either hoisting code
758 into the preheader block, or by sinking code to the exit blocks if it is safe.
759 This pass also promotes must-aliased memory locations in the loop to live in
760 registers, thus hoisting and sinking "invariant" loads and stores.
761
762 This pass uses alias analysis for two purposes:
763
764 #. Moving loop invariant loads and calls out of loops.  If we can determine
765    that a load or call inside of a loop never aliases anything stored to, we
766    can hoist it or sink it like any other instruction.
767
768 #. Scalar Promotion of Memory.  If there is a store instruction inside of the
769    loop, we try to move the store to happen AFTER the loop instead of inside of
770    the loop.  This can only happen if a few conditions are true:
771
772    #. The pointer stored through is loop invariant.
773    #. There are no stores or loads in the loop which *may* alias the pointer.
774       There are no calls in the loop which mod/ref the pointer.
775
776    If these conditions are true, we can promote the loads and stores in the
777    loop of the pointer to use a temporary alloca'd variable.  We then use the
778    :ref:`mem2reg <passes-mem2reg>` functionality to construct the appropriate
779    SSA form for the variable.
780
781 ``-loop-deletion``: Delete dead loops
782 -------------------------------------
783
784 This file implements the Dead Loop Deletion Pass.  This pass is responsible for
785 eliminating loops with non-infinite computable trip counts that have no side
786 effects or volatile instructions, and do not contribute to the computation of
787 the function's return value.
788
789 .. _passes-loop-extract:
790
791 ``-loop-extract``: Extract loops into new functions
792 ---------------------------------------------------
793
794 A pass wrapper around the ``ExtractLoop()`` scalar transformation to extract
795 each top-level loop into its own new function.  If the loop is the *only* loop
796 in a given function, it is not touched.  This is a pass most useful for
797 debugging via bugpoint.
798
799 ``-loop-extract-single``: Extract at most one loop into a new function
800 ----------------------------------------------------------------------
801
802 Similar to :ref:`Extract loops into new functions <passes-loop-extract>`, this
803 pass extracts one natural loop from the program into a function if it can.
804 This is used by :program:`bugpoint`.
805
806 ``-loop-reduce``: Loop Strength Reduction
807 -----------------------------------------
808
809 This pass performs a strength reduction on array references inside loops that
810 have as one or more of their components the loop induction variable.  This is
811 accomplished by creating a new value to hold the initial value of the array
812 access for the first iteration, and then creating a new GEP instruction in the
813 loop to increment the value by the appropriate amount.
814
815 ``-loop-rotate``: Rotate Loops
816 ------------------------------
817
818 A simple loop rotation transformation.
819
820 ``-loop-simplify``: Canonicalize natural loops
821 ----------------------------------------------
822
823 This pass performs several transformations to transform natural loops into a
824 simpler form, which makes subsequent analyses and transformations simpler and
825 more effective.
826
827 Loop pre-header insertion guarantees that there is a single, non-critical entry
828 edge from outside of the loop to the loop header.  This simplifies a number of
829 analyses and transformations, such as :ref:`LICM <passes-licm>`.
830
831 Loop exit-block insertion guarantees that all exit blocks from the loop (blocks
832 which are outside of the loop that have predecessors inside of the loop) only
833 have predecessors from inside of the loop (and are thus dominated by the loop
834 header).  This simplifies transformations such as store-sinking that are built
835 into LICM.
836
837 This pass also guarantees that loops will have exactly one backedge.
838
839 Note that the :ref:`simplifycfg <passes-simplifycfg>` pass will clean up blocks
840 which are split out but end up being unnecessary, so usage of this pass should
841 not pessimize generated code.
842
843 This pass obviously modifies the CFG, but updates loop information and
844 dominator information.
845
846 ``-loop-unroll``: Unroll loops
847 ------------------------------
848
849 This pass implements a simple loop unroller.  It works best when loops have
850 been canonicalized by the :ref:`indvars <passes-indvars>` pass, allowing it to
851 determine the trip counts of loops easily.
852
853 ``-loop-unswitch``: Unswitch loops
854 ----------------------------------
855
856 This pass transforms loops that contain branches on loop-invariant conditions
857 to have multiple loops.  For example, it turns the left into the right code:
858
859 .. code-block:: c++
860
861   for (...)                  if (lic)
862       A                          for (...)
863       if (lic)                       A; B; C
864           B                  else
865       C                          for (...)
866                                      A; C
867
868 This can increase the size of the code exponentially (doubling it every time a
869 loop is unswitched) so we only unswitch if the resultant code will be smaller
870 than a threshold.
871
872 This pass expects :ref:`LICM <passes-licm>` to be run before it to hoist
873 invariant conditions out of the loop, to make the unswitching opportunity
874 obvious.
875
876 ``-loweratomic``: Lower atomic intrinsics to non-atomic form
877 ------------------------------------------------------------
878
879 This pass lowers atomic intrinsics to non-atomic form for use in a known
880 non-preemptible environment.
881
882 The pass does not verify that the environment is non-preemptible (in general
883 this would require knowledge of the entire call graph of the program including
884 any libraries which may not be available in bitcode form); it simply lowers
885 every atomic intrinsic.
886
887 ``-lowerinvoke``: Lower invokes to calls, for unwindless code generators
888 ------------------------------------------------------------------------
889
890 This transformation is designed for use by code generators which do not yet
891 support stack unwinding.  This pass converts ``invoke`` instructions to
892 ``call`` instructions, so that any exception-handling ``landingpad`` blocks
893 become dead code (which can be removed by running the ``-simplifycfg`` pass
894 afterwards).
895
896 ``-lowerswitch``: Lower ``SwitchInst``\ s to branches
897 -----------------------------------------------------
898
899 Rewrites switch instructions with a sequence of branches, which allows targets
900 to get away with not implementing the switch instruction until it is
901 convenient.
902
903 .. _passes-mem2reg:
904
905 ``-mem2reg``: Promote Memory to Register
906 ----------------------------------------
907
908 This file promotes memory references to be register references.  It promotes
909 alloca instructions which only have loads and stores as uses.  An ``alloca`` is
910 transformed by using dominator frontiers to place phi nodes, then traversing
911 the function in depth-first order to rewrite loads and stores as appropriate.
912 This is just the standard SSA construction algorithm to construct "pruned" SSA
913 form.
914
915 ``-memcpyopt``: MemCpy Optimization
916 -----------------------------------
917
918 This pass performs various transformations related to eliminating ``memcpy``
919 calls, or transforming sets of stores into ``memset``\ s.
920
921 ``-mergefunc``: Merge Functions
922 -------------------------------
923
924 This pass looks for equivalent functions that are mergable and folds them.
925
926 A hash is computed from the function, based on its type and number of basic
927 blocks.
928
929 Once all hashes are computed, we perform an expensive equality comparison on
930 each function pair.  This takes n^2/2 comparisons per bucket, so it's important
931 that the hash function be high quality.  The equality comparison iterates
932 through each instruction in each basic block.
933
934 When a match is found the functions are folded.  If both functions are
935 overridable, we move the functionality into a new internal function and leave
936 two overridable thunks to it.
937
938 ``-mergereturn``: Unify function exit nodes
939 -------------------------------------------
940
941 Ensure that functions have at most one ``ret`` instruction in them.
942 Additionally, it keeps track of which node is the new exit node of the CFG.
943
944 ``-partial-inliner``: Partial Inliner
945 -------------------------------------
946
947 This pass performs partial inlining, typically by inlining an ``if`` statement
948 that surrounds the body of the function.
949
950 ``-prune-eh``: Remove unused exception handling info
951 ----------------------------------------------------
952
953 This file implements a simple interprocedural pass which walks the call-graph,
954 turning invoke instructions into call instructions if and only if the callee
955 cannot throw an exception.  It implements this as a bottom-up traversal of the
956 call-graph.
957
958 ``-reassociate``: Reassociate expressions
959 -----------------------------------------
960
961 This pass reassociates commutative expressions in an order that is designed to
962 promote better constant propagation, GCSE, :ref:`LICM <passes-licm>`, PRE, etc.
963
964 For example: 4 + (x + 5) ⇒ x + (4 + 5)
965
966 In the implementation of this algorithm, constants are assigned rank = 0,
967 function arguments are rank = 1, and other values are assigned ranks
968 corresponding to the reverse post order traversal of current function (starting
969 at 2), which effectively gives values in deep loops higher rank than values not
970 in loops.
971
972 ``-reg2mem``: Demote all values to stack slots
973 ----------------------------------------------
974
975 This file demotes all registers to memory references.  It is intended to be the
976 inverse of :ref:`mem2reg <passes-mem2reg>`.  By converting to ``load``
977 instructions, the only values live across basic blocks are ``alloca``
978 instructions and ``load`` instructions before ``phi`` nodes.  It is intended
979 that this should make CFG hacking much easier.  To make later hacking easier,
980 the entry block is split into two, such that all introduced ``alloca``
981 instructions (and nothing else) are in the entry block.
982
983 ``-scalarrepl``: Scalar Replacement of Aggregates (DT)
984 ------------------------------------------------------
985
986 The well-known scalar replacement of aggregates transformation.  This transform
987 breaks up ``alloca`` instructions of aggregate type (structure or array) into
988 individual ``alloca`` instructions for each member if possible.  Then, if
989 possible, it transforms the individual ``alloca`` instructions into nice clean
990 scalar SSA form.
991
992 This combines a simple scalar replacement of aggregates algorithm with the
993 :ref:`mem2reg <passes-mem2reg>` algorithm because they often interact,
994 especially for C++ programs.  As such, iterating between ``scalarrepl``, then
995 :ref:`mem2reg <passes-mem2reg>` until we run out of things to promote works
996 well.
997
998 .. _passes-sccp:
999
1000 ``-sccp``: Sparse Conditional Constant Propagation
1001 --------------------------------------------------
1002
1003 Sparse conditional constant propagation and merging, which can be summarized
1004 as:
1005
1006 * Assumes values are constant unless proven otherwise
1007 * Assumes BasicBlocks are dead unless proven otherwise
1008 * Proves values to be constant, and replaces them with constants
1009 * Proves conditional branches to be unconditional
1010
1011 Note that this pass has a habit of making definitions be dead.  It is a good
1012 idea to run a :ref:`DCE <passes-dce>` pass sometime after running this pass.
1013
1014 ``-simplify-libcalls``: Simplify well-known library calls
1015 ---------------------------------------------------------
1016
1017 Applies a variety of small optimizations for calls to specific well-known
1018 function calls (e.g. runtime library functions).  For example, a call
1019 ``exit(3)`` that occurs within the ``main()`` function can be transformed into
1020 simply ``return 3``.
1021
1022 .. _passes-simplifycfg:
1023
1024 ``-simplifycfg``: Simplify the CFG
1025 ----------------------------------
1026
1027 Performs dead code elimination and basic block merging.  Specifically:
1028
1029 * Removes basic blocks with no predecessors.
1030 * Merges a basic block into its predecessor if there is only one and the
1031   predecessor only has one successor.
1032 * Eliminates PHI nodes for basic blocks with a single predecessor.
1033 * Eliminates a basic block that only contains an unconditional branch.
1034
1035 ``-sink``: Code sinking
1036 -----------------------
1037
1038 This pass moves instructions into successor blocks, when possible, so that they
1039 aren't executed on paths where their results aren't needed.
1040
1041 ``-strip``: Strip all symbols from a module
1042 -------------------------------------------
1043
1044 Performs code stripping.  This transformation can delete:
1045
1046 * names for virtual registers
1047 * symbols for internal globals and functions
1048 * debug information
1049
1050 Note that this transformation makes code much less readable, so it should only
1051 be used in situations where the strip utility would be used, such as reducing
1052 code size or making it harder to reverse engineer code.
1053
1054 ``-strip-dead-debug-info``: Strip debug info for unused symbols
1055 ---------------------------------------------------------------
1056
1057 .. FIXME: this description is the same as for -strip
1058
1059 performs code stripping. this transformation can delete:
1060
1061 * names for virtual registers
1062 * symbols for internal globals and functions
1063 * debug information
1064
1065 note that this transformation makes code much less readable, so it should only
1066 be used in situations where the strip utility would be used, such as reducing
1067 code size or making it harder to reverse engineer code.
1068
1069 ``-strip-dead-prototypes``: Strip Unused Function Prototypes
1070 ------------------------------------------------------------
1071
1072 This pass loops over all of the functions in the input module, looking for dead
1073 declarations and removes them.  Dead declarations are declarations of functions
1074 for which no implementation is available (i.e., declarations for unused library
1075 functions).
1076
1077 ``-strip-debug-declare``: Strip all ``llvm.dbg.declare`` intrinsics
1078 -------------------------------------------------------------------
1079
1080 .. FIXME: this description is the same as for -strip
1081
1082 This pass implements code stripping.  Specifically, it can delete:
1083
1084 #. names for virtual registers
1085 #. symbols for internal globals and functions
1086 #. debug information
1087
1088 Note that this transformation makes code much less readable, so it should only
1089 be used in situations where the 'strip' utility would be used, such as reducing
1090 code size or making it harder to reverse engineer code.
1091
1092 ``-strip-nondebug``: Strip all symbols, except dbg symbols, from a module
1093 -------------------------------------------------------------------------
1094
1095 .. FIXME: this description is the same as for -strip
1096
1097 This pass implements code stripping.  Specifically, it can delete:
1098
1099 #. names for virtual registers
1100 #. symbols for internal globals and functions
1101 #. debug information
1102
1103 Note that this transformation makes code much less readable, so it should only
1104 be used in situations where the 'strip' utility would be used, such as reducing
1105 code size or making it harder to reverse engineer code.
1106
1107 ``-tailcallelim``: Tail Call Elimination
1108 ----------------------------------------
1109
1110 This file transforms calls of the current function (self recursion) followed by
1111 a return instruction with a branch to the entry of the function, creating a
1112 loop.  This pass also implements the following extensions to the basic
1113 algorithm:
1114
1115 #. Trivial instructions between the call and return do not prevent the
1116    transformation from taking place, though currently the analysis cannot
1117    support moving any really useful instructions (only dead ones).
1118 #. This pass transforms functions that are prevented from being tail recursive
1119    by an associative expression to use an accumulator variable, thus compiling
1120    the typical naive factorial or fib implementation into efficient code.
1121 #. TRE is performed if the function returns void, if the return returns the
1122    result returned by the call, or if the function returns a run-time constant
1123    on all exits from the function.  It is possible, though unlikely, that the
1124    return returns something else (like constant 0), and can still be TRE'd.  It
1125    can be TRE'd if *all other* return instructions in the function return the
1126    exact same value.
1127 #. If it can prove that callees do not access theier caller stack frame, they
1128    are marked as eligible for tail call elimination (by the code generator).
1129
1130 Utility Passes
1131 ==============
1132
1133 This section describes the LLVM Utility Passes.
1134
1135 ``-deadarghaX0r``: Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)
1136 ------------------------------------------------------------------------
1137
1138 Same as dead argument elimination, but deletes arguments to functions which are
1139 external.  This is only for use by :doc:`bugpoint <Bugpoint>`.
1140
1141 ``-extract-blocks``: Extract Basic Blocks From Module (for bugpoint use)
1142 ------------------------------------------------------------------------
1143
1144 This pass is used by bugpoint to extract all blocks from the module into their
1145 own functions.
1146
1147 ``-instnamer``: Assign names to anonymous instructions
1148 ------------------------------------------------------
1149
1150 This is a little utility pass that gives instructions names, this is mostly
1151 useful when diffing the effect of an optimization because deleting an unnamed
1152 instruction can change all other instruction numbering, making the diff very
1153 noisy.
1154
1155 ``-preverify``: Preliminary module verification
1156 -----------------------------------------------
1157
1158 Ensures that the module is in the form required by the :ref:`Module Verifier
1159 <passes-verify>` pass.  Running the verifier runs this pass automatically, so
1160 there should be no need to use it directly.
1161
1162 .. _passes-verify:
1163
1164 ``-verify``: Module Verifier
1165 ----------------------------
1166
1167 Verifies an LLVM IR code.  This is useful to run after an optimization which is
1168 undergoing testing.  Note that llvm-as verifies its input before emitting
1169 bitcode, and also that malformed bitcode is likely to make LLVM crash.  All
1170 language front-ends are therefore encouraged to verify their output before
1171 performing optimizing transformations.
1172
1173 #. Both of a binary operator's parameters are of the same type.
1174 #. Verify that the indices of mem access instructions match other operands.
1175 #. Verify that arithmetic and other things are only performed on first-class
1176    types.  Verify that shifts and logicals only happen on integrals f.e.
1177 #. All of the constants in a switch statement are of the correct type.
1178 #. The code is in valid SSA form.
1179 #. It is illegal to put a label into any other type (like a structure) or to
1180    return one.
1181 #. Only phi nodes can be self referential: ``%x = add i32 %x``, ``%x`` is
1182    invalid.
1183 #. PHI nodes must have an entry for each predecessor, with no extras.
1184 #. PHI nodes must be the first thing in a basic block, all grouped together.
1185 #. PHI nodes must have at least one entry.
1186 #. All basic blocks should only end with terminator insts, not contain them.
1187 #. The entry node to a function must not have predecessors.
1188 #. All Instructions must be embedded into a basic block.
1189 #. Functions cannot take a void-typed parameter.
1190 #. Verify that a function's argument list agrees with its declared type.
1191 #. It is illegal to specify a name for a void value.
1192 #. It is illegal to have an internal global value with no initializer.
1193 #. It is illegal to have a ``ret`` instruction that returns a value that does
1194    not agree with the function return value type.
1195 #. Function call argument types match the function prototype.
1196 #. All other things that are tested by asserts spread about the code.
1197
1198 Note that this does not provide full security verification (like Java), but
1199 instead just tries to ensure that code is well-formed.
1200
1201 ``-view-cfg``: View CFG of function
1202 -----------------------------------
1203
1204 Displays the control flow graph using the GraphViz tool.
1205
1206 ``-view-cfg-only``: View CFG of function (with no function bodies)
1207 ------------------------------------------------------------------
1208
1209 Displays the control flow graph using the GraphViz tool, but omitting function
1210 bodies.
1211
1212 ``-view-dom``: View dominance tree of function
1213 ----------------------------------------------
1214
1215 Displays the dominator tree using the GraphViz tool.
1216
1217 ``-view-dom-only``: View dominance tree of function (with no function bodies)
1218 -----------------------------------------------------------------------------
1219
1220 Displays the dominator tree using the GraphViz tool, but omitting function
1221 bodies.
1222
1223 ``-view-postdom``: View postdominance tree of function
1224 ------------------------------------------------------
1225
1226 Displays the post dominator tree using the GraphViz tool.
1227
1228 ``-view-postdom-only``: View postdominance tree of function (with no function bodies)
1229 -------------------------------------------------------------------------------------
1230
1231 Displays the post dominator tree using the GraphViz tool, but omitting function
1232 bodies.
1233