Simplify formatting and sort these. No functionality changed.
[oota-llvm.git] / include / llvm / CodeGen / Passes.h
1 //===-- Passes.h - Target independent code generation passes ----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines interfaces to access the target independent code generation
11 // passes provided by the LLVM backend.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_CODEGEN_PASSES_H
16 #define LLVM_CODEGEN_PASSES_H
17
18 #include "llvm/Pass.h"
19 #include "llvm/Target/TargetMachine.h"
20 #include <string>
21
22 namespace llvm {
23
24 class FunctionPass;
25 class MachineFunctionPass;
26 class PassConfigImpl;
27 class PassInfo;
28 class PassManagerBase;
29 class ScheduleDAGInstrs;
30 class TargetLowering;
31 class TargetLoweringBase;
32 class TargetRegisterClass;
33 class raw_ostream;
34 struct MachineSchedContext;
35
36 /// Discriminated union of Pass ID types.
37 ///
38 /// The PassConfig API prefers dealing with IDs because they are safer and more
39 /// efficient. IDs decouple configuration from instantiation. This way, when a
40 /// pass is overriden, it isn't unnecessarily instantiated. It is also unsafe to
41 /// refer to a Pass pointer after adding it to a pass manager, which deletes
42 /// redundant pass instances.
43 ///
44 /// However, it is convient to directly instantiate target passes with
45 /// non-default ctors. These often don't have a registered PassInfo. Rather than
46 /// force all target passes to implement the pass registry boilerplate, allow
47 /// the PassConfig API to handle either type.
48 ///
49 /// AnalysisID is sadly char*, so PointerIntPair won't work.
50 class IdentifyingPassPtr {
51   union {
52     AnalysisID ID;
53     Pass *P;
54   };
55   bool IsInstance;
56 public:
57   IdentifyingPassPtr() : P(0), IsInstance(false) {}
58   IdentifyingPassPtr(AnalysisID IDPtr) : ID(IDPtr), IsInstance(false) {}
59   IdentifyingPassPtr(Pass *InstancePtr) : P(InstancePtr), IsInstance(true) {}
60
61   bool isValid() const { return P; }
62   bool isInstance() const { return IsInstance; }
63
64   AnalysisID getID() const {
65     assert(!IsInstance && "Not a Pass ID");
66     return ID;
67   }
68   Pass *getInstance() const {
69     assert(IsInstance && "Not a Pass Instance");
70     return P;
71   }
72 };
73
74 template <> struct isPodLike<IdentifyingPassPtr> {
75   static const bool value = true;
76 };
77
78 /// Target-Independent Code Generator Pass Configuration Options.
79 ///
80 /// This is an ImmutablePass solely for the purpose of exposing CodeGen options
81 /// to the internals of other CodeGen passes.
82 class TargetPassConfig : public ImmutablePass {
83 public:
84   /// Pseudo Pass IDs. These are defined within TargetPassConfig because they
85   /// are unregistered pass IDs. They are only useful for use with
86   /// TargetPassConfig APIs to identify multiple occurrences of the same pass.
87   ///
88
89   /// EarlyTailDuplicate - A clone of the TailDuplicate pass that runs early
90   /// during codegen, on SSA form.
91   static char EarlyTailDuplicateID;
92
93   /// PostRAMachineLICM - A clone of the LICM pass that runs during late machine
94   /// optimization after regalloc.
95   static char PostRAMachineLICMID;
96
97 private:
98   PassManagerBase *PM;
99   AnalysisID StartAfter;
100   AnalysisID StopAfter;
101   bool Started;
102   bool Stopped;
103
104 protected:
105   TargetMachine *TM;
106   PassConfigImpl *Impl; // Internal data structures
107   bool Initialized;     // Flagged after all passes are configured.
108
109   // Target Pass Options
110   // Targets provide a default setting, user flags override.
111   //
112   bool DisableVerify;
113
114   /// Default setting for -enable-tail-merge on this target.
115   bool EnableTailMerge;
116
117 public:
118   TargetPassConfig(TargetMachine *tm, PassManagerBase &pm);
119   // Dummy constructor.
120   TargetPassConfig();
121
122   virtual ~TargetPassConfig();
123
124   static char ID;
125
126   /// Get the right type of TargetMachine for this target.
127   template<typename TMC> TMC &getTM() const {
128     return *static_cast<TMC*>(TM);
129   }
130
131   const TargetLowering *getTargetLowering() const {
132     return TM->getTargetLowering();
133   }
134
135   //
136   void setInitialized() { Initialized = true; }
137
138   CodeGenOpt::Level getOptLevel() const { return TM->getOptLevel(); }
139
140   /// setStartStopPasses - Set the StartAfter and StopAfter passes to allow
141   /// running only a portion of the normal code-gen pass sequence.  If the
142   /// Start pass ID is zero, then compilation will begin at the normal point;
143   /// otherwise, clear the Started flag to indicate that passes should not be
144   /// added until the starting pass is seen.  If the Stop pass ID is zero,
145   /// then compilation will continue to the end.
146   void setStartStopPasses(AnalysisID Start, AnalysisID Stop) {
147     StartAfter = Start;
148     StopAfter = Stop;
149     Started = (StartAfter == 0);
150   }
151
152   void setDisableVerify(bool Disable) { setOpt(DisableVerify, Disable); }
153
154   bool getEnableTailMerge() const { return EnableTailMerge; }
155   void setEnableTailMerge(bool Enable) { setOpt(EnableTailMerge, Enable); }
156
157   /// Allow the target to override a specific pass without overriding the pass
158   /// pipeline. When passes are added to the standard pipeline at the
159   /// point where StandardID is expected, add TargetID in its place.
160   void substitutePass(AnalysisID StandardID, IdentifyingPassPtr TargetID);
161
162   /// Insert InsertedPassID pass after TargetPassID pass.
163   void insertPass(AnalysisID TargetPassID, IdentifyingPassPtr InsertedPassID);
164
165   /// Allow the target to enable a specific standard pass by default.
166   void enablePass(AnalysisID PassID) { substitutePass(PassID, PassID); }
167
168   /// Allow the target to disable a specific standard pass by default.
169   void disablePass(AnalysisID PassID) {
170     substitutePass(PassID, IdentifyingPassPtr());
171   }
172
173   /// Return the pass substituted for StandardID by the target.
174   /// If no substitution exists, return StandardID.
175   IdentifyingPassPtr getPassSubstitution(AnalysisID StandardID) const;
176
177   /// Return true if the optimized regalloc pipeline is enabled.
178   bool getOptimizeRegAlloc() const;
179
180   /// Add common target configurable passes that perform LLVM IR to IR
181   /// transforms following machine independent optimization.
182   virtual void addIRPasses();
183
184   /// Add passes to lower exception handling for the code generator.
185   void addPassesToHandleExceptions();
186
187   /// Add pass to prepare the LLVM IR for code generation. This should be done
188   /// before exception handling preparation passes.
189   virtual void addCodeGenPrepare();
190
191   /// Add common passes that perform LLVM IR to IR transforms in preparation for
192   /// instruction selection.
193   virtual void addISelPrepare();
194
195   /// addInstSelector - This method should install an instruction selector pass,
196   /// which converts from LLVM code to machine instructions.
197   virtual bool addInstSelector() {
198     return true;
199   }
200
201   /// Add the complete, standard set of LLVM CodeGen passes.
202   /// Fully developed targets will not generally override this.
203   virtual void addMachinePasses();
204
205   /// createTargetScheduler - Create an instance of ScheduleDAGInstrs to be run
206   /// within the standard MachineScheduler pass for this function and target at
207   /// the current optimization level.
208   ///
209   /// This can also be used to plug a new MachineSchedStrategy into an instance
210   /// of the standard ScheduleDAGMI:
211   ///   return new ScheduleDAGMI(C, new MyStrategy(C))
212   ///
213   /// Return NULL to select the default (generic) machine scheduler.
214   virtual ScheduleDAGInstrs *
215   createMachineScheduler(MachineSchedContext *C) const {
216     return 0;
217   }
218
219 protected:
220   // Helper to verify the analysis is really immutable.
221   void setOpt(bool &Opt, bool Val);
222
223   /// Methods with trivial inline returns are convenient points in the common
224   /// codegen pass pipeline where targets may insert passes. Methods with
225   /// out-of-line standard implementations are major CodeGen stages called by
226   /// addMachinePasses. Some targets may override major stages when inserting
227   /// passes is insufficient, but maintaining overriden stages is more work.
228   ///
229
230   /// addPreISelPasses - This method should add any "last minute" LLVM->LLVM
231   /// passes (which are run just before instruction selector).
232   virtual bool addPreISel() {
233     return true;
234   }
235
236   /// addMachineSSAOptimization - Add standard passes that optimize machine
237   /// instructions in SSA form.
238   virtual void addMachineSSAOptimization();
239
240   /// Add passes that optimize instruction level parallelism for out-of-order
241   /// targets. These passes are run while the machine code is still in SSA
242   /// form, so they can use MachineTraceMetrics to control their heuristics.
243   ///
244   /// All passes added here should preserve the MachineDominatorTree,
245   /// MachineLoopInfo, and MachineTraceMetrics analyses.
246   virtual bool addILPOpts() {
247     return false;
248   }
249
250   /// addPreRegAlloc - This method may be implemented by targets that want to
251   /// run passes immediately before register allocation. This should return
252   /// true if -print-machineinstrs should print after these passes.
253   virtual bool addPreRegAlloc() {
254     return false;
255   }
256
257   /// createTargetRegisterAllocator - Create the register allocator pass for
258   /// this target at the current optimization level.
259   virtual FunctionPass *createTargetRegisterAllocator(bool Optimized);
260
261   /// addFastRegAlloc - Add the minimum set of target-independent passes that
262   /// are required for fast register allocation.
263   virtual void addFastRegAlloc(FunctionPass *RegAllocPass);
264
265   /// addOptimizedRegAlloc - Add passes related to register allocation.
266   /// LLVMTargetMachine provides standard regalloc passes for most targets.
267   virtual void addOptimizedRegAlloc(FunctionPass *RegAllocPass);
268
269   /// addPreRewrite - Add passes to the optimized register allocation pipeline
270   /// after register allocation is complete, but before virtual registers are
271   /// rewritten to physical registers.
272   ///
273   /// These passes must preserve VirtRegMap and LiveIntervals, and when running
274   /// after RABasic or RAGreedy, they should take advantage of LiveRegMatrix.
275   /// When these passes run, VirtRegMap contains legal physreg assignments for
276   /// all virtual registers.
277   virtual bool addPreRewrite() {
278     return false;
279   }
280
281   /// addPostRegAlloc - This method may be implemented by targets that want to
282   /// run passes after register allocation pass pipeline but before
283   /// prolog-epilog insertion.  This should return true if -print-machineinstrs
284   /// should print after these passes.
285   virtual bool addPostRegAlloc() {
286     return false;
287   }
288
289   /// Add passes that optimize machine instructions after register allocation.
290   virtual void addMachineLateOptimization();
291
292   /// addPreSched2 - This method may be implemented by targets that want to
293   /// run passes after prolog-epilog insertion and before the second instruction
294   /// scheduling pass.  This should return true if -print-machineinstrs should
295   /// print after these passes.
296   virtual bool addPreSched2() {
297     return false;
298   }
299
300   /// addGCPasses - Add late codegen passes that analyze code for garbage
301   /// collection. This should return true if GC info should be printed after
302   /// these passes.
303   virtual bool addGCPasses();
304
305   /// Add standard basic block placement passes.
306   virtual void addBlockPlacement();
307
308   /// addPreEmitPass - This pass may be implemented by targets that want to run
309   /// passes immediately before machine code is emitted.  This should return
310   /// true if -print-machineinstrs should print out the code after the passes.
311   virtual bool addPreEmitPass() {
312     return false;
313   }
314
315   /// Utilities for targets to add passes to the pass manager.
316   ///
317
318   /// Add a CodeGen pass at this point in the pipeline after checking overrides.
319   /// Return the pass that was added, or zero if no pass was added.
320   AnalysisID addPass(AnalysisID PassID);
321
322   /// Add a pass to the PassManager if that pass is supposed to be run, as
323   /// determined by the StartAfter and StopAfter options. Takes ownership of the
324   /// pass.
325   void addPass(Pass *P);
326
327   /// addMachinePasses helper to create the target-selected or overriden
328   /// regalloc pass.
329   FunctionPass *createRegAllocPass(bool Optimized);
330
331   /// printAndVerify - Add a pass to dump then verify the machine function, if
332   /// those steps are enabled.
333   ///
334   void printAndVerify(const char *Banner);
335 };
336 } // namespace llvm
337
338 /// List of target independent CodeGen pass IDs.
339 namespace llvm {
340   /// \brief Create a basic TargetTransformInfo analysis pass.
341   ///
342   /// This pass implements the target transform info analysis using the target
343   /// independent information available to the LLVM code generator.
344   ImmutablePass *
345   createBasicTargetTransformInfoPass(const TargetMachine *TM);
346
347   /// createUnreachableBlockEliminationPass - The LLVM code generator does not
348   /// work well with unreachable basic blocks (what live ranges make sense for a
349   /// block that cannot be reached?).  As such, a code generator should either
350   /// not instruction select unreachable blocks, or run this pass as its
351   /// last LLVM modifying pass to clean up blocks that are not reachable from
352   /// the entry block.
353   FunctionPass *createUnreachableBlockEliminationPass();
354
355   /// MachineFunctionPrinter pass - This pass prints out the machine function to
356   /// the given stream as a debugging tool.
357   MachineFunctionPass *
358   createMachineFunctionPrinterPass(raw_ostream &OS,
359                                    const std::string &Banner ="");
360
361   /// MachineLoopInfo - This pass is a loop analysis pass.
362   extern char &MachineLoopInfoID;
363
364   /// MachineDominators - This pass is a machine dominators analysis pass.
365   extern char &MachineDominatorsID;
366
367   /// EdgeBundles analysis - Bundle machine CFG edges.
368   extern char &EdgeBundlesID;
369
370   /// LiveVariables pass - This pass computes the set of blocks in which each
371   /// variable is life and sets machine operand kill flags.
372   extern char &LiveVariablesID;
373
374   /// PHIElimination - This pass eliminates machine instruction PHI nodes
375   /// by inserting copy instructions.  This destroys SSA information, but is the
376   /// desired input for some register allocators.  This pass is "required" by
377   /// these register allocator like this: AU.addRequiredID(PHIEliminationID);
378   extern char &PHIEliminationID;
379
380   /// LiveIntervals - This analysis keeps track of the live ranges of virtual
381   /// and physical registers.
382   extern char &LiveIntervalsID;
383
384   /// LiveStacks pass. An analysis keeping track of the liveness of stack slots.
385   extern char &LiveStacksID;
386
387   /// TwoAddressInstruction - This pass reduces two-address instructions to
388   /// use two operands. This destroys SSA information but it is desired by
389   /// register allocators.
390   extern char &TwoAddressInstructionPassID;
391
392   /// ProcessImpicitDefs pass - This pass removes IMPLICIT_DEFs.
393   extern char &ProcessImplicitDefsID;
394
395   /// RegisterCoalescer - This pass merges live ranges to eliminate copies.
396   extern char &RegisterCoalescerID;
397
398   /// MachineScheduler - This pass schedules machine instructions.
399   extern char &MachineSchedulerID;
400
401   /// SpillPlacement analysis. Suggest optimal placement of spill code between
402   /// basic blocks.
403   extern char &SpillPlacementID;
404
405   /// VirtRegRewriter pass. Rewrite virtual registers to physical registers as
406   /// assigned in VirtRegMap.
407   extern char &VirtRegRewriterID;
408
409   /// UnreachableMachineBlockElimination - This pass removes unreachable
410   /// machine basic blocks.
411   extern char &UnreachableMachineBlockElimID;
412
413   /// DeadMachineInstructionElim - This pass removes dead machine instructions.
414   extern char &DeadMachineInstructionElimID;
415
416   /// FastRegisterAllocation Pass - This pass register allocates as fast as
417   /// possible. It is best suited for debug code where live ranges are short.
418   ///
419   FunctionPass *createFastRegisterAllocator();
420
421   /// BasicRegisterAllocation Pass - This pass implements a degenerate global
422   /// register allocator using the basic regalloc framework.
423   ///
424   FunctionPass *createBasicRegisterAllocator();
425
426   /// Greedy register allocation pass - This pass implements a global register
427   /// allocator for optimized builds.
428   ///
429   FunctionPass *createGreedyRegisterAllocator();
430
431   /// PBQPRegisterAllocation Pass - This pass implements the Partitioned Boolean
432   /// Quadratic Prograaming (PBQP) based register allocator.
433   ///
434   FunctionPass *createDefaultPBQPRegisterAllocator();
435
436   /// PrologEpilogCodeInserter - This pass inserts prolog and epilog code,
437   /// and eliminates abstract frame references.
438   extern char &PrologEpilogCodeInserterID;
439
440   /// ExpandPostRAPseudos - This pass expands pseudo instructions after
441   /// register allocation.
442   extern char &ExpandPostRAPseudosID;
443
444   /// createPostRAScheduler - This pass performs post register allocation
445   /// scheduling.
446   extern char &PostRASchedulerID;
447
448   /// BranchFolding - This pass performs machine code CFG based
449   /// optimizations to delete branches to branches, eliminate branches to
450   /// successor blocks (creating fall throughs), and eliminating branches over
451   /// branches.
452   extern char &BranchFolderPassID;
453
454   /// MachineFunctionPrinterPass - This pass prints out MachineInstr's.
455   extern char &MachineFunctionPrinterPassID;
456
457   /// TailDuplicate - Duplicate blocks with unconditional branches
458   /// into tails of their predecessors.
459   extern char &TailDuplicateID;
460
461   /// MachineTraceMetrics - This pass computes critical path and CPU resource
462   /// usage in an ensemble of traces.
463   extern char &MachineTraceMetricsID;
464
465   /// EarlyIfConverter - This pass performs if-conversion on SSA form by
466   /// inserting cmov instructions.
467   extern char &EarlyIfConverterID;
468
469   /// StackSlotColoring - This pass performs stack coloring and merging.
470   /// It merges disjoint allocas to reduce the stack size.
471   extern char &StackColoringID;
472
473   /// IfConverter - This pass performs machine code if conversion.
474   extern char &IfConverterID;
475
476   /// MachineBlockPlacement - This pass places basic blocks based on branch
477   /// probabilities.
478   extern char &MachineBlockPlacementID;
479
480   /// MachineBlockPlacementStats - This pass collects statistics about the
481   /// basic block placement using branch probabilities and block frequency
482   /// information.
483   extern char &MachineBlockPlacementStatsID;
484
485   /// GCLowering Pass - Performs target-independent LLVM IR transformations for
486   /// highly portable strategies.
487   ///
488   FunctionPass *createGCLoweringPass();
489
490   /// GCMachineCodeAnalysis - Target-independent pass to mark safe points
491   /// in machine code. Must be added very late during code generation, just
492   /// prior to output, and importantly after all CFG transformations (such as
493   /// branch folding).
494   extern char &GCMachineCodeAnalysisID;
495
496   /// Creates a pass to print GC metadata.
497   ///
498   FunctionPass *createGCInfoPrinter(raw_ostream &OS);
499
500   /// MachineCSE - This pass performs global CSE on machine instructions.
501   extern char &MachineCSEID;
502
503   /// MachineLICM - This pass performs LICM on machine instructions.
504   extern char &MachineLICMID;
505
506   /// MachineSinking - This pass performs sinking on machine instructions.
507   extern char &MachineSinkingID;
508
509   /// MachineCopyPropagation - This pass performs copy propagation on
510   /// machine instructions.
511   extern char &MachineCopyPropagationID;
512
513   /// PeepholeOptimizer - This pass performs peephole optimizations -
514   /// like extension and comparison eliminations.
515   extern char &PeepholeOptimizerID;
516
517   /// OptimizePHIs - This pass optimizes machine instruction PHIs
518   /// to take advantage of opportunities created during DAG legalization.
519   extern char &OptimizePHIsID;
520
521   /// StackSlotColoring - This pass performs stack slot coloring.
522   extern char &StackSlotColoringID;
523
524   /// createStackProtectorPass - This pass adds stack protectors to functions.
525   ///
526   FunctionPass *createStackProtectorPass(const TargetMachine *TM);
527
528   /// createMachineVerifierPass - This pass verifies cenerated machine code
529   /// instructions for correctness.
530   ///
531   FunctionPass *createMachineVerifierPass(const char *Banner = 0);
532
533   /// createDwarfEHPass - This pass mulches exception handling code into a form
534   /// adapted to code generation.  Required if using dwarf exception handling.
535   FunctionPass *createDwarfEHPass(const TargetMachine *TM);
536
537   /// createSjLjEHPreparePass - This pass adapts exception handling code to use
538   /// the GCC-style builtin setjmp/longjmp (sjlj) to handling EH control flow.
539   ///
540   FunctionPass *createSjLjEHPreparePass(const TargetMachine *TM);
541
542   /// LocalStackSlotAllocation - This pass assigns local frame indices to stack
543   /// slots relative to one another and allocates base registers to access them
544   /// when it is estimated by the target to be out of range of normal frame
545   /// pointer or stack pointer index addressing.
546   extern char &LocalStackSlotAllocationID;
547
548   /// ExpandISelPseudos - This pass expands pseudo-instructions.
549   extern char &ExpandISelPseudosID;
550
551   /// createExecutionDependencyFixPass - This pass fixes execution time
552   /// problems with dependent instructions, such as switching execution
553   /// domains to match.
554   ///
555   /// The pass will examine instructions using and defining registers in RC.
556   ///
557   FunctionPass *createExecutionDependencyFixPass(const TargetRegisterClass *RC);
558
559   /// UnpackMachineBundles - This pass unpack machine instruction bundles.
560   extern char &UnpackMachineBundlesID;
561
562   /// FinalizeMachineBundles - This pass finalize machine instruction
563   /// bundles (created earlier, e.g. during pre-RA scheduling).
564   extern char &FinalizeMachineBundlesID;
565
566 } // End llvm namespace
567
568 #endif