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;
27 class PassManagerBase;
28 class TargetLoweringBase;
30 class TargetRegisterClass;
38 /// Discriminated union of Pass ID types.
40 /// The PassConfig API prefers dealing with IDs because they are safer and more
41 /// efficient. IDs decouple configuration from instantiation. This way, when a
42 /// pass is overriden, it isn't unnecessarily instantiated. It is also unsafe to
43 /// refer to a Pass pointer after adding it to a pass manager, which deletes
44 /// redundant pass instances.
46 /// However, it is convient to directly instantiate target passes with
47 /// non-default ctors. These often don't have a registered PassInfo. Rather than
48 /// force all target passes to implement the pass registry boilerplate, allow
49 /// the PassConfig API to handle either type.
51 /// AnalysisID is sadly char*, so PointerIntPair won't work.
52 class IdentifyingPassPtr {
56 IdentifyingPassPtr(): P(0), IsInstance(false) {}
57 IdentifyingPassPtr(AnalysisID IDPtr): P((void*)IDPtr), IsInstance(false) {}
58 IdentifyingPassPtr(Pass *InstancePtr)
59 : P((void*)InstancePtr), IsInstance(true) {}
61 bool isValid() const { return P; }
62 bool isInstance() const { return IsInstance; }
64 AnalysisID getID() const {
65 assert(!IsInstance && "Not a Pass ID");
68 Pass *getInstance() const {
69 assert(IsInstance && "Not a Pass Instance");
74 template <> struct isPodLike<IdentifyingPassPtr> {
75 static const bool value = true;
78 /// Target-Independent Code Generator Pass Configuration Options.
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 {
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.
89 /// EarlyTailDuplicate - A clone of the TailDuplicate pass that runs early
90 /// during codegen, on SSA form.
91 static char EarlyTailDuplicateID;
93 /// PostRAMachineLICM - A clone of the LICM pass that runs during late machine
94 /// optimization after regalloc.
95 static char PostRAMachineLICMID;
99 AnalysisID StartAfter;
100 AnalysisID StopAfter;
106 PassConfigImpl *Impl; // Internal data structures
107 bool Initialized; // Flagged after all passes are configured.
109 // Target Pass Options
110 // Targets provide a default setting, user flags override.
114 /// Default setting for -enable-tail-merge on this target.
115 bool EnableTailMerge;
118 TargetPassConfig(TargetMachine *tm, PassManagerBase &pm);
119 // Dummy constructor.
122 virtual ~TargetPassConfig();
126 /// Get the right type of TargetMachine for this target.
127 template<typename TMC> TMC &getTM() const {
128 return *static_cast<TMC*>(TM);
131 const TargetLowering *getTargetLowering() const {
132 return TM->getTargetLowering();
136 void setInitialized() { Initialized = true; }
138 CodeGenOpt::Level getOptLevel() const { return TM->getOptLevel(); }
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) {
149 Started = (StartAfter == 0);
152 void setDisableVerify(bool Disable) { setOpt(DisableVerify, Disable); }
154 bool getEnableTailMerge() const { return EnableTailMerge; }
155 void setEnableTailMerge(bool Enable) { setOpt(EnableTailMerge, Enable); }
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);
162 /// Insert InsertedPassID pass after TargetPassID pass.
163 void insertPass(AnalysisID TargetPassID, IdentifyingPassPtr InsertedPassID);
165 /// Allow the target to enable a specific standard pass by default.
166 void enablePass(AnalysisID PassID) { substitutePass(PassID, PassID); }
168 /// Allow the target to disable a specific standard pass by default.
169 void disablePass(AnalysisID PassID) {
170 substitutePass(PassID, IdentifyingPassPtr());
173 /// Return the pass substituted for StandardID by the target.
174 /// If no substitution exists, return StandardID.
175 IdentifyingPassPtr getPassSubstitution(AnalysisID StandardID) const;
177 /// Return true if the optimized regalloc pipeline is enabled.
178 bool getOptimizeRegAlloc() const;
180 /// Add common target configurable passes that perform LLVM IR to IR
181 /// transforms following machine independent optimization.
182 virtual void addIRPasses();
184 /// Add passes to lower exception handling for the code generator.
185 void addPassesToHandleExceptions();
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();
191 /// Add common passes that perform LLVM IR to IR transforms in preparation for
192 /// instruction selection.
193 virtual void addISelPrepare();
195 /// addInstSelector - This method should install an instruction selector pass,
196 /// which converts from LLVM code to machine instructions.
197 virtual bool addInstSelector() {
201 /// Add the complete, standard set of LLVM CodeGen passes.
202 /// Fully developed targets will not generally override this.
203 virtual void addMachinePasses();
206 // Helper to verify the analysis is really immutable.
207 void setOpt(bool &Opt, bool Val);
209 /// Methods with trivial inline returns are convenient points in the common
210 /// codegen pass pipeline where targets may insert passes. Methods with
211 /// out-of-line standard implementations are major CodeGen stages called by
212 /// addMachinePasses. Some targets may override major stages when inserting
213 /// passes is insufficient, but maintaining overriden stages is more work.
216 /// addPreISelPasses - This method should add any "last minute" LLVM->LLVM
217 /// passes (which are run just before instruction selector).
218 virtual bool addPreISel() {
222 /// addMachineSSAOptimization - Add standard passes that optimize machine
223 /// instructions in SSA form.
224 virtual void addMachineSSAOptimization();
226 /// Add passes that optimize instruction level parallelism for out-of-order
227 /// targets. These passes are run while the machine code is still in SSA
228 /// form, so they can use MachineTraceMetrics to control their heuristics.
230 /// All passes added here should preserve the MachineDominatorTree,
231 /// MachineLoopInfo, and MachineTraceMetrics analyses.
232 virtual bool addILPOpts() {
236 /// addPreRegAlloc - This method may be implemented by targets that want to
237 /// run passes immediately before register allocation. This should return
238 /// true if -print-machineinstrs should print after these passes.
239 virtual bool addPreRegAlloc() {
243 /// createTargetRegisterAllocator - Create the register allocator pass for
244 /// this target at the current optimization level.
245 virtual FunctionPass *createTargetRegisterAllocator(bool Optimized);
247 /// addFastRegAlloc - Add the minimum set of target-independent passes that
248 /// are required for fast register allocation.
249 virtual void addFastRegAlloc(FunctionPass *RegAllocPass);
251 /// addOptimizedRegAlloc - Add passes related to register allocation.
252 /// LLVMTargetMachine provides standard regalloc passes for most targets.
253 virtual void addOptimizedRegAlloc(FunctionPass *RegAllocPass);
255 /// addPreRewrite - Add passes to the optimized register allocation pipeline
256 /// after register allocation is complete, but before virtual registers are
257 /// rewritten to physical registers.
259 /// These passes must preserve VirtRegMap and LiveIntervals, and when running
260 /// after RABasic or RAGreedy, they should take advantage of LiveRegMatrix.
261 /// When these passes run, VirtRegMap contains legal physreg assignments for
262 /// all virtual registers.
263 virtual bool addPreRewrite() {
267 /// addPostRegAlloc - This method may be implemented by targets that want to
268 /// run passes after register allocation pass pipeline but before
269 /// prolog-epilog insertion. This should return true if -print-machineinstrs
270 /// should print after these passes.
271 virtual bool addPostRegAlloc() {
275 /// Add passes that optimize machine instructions after register allocation.
276 virtual void addMachineLateOptimization();
278 /// addPreSched2 - This method may be implemented by targets that want to
279 /// run passes after prolog-epilog insertion and before the second instruction
280 /// scheduling pass. This should return true if -print-machineinstrs should
281 /// print after these passes.
282 virtual bool addPreSched2() {
286 /// addGCPasses - Add late codegen passes that analyze code for garbage
287 /// collection. This should return true if GC info should be printed after
289 virtual bool addGCPasses();
291 /// Add standard basic block placement passes.
292 virtual void addBlockPlacement();
294 /// addPreEmitPass - This pass may be implemented by targets that want to run
295 /// passes immediately before machine code is emitted. This should return
296 /// true if -print-machineinstrs should print out the code after the passes.
297 virtual bool addPreEmitPass() {
301 /// Utilities for targets to add passes to the pass manager.
304 /// Add a CodeGen pass at this point in the pipeline after checking overrides.
305 /// Return the pass that was added, or zero if no pass was added.
306 AnalysisID addPass(AnalysisID PassID);
308 /// Add a pass to the PassManager if that pass is supposed to be run, as
309 /// determined by the StartAfter and StopAfter options.
310 void addPass(Pass *P);
312 /// addMachinePasses helper to create the target-selected or overriden
314 FunctionPass *createRegAllocPass(bool Optimized);
316 /// printAndVerify - Add a pass to dump then verify the machine function, if
317 /// those steps are enabled.
319 void printAndVerify(const char *Banner);
323 /// List of target independent CodeGen pass IDs.
325 /// \brief Create a basic TargetTransformInfo analysis pass.
327 /// This pass implements the target transform info analysis using the target
328 /// independent information available to the LLVM code generator.
330 createBasicTargetTransformInfoPass(const TargetLoweringBase *TLI);
332 /// createUnreachableBlockEliminationPass - The LLVM code generator does not
333 /// work well with unreachable basic blocks (what live ranges make sense for a
334 /// block that cannot be reached?). As such, a code generator should either
335 /// not instruction select unreachable blocks, or run this pass as its
336 /// last LLVM modifying pass to clean up blocks that are not reachable from
338 FunctionPass *createUnreachableBlockEliminationPass();
340 /// MachineFunctionPrinter pass - This pass prints out the machine function to
341 /// the given stream as a debugging tool.
342 MachineFunctionPass *
343 createMachineFunctionPrinterPass(raw_ostream &OS,
344 const std::string &Banner ="");
346 /// MachineLoopInfo - This pass is a loop analysis pass.
347 extern char &MachineLoopInfoID;
349 /// MachineDominators - This pass is a machine dominators analysis pass.
350 extern char &MachineDominatorsID;
352 /// EdgeBundles analysis - Bundle machine CFG edges.
353 extern char &EdgeBundlesID;
355 /// LiveVariables pass - This pass computes the set of blocks in which each
356 /// variable is life and sets machine operand kill flags.
357 extern char &LiveVariablesID;
359 /// PHIElimination - This pass eliminates machine instruction PHI nodes
360 /// by inserting copy instructions. This destroys SSA information, but is the
361 /// desired input for some register allocators. This pass is "required" by
362 /// these register allocator like this: AU.addRequiredID(PHIEliminationID);
363 extern char &PHIEliminationID;
365 /// StrongPHIElimination - This pass eliminates machine instruction PHI
366 /// nodes by inserting copy instructions. This destroys SSA information, but
367 /// is the desired input for some register allocators. This pass is
368 /// "required" by these register allocator like this:
369 /// AU.addRequiredID(PHIEliminationID);
370 /// This pass is still in development
371 extern char &StrongPHIEliminationID;
373 /// LiveIntervals - This analysis keeps track of the live ranges of virtual
374 /// and physical registers.
375 extern char &LiveIntervalsID;
377 /// LiveStacks pass. An analysis keeping track of the liveness of stack slots.
378 extern char &LiveStacksID;
380 /// TwoAddressInstruction - This pass reduces two-address instructions to
381 /// use two operands. This destroys SSA information but it is desired by
382 /// register allocators.
383 extern char &TwoAddressInstructionPassID;
385 /// ProcessImpicitDefs pass - This pass removes IMPLICIT_DEFs.
386 extern char &ProcessImplicitDefsID;
388 /// RegisterCoalescer - This pass merges live ranges to eliminate copies.
389 extern char &RegisterCoalescerID;
391 /// MachineScheduler - This pass schedules machine instructions.
392 extern char &MachineSchedulerID;
394 /// SpillPlacement analysis. Suggest optimal placement of spill code between
396 extern char &SpillPlacementID;
398 /// VirtRegRewriter pass. Rewrite virtual registers to physical registers as
399 /// assigned in VirtRegMap.
400 extern char &VirtRegRewriterID;
402 /// UnreachableMachineBlockElimination - This pass removes unreachable
403 /// machine basic blocks.
404 extern char &UnreachableMachineBlockElimID;
406 /// DeadMachineInstructionElim - This pass removes dead machine instructions.
407 extern char &DeadMachineInstructionElimID;
409 /// FastRegisterAllocation Pass - This pass register allocates as fast as
410 /// possible. It is best suited for debug code where live ranges are short.
412 FunctionPass *createFastRegisterAllocator();
414 /// BasicRegisterAllocation Pass - This pass implements a degenerate global
415 /// register allocator using the basic regalloc framework.
417 FunctionPass *createBasicRegisterAllocator();
419 /// Greedy register allocation pass - This pass implements a global register
420 /// allocator for optimized builds.
422 FunctionPass *createGreedyRegisterAllocator();
424 /// PBQPRegisterAllocation Pass - This pass implements the Partitioned Boolean
425 /// Quadratic Prograaming (PBQP) based register allocator.
427 FunctionPass *createDefaultPBQPRegisterAllocator();
429 /// PrologEpilogCodeInserter - This pass inserts prolog and epilog code,
430 /// and eliminates abstract frame references.
431 extern char &PrologEpilogCodeInserterID;
433 /// ExpandPostRAPseudos - This pass expands pseudo instructions after
434 /// register allocation.
435 extern char &ExpandPostRAPseudosID;
437 /// createPostRAScheduler - This pass performs post register allocation
439 extern char &PostRASchedulerID;
441 /// BranchFolding - This pass performs machine code CFG based
442 /// optimizations to delete branches to branches, eliminate branches to
443 /// successor blocks (creating fall throughs), and eliminating branches over
445 extern char &BranchFolderPassID;
447 /// MachineFunctionPrinterPass - This pass prints out MachineInstr's.
448 extern char &MachineFunctionPrinterPassID;
450 /// TailDuplicate - Duplicate blocks with unconditional branches
451 /// into tails of their predecessors.
452 extern char &TailDuplicateID;
454 /// MachineTraceMetrics - This pass computes critical path and CPU resource
455 /// usage in an ensemble of traces.
456 extern char &MachineTraceMetricsID;
458 /// EarlyIfConverter - This pass performs if-conversion on SSA form by
459 /// inserting cmov instructions.
460 extern char &EarlyIfConverterID;
462 /// StackSlotColoring - This pass performs stack coloring and merging.
463 /// It merges disjoint allocas to reduce the stack size.
464 extern char &StackColoringID;
466 /// IfConverter - This pass performs machine code if conversion.
467 extern char &IfConverterID;
469 /// MachineBlockPlacement - This pass places basic blocks based on branch
471 extern char &MachineBlockPlacementID;
473 /// MachineBlockPlacementStats - This pass collects statistics about the
474 /// basic block placement using branch probabilities and block frequency
476 extern char &MachineBlockPlacementStatsID;
478 /// GCLowering Pass - Performs target-independent LLVM IR transformations for
479 /// highly portable strategies.
481 FunctionPass *createGCLoweringPass();
483 /// GCMachineCodeAnalysis - Target-independent pass to mark safe points
484 /// in machine code. Must be added very late during code generation, just
485 /// prior to output, and importantly after all CFG transformations (such as
487 extern char &GCMachineCodeAnalysisID;
489 /// Creates a pass to print GC metadata.
491 FunctionPass *createGCInfoPrinter(raw_ostream &OS);
493 /// MachineCSE - This pass performs global CSE on machine instructions.
494 extern char &MachineCSEID;
496 /// MachineLICM - This pass performs LICM on machine instructions.
497 extern char &MachineLICMID;
499 /// MachineSinking - This pass performs sinking on machine instructions.
500 extern char &MachineSinkingID;
502 /// MachineCopyPropagation - This pass performs copy propagation on
503 /// machine instructions.
504 extern char &MachineCopyPropagationID;
506 /// PeepholeOptimizer - This pass performs peephole optimizations -
507 /// like extension and comparison eliminations.
508 extern char &PeepholeOptimizerID;
510 /// OptimizePHIs - This pass optimizes machine instruction PHIs
511 /// to take advantage of opportunities created during DAG legalization.
512 extern char &OptimizePHIsID;
514 /// StackSlotColoring - This pass performs stack slot coloring.
515 extern char &StackSlotColoringID;
517 /// createStackProtectorPass - This pass adds stack protectors to functions.
519 FunctionPass *createStackProtectorPass(const TargetLoweringBase *tli);
521 /// createMachineVerifierPass - This pass verifies cenerated machine code
522 /// instructions for correctness.
524 FunctionPass *createMachineVerifierPass(const char *Banner = 0);
526 /// createDwarfEHPass - This pass mulches exception handling code into a form
527 /// adapted to code generation. Required if using dwarf exception handling.
528 FunctionPass *createDwarfEHPass(const TargetMachine *tm);
530 /// createSjLjEHPreparePass - This pass adapts exception handling code to use
531 /// the GCC-style builtin setjmp/longjmp (sjlj) to handling EH control flow.
533 FunctionPass *createSjLjEHPreparePass(const TargetLoweringBase *tli);
535 /// LocalStackSlotAllocation - This pass assigns local frame indices to stack
536 /// slots relative to one another and allocates base registers to access them
537 /// when it is estimated by the target to be out of range of normal frame
538 /// pointer or stack pointer index addressing.
539 extern char &LocalStackSlotAllocationID;
541 /// ExpandISelPseudos - This pass expands pseudo-instructions.
542 extern char &ExpandISelPseudosID;
544 /// createExecutionDependencyFixPass - This pass fixes execution time
545 /// problems with dependent instructions, such as switching execution
546 /// domains to match.
548 /// The pass will examine instructions using and defining registers in RC.
550 FunctionPass *createExecutionDependencyFixPass(const TargetRegisterClass *RC);
552 /// UnpackMachineBundles - This pass unpack machine instruction bundles.
553 extern char &UnpackMachineBundlesID;
555 /// FinalizeMachineBundles - This pass finalize machine instruction
556 /// bundles (created earlier, e.g. during pre-RA scheduling).
557 extern char &FinalizeMachineBundlesID;
559 } // End llvm namespace