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