blob: ab9241678997a942cf9ac9760c0141066b47c3ba [file] [log] [blame]
Chris Lattneraa4c91f2003-12-28 07:59:53 +00001//===-- Passes.cpp - Target independent code generation passes ------------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanedf128a2005-04-21 22:36:52 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Alkis Evlogimenos7237ece2003-10-02 16:57:49 +00009//
10// This file defines interfaces to access the target independent code
11// generation passes provided by the LLVM backend.
12//
13//===---------------------------------------------------------------------===//
14
Andrew Trickd5422652012-02-04 02:56:48 +000015#include "llvm/Analysis/Passes.h"
16#include "llvm/Analysis/Verifier.h"
17#include "llvm/Transforms/Scalar.h"
18#include "llvm/PassManager.h"
19#include "llvm/CodeGen/GCStrategy.h"
Andrew Trickd5422652012-02-04 02:56:48 +000020#include "llvm/CodeGen/MachineFunctionPass.h"
Alkis Evlogimenos7237ece2003-10-02 16:57:49 +000021#include "llvm/CodeGen/Passes.h"
Andrew Trickd5422652012-02-04 02:56:48 +000022#include "llvm/CodeGen/RegAllocRegistry.h"
23#include "llvm/Target/TargetLowering.h"
Andrew Trickd5422652012-02-04 02:56:48 +000024#include "llvm/Target/TargetOptions.h"
Bob Wilson564fbf62012-07-02 19:48:31 +000025#include "llvm/MC/MCAsmInfo.h"
Andrew Trickd5422652012-02-04 02:56:48 +000026#include "llvm/Assembly/PrintModulePass.h"
27#include "llvm/Support/CommandLine.h"
28#include "llvm/Support/Debug.h"
Andrew Trick74613342012-02-04 02:56:45 +000029#include "llvm/Support/ErrorHandling.h"
Jim Laskey13ec7022006-08-01 14:21:23 +000030
Chris Lattneraa4c91f2003-12-28 07:59:53 +000031using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000032
Andrew Trickd5422652012-02-04 02:56:48 +000033static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
34 cl::desc("Disable Post Regalloc"));
35static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
36 cl::desc("Disable branch folding"));
37static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
38 cl::desc("Disable tail duplication"));
39static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
40 cl::desc("Disable pre-register allocation tail duplication"));
Chandler Carruth9e67db42012-04-16 13:49:17 +000041static cl::opt<bool> DisableBlockPlacement("disable-block-placement",
42 cl::Hidden, cl::desc("Disable the probability-driven block placement, and "
43 "re-enable the old code placement pass"));
Andrew Trickd5422652012-02-04 02:56:48 +000044static cl::opt<bool> EnableBlockPlacementStats("enable-block-placement-stats",
45 cl::Hidden, cl::desc("Collect probability-driven block placement stats"));
46static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden,
47 cl::desc("Disable code placement"));
48static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
49 cl::desc("Disable Stack Slot Coloring"));
50static cl::opt<bool> DisableMachineDCE("disable-machine-dce", cl::Hidden,
51 cl::desc("Disable Machine Dead Code Elimination"));
52static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
53 cl::desc("Disable Machine LICM"));
54static cl::opt<bool> DisableMachineCSE("disable-machine-cse", cl::Hidden,
55 cl::desc("Disable Machine Common Subexpression Elimination"));
Andrew Trick8dd26252012-02-10 04:10:36 +000056static cl::opt<cl::boolOrDefault>
57OptimizeRegAlloc("optimize-regalloc", cl::Hidden,
58 cl::desc("Enable optimized register allocation compilation path."));
Andrew Trick746f24b2012-02-11 07:11:32 +000059static cl::opt<cl::boolOrDefault>
60EnableMachineSched("enable-misched", cl::Hidden,
Andrew Trick8dd26252012-02-10 04:10:36 +000061 cl::desc("Enable the machine instruction scheduling pass."));
62static cl::opt<bool> EnableStrongPHIElim("strong-phi-elim", cl::Hidden,
63 cl::desc("Use strong PHI elimination."));
Andrew Trickd5422652012-02-04 02:56:48 +000064static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm",
65 cl::Hidden,
66 cl::desc("Disable Machine LICM"));
67static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
68 cl::desc("Disable Machine Sinking"));
69static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
70 cl::desc("Disable Loop Strength Reduction Pass"));
71static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
72 cl::desc("Disable Codegen Prepare"));
73static cl::opt<bool> DisableCopyProp("disable-copyprop", cl::Hidden,
Evan Cheng01b623c2012-02-20 23:28:17 +000074 cl::desc("Disable Copy Propagation pass"));
Andrew Trickd5422652012-02-04 02:56:48 +000075static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
76 cl::desc("Print LLVM IR produced by the loop-reduce pass"));
77static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
78 cl::desc("Print LLVM IR input to isel pass"));
79static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
80 cl::desc("Dump garbage collector data"));
81static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
82 cl::desc("Verify generated machine code"),
83 cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
Bob Wilson6e1b8122012-05-30 00:17:12 +000084static cl::opt<std::string>
85PrintMachineInstrs("print-machineinstrs", cl::ValueOptional,
86 cl::desc("Print machine instrs"),
87 cl::value_desc("pass-name"), cl::init("option-unspecified"));
Andrew Trickd5422652012-02-04 02:56:48 +000088
Andrew Trick79bf2882012-02-15 03:21:51 +000089/// Allow standard passes to be disabled by command line options. This supports
90/// simple binary flags that either suppress the pass or do nothing.
91/// i.e. -disable-mypass=false has no effect.
92/// These should be converted to boolOrDefault in order to use applyOverride.
93static AnalysisID applyDisable(AnalysisID ID, bool Override) {
94 if (Override)
95 return &NoPassID;
96 return ID;
97}
98
99/// Allow Pass selection to be overriden by command line options. This supports
100/// flags with ternary conditions. TargetID is passed through by default. The
101/// pass is suppressed when the option is false. When the option is true, the
102/// StandardID is selected if the target provides no default.
103static AnalysisID applyOverride(AnalysisID TargetID, cl::boolOrDefault Override,
104 AnalysisID StandardID) {
Andrew Trick746f24b2012-02-11 07:11:32 +0000105 switch (Override) {
106 case cl::BOU_UNSET:
Andrew Trick79bf2882012-02-15 03:21:51 +0000107 return TargetID;
Andrew Trick746f24b2012-02-11 07:11:32 +0000108 case cl::BOU_TRUE:
Andrew Trick79bf2882012-02-15 03:21:51 +0000109 if (TargetID != &NoPassID)
110 return TargetID;
111 if (StandardID == &NoPassID)
Andrew Trick746f24b2012-02-11 07:11:32 +0000112 report_fatal_error("Target cannot enable pass");
Andrew Trick79bf2882012-02-15 03:21:51 +0000113 return StandardID;
Andrew Trick746f24b2012-02-11 07:11:32 +0000114 case cl::BOU_FALSE:
Andrew Trick79bf2882012-02-15 03:21:51 +0000115 return &NoPassID;
Andrew Trick746f24b2012-02-11 07:11:32 +0000116 }
117 llvm_unreachable("Invalid command line option state");
118}
119
Andrew Trick79bf2882012-02-15 03:21:51 +0000120/// Allow standard passes to be disabled by the command line, regardless of who
121/// is adding the pass.
122///
123/// StandardID is the pass identified in the standard pass pipeline and provided
124/// to addPass(). It may be a target-specific ID in the case that the target
125/// directly adds its own pass, but in that case we harmlessly fall through.
126///
127/// TargetID is the pass that the target has configured to override StandardID.
128///
129/// StandardID may be a pseudo ID. In that case TargetID is the name of the real
130/// pass to run. This allows multiple options to control a single pass depending
131/// on where in the pipeline that pass is added.
132static AnalysisID overridePass(AnalysisID StandardID, AnalysisID TargetID) {
133 if (StandardID == &PostRASchedulerID)
134 return applyDisable(TargetID, DisablePostRA);
135
136 if (StandardID == &BranchFolderPassID)
137 return applyDisable(TargetID, DisableBranchFold);
138
139 if (StandardID == &TailDuplicateID)
140 return applyDisable(TargetID, DisableTailDuplicate);
141
142 if (StandardID == &TargetPassConfig::EarlyTailDuplicateID)
143 return applyDisable(TargetID, DisableEarlyTailDup);
144
145 if (StandardID == &MachineBlockPlacementID)
146 return applyDisable(TargetID, DisableCodePlace);
147
148 if (StandardID == &CodePlacementOptID)
149 return applyDisable(TargetID, DisableCodePlace);
150
151 if (StandardID == &StackSlotColoringID)
152 return applyDisable(TargetID, DisableSSC);
153
154 if (StandardID == &DeadMachineInstructionElimID)
155 return applyDisable(TargetID, DisableMachineDCE);
156
157 if (StandardID == &MachineLICMID)
158 return applyDisable(TargetID, DisableMachineLICM);
159
160 if (StandardID == &MachineCSEID)
161 return applyDisable(TargetID, DisableMachineCSE);
162
163 if (StandardID == &MachineSchedulerID)
164 return applyOverride(TargetID, EnableMachineSched, StandardID);
165
166 if (StandardID == &TargetPassConfig::PostRAMachineLICMID)
167 return applyDisable(TargetID, DisablePostRAMachineLICM);
168
169 if (StandardID == &MachineSinkingID)
170 return applyDisable(TargetID, DisableMachineSink);
171
172 if (StandardID == &MachineCopyPropagationID)
173 return applyDisable(TargetID, DisableCopyProp);
174
175 return TargetID;
176}
177
Jim Laskeyeb577ba2006-08-02 12:30:23 +0000178//===---------------------------------------------------------------------===//
Andrew Trick74613342012-02-04 02:56:45 +0000179/// TargetPassConfig
180//===---------------------------------------------------------------------===//
181
182INITIALIZE_PASS(TargetPassConfig, "targetpassconfig",
183 "Target Pass Configuration", false, false)
184char TargetPassConfig::ID = 0;
185
Andrew Trick746f24b2012-02-11 07:11:32 +0000186static char NoPassIDAnchor = 0;
187char &llvm::NoPassID = NoPassIDAnchor;
188
Andrew Trick79bf2882012-02-15 03:21:51 +0000189// Pseudo Pass IDs.
190char TargetPassConfig::EarlyTailDuplicateID = 0;
191char TargetPassConfig::PostRAMachineLICMID = 0;
192
Andrew Trick5e108ee2012-02-15 03:21:47 +0000193namespace llvm {
194class PassConfigImpl {
195public:
196 // List of passes explicitly substituted by this target. Normally this is
197 // empty, but it is a convenient way to suppress or replace specific passes
198 // that are part of a standard pass pipeline without overridding the entire
199 // pipeline. This mechanism allows target options to inherit a standard pass's
200 // user interface. For example, a target may disable a standard pass by
201 // default by substituting NoPass, and the user may still enable that standard
202 // pass with an explicit command line option.
203 DenseMap<AnalysisID,AnalysisID> TargetPasses;
Bob Wilson6e1b8122012-05-30 00:17:12 +0000204
205 /// Store the pairs of <AnalysisID, AnalysisID> of which the second pass
206 /// is inserted after each instance of the first one.
207 SmallVector<std::pair<AnalysisID, AnalysisID>, 4> InsertedPasses;
Andrew Trick5e108ee2012-02-15 03:21:47 +0000208};
209} // namespace llvm
210
Andrew Trick74613342012-02-04 02:56:45 +0000211// Out of line virtual method.
Andrew Trick5e108ee2012-02-15 03:21:47 +0000212TargetPassConfig::~TargetPassConfig() {
213 delete Impl;
214}
Andrew Trick74613342012-02-04 02:56:45 +0000215
Andrew Trick61f1e3d2012-02-08 21:22:48 +0000216// Out of line constructor provides default values for pass options and
217// registers all common codegen passes.
Andrew Trick061efcf2012-02-04 02:56:59 +0000218TargetPassConfig::TargetPassConfig(TargetMachine *tm, PassManagerBase &pm)
Bob Wilson564fbf62012-07-02 19:48:31 +0000219 : ImmutablePass(ID), PM(&pm), TM(tm), Impl(0), Initialized(false),
Andrew Trickffea03f2012-02-08 21:22:39 +0000220 DisableVerify(false),
221 EnableTailMerge(true) {
222
Andrew Trick5e108ee2012-02-15 03:21:47 +0000223 Impl = new PassConfigImpl();
224
Andrew Trick74613342012-02-04 02:56:45 +0000225 // Register all target independent codegen passes to activate their PassIDs,
226 // including this pass itself.
227 initializeCodeGen(*PassRegistry::getPassRegistry());
Andrew Trick79bf2882012-02-15 03:21:51 +0000228
229 // Substitute Pseudo Pass IDs for real ones.
230 substitutePass(EarlyTailDuplicateID, TailDuplicateID);
231 substitutePass(PostRAMachineLICMID, MachineLICMID);
232
233 // Temporarily disable experimental passes.
234 substitutePass(MachineSchedulerID, NoPassID);
Andrew Trick74613342012-02-04 02:56:45 +0000235}
236
Bob Wilson6e1b8122012-05-30 00:17:12 +0000237/// Insert InsertedPassID pass after TargetPassID.
238void TargetPassConfig::insertPass(const char &TargetPassID,
239 const char &InsertedPassID) {
240 assert(&TargetPassID != &InsertedPassID && "Insert a pass after itself!");
241 std::pair<AnalysisID, AnalysisID> P(&TargetPassID, &InsertedPassID);
242 Impl->InsertedPasses.push_back(P);
243}
244
Andrew Trick74613342012-02-04 02:56:45 +0000245/// createPassConfig - Create a pass configuration object to be used by
246/// addPassToEmitX methods for generating a pipeline of CodeGen passes.
247///
248/// Targets may override this to extend TargetPassConfig.
Andrew Trick061efcf2012-02-04 02:56:59 +0000249TargetPassConfig *LLVMTargetMachine::createPassConfig(PassManagerBase &PM) {
250 return new TargetPassConfig(this, PM);
Andrew Trick74613342012-02-04 02:56:45 +0000251}
252
253TargetPassConfig::TargetPassConfig()
Bill Wendling7c4ce302012-05-01 08:27:43 +0000254 : ImmutablePass(ID), PM(0) {
Andrew Trick74613342012-02-04 02:56:45 +0000255 llvm_unreachable("TargetPassConfig should not be constructed on-the-fly");
256}
257
Andrew Trickffea03f2012-02-08 21:22:39 +0000258// Helper to verify the analysis is really immutable.
259void TargetPassConfig::setOpt(bool &Opt, bool Val) {
260 assert(!Initialized && "PassConfig is immutable");
261 Opt = Val;
262}
263
Andrew Trick5e108ee2012-02-15 03:21:47 +0000264void TargetPassConfig::substitutePass(char &StandardID, char &TargetID) {
265 Impl->TargetPasses[&StandardID] = &TargetID;
266}
Andrew Trick746f24b2012-02-11 07:11:32 +0000267
Andrew Trick5e108ee2012-02-15 03:21:47 +0000268AnalysisID TargetPassConfig::getPassSubstitution(AnalysisID ID) const {
269 DenseMap<AnalysisID, AnalysisID>::const_iterator
270 I = Impl->TargetPasses.find(ID);
271 if (I == Impl->TargetPasses.end())
272 return ID;
273 return I->second;
274}
275
Bob Wilson564fbf62012-07-02 19:48:31 +0000276/// Add a pass to the PassManager.
277void TargetPassConfig::addPass(Pass *P) {
278 PM->add(P);
279}
280
Andrew Trick5e108ee2012-02-15 03:21:47 +0000281/// Add a CodeGen pass at this point in the pipeline after checking for target
282/// and command line overrides.
283AnalysisID TargetPassConfig::addPass(char &ID) {
284 assert(!Initialized && "PassConfig is immutable");
285
Andrew Trick79bf2882012-02-15 03:21:51 +0000286 AnalysisID TargetID = getPassSubstitution(&ID);
287 AnalysisID FinalID = overridePass(&ID, TargetID);
Andrew Trick5e108ee2012-02-15 03:21:47 +0000288 if (FinalID == &NoPassID)
289 return FinalID;
290
291 Pass *P = Pass::createPass(FinalID);
Andrew Trickebe18ef2012-02-08 21:22:34 +0000292 if (!P)
293 llvm_unreachable("Pass ID not registered");
Bob Wilson564fbf62012-07-02 19:48:31 +0000294 addPass(P);
Bob Wilson6e1b8122012-05-30 00:17:12 +0000295 // Add the passes after the pass P if there is any.
296 for (SmallVector<std::pair<AnalysisID, AnalysisID>, 4>::iterator
297 I = Impl->InsertedPasses.begin(), E = Impl->InsertedPasses.end();
298 I != E; ++I) {
299 if ((*I).first == &ID) {
300 assert((*I).second && "Illegal Pass ID!");
301 Pass *NP = Pass::createPass((*I).second);
302 assert(NP && "Pass ID not registered");
Bob Wilson564fbf62012-07-02 19:48:31 +0000303 addPass(NP);
Bob Wilson6e1b8122012-05-30 00:17:12 +0000304 }
305 }
Andrew Trick5e108ee2012-02-15 03:21:47 +0000306 return FinalID;
Andrew Trick061efcf2012-02-04 02:56:59 +0000307}
Andrew Trickd5422652012-02-04 02:56:48 +0000308
Bob Wilson564fbf62012-07-02 19:48:31 +0000309void TargetPassConfig::printAndVerify(const char *Banner) {
Andrew Trickd5422652012-02-04 02:56:48 +0000310 if (TM->shouldPrintMachineCode())
Bob Wilson564fbf62012-07-02 19:48:31 +0000311 addPass(createMachineFunctionPrinterPass(dbgs(), Banner));
Andrew Trickd5422652012-02-04 02:56:48 +0000312
313 if (VerifyMachineCode)
Bob Wilson564fbf62012-07-02 19:48:31 +0000314 addPass(createMachineVerifierPass(Banner));
Andrew Trickd5422652012-02-04 02:56:48 +0000315}
316
Andrew Trick061efcf2012-02-04 02:56:59 +0000317/// Add common target configurable passes that perform LLVM IR to IR transforms
318/// following machine independent optimization.
319void TargetPassConfig::addIRPasses() {
Andrew Trickd5422652012-02-04 02:56:48 +0000320 // Basic AliasAnalysis support.
321 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
322 // BasicAliasAnalysis wins if they disagree. This is intended to help
323 // support "obvious" type-punning idioms.
Bob Wilson564fbf62012-07-02 19:48:31 +0000324 addPass(createTypeBasedAliasAnalysisPass());
325 addPass(createBasicAliasAnalysisPass());
Andrew Trickd5422652012-02-04 02:56:48 +0000326
327 // Before running any passes, run the verifier to determine if the input
328 // coming from the front-end and/or optimizer is valid.
329 if (!DisableVerify)
Bob Wilson564fbf62012-07-02 19:48:31 +0000330 addPass(createVerifierPass());
Andrew Trickd5422652012-02-04 02:56:48 +0000331
332 // Run loop strength reduction before anything else.
333 if (getOptLevel() != CodeGenOpt::None && !DisableLSR) {
Bob Wilson564fbf62012-07-02 19:48:31 +0000334 addPass(createLoopStrengthReducePass(getTargetLowering()));
Andrew Trickd5422652012-02-04 02:56:48 +0000335 if (PrintLSR)
Bob Wilson564fbf62012-07-02 19:48:31 +0000336 addPass(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
Andrew Trickd5422652012-02-04 02:56:48 +0000337 }
338
Bob Wilson564fbf62012-07-02 19:48:31 +0000339 addPass(createGCLoweringPass());
Andrew Trickd5422652012-02-04 02:56:48 +0000340
341 // Make sure that no unreachable blocks are instruction selected.
Bob Wilson564fbf62012-07-02 19:48:31 +0000342 addPass(createUnreachableBlockEliminationPass());
343}
344
345/// Turn exception handling constructs into something the code generators can
346/// handle.
347void TargetPassConfig::addPassesToHandleExceptions() {
348 switch (TM->getMCAsmInfo()->getExceptionHandlingType()) {
349 case ExceptionHandling::SjLj:
350 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
351 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
352 // catch info can get misplaced when a selector ends up more than one block
353 // removed from the parent invoke(s). This could happen when a landing
354 // pad is shared by multiple invokes and is also a target of a normal
355 // edge from elsewhere.
356 addPass(createSjLjEHPreparePass(TM->getTargetLowering()));
357 // FALLTHROUGH
358 case ExceptionHandling::DwarfCFI:
359 case ExceptionHandling::ARM:
360 case ExceptionHandling::Win64:
361 addPass(createDwarfEHPass(TM));
362 break;
363 case ExceptionHandling::None:
364 addPass(createLowerInvokePass(TM->getTargetLowering()));
365
366 // The lower invoke pass may create unreachable code. Remove it.
367 addPass(createUnreachableBlockEliminationPass());
368 break;
369 }
Andrew Trick061efcf2012-02-04 02:56:59 +0000370}
Andrew Trickd5422652012-02-04 02:56:48 +0000371
Andrew Trick061efcf2012-02-04 02:56:59 +0000372/// Add common passes that perform LLVM IR to IR transforms in preparation for
373/// instruction selection.
374void TargetPassConfig::addISelPrepare() {
Andrew Trickd5422652012-02-04 02:56:48 +0000375 if (getOptLevel() != CodeGenOpt::None && !DisableCGP)
Bob Wilson564fbf62012-07-02 19:48:31 +0000376 addPass(createCodeGenPreparePass(getTargetLowering()));
Andrew Trickd5422652012-02-04 02:56:48 +0000377
Bob Wilson564fbf62012-07-02 19:48:31 +0000378 addPass(createStackProtectorPass(getTargetLowering()));
Andrew Trickd5422652012-02-04 02:56:48 +0000379
380 addPreISel();
381
382 if (PrintISelInput)
Bob Wilson564fbf62012-07-02 19:48:31 +0000383 addPass(createPrintFunctionPass("\n\n"
Bill Wendling7c4ce302012-05-01 08:27:43 +0000384 "*** Final LLVM Code input to ISel ***\n",
385 &dbgs()));
Andrew Trickd5422652012-02-04 02:56:48 +0000386
387 // All passes which modify the LLVM IR are now complete; run the verifier
388 // to ensure that the IR is valid.
389 if (!DisableVerify)
Bob Wilson564fbf62012-07-02 19:48:31 +0000390 addPass(createVerifierPass());
Andrew Trick061efcf2012-02-04 02:56:59 +0000391}
Andrew Trickd5422652012-02-04 02:56:48 +0000392
Andrew Trickf7b96312012-02-09 00:40:55 +0000393/// Add the complete set of target-independent postISel code generator passes.
394///
395/// This can be read as the standard order of major LLVM CodeGen stages. Stages
396/// with nontrivial configuration or multiple passes are broken out below in
397/// add%Stage routines.
398///
399/// Any TargetPassConfig::addXX routine may be overriden by the Target. The
400/// addPre/Post methods with empty header implementations allow injecting
401/// target-specific fixups just before or after major stages. Additionally,
402/// targets have the flexibility to change pass order within a stage by
403/// overriding default implementation of add%Stage routines below. Each
404/// technique has maintainability tradeoffs because alternate pass orders are
405/// not well supported. addPre/Post works better if the target pass is easily
406/// tied to a common pass. But if it has subtle dependencies on multiple passes,
Andrew Trick06efdd22012-02-10 07:08:25 +0000407/// the target should override the stage instead.
Andrew Trickf7b96312012-02-09 00:40:55 +0000408///
409/// TODO: We could use a single addPre/Post(ID) hook to allow pass injection
410/// before/after any target-independent pass. But it's currently overkill.
Andrew Trick061efcf2012-02-04 02:56:59 +0000411void TargetPassConfig::addMachinePasses() {
Andrew Trickd5422652012-02-04 02:56:48 +0000412 // Print the instruction selected machine code...
413 printAndVerify("After Instruction Selection");
414
Bob Wilson6e1b8122012-05-30 00:17:12 +0000415 // Insert a machine instr printer pass after the specified pass.
416 // If -print-machineinstrs specified, print machineinstrs after all passes.
417 if (StringRef(PrintMachineInstrs.getValue()).equals(""))
418 TM->Options.PrintMachineCode = true;
419 else if (!StringRef(PrintMachineInstrs.getValue())
420 .equals("option-unspecified")) {
421 const PassRegistry *PR = PassRegistry::getPassRegistry();
422 const PassInfo *TPI = PR->getPassInfo(PrintMachineInstrs.getValue());
423 const PassInfo *IPI = PR->getPassInfo(StringRef("print-machineinstrs"));
424 assert (TPI && IPI && "Pass ID not registered!");
425 const char *TID = (char *)(TPI->getTypeInfo());
426 const char *IID = (char *)(IPI->getTypeInfo());
427 insertPass(*TID, *IID);
428 }
429
Andrew Trickd5422652012-02-04 02:56:48 +0000430 // Expand pseudo-instructions emitted by ISel.
Andrew Trick1dd8c852012-02-08 21:23:13 +0000431 addPass(ExpandISelPseudosID);
Andrew Trickd5422652012-02-04 02:56:48 +0000432
Andrew Trickf7b96312012-02-09 00:40:55 +0000433 // Add passes that optimize machine instructions in SSA form.
Andrew Trickd5422652012-02-04 02:56:48 +0000434 if (getOptLevel() != CodeGenOpt::None) {
Andrew Trickf7b96312012-02-09 00:40:55 +0000435 addMachineSSAOptimization();
436 }
437 else {
438 // If the target requests it, assign local variables to stack slots relative
439 // to one another and simplify frame index references where possible.
440 addPass(LocalStackSlotAllocationID);
Andrew Trickd5422652012-02-04 02:56:48 +0000441 }
442
443 // Run pre-ra passes.
444 if (addPreRegAlloc())
445 printAndVerify("After PreRegAlloc passes");
446
Andrew Trickf7b96312012-02-09 00:40:55 +0000447 // Run register allocation and passes that are tightly coupled with it,
448 // including phi elimination and scheduling.
Andrew Trick8dd26252012-02-10 04:10:36 +0000449 if (getOptimizeRegAlloc())
450 addOptimizedRegAlloc(createRegAllocPass(true));
451 else
452 addFastRegAlloc(createRegAllocPass(false));
Andrew Trickd5422652012-02-04 02:56:48 +0000453
454 // Run post-ra passes.
455 if (addPostRegAlloc())
456 printAndVerify("After PostRegAlloc passes");
457
458 // Insert prolog/epilog code. Eliminate abstract frame index references...
Andrew Trick1dd8c852012-02-08 21:23:13 +0000459 addPass(PrologEpilogCodeInserterID);
Andrew Trickd5422652012-02-04 02:56:48 +0000460 printAndVerify("After PrologEpilogCodeInserter");
461
Andrew Trickf7b96312012-02-09 00:40:55 +0000462 /// Add passes that optimize machine instructions after register allocation.
463 if (getOptLevel() != CodeGenOpt::None)
464 addMachineLateOptimization();
Andrew Trickd5422652012-02-04 02:56:48 +0000465
466 // Expand pseudo instructions before second scheduling pass.
Andrew Trick1dd8c852012-02-08 21:23:13 +0000467 addPass(ExpandPostRAPseudosID);
Jakob Stoklund Olesen2ef5bf62012-03-28 20:49:30 +0000468 printAndVerify("After ExpandPostRAPseudos");
Andrew Trickd5422652012-02-04 02:56:48 +0000469
470 // Run pre-sched2 passes.
471 if (addPreSched2())
Jakob Stoklund Olesen78811662012-03-28 23:31:15 +0000472 printAndVerify("After PreSched2 passes");
Andrew Trickd5422652012-02-04 02:56:48 +0000473
474 // Second pass scheduler.
Andrew Trick79bf2882012-02-15 03:21:51 +0000475 if (getOptLevel() != CodeGenOpt::None) {
Andrew Trick1dd8c852012-02-08 21:23:13 +0000476 addPass(PostRASchedulerID);
Jakob Stoklund Olesen8b4c5022012-03-28 23:54:28 +0000477 printAndVerify("After PostRAScheduler");
Andrew Trickd5422652012-02-04 02:56:48 +0000478 }
479
Andrew Trickf7b96312012-02-09 00:40:55 +0000480 // GC
Andrew Trick1dd8c852012-02-08 21:23:13 +0000481 addPass(GCMachineCodeAnalysisID);
Andrew Trickd5422652012-02-04 02:56:48 +0000482 if (PrintGCInfo)
Bob Wilson564fbf62012-07-02 19:48:31 +0000483 addPass(createGCInfoPrinter(dbgs()));
Andrew Trickd5422652012-02-04 02:56:48 +0000484
Andrew Trickf7b96312012-02-09 00:40:55 +0000485 // Basic block placement.
Andrew Trick79bf2882012-02-15 03:21:51 +0000486 if (getOptLevel() != CodeGenOpt::None)
Andrew Trickf7b96312012-02-09 00:40:55 +0000487 addBlockPlacement();
Andrew Trickd5422652012-02-04 02:56:48 +0000488
489 if (addPreEmitPass())
Jakob Stoklund Olesen8b4c5022012-03-28 23:54:28 +0000490 printAndVerify("After PreEmit passes");
Andrew Trickd5422652012-02-04 02:56:48 +0000491}
492
Andrew Trickf7b96312012-02-09 00:40:55 +0000493/// Add passes that optimize machine instructions in SSA form.
494void TargetPassConfig::addMachineSSAOptimization() {
495 // Pre-ra tail duplication.
Andrew Trick79bf2882012-02-15 03:21:51 +0000496 if (addPass(EarlyTailDuplicateID) != &NoPassID)
Andrew Trickf7b96312012-02-09 00:40:55 +0000497 printAndVerify("After Pre-RegAlloc TailDuplicate");
Andrew Trickf7b96312012-02-09 00:40:55 +0000498
499 // Optimize PHIs before DCE: removing dead PHI cycles may make more
500 // instructions dead.
501 addPass(OptimizePHIsID);
502
503 // If the target requests it, assign local variables to stack slots relative
504 // to one another and simplify frame index references where possible.
505 addPass(LocalStackSlotAllocationID);
506
507 // With optimization, dead code should already be eliminated. However
508 // there is one known exception: lowered code for arguments that are only
509 // used by tail calls, where the tail calls reuse the incoming stack
510 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
Andrew Trick79bf2882012-02-15 03:21:51 +0000511 addPass(DeadMachineInstructionElimID);
Andrew Trickf7b96312012-02-09 00:40:55 +0000512 printAndVerify("After codegen DCE pass");
513
Andrew Trick79bf2882012-02-15 03:21:51 +0000514 addPass(MachineLICMID);
515 addPass(MachineCSEID);
516 addPass(MachineSinkingID);
Andrew Trickf7b96312012-02-09 00:40:55 +0000517 printAndVerify("After Machine LICM, CSE and Sinking passes");
518
519 addPass(PeepholeOptimizerID);
520 printAndVerify("After codegen peephole optimization pass");
521}
522
Andrew Trick74613342012-02-04 02:56:45 +0000523//===---------------------------------------------------------------------===//
Andrew Trickf7b96312012-02-09 00:40:55 +0000524/// Register Allocation Pass Configuration
Jim Laskeyeb577ba2006-08-02 12:30:23 +0000525//===---------------------------------------------------------------------===//
Andrew Trickf7b96312012-02-09 00:40:55 +0000526
Andrew Trick8dd26252012-02-10 04:10:36 +0000527bool TargetPassConfig::getOptimizeRegAlloc() const {
528 switch (OptimizeRegAlloc) {
529 case cl::BOU_UNSET: return getOptLevel() != CodeGenOpt::None;
530 case cl::BOU_TRUE: return true;
531 case cl::BOU_FALSE: return false;
532 }
533 llvm_unreachable("Invalid optimize-regalloc state");
534}
535
Andrew Trickf7b96312012-02-09 00:40:55 +0000536/// RegisterRegAlloc's global Registry tracks allocator registration.
Jim Laskeyeb577ba2006-08-02 12:30:23 +0000537MachinePassRegistry RegisterRegAlloc::Registry;
538
Andrew Trickf7b96312012-02-09 00:40:55 +0000539/// A dummy default pass factory indicates whether the register allocator is
540/// overridden on the command line.
Andrew Trick8dd26252012-02-10 04:10:36 +0000541static FunctionPass *useDefaultRegisterAllocator() { return 0; }
Jakob Stoklund Olesen700bfad2010-05-27 23:57:25 +0000542static RegisterRegAlloc
543defaultRegAlloc("default",
544 "pick register allocator based on -O option",
Andrew Trick8dd26252012-02-10 04:10:36 +0000545 useDefaultRegisterAllocator);
Jim Laskeyeb577ba2006-08-02 12:30:23 +0000546
Andrew Trickf7b96312012-02-09 00:40:55 +0000547/// -regalloc=... command line option.
Dan Gohman844731a2008-05-13 00:00:25 +0000548static cl::opt<RegisterRegAlloc::FunctionPassCtor, false,
549 RegisterPassParser<RegisterRegAlloc> >
550RegAlloc("regalloc",
Andrew Trick8dd26252012-02-10 04:10:36 +0000551 cl::init(&useDefaultRegisterAllocator),
Jakob Stoklund Olesen700bfad2010-05-27 23:57:25 +0000552 cl::desc("Register allocator to use"));
Alkis Evlogimenos7237ece2003-10-02 16:57:49 +0000553
Jim Laskeyeb577ba2006-08-02 12:30:23 +0000554
Andrew Trick8dd26252012-02-10 04:10:36 +0000555/// Instantiate the default register allocator pass for this target for either
556/// the optimized or unoptimized allocation path. This will be added to the pass
557/// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
558/// in the optimized case.
559///
560/// A target that uses the standard regalloc pass order for fast or optimized
561/// allocation may still override this for per-target regalloc
562/// selection. But -regalloc=... always takes precedence.
563FunctionPass *TargetPassConfig::createTargetRegisterAllocator(bool Optimized) {
564 if (Optimized)
565 return createGreedyRegisterAllocator();
566 else
567 return createFastRegisterAllocator();
568}
569
570/// Find and instantiate the register allocation pass requested by this target
571/// at the current optimization level. Different register allocators are
572/// defined as separate passes because they may require different analysis.
573///
574/// This helper ensures that the regalloc= option is always available,
575/// even for targets that override the default allocator.
576///
577/// FIXME: When MachinePassRegistry register pass IDs instead of function ptrs,
578/// this can be folded into addPass.
579FunctionPass *TargetPassConfig::createRegAllocPass(bool Optimized) {
Jim Laskey9ff542f2006-08-01 18:29:48 +0000580 RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
Jakob Stoklund Olesen700bfad2010-05-27 23:57:25 +0000581
Andrew Trick8dd26252012-02-10 04:10:36 +0000582 // Initialize the global default.
Jim Laskey13ec7022006-08-01 14:21:23 +0000583 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +0000584 Ctor = RegAlloc;
585 RegisterRegAlloc::setDefault(RegAlloc);
Jim Laskey13ec7022006-08-01 14:21:23 +0000586 }
Andrew Trick8dd26252012-02-10 04:10:36 +0000587 if (Ctor != useDefaultRegisterAllocator)
Jakob Stoklund Olesen700bfad2010-05-27 23:57:25 +0000588 return Ctor();
589
Andrew Trick8dd26252012-02-10 04:10:36 +0000590 // With no -regalloc= override, ask the target for a regalloc pass.
591 return createTargetRegisterAllocator(Optimized);
592}
593
594/// Add the minimum set of target-independent passes that are required for
595/// register allocation. No coalescing or scheduling.
596void TargetPassConfig::addFastRegAlloc(FunctionPass *RegAllocPass) {
597 addPass(PHIEliminationID);
598 addPass(TwoAddressInstructionPassID);
599
Bob Wilson564fbf62012-07-02 19:48:31 +0000600 addPass(RegAllocPass);
Andrew Trick8dd26252012-02-10 04:10:36 +0000601 printAndVerify("After Register Allocation");
Jim Laskey33a0a6d2006-07-27 20:05:00 +0000602}
Andrew Trickf7b96312012-02-09 00:40:55 +0000603
604/// Add standard target-independent passes that are tightly coupled with
Andrew Trick8dd26252012-02-10 04:10:36 +0000605/// optimized register allocation, including coalescing, machine instruction
606/// scheduling, and register allocation itself.
607void TargetPassConfig::addOptimizedRegAlloc(FunctionPass *RegAllocPass) {
Jakob Stoklund Olesen5984d2b2012-06-25 18:12:18 +0000608 addPass(ProcessImplicitDefsID);
609
Andrew Trick8dd26252012-02-10 04:10:36 +0000610 // LiveVariables currently requires pure SSA form.
611 //
612 // FIXME: Once TwoAddressInstruction pass no longer uses kill flags,
613 // LiveVariables can be removed completely, and LiveIntervals can be directly
614 // computed. (We still either need to regenerate kill flags after regalloc, or
615 // preferably fix the scavenger to not depend on them).
616 addPass(LiveVariablesID);
617
618 // Add passes that move from transformed SSA into conventional SSA. This is a
619 // "copy coalescing" problem.
620 //
621 if (!EnableStrongPHIElim) {
622 // Edge splitting is smarter with machine loop info.
623 addPass(MachineLoopInfoID);
624 addPass(PHIEliminationID);
625 }
626 addPass(TwoAddressInstructionPassID);
627
Andrew Trick8dd26252012-02-10 04:10:36 +0000628 if (EnableStrongPHIElim)
629 addPass(StrongPHIEliminationID);
630
631 addPass(RegisterCoalescerID);
632
633 // PreRA instruction scheduling.
Andrew Trick17d35e52012-03-14 04:00:41 +0000634 if (addPass(MachineSchedulerID) != &NoPassID)
635 printAndVerify("After Machine Scheduling");
Andrew Trick8dd26252012-02-10 04:10:36 +0000636
637 // Add the selected register allocation pass.
Bob Wilson564fbf62012-07-02 19:48:31 +0000638 addPass(RegAllocPass);
Jakob Stoklund Olesen34f5a2b2012-06-26 17:09:29 +0000639 printAndVerify("After Register Allocation, before rewriter");
640
641 // Allow targets to change the register assignments before rewriting.
642 if (addPreRewrite())
643 printAndVerify("After pre-rewrite passes");
Andrew Trickf7b96312012-02-09 00:40:55 +0000644
Jakob Stoklund Olesen05ec7122012-06-08 23:44:45 +0000645 // Finally rewrite virtual registers.
646 addPass(VirtRegRewriterID);
647 printAndVerify("After Virtual Register Rewriter");
648
Andrew Trick746f24b2012-02-11 07:11:32 +0000649 // FinalizeRegAlloc is convenient until MachineInstrBundles is more mature,
650 // but eventually, all users of it should probably be moved to addPostRA and
651 // it can go away. Currently, it's the intended place for targets to run
652 // FinalizeMachineBundles, because passes other than MachineScheduling an
653 // RegAlloc itself may not be aware of bundles.
654 if (addFinalizeRegAlloc())
655 printAndVerify("After RegAlloc finalization");
656
Andrew Trickf7b96312012-02-09 00:40:55 +0000657 // Perform stack slot coloring and post-ra machine LICM.
Andrew Trick8dd26252012-02-10 04:10:36 +0000658 //
659 // FIXME: Re-enable coloring with register when it's capable of adding
660 // kill markers.
Andrew Trick900d7b72012-02-15 07:57:03 +0000661 addPass(StackSlotColoringID);
662
663 // Run post-ra machine LICM to hoist reloads / remats.
664 //
665 // FIXME: can this move into MachineLateOptimization?
666 addPass(PostRAMachineLICMID);
667
668 printAndVerify("After StackSlotColoring and postra Machine LICM");
Andrew Trickf7b96312012-02-09 00:40:55 +0000669}
670
671//===---------------------------------------------------------------------===//
672/// Post RegAlloc Pass Configuration
673//===---------------------------------------------------------------------===//
674
675/// Add passes that optimize machine instructions after register allocation.
676void TargetPassConfig::addMachineLateOptimization() {
677 // Branch folding must be run after regalloc and prolog/epilog insertion.
Andrew Trick79bf2882012-02-15 03:21:51 +0000678 if (addPass(BranchFolderPassID) != &NoPassID)
Jakob Stoklund Olesen663ee202012-03-28 20:47:37 +0000679 printAndVerify("After BranchFolding");
Andrew Trickf7b96312012-02-09 00:40:55 +0000680
681 // Tail duplication.
Andrew Trick79bf2882012-02-15 03:21:51 +0000682 if (addPass(TailDuplicateID) != &NoPassID)
Jakob Stoklund Olesen663ee202012-03-28 20:47:37 +0000683 printAndVerify("After TailDuplicate");
Andrew Trickf7b96312012-02-09 00:40:55 +0000684
685 // Copy propagation.
Andrew Trick79bf2882012-02-15 03:21:51 +0000686 if (addPass(MachineCopyPropagationID) != &NoPassID)
Jakob Stoklund Olesen663ee202012-03-28 20:47:37 +0000687 printAndVerify("After copy propagation pass");
Andrew Trickf7b96312012-02-09 00:40:55 +0000688}
689
690/// Add standard basic block placement passes.
691void TargetPassConfig::addBlockPlacement() {
Andrew Trick79bf2882012-02-15 03:21:51 +0000692 AnalysisID ID = &NoPassID;
Chandler Carruth9e67db42012-04-16 13:49:17 +0000693 if (!DisableBlockPlacement) {
694 // MachineBlockPlacement is a new pass which subsumes the functionality of
695 // CodPlacementOpt. The old code placement pass can be restored by
696 // disabling block placement, but eventually it will be removed.
Andrew Trick79bf2882012-02-15 03:21:51 +0000697 ID = addPass(MachineBlockPlacementID);
Andrew Trickf7b96312012-02-09 00:40:55 +0000698 } else {
Andrew Trick79bf2882012-02-15 03:21:51 +0000699 ID = addPass(CodePlacementOptID);
Andrew Trickf7b96312012-02-09 00:40:55 +0000700 }
Andrew Trick79bf2882012-02-15 03:21:51 +0000701 if (ID != &NoPassID) {
702 // Run a separate pass to collect block placement statistics.
703 if (EnableBlockPlacementStats)
704 addPass(MachineBlockPlacementStatsID);
Andrew Trickf7b96312012-02-09 00:40:55 +0000705
Jakob Stoklund Olesen8b4c5022012-03-28 23:54:28 +0000706 printAndVerify("After machine block placement.");
Andrew Trickf7b96312012-02-09 00:40:55 +0000707 }
708}