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;
28 class ScheduleDAGInstrs;
30 class TargetLoweringBase;
31 class TargetRegisterClass;
33 struct MachineSchedContext;
35 // The old pass manager infrastructure is hidden in a legacy namespace now.
37 class PassManagerBase;
39 using legacy::PassManagerBase;
41 /// Discriminated union of Pass ID types.
43 /// The PassConfig API prefers dealing with IDs because they are safer and more
44 /// efficient. IDs decouple configuration from instantiation. This way, when a
45 /// pass is overriden, it isn't unnecessarily instantiated. It is also unsafe to
46 /// refer to a Pass pointer after adding it to a pass manager, which deletes
47 /// redundant pass instances.
49 /// However, it is convient to directly instantiate target passes with
50 /// non-default ctors. These often don't have a registered PassInfo. Rather than
51 /// force all target passes to implement the pass registry boilerplate, allow
52 /// the PassConfig API to handle either type.
54 /// AnalysisID is sadly char*, so PointerIntPair won't work.
55 class IdentifyingPassPtr {
62 IdentifyingPassPtr() : P(nullptr), IsInstance(false) {}
63 IdentifyingPassPtr(AnalysisID IDPtr) : ID(IDPtr), IsInstance(false) {}
64 IdentifyingPassPtr(Pass *InstancePtr) : P(InstancePtr), IsInstance(true) {}
66 bool isValid() const { return P; }
67 bool isInstance() const { return IsInstance; }
69 AnalysisID getID() const {
70 assert(!IsInstance && "Not a Pass ID");
73 Pass *getInstance() const {
74 assert(IsInstance && "Not a Pass Instance");
79 template <> struct isPodLike<IdentifyingPassPtr> {
80 static const bool value = true;
83 /// Target-Independent Code Generator Pass Configuration Options.
85 /// This is an ImmutablePass solely for the purpose of exposing CodeGen options
86 /// to the internals of other CodeGen passes.
87 class TargetPassConfig : public ImmutablePass {
89 /// Pseudo Pass IDs. These are defined within TargetPassConfig because they
90 /// are unregistered pass IDs. They are only useful for use with
91 /// TargetPassConfig APIs to identify multiple occurrences of the same pass.
94 /// EarlyTailDuplicate - A clone of the TailDuplicate pass that runs early
95 /// during codegen, on SSA form.
96 static char EarlyTailDuplicateID;
98 /// PostRAMachineLICM - A clone of the LICM pass that runs during late machine
99 /// optimization after regalloc.
100 static char PostRAMachineLICMID;
104 AnalysisID StartAfter;
105 AnalysisID StopAfter;
111 PassConfigImpl *Impl; // Internal data structures
112 bool Initialized; // Flagged after all passes are configured.
114 // Target Pass Options
115 // Targets provide a default setting, user flags override.
119 /// Default setting for -enable-tail-merge on this target.
120 bool EnableTailMerge;
123 TargetPassConfig(TargetMachine *tm, PassManagerBase &pm);
124 // Dummy constructor.
127 virtual ~TargetPassConfig();
131 /// Get the right type of TargetMachine for this target.
132 template<typename TMC> TMC &getTM() const {
133 return *static_cast<TMC*>(TM);
137 void setInitialized() { Initialized = true; }
139 CodeGenOpt::Level getOptLevel() const { return TM->getOptLevel(); }
141 /// setStartStopPasses - Set the StartAfter and StopAfter passes to allow
142 /// running only a portion of the normal code-gen pass sequence. If the
143 /// Start pass ID is zero, then compilation will begin at the normal point;
144 /// otherwise, clear the Started flag to indicate that passes should not be
145 /// added until the starting pass is seen. If the Stop pass ID is zero,
146 /// then compilation will continue to the end.
147 void setStartStopPasses(AnalysisID Start, AnalysisID Stop) {
150 Started = (StartAfter == nullptr);
153 void setDisableVerify(bool Disable) { setOpt(DisableVerify, Disable); }
155 bool getEnableTailMerge() const { return EnableTailMerge; }
156 void setEnableTailMerge(bool Enable) { setOpt(EnableTailMerge, Enable); }
158 /// Allow the target to override a specific pass without overriding the pass
159 /// pipeline. When passes are added to the standard pipeline at the
160 /// point where StandardID is expected, add TargetID in its place.
161 void substitutePass(AnalysisID StandardID, IdentifyingPassPtr TargetID);
163 /// Insert InsertedPassID pass after TargetPassID pass.
164 void insertPass(AnalysisID TargetPassID, IdentifyingPassPtr InsertedPassID);
166 /// Allow the target to enable a specific standard pass by default.
167 void enablePass(AnalysisID PassID) { substitutePass(PassID, PassID); }
169 /// Allow the target to disable a specific standard pass by default.
170 void disablePass(AnalysisID PassID) {
171 substitutePass(PassID, IdentifyingPassPtr());
174 /// Return the pass substituted for StandardID by the target.
175 /// If no substitution exists, return StandardID.
176 IdentifyingPassPtr getPassSubstitution(AnalysisID StandardID) const;
178 /// Return true if the optimized regalloc pipeline is enabled.
179 bool getOptimizeRegAlloc() const;
181 /// Return true if the default global register allocator is in use and
182 /// has not be overriden on the command line with '-regalloc=...'
183 bool usingDefaultRegAlloc() const;
185 /// Add common target configurable passes that perform LLVM IR to IR
186 /// transforms following machine independent optimization.
187 virtual void addIRPasses();
189 /// Add passes to lower exception handling for the code generator.
190 void addPassesToHandleExceptions();
192 /// Add pass to prepare the LLVM IR for code generation. This should be done
193 /// before exception handling preparation passes.
194 virtual void addCodeGenPrepare();
196 /// Add common passes that perform LLVM IR to IR transforms in preparation for
197 /// instruction selection.
198 virtual void addISelPrepare();
200 /// addInstSelector - This method should install an instruction selector pass,
201 /// which converts from LLVM code to machine instructions.
202 virtual bool addInstSelector() {
206 /// Add the complete, standard set of LLVM CodeGen passes.
207 /// Fully developed targets will not generally override this.
208 virtual void addMachinePasses();
210 /// Create an instance of ScheduleDAGInstrs to be run within the standard
211 /// MachineScheduler pass for this function and target at the current
212 /// optimization level.
214 /// This can also be used to plug a new MachineSchedStrategy into an instance
215 /// of the standard ScheduleDAGMI:
216 /// return new ScheduleDAGMI(C, new MyStrategy(C))
218 /// Return NULL to select the default (generic) machine scheduler.
219 virtual ScheduleDAGInstrs *
220 createMachineScheduler(MachineSchedContext *C) const {
224 /// Similar to createMachineScheduler but used when postRA machine scheduling
226 virtual ScheduleDAGInstrs *
227 createPostMachineScheduler(MachineSchedContext *C) const {
232 // Helper to verify the analysis is really immutable.
233 void setOpt(bool &Opt, bool Val);
235 /// Methods with trivial inline returns are convenient points in the common
236 /// codegen pass pipeline where targets may insert passes. Methods with
237 /// out-of-line standard implementations are major CodeGen stages called by
238 /// addMachinePasses. Some targets may override major stages when inserting
239 /// passes is insufficient, but maintaining overriden stages is more work.
242 /// addPreISelPasses - This method should add any "last minute" LLVM->LLVM
243 /// passes (which are run just before instruction selector).
244 virtual bool addPreISel() {
248 /// addMachineSSAOptimization - Add standard passes that optimize machine
249 /// instructions in SSA form.
250 virtual void addMachineSSAOptimization();
252 /// Add passes that optimize instruction level parallelism for out-of-order
253 /// targets. These passes are run while the machine code is still in SSA
254 /// form, so they can use MachineTraceMetrics to control their heuristics.
256 /// All passes added here should preserve the MachineDominatorTree,
257 /// MachineLoopInfo, and MachineTraceMetrics analyses.
258 virtual bool addILPOpts() {
262 /// addPreRegAlloc - This method may be implemented by targets that want to
263 /// run passes immediately before register allocation. This should return
264 /// true if -print-machineinstrs should print after these passes.
265 virtual bool addPreRegAlloc() {
269 /// createTargetRegisterAllocator - Create the register allocator pass for
270 /// this target at the current optimization level.
271 virtual FunctionPass *createTargetRegisterAllocator(bool Optimized);
273 /// addFastRegAlloc - Add the minimum set of target-independent passes that
274 /// are required for fast register allocation.
275 virtual void addFastRegAlloc(FunctionPass *RegAllocPass);
277 /// addOptimizedRegAlloc - Add passes related to register allocation.
278 /// LLVMTargetMachine provides standard regalloc passes for most targets.
279 virtual void addOptimizedRegAlloc(FunctionPass *RegAllocPass);
281 /// addPreRewrite - Add passes to the optimized register allocation pipeline
282 /// after register allocation is complete, but before virtual registers are
283 /// rewritten to physical registers.
285 /// These passes must preserve VirtRegMap and LiveIntervals, and when running
286 /// after RABasic or RAGreedy, they should take advantage of LiveRegMatrix.
287 /// When these passes run, VirtRegMap contains legal physreg assignments for
288 /// all virtual registers.
289 virtual bool addPreRewrite() {
293 /// addPostRegAlloc - This method may be implemented by targets that want to
294 /// run passes after register allocation pass pipeline but before
295 /// prolog-epilog insertion. This should return true if -print-machineinstrs
296 /// should print after these passes.
297 virtual bool addPostRegAlloc() {
301 /// Add passes that optimize machine instructions after register allocation.
302 virtual void addMachineLateOptimization();
304 /// addPreSched2 - This method may be implemented by targets that want to
305 /// run passes after prolog-epilog insertion and before the second instruction
306 /// scheduling pass. This should return true if -print-machineinstrs should
307 /// print after these passes.
308 virtual bool addPreSched2() {
312 /// addGCPasses - Add late codegen passes that analyze code for garbage
313 /// collection. This should return true if GC info should be printed after
315 virtual bool addGCPasses();
317 /// Add standard basic block placement passes.
318 virtual void addBlockPlacement();
320 /// addPreEmitPass - This pass may be implemented by targets that want to run
321 /// passes immediately before machine code is emitted. This should return
322 /// true if -print-machineinstrs should print out the code after the passes.
323 virtual bool addPreEmitPass() {
327 /// Utilities for targets to add passes to the pass manager.
330 /// Add a CodeGen pass at this point in the pipeline after checking overrides.
331 /// Return the pass that was added, or zero if no pass was added.
332 AnalysisID addPass(AnalysisID PassID);
334 /// Add a pass to the PassManager if that pass is supposed to be run, as
335 /// determined by the StartAfter and StopAfter options. Takes ownership of the
337 void addPass(Pass *P);
339 /// addMachinePasses helper to create the target-selected or overriden
341 FunctionPass *createRegAllocPass(bool Optimized);
343 /// printAndVerify - Add a pass to dump then verify the machine function, if
344 /// those steps are enabled.
346 void printAndVerify(const char *Banner);
350 /// List of target independent CodeGen pass IDs.
352 FunctionPass *createAtomicExpandPass(const TargetMachine *TM);
354 /// \brief Create a basic TargetTransformInfo analysis pass.
356 /// This pass implements the target transform info analysis using the target
357 /// independent information available to the LLVM code generator.
359 createBasicTargetTransformInfoPass(const TargetMachine *TM);
361 /// createUnreachableBlockEliminationPass - The LLVM code generator does not
362 /// work well with unreachable basic blocks (what live ranges make sense for a
363 /// block that cannot be reached?). As such, a code generator should either
364 /// not instruction select unreachable blocks, or run this pass as its
365 /// last LLVM modifying pass to clean up blocks that are not reachable from
367 FunctionPass *createUnreachableBlockEliminationPass();
369 /// MachineFunctionPrinter pass - This pass prints out the machine function to
370 /// the given stream as a debugging tool.
371 MachineFunctionPass *
372 createMachineFunctionPrinterPass(raw_ostream &OS,
373 const std::string &Banner ="");
375 /// createCodeGenPreparePass - Transform the code to expose more pattern
376 /// matching during instruction selection.
377 FunctionPass *createCodeGenPreparePass(const TargetMachine *TM = nullptr);
379 /// AtomicExpandID -- Lowers atomic operations in terms of either cmpxchg
380 /// load-linked/store-conditional loops.
381 extern char &AtomicExpandID;
383 /// MachineLoopInfo - This pass is a loop analysis pass.
384 extern char &MachineLoopInfoID;
386 /// MachineDominators - This pass is a machine dominators analysis pass.
387 extern char &MachineDominatorsID;
389 /// MachineDominanaceFrontier - This pass is a machine dominators analysis pass.
390 extern char &MachineDominanceFrontierID;
392 /// EdgeBundles analysis - Bundle machine CFG edges.
393 extern char &EdgeBundlesID;
395 /// LiveVariables pass - This pass computes the set of blocks in which each
396 /// variable is life and sets machine operand kill flags.
397 extern char &LiveVariablesID;
399 /// PHIElimination - This pass eliminates machine instruction PHI nodes
400 /// by inserting copy instructions. This destroys SSA information, but is the
401 /// desired input for some register allocators. This pass is "required" by
402 /// these register allocator like this: AU.addRequiredID(PHIEliminationID);
403 extern char &PHIEliminationID;
405 /// LiveIntervals - This analysis keeps track of the live ranges of virtual
406 /// and physical registers.
407 extern char &LiveIntervalsID;
409 /// LiveStacks pass. An analysis keeping track of the liveness of stack slots.
410 extern char &LiveStacksID;
412 /// TwoAddressInstruction - This pass reduces two-address instructions to
413 /// use two operands. This destroys SSA information but it is desired by
414 /// register allocators.
415 extern char &TwoAddressInstructionPassID;
417 /// ProcessImpicitDefs pass - This pass removes IMPLICIT_DEFs.
418 extern char &ProcessImplicitDefsID;
420 /// RegisterCoalescer - This pass merges live ranges to eliminate copies.
421 extern char &RegisterCoalescerID;
423 /// MachineScheduler - This pass schedules machine instructions.
424 extern char &MachineSchedulerID;
426 /// PostMachineScheduler - This pass schedules machine instructions postRA.
427 extern char &PostMachineSchedulerID;
429 /// SpillPlacement analysis. Suggest optimal placement of spill code between
431 extern char &SpillPlacementID;
433 /// VirtRegRewriter pass. Rewrite virtual registers to physical registers as
434 /// assigned in VirtRegMap.
435 extern char &VirtRegRewriterID;
437 /// UnreachableMachineBlockElimination - This pass removes unreachable
438 /// machine basic blocks.
439 extern char &UnreachableMachineBlockElimID;
441 /// DeadMachineInstructionElim - This pass removes dead machine instructions.
442 extern char &DeadMachineInstructionElimID;
444 /// FastRegisterAllocation Pass - This pass register allocates as fast as
445 /// possible. It is best suited for debug code where live ranges are short.
447 FunctionPass *createFastRegisterAllocator();
449 /// BasicRegisterAllocation Pass - This pass implements a degenerate global
450 /// register allocator using the basic regalloc framework.
452 FunctionPass *createBasicRegisterAllocator();
454 /// Greedy register allocation pass - This pass implements a global register
455 /// allocator for optimized builds.
457 FunctionPass *createGreedyRegisterAllocator();
459 /// PBQPRegisterAllocation Pass - This pass implements the Partitioned Boolean
460 /// Quadratic Prograaming (PBQP) based register allocator.
462 FunctionPass *createDefaultPBQPRegisterAllocator();
464 /// PrologEpilogCodeInserter - This pass inserts prolog and epilog code,
465 /// and eliminates abstract frame references.
466 extern char &PrologEpilogCodeInserterID;
468 /// ExpandPostRAPseudos - This pass expands pseudo instructions after
469 /// register allocation.
470 extern char &ExpandPostRAPseudosID;
472 /// createPostRAScheduler - This pass performs post register allocation
474 extern char &PostRASchedulerID;
476 /// BranchFolding - This pass performs machine code CFG based
477 /// optimizations to delete branches to branches, eliminate branches to
478 /// successor blocks (creating fall throughs), and eliminating branches over
480 extern char &BranchFolderPassID;
482 /// MachineFunctionPrinterPass - This pass prints out MachineInstr's.
483 extern char &MachineFunctionPrinterPassID;
485 /// TailDuplicate - Duplicate blocks with unconditional branches
486 /// into tails of their predecessors.
487 extern char &TailDuplicateID;
489 /// MachineTraceMetrics - This pass computes critical path and CPU resource
490 /// usage in an ensemble of traces.
491 extern char &MachineTraceMetricsID;
493 /// EarlyIfConverter - This pass performs if-conversion on SSA form by
494 /// inserting cmov instructions.
495 extern char &EarlyIfConverterID;
497 /// This pass performs instruction combining using trace metrics to estimate
498 /// critical-path and resource depth.
499 extern char &MachineCombinerID;
501 /// StackSlotColoring - This pass performs stack coloring and merging.
502 /// It merges disjoint allocas to reduce the stack size.
503 extern char &StackColoringID;
505 /// IfConverter - This pass performs machine code if conversion.
506 extern char &IfConverterID;
508 /// MachineBlockPlacement - This pass places basic blocks based on branch
510 extern char &MachineBlockPlacementID;
512 /// MachineBlockPlacementStats - This pass collects statistics about the
513 /// basic block placement using branch probabilities and block frequency
515 extern char &MachineBlockPlacementStatsID;
517 /// GCLowering Pass - Performs target-independent LLVM IR transformations for
518 /// highly portable strategies.
520 FunctionPass *createGCLoweringPass();
522 /// GCMachineCodeAnalysis - Target-independent pass to mark safe points
523 /// in machine code. Must be added very late during code generation, just
524 /// prior to output, and importantly after all CFG transformations (such as
526 extern char &GCMachineCodeAnalysisID;
528 /// Creates a pass to print GC metadata.
530 FunctionPass *createGCInfoPrinter(raw_ostream &OS);
532 /// MachineCSE - This pass performs global CSE on machine instructions.
533 extern char &MachineCSEID;
535 /// MachineLICM - This pass performs LICM on machine instructions.
536 extern char &MachineLICMID;
538 /// MachineSinking - This pass performs sinking on machine instructions.
539 extern char &MachineSinkingID;
541 /// MachineCopyPropagation - This pass performs copy propagation on
542 /// machine instructions.
543 extern char &MachineCopyPropagationID;
545 /// PeepholeOptimizer - This pass performs peephole optimizations -
546 /// like extension and comparison eliminations.
547 extern char &PeepholeOptimizerID;
549 /// OptimizePHIs - This pass optimizes machine instruction PHIs
550 /// to take advantage of opportunities created during DAG legalization.
551 extern char &OptimizePHIsID;
553 /// StackSlotColoring - This pass performs stack slot coloring.
554 extern char &StackSlotColoringID;
556 /// createStackProtectorPass - This pass adds stack protectors to functions.
558 FunctionPass *createStackProtectorPass(const TargetMachine *TM);
560 /// createMachineVerifierPass - This pass verifies cenerated machine code
561 /// instructions for correctness.
563 FunctionPass *createMachineVerifierPass(const char *Banner = nullptr);
565 /// createDwarfEHPass - This pass mulches exception handling code into a form
566 /// adapted to code generation. Required if using dwarf exception handling.
567 FunctionPass *createDwarfEHPass(const TargetMachine *TM);
569 /// createSjLjEHPreparePass - This pass adapts exception handling code to use
570 /// the GCC-style builtin setjmp/longjmp (sjlj) to handling EH control flow.
572 FunctionPass *createSjLjEHPreparePass(const TargetMachine *TM);
574 /// LocalStackSlotAllocation - This pass assigns local frame indices to stack
575 /// slots relative to one another and allocates base registers to access them
576 /// when it is estimated by the target to be out of range of normal frame
577 /// pointer or stack pointer index addressing.
578 extern char &LocalStackSlotAllocationID;
580 /// ExpandISelPseudos - This pass expands pseudo-instructions.
581 extern char &ExpandISelPseudosID;
583 /// createExecutionDependencyFixPass - This pass fixes execution time
584 /// problems with dependent instructions, such as switching execution
585 /// domains to match.
587 /// The pass will examine instructions using and defining registers in RC.
589 FunctionPass *createExecutionDependencyFixPass(const TargetRegisterClass *RC);
591 /// UnpackMachineBundles - This pass unpack machine instruction bundles.
592 extern char &UnpackMachineBundlesID;
594 /// FinalizeMachineBundles - This pass finalize machine instruction
595 /// bundles (created earlier, e.g. during pre-RA scheduling).
596 extern char &FinalizeMachineBundlesID;
598 /// StackMapLiveness - This pass analyses the register live-out set of
599 /// stackmap/patchpoint intrinsics and attaches the calculated information to
600 /// the intrinsic for later emission to the StackMap.
601 extern char &StackMapLivenessID;
603 /// createJumpInstrTables - This pass creates jump-instruction tables.
604 ModulePass *createJumpInstrTablesPass();
605 } // End llvm namespace
607 /// This initializer registers TargetMachine constructor, so the pass being
608 /// initialized can use target dependent interfaces. Please do not move this
609 /// macro to be together with INITIALIZE_PASS, which is a complete target
610 /// independent initializer, and we don't want to make libScalarOpts depend
612 #define INITIALIZE_TM_PASS(passName, arg, name, cfg, analysis) \
613 static void* initialize##passName##PassOnce(PassRegistry &Registry) { \
614 PassInfo *PI = new PassInfo(name, arg, & passName ::ID, \
615 PassInfo::NormalCtor_t(callDefaultCtor< passName >), cfg, analysis, \
616 PassInfo::TargetMachineCtor_t(callTargetMachineCtor< passName >)); \
617 Registry.registerPass(*PI, true); \
620 void llvm::initialize##passName##Pass(PassRegistry &Registry) { \
621 CALL_ONCE_INITIALIZATION(initialize##passName##PassOnce) \