1 //===-- Passes.h - Target independent code generation passes ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines interfaces to access the target independent code generation
11 // passes provided by the LLVM backend.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CODEGEN_PASSES_H
16 #define LLVM_CODEGEN_PASSES_H
18 #include "llvm/Pass.h"
19 #include "llvm/Target/TargetMachine.h"
25 class MachineFunctionPass;
26 struct MachineSchedContext;
28 class PassManagerBase;
29 class ScheduleDAGInstrs;
30 class TargetLoweringBase;
32 class TargetRegisterClass;
40 /// Discriminated union of Pass ID types.
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.
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.
53 /// AnalysisID is sadly char*, so PointerIntPair won't work.
54 class IdentifyingPassPtr {
61 IdentifyingPassPtr() : P(0), IsInstance(false) {}
62 IdentifyingPassPtr(AnalysisID IDPtr) : ID(IDPtr), IsInstance(false) {}
63 IdentifyingPassPtr(Pass *InstancePtr) : P(InstancePtr), IsInstance(true) {}
65 bool isValid() const { return P; }
66 bool isInstance() const { return IsInstance; }
68 AnalysisID getID() const {
69 assert(!IsInstance && "Not a Pass ID");
72 Pass *getInstance() const {
73 assert(IsInstance && "Not a Pass Instance");
78 template <> struct isPodLike<IdentifyingPassPtr> {
79 static const bool value = true;
82 /// Target-Independent Code Generator Pass Configuration Options.
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 {
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.
93 /// EarlyTailDuplicate - A clone of the TailDuplicate pass that runs early
94 /// during codegen, on SSA form.
95 static char EarlyTailDuplicateID;
97 /// PostRAMachineLICM - A clone of the LICM pass that runs during late machine
98 /// optimization after regalloc.
99 static char PostRAMachineLICMID;
103 AnalysisID StartAfter;
104 AnalysisID StopAfter;
110 PassConfigImpl *Impl; // Internal data structures
111 bool Initialized; // Flagged after all passes are configured.
113 // Target Pass Options
114 // Targets provide a default setting, user flags override.
118 /// Default setting for -enable-tail-merge on this target.
119 bool EnableTailMerge;
122 TargetPassConfig(TargetMachine *tm, PassManagerBase &pm);
123 // Dummy constructor.
126 virtual ~TargetPassConfig();
130 /// Get the right type of TargetMachine for this target.
131 template<typename TMC> TMC &getTM() const {
132 return *static_cast<TMC*>(TM);
135 const TargetLowering *getTargetLowering() const {
136 return TM->getTargetLowering();
140 void setInitialized() { Initialized = true; }
142 CodeGenOpt::Level getOptLevel() const { return TM->getOptLevel(); }
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) {
153 Started = (StartAfter == 0);
156 void setDisableVerify(bool Disable) { setOpt(DisableVerify, Disable); }
158 bool getEnableTailMerge() const { return EnableTailMerge; }
159 void setEnableTailMerge(bool Enable) { setOpt(EnableTailMerge, Enable); }
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);
166 /// Insert InsertedPassID pass after TargetPassID pass.
167 void insertPass(AnalysisID TargetPassID, IdentifyingPassPtr InsertedPassID);
169 /// Allow the target to enable a specific standard pass by default.
170 void enablePass(AnalysisID PassID) { substitutePass(PassID, PassID); }
172 /// Allow the target to disable a specific standard pass by default.
173 void disablePass(AnalysisID PassID) {
174 substitutePass(PassID, IdentifyingPassPtr());
177 /// Return the pass substituted for StandardID by the target.
178 /// If no substitution exists, return StandardID.
179 IdentifyingPassPtr getPassSubstitution(AnalysisID StandardID) const;
181 /// Return true if the optimized regalloc pipeline is enabled.
182 bool getOptimizeRegAlloc() const;
184 /// Add common target configurable passes that perform LLVM IR to IR
185 /// transforms following machine independent optimization.
186 virtual void addIRPasses();
188 /// Add passes to lower exception handling for the code generator.
189 void addPassesToHandleExceptions();
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();
195 /// Add common passes that perform LLVM IR to IR transforms in preparation for
196 /// instruction selection.
197 virtual void addISelPrepare();
199 /// addInstSelector - This method should install an instruction selector pass,
200 /// which converts from LLVM code to machine instructions.
201 virtual bool addInstSelector() {
205 /// Add the complete, standard set of LLVM CodeGen passes.
206 /// Fully developed targets will not generally override this.
207 virtual void addMachinePasses();
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.
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))
217 /// Return NULL to select the default (generic) machine scheduler.
218 virtual ScheduleDAGInstrs *
219 createMachineScheduler(MachineSchedContext *C) const {
224 // Helper to verify the analysis is really immutable.
225 void setOpt(bool &Opt, bool Val);
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.
234 /// addPreISelPasses - This method should add any "last minute" LLVM->LLVM
235 /// passes (which are run just before instruction selector).
236 virtual bool addPreISel() {
240 /// addMachineSSAOptimization - Add standard passes that optimize machine
241 /// instructions in SSA form.
242 virtual void addMachineSSAOptimization();
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.
248 /// All passes added here should preserve the MachineDominatorTree,
249 /// MachineLoopInfo, and MachineTraceMetrics analyses.
250 virtual bool addILPOpts() {
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() {
261 /// createTargetRegisterAllocator - Create the register allocator pass for
262 /// this target at the current optimization level.
263 virtual FunctionPass *createTargetRegisterAllocator(bool Optimized);
265 /// addFastRegAlloc - Add the minimum set of target-independent passes that
266 /// are required for fast register allocation.
267 virtual void addFastRegAlloc(FunctionPass *RegAllocPass);
269 /// addOptimizedRegAlloc - Add passes related to register allocation.
270 /// LLVMTargetMachine provides standard regalloc passes for most targets.
271 virtual void addOptimizedRegAlloc(FunctionPass *RegAllocPass);
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.
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() {
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() {
293 /// Add passes that optimize machine instructions after register allocation.
294 virtual void addMachineLateOptimization();
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() {
304 /// addGCPasses - Add late codegen passes that analyze code for garbage
305 /// collection. This should return true if GC info should be printed after
307 virtual bool addGCPasses();
309 /// Add standard basic block placement passes.
310 virtual void addBlockPlacement();
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() {
319 /// Utilities for targets to add passes to the pass manager.
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);
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
329 void addPass(Pass *P);
331 /// addMachinePasses helper to create the target-selected or overriden
333 FunctionPass *createRegAllocPass(bool Optimized);
335 /// printAndVerify - Add a pass to dump then verify the machine function, if
336 /// those steps are enabled.
338 void printAndVerify(const char *Banner);
342 /// List of target independent CodeGen pass IDs.
344 /// \brief Create a basic TargetTransformInfo analysis pass.
346 /// This pass implements the target transform info analysis using the target
347 /// independent information available to the LLVM code generator.
349 createBasicTargetTransformInfoPass(const TargetMachine *TM);
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
357 FunctionPass *createUnreachableBlockEliminationPass();
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 ="");
365 /// MachineLoopInfo - This pass is a loop analysis pass.
366 extern char &MachineLoopInfoID;
368 /// MachineDominators - This pass is a machine dominators analysis pass.
369 extern char &MachineDominatorsID;
371 /// EdgeBundles analysis - Bundle machine CFG edges.
372 extern char &EdgeBundlesID;
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;
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;
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;
392 /// LiveIntervals - This analysis keeps track of the live ranges of virtual
393 /// and physical registers.
394 extern char &LiveIntervalsID;
396 /// LiveStacks pass. An analysis keeping track of the liveness of stack slots.
397 extern char &LiveStacksID;
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;
404 /// ProcessImpicitDefs pass - This pass removes IMPLICIT_DEFs.
405 extern char &ProcessImplicitDefsID;
407 /// RegisterCoalescer - This pass merges live ranges to eliminate copies.
408 extern char &RegisterCoalescerID;
410 /// MachineScheduler - This pass schedules machine instructions.
411 extern char &MachineSchedulerID;
413 /// SpillPlacement analysis. Suggest optimal placement of spill code between
415 extern char &SpillPlacementID;
417 /// VirtRegRewriter pass. Rewrite virtual registers to physical registers as
418 /// assigned in VirtRegMap.
419 extern char &VirtRegRewriterID;
421 /// UnreachableMachineBlockElimination - This pass removes unreachable
422 /// machine basic blocks.
423 extern char &UnreachableMachineBlockElimID;
425 /// DeadMachineInstructionElim - This pass removes dead machine instructions.
426 extern char &DeadMachineInstructionElimID;
428 /// FastRegisterAllocation Pass - This pass register allocates as fast as
429 /// possible. It is best suited for debug code where live ranges are short.
431 FunctionPass *createFastRegisterAllocator();
433 /// BasicRegisterAllocation Pass - This pass implements a degenerate global
434 /// register allocator using the basic regalloc framework.
436 FunctionPass *createBasicRegisterAllocator();
438 /// Greedy register allocation pass - This pass implements a global register
439 /// allocator for optimized builds.
441 FunctionPass *createGreedyRegisterAllocator();
443 /// PBQPRegisterAllocation Pass - This pass implements the Partitioned Boolean
444 /// Quadratic Prograaming (PBQP) based register allocator.
446 FunctionPass *createDefaultPBQPRegisterAllocator();
448 /// PrologEpilogCodeInserter - This pass inserts prolog and epilog code,
449 /// and eliminates abstract frame references.
450 extern char &PrologEpilogCodeInserterID;
452 /// ExpandPostRAPseudos - This pass expands pseudo instructions after
453 /// register allocation.
454 extern char &ExpandPostRAPseudosID;
456 /// createPostRAScheduler - This pass performs post register allocation
458 extern char &PostRASchedulerID;
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
464 extern char &BranchFolderPassID;
466 /// MachineFunctionPrinterPass - This pass prints out MachineInstr's.
467 extern char &MachineFunctionPrinterPassID;
469 /// TailDuplicate - Duplicate blocks with unconditional branches
470 /// into tails of their predecessors.
471 extern char &TailDuplicateID;
473 /// MachineTraceMetrics - This pass computes critical path and CPU resource
474 /// usage in an ensemble of traces.
475 extern char &MachineTraceMetricsID;
477 /// EarlyIfConverter - This pass performs if-conversion on SSA form by
478 /// inserting cmov instructions.
479 extern char &EarlyIfConverterID;
481 /// StackSlotColoring - This pass performs stack coloring and merging.
482 /// It merges disjoint allocas to reduce the stack size.
483 extern char &StackColoringID;
485 /// IfConverter - This pass performs machine code if conversion.
486 extern char &IfConverterID;
488 /// MachineBlockPlacement - This pass places basic blocks based on branch
490 extern char &MachineBlockPlacementID;
492 /// MachineBlockPlacementStats - This pass collects statistics about the
493 /// basic block placement using branch probabilities and block frequency
495 extern char &MachineBlockPlacementStatsID;
497 /// GCLowering Pass - Performs target-independent LLVM IR transformations for
498 /// highly portable strategies.
500 FunctionPass *createGCLoweringPass();
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
506 extern char &GCMachineCodeAnalysisID;
508 /// Creates a pass to print GC metadata.
510 FunctionPass *createGCInfoPrinter(raw_ostream &OS);
512 /// MachineCSE - This pass performs global CSE on machine instructions.
513 extern char &MachineCSEID;
515 /// MachineLICM - This pass performs LICM on machine instructions.
516 extern char &MachineLICMID;
518 /// MachineSinking - This pass performs sinking on machine instructions.
519 extern char &MachineSinkingID;
521 /// MachineCopyPropagation - This pass performs copy propagation on
522 /// machine instructions.
523 extern char &MachineCopyPropagationID;
525 /// PeepholeOptimizer - This pass performs peephole optimizations -
526 /// like extension and comparison eliminations.
527 extern char &PeepholeOptimizerID;
529 /// OptimizePHIs - This pass optimizes machine instruction PHIs
530 /// to take advantage of opportunities created during DAG legalization.
531 extern char &OptimizePHIsID;
533 /// StackSlotColoring - This pass performs stack slot coloring.
534 extern char &StackSlotColoringID;
536 /// createStackProtectorPass - This pass adds stack protectors to functions.
538 FunctionPass *createStackProtectorPass(const TargetMachine *TM);
540 /// createMachineVerifierPass - This pass verifies cenerated machine code
541 /// instructions for correctness.
543 FunctionPass *createMachineVerifierPass(const char *Banner = 0);
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);
549 /// createSjLjEHPreparePass - This pass adapts exception handling code to use
550 /// the GCC-style builtin setjmp/longjmp (sjlj) to handling EH control flow.
552 FunctionPass *createSjLjEHPreparePass(const TargetMachine *TM);
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;
560 /// ExpandISelPseudos - This pass expands pseudo-instructions.
561 extern char &ExpandISelPseudosID;
563 /// createExecutionDependencyFixPass - This pass fixes execution time
564 /// problems with dependent instructions, such as switching execution
565 /// domains to match.
567 /// The pass will examine instructions using and defining registers in RC.
569 FunctionPass *createExecutionDependencyFixPass(const TargetRegisterClass *RC);
571 /// UnpackMachineBundles - This pass unpack machine instruction bundles.
572 extern char &UnpackMachineBundlesID;
574 /// FinalizeMachineBundles - This pass finalize machine instruction
575 /// bundles (created earlier, e.g. during pre-RA scheduling).
576 extern char &FinalizeMachineBundlesID;
578 } // End llvm namespace