TargetPassConfig.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948
  1. //===-- TargetPassConfig.cpp - Target independent code generation passes --===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines interfaces to access the target independent code
  11. // generation passes provided by the LLVM backend.
  12. //
  13. //===---------------------------------------------------------------------===//
  14. #include "llvm/CodeGen/TargetPassConfig.h"
  15. #include "llvm/Analysis/BasicAliasAnalysis.h"
  16. #include "llvm/Analysis/CFLAndersAliasAnalysis.h"
  17. #include "llvm/Analysis/CFLSteensAliasAnalysis.h"
  18. #include "llvm/Analysis/CallGraphSCCPass.h"
  19. #include "llvm/Analysis/Passes.h"
  20. #include "llvm/Analysis/ScopedNoAliasAA.h"
  21. #include "llvm/Analysis/TypeBasedAliasAnalysis.h"
  22. #include "llvm/CodeGen/MachineFunctionPass.h"
  23. #include "llvm/CodeGen/RegAllocRegistry.h"
  24. #include "llvm/CodeGen/RegisterUsageInfo.h"
  25. #include "llvm/IR/IRPrintingPasses.h"
  26. #include "llvm/IR/LegacyPassManager.h"
  27. #include "llvm/IR/Verifier.h"
  28. #include "llvm/MC/MCAsmInfo.h"
  29. #include "llvm/Support/Debug.h"
  30. #include "llvm/Support/ErrorHandling.h"
  31. #include "llvm/Support/raw_ostream.h"
  32. #include "llvm/Target/TargetMachine.h"
  33. #include "llvm/Transforms/Instrumentation.h"
  34. #include "llvm/Transforms/Scalar.h"
  35. #include "llvm/Transforms/Utils/SymbolRewriter.h"
  36. using namespace llvm;
  37. static cl::opt<bool> DisablePostRASched("disable-post-ra", cl::Hidden,
  38. cl::desc("Disable Post Regalloc Scheduler"));
  39. static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
  40. cl::desc("Disable branch folding"));
  41. static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
  42. cl::desc("Disable tail duplication"));
  43. static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
  44. cl::desc("Disable pre-register allocation tail duplication"));
  45. static cl::opt<bool> DisableBlockPlacement("disable-block-placement",
  46. cl::Hidden, cl::desc("Disable probability-driven block placement"));
  47. static cl::opt<bool> EnableBlockPlacementStats("enable-block-placement-stats",
  48. cl::Hidden, cl::desc("Collect probability-driven block placement stats"));
  49. static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
  50. cl::desc("Disable Stack Slot Coloring"));
  51. static cl::opt<bool> DisableMachineDCE("disable-machine-dce", cl::Hidden,
  52. cl::desc("Disable Machine Dead Code Elimination"));
  53. static cl::opt<bool> DisableEarlyIfConversion("disable-early-ifcvt", cl::Hidden,
  54. cl::desc("Disable Early If-conversion"));
  55. static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
  56. cl::desc("Disable Machine LICM"));
  57. static cl::opt<bool> DisableMachineCSE("disable-machine-cse", cl::Hidden,
  58. cl::desc("Disable Machine Common Subexpression Elimination"));
  59. static cl::opt<cl::boolOrDefault> OptimizeRegAlloc(
  60. "optimize-regalloc", cl::Hidden,
  61. cl::desc("Enable optimized register allocation compilation path."));
  62. static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm",
  63. cl::Hidden,
  64. cl::desc("Disable Machine LICM"));
  65. static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
  66. cl::desc("Disable Machine Sinking"));
  67. static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
  68. cl::desc("Disable Loop Strength Reduction Pass"));
  69. static cl::opt<bool> DisableConstantHoisting("disable-constant-hoisting",
  70. cl::Hidden, cl::desc("Disable ConstantHoisting"));
  71. static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
  72. cl::desc("Disable Codegen Prepare"));
  73. static cl::opt<bool> DisableCopyProp("disable-copyprop", cl::Hidden,
  74. cl::desc("Disable Copy Propagation pass"));
  75. static cl::opt<bool> DisablePartialLibcallInlining("disable-partial-libcall-inlining",
  76. cl::Hidden, cl::desc("Disable Partial Libcall Inlining"));
  77. static cl::opt<bool> EnableImplicitNullChecks(
  78. "enable-implicit-null-checks",
  79. cl::desc("Fold null checks into faulting memory operations"),
  80. cl::init(false));
  81. static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
  82. cl::desc("Print LLVM IR produced by the loop-reduce pass"));
  83. static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
  84. cl::desc("Print LLVM IR input to isel pass"));
  85. static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
  86. cl::desc("Dump garbage collector data"));
  87. static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
  88. cl::desc("Verify generated machine code"),
  89. cl::init(false),
  90. cl::ZeroOrMore);
  91. static cl::opt<bool> EnableMachineOutliner("enable-machine-outliner",
  92. cl::Hidden,
  93. cl::desc("Enable machine outliner"));
  94. static cl::opt<std::string>
  95. PrintMachineInstrs("print-machineinstrs", cl::ValueOptional,
  96. cl::desc("Print machine instrs"),
  97. cl::value_desc("pass-name"), cl::init("option-unspecified"));
  98. static cl::opt<int> EnableGlobalISelAbort(
  99. "global-isel-abort", cl::Hidden,
  100. cl::desc("Enable abort calls when \"global\" instruction selection "
  101. "fails to lower/select an instruction: 0 disable the abort, "
  102. "1 enable the abort, and "
  103. "2 disable the abort but emit a diagnostic on failure"),
  104. cl::init(1));
  105. // Temporary option to allow experimenting with MachineScheduler as a post-RA
  106. // scheduler. Targets can "properly" enable this with
  107. // substitutePass(&PostRASchedulerID, &PostMachineSchedulerID).
  108. // Targets can return true in targetSchedulesPostRAScheduling() and
  109. // insert a PostRA scheduling pass wherever it wants.
  110. cl::opt<bool> MISchedPostRA("misched-postra", cl::Hidden,
  111. cl::desc("Run MachineScheduler post regalloc (independent of preRA sched)"));
  112. // Experimental option to run live interval analysis early.
  113. static cl::opt<bool> EarlyLiveIntervals("early-live-intervals", cl::Hidden,
  114. cl::desc("Run live interval analysis earlier in the pipeline"));
  115. // Experimental option to use CFL-AA in codegen
  116. enum class CFLAAType { None, Steensgaard, Andersen, Both };
  117. static cl::opt<CFLAAType> UseCFLAA(
  118. "use-cfl-aa-in-codegen", cl::init(CFLAAType::None), cl::Hidden,
  119. cl::desc("Enable the new, experimental CFL alias analysis in CodeGen"),
  120. cl::values(clEnumValN(CFLAAType::None, "none", "Disable CFL-AA"),
  121. clEnumValN(CFLAAType::Steensgaard, "steens",
  122. "Enable unification-based CFL-AA"),
  123. clEnumValN(CFLAAType::Andersen, "anders",
  124. "Enable inclusion-based CFL-AA"),
  125. clEnumValN(CFLAAType::Both, "both",
  126. "Enable both variants of CFL-AA")));
  127. /// Allow standard passes to be disabled by command line options. This supports
  128. /// simple binary flags that either suppress the pass or do nothing.
  129. /// i.e. -disable-mypass=false has no effect.
  130. /// These should be converted to boolOrDefault in order to use applyOverride.
  131. static IdentifyingPassPtr applyDisable(IdentifyingPassPtr PassID,
  132. bool Override) {
  133. if (Override)
  134. return IdentifyingPassPtr();
  135. return PassID;
  136. }
  137. /// Allow standard passes to be disabled by the command line, regardless of who
  138. /// is adding the pass.
  139. ///
  140. /// StandardID is the pass identified in the standard pass pipeline and provided
  141. /// to addPass(). It may be a target-specific ID in the case that the target
  142. /// directly adds its own pass, but in that case we harmlessly fall through.
  143. ///
  144. /// TargetID is the pass that the target has configured to override StandardID.
  145. ///
  146. /// StandardID may be a pseudo ID. In that case TargetID is the name of the real
  147. /// pass to run. This allows multiple options to control a single pass depending
  148. /// on where in the pipeline that pass is added.
  149. static IdentifyingPassPtr overridePass(AnalysisID StandardID,
  150. IdentifyingPassPtr TargetID) {
  151. if (StandardID == &PostRASchedulerID)
  152. return applyDisable(TargetID, DisablePostRASched);
  153. if (StandardID == &BranchFolderPassID)
  154. return applyDisable(TargetID, DisableBranchFold);
  155. if (StandardID == &TailDuplicateID)
  156. return applyDisable(TargetID, DisableTailDuplicate);
  157. if (StandardID == &TargetPassConfig::EarlyTailDuplicateID)
  158. return applyDisable(TargetID, DisableEarlyTailDup);
  159. if (StandardID == &MachineBlockPlacementID)
  160. return applyDisable(TargetID, DisableBlockPlacement);
  161. if (StandardID == &StackSlotColoringID)
  162. return applyDisable(TargetID, DisableSSC);
  163. if (StandardID == &DeadMachineInstructionElimID)
  164. return applyDisable(TargetID, DisableMachineDCE);
  165. if (StandardID == &EarlyIfConverterID)
  166. return applyDisable(TargetID, DisableEarlyIfConversion);
  167. if (StandardID == &MachineLICMID)
  168. return applyDisable(TargetID, DisableMachineLICM);
  169. if (StandardID == &MachineCSEID)
  170. return applyDisable(TargetID, DisableMachineCSE);
  171. if (StandardID == &TargetPassConfig::PostRAMachineLICMID)
  172. return applyDisable(TargetID, DisablePostRAMachineLICM);
  173. if (StandardID == &MachineSinkingID)
  174. return applyDisable(TargetID, DisableMachineSink);
  175. if (StandardID == &MachineCopyPropagationID)
  176. return applyDisable(TargetID, DisableCopyProp);
  177. return TargetID;
  178. }
  179. //===---------------------------------------------------------------------===//
  180. /// TargetPassConfig
  181. //===---------------------------------------------------------------------===//
  182. INITIALIZE_PASS(TargetPassConfig, "targetpassconfig",
  183. "Target Pass Configuration", false, false)
  184. char TargetPassConfig::ID = 0;
  185. // Pseudo Pass IDs.
  186. char TargetPassConfig::EarlyTailDuplicateID = 0;
  187. char TargetPassConfig::PostRAMachineLICMID = 0;
  188. namespace {
  189. struct InsertedPass {
  190. AnalysisID TargetPassID;
  191. IdentifyingPassPtr InsertedPassID;
  192. bool VerifyAfter;
  193. bool PrintAfter;
  194. InsertedPass(AnalysisID TargetPassID, IdentifyingPassPtr InsertedPassID,
  195. bool VerifyAfter, bool PrintAfter)
  196. : TargetPassID(TargetPassID), InsertedPassID(InsertedPassID),
  197. VerifyAfter(VerifyAfter), PrintAfter(PrintAfter) {}
  198. Pass *getInsertedPass() const {
  199. assert(InsertedPassID.isValid() && "Illegal Pass ID!");
  200. if (InsertedPassID.isInstance())
  201. return InsertedPassID.getInstance();
  202. Pass *NP = Pass::createPass(InsertedPassID.getID());
  203. assert(NP && "Pass ID not registered");
  204. return NP;
  205. }
  206. };
  207. }
  208. namespace llvm {
  209. class PassConfigImpl {
  210. public:
  211. // List of passes explicitly substituted by this target. Normally this is
  212. // empty, but it is a convenient way to suppress or replace specific passes
  213. // that are part of a standard pass pipeline without overridding the entire
  214. // pipeline. This mechanism allows target options to inherit a standard pass's
  215. // user interface. For example, a target may disable a standard pass by
  216. // default by substituting a pass ID of zero, and the user may still enable
  217. // that standard pass with an explicit command line option.
  218. DenseMap<AnalysisID,IdentifyingPassPtr> TargetPasses;
  219. /// Store the pairs of <AnalysisID, AnalysisID> of which the second pass
  220. /// is inserted after each instance of the first one.
  221. SmallVector<InsertedPass, 4> InsertedPasses;
  222. };
  223. } // namespace llvm
  224. // Out of line virtual method.
  225. TargetPassConfig::~TargetPassConfig() {
  226. delete Impl;
  227. }
  228. // Out of line constructor provides default values for pass options and
  229. // registers all common codegen passes.
  230. TargetPassConfig::TargetPassConfig(TargetMachine *tm, PassManagerBase &pm)
  231. : ImmutablePass(ID), PM(&pm), Started(true), Stopped(false),
  232. AddingMachinePasses(false), TM(tm), Impl(nullptr), Initialized(false),
  233. DisableVerify(false), EnableTailMerge(true),
  234. RequireCodeGenSCCOrder(false) {
  235. Impl = new PassConfigImpl();
  236. // Register all target independent codegen passes to activate their PassIDs,
  237. // including this pass itself.
  238. initializeCodeGen(*PassRegistry::getPassRegistry());
  239. // Also register alias analysis passes required by codegen passes.
  240. initializeBasicAAWrapperPassPass(*PassRegistry::getPassRegistry());
  241. initializeAAResultsWrapperPassPass(*PassRegistry::getPassRegistry());
  242. // Substitute Pseudo Pass IDs for real ones.
  243. substitutePass(&EarlyTailDuplicateID, &TailDuplicateID);
  244. substitutePass(&PostRAMachineLICMID, &MachineLICMID);
  245. if (StringRef(PrintMachineInstrs.getValue()).equals(""))
  246. TM->Options.PrintMachineCode = true;
  247. if (TM->Options.EnableIPRA)
  248. setRequiresCodeGenSCCOrder();
  249. }
  250. CodeGenOpt::Level TargetPassConfig::getOptLevel() const {
  251. return TM->getOptLevel();
  252. }
  253. /// Insert InsertedPassID pass after TargetPassID.
  254. void TargetPassConfig::insertPass(AnalysisID TargetPassID,
  255. IdentifyingPassPtr InsertedPassID,
  256. bool VerifyAfter, bool PrintAfter) {
  257. assert(((!InsertedPassID.isInstance() &&
  258. TargetPassID != InsertedPassID.getID()) ||
  259. (InsertedPassID.isInstance() &&
  260. TargetPassID != InsertedPassID.getInstance()->getPassID())) &&
  261. "Insert a pass after itself!");
  262. Impl->InsertedPasses.emplace_back(TargetPassID, InsertedPassID, VerifyAfter,
  263. PrintAfter);
  264. }
  265. /// createPassConfig - Create a pass configuration object to be used by
  266. /// addPassToEmitX methods for generating a pipeline of CodeGen passes.
  267. ///
  268. /// Targets may override this to extend TargetPassConfig.
  269. TargetPassConfig *LLVMTargetMachine::createPassConfig(PassManagerBase &PM) {
  270. return new TargetPassConfig(this, PM);
  271. }
  272. TargetPassConfig::TargetPassConfig()
  273. : ImmutablePass(ID), PM(nullptr) {
  274. report_fatal_error("Trying to construct TargetPassConfig without a target "
  275. "machine. Scheduling a CodeGen pass without a target "
  276. "triple set?");
  277. }
  278. // Helper to verify the analysis is really immutable.
  279. void TargetPassConfig::setOpt(bool &Opt, bool Val) {
  280. assert(!Initialized && "PassConfig is immutable");
  281. Opt = Val;
  282. }
  283. void TargetPassConfig::substitutePass(AnalysisID StandardID,
  284. IdentifyingPassPtr TargetID) {
  285. Impl->TargetPasses[StandardID] = TargetID;
  286. }
  287. IdentifyingPassPtr TargetPassConfig::getPassSubstitution(AnalysisID ID) const {
  288. DenseMap<AnalysisID, IdentifyingPassPtr>::const_iterator
  289. I = Impl->TargetPasses.find(ID);
  290. if (I == Impl->TargetPasses.end())
  291. return ID;
  292. return I->second;
  293. }
  294. bool TargetPassConfig::isPassSubstitutedOrOverridden(AnalysisID ID) const {
  295. IdentifyingPassPtr TargetID = getPassSubstitution(ID);
  296. IdentifyingPassPtr FinalPtr = overridePass(ID, TargetID);
  297. return !FinalPtr.isValid() || FinalPtr.isInstance() ||
  298. FinalPtr.getID() != ID;
  299. }
  300. /// Add a pass to the PassManager if that pass is supposed to be run. If the
  301. /// Started/Stopped flags indicate either that the compilation should start at
  302. /// a later pass or that it should stop after an earlier pass, then do not add
  303. /// the pass. Finally, compare the current pass against the StartAfter
  304. /// and StopAfter options and change the Started/Stopped flags accordingly.
  305. void TargetPassConfig::addPass(Pass *P, bool verifyAfter, bool printAfter) {
  306. assert(!Initialized && "PassConfig is immutable");
  307. // Cache the Pass ID here in case the pass manager finds this pass is
  308. // redundant with ones already scheduled / available, and deletes it.
  309. // Fundamentally, once we add the pass to the manager, we no longer own it
  310. // and shouldn't reference it.
  311. AnalysisID PassID = P->getPassID();
  312. if (StartBefore == PassID)
  313. Started = true;
  314. if (StopBefore == PassID)
  315. Stopped = true;
  316. if (Started && !Stopped) {
  317. std::string Banner;
  318. // Construct banner message before PM->add() as that may delete the pass.
  319. if (AddingMachinePasses && (printAfter || verifyAfter))
  320. Banner = std::string("After ") + std::string(P->getPassName());
  321. PM->add(P);
  322. if (AddingMachinePasses) {
  323. if (printAfter)
  324. addPrintPass(Banner);
  325. if (verifyAfter)
  326. addVerifyPass(Banner);
  327. }
  328. // Add the passes after the pass P if there is any.
  329. for (auto IP : Impl->InsertedPasses) {
  330. if (IP.TargetPassID == PassID)
  331. addPass(IP.getInsertedPass(), IP.VerifyAfter, IP.PrintAfter);
  332. }
  333. } else {
  334. delete P;
  335. }
  336. if (StopAfter == PassID)
  337. Stopped = true;
  338. if (StartAfter == PassID)
  339. Started = true;
  340. if (Stopped && !Started)
  341. report_fatal_error("Cannot stop compilation after pass that is not run");
  342. }
  343. /// Add a CodeGen pass at this point in the pipeline after checking for target
  344. /// and command line overrides.
  345. ///
  346. /// addPass cannot return a pointer to the pass instance because is internal the
  347. /// PassManager and the instance we create here may already be freed.
  348. AnalysisID TargetPassConfig::addPass(AnalysisID PassID, bool verifyAfter,
  349. bool printAfter) {
  350. IdentifyingPassPtr TargetID = getPassSubstitution(PassID);
  351. IdentifyingPassPtr FinalPtr = overridePass(PassID, TargetID);
  352. if (!FinalPtr.isValid())
  353. return nullptr;
  354. Pass *P;
  355. if (FinalPtr.isInstance())
  356. P = FinalPtr.getInstance();
  357. else {
  358. P = Pass::createPass(FinalPtr.getID());
  359. if (!P)
  360. llvm_unreachable("Pass ID not registered");
  361. }
  362. AnalysisID FinalID = P->getPassID();
  363. addPass(P, verifyAfter, printAfter); // Ends the lifetime of P.
  364. return FinalID;
  365. }
  366. void TargetPassConfig::printAndVerify(const std::string &Banner) {
  367. addPrintPass(Banner);
  368. addVerifyPass(Banner);
  369. }
  370. void TargetPassConfig::addPrintPass(const std::string &Banner) {
  371. if (TM->shouldPrintMachineCode())
  372. PM->add(createMachineFunctionPrinterPass(dbgs(), Banner));
  373. }
  374. void TargetPassConfig::addVerifyPass(const std::string &Banner) {
  375. if (VerifyMachineCode)
  376. PM->add(createMachineVerifierPass(Banner));
  377. }
  378. /// Add common target configurable passes that perform LLVM IR to IR transforms
  379. /// following machine independent optimization.
  380. void TargetPassConfig::addIRPasses() {
  381. switch (UseCFLAA) {
  382. case CFLAAType::Steensgaard:
  383. addPass(createCFLSteensAAWrapperPass());
  384. break;
  385. case CFLAAType::Andersen:
  386. addPass(createCFLAndersAAWrapperPass());
  387. break;
  388. case CFLAAType::Both:
  389. addPass(createCFLAndersAAWrapperPass());
  390. addPass(createCFLSteensAAWrapperPass());
  391. break;
  392. default:
  393. break;
  394. }
  395. // Basic AliasAnalysis support.
  396. // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
  397. // BasicAliasAnalysis wins if they disagree. This is intended to help
  398. // support "obvious" type-punning idioms.
  399. addPass(createTypeBasedAAWrapperPass());
  400. addPass(createScopedNoAliasAAWrapperPass());
  401. addPass(createBasicAAWrapperPass());
  402. // Before running any passes, run the verifier to determine if the input
  403. // coming from the front-end and/or optimizer is valid.
  404. if (!DisableVerify)
  405. addPass(createVerifierPass());
  406. // Run loop strength reduction before anything else.
  407. if (getOptLevel() != CodeGenOpt::None && !DisableLSR) {
  408. addPass(createLoopStrengthReducePass());
  409. if (PrintLSR)
  410. addPass(createPrintFunctionPass(dbgs(), "\n\n*** Code after LSR ***\n"));
  411. }
  412. // Run GC lowering passes for builtin collectors
  413. // TODO: add a pass insertion point here
  414. addPass(createGCLoweringPass());
  415. addPass(createShadowStackGCLoweringPass());
  416. // Make sure that no unreachable blocks are instruction selected.
  417. addPass(createUnreachableBlockEliminationPass());
  418. // Prepare expensive constants for SelectionDAG.
  419. if (getOptLevel() != CodeGenOpt::None && !DisableConstantHoisting)
  420. addPass(createConstantHoistingPass());
  421. if (getOptLevel() != CodeGenOpt::None && !DisablePartialLibcallInlining)
  422. addPass(createPartiallyInlineLibCallsPass());
  423. // Insert calls to mcount-like functions.
  424. addPass(createCountingFunctionInserterPass());
  425. // Add scalarization of target's unsupported masked memory intrinsics pass.
  426. // the unsupported intrinsic will be replaced with a chain of basic blocks,
  427. // that stores/loads element one-by-one if the appropriate mask bit is set.
  428. addPass(createScalarizeMaskedMemIntrinPass());
  429. // Expand reduction intrinsics into shuffle sequences if the target wants to.
  430. addPass(createExpandReductionsPass());
  431. }
  432. /// Turn exception handling constructs into something the code generators can
  433. /// handle.
  434. void TargetPassConfig::addPassesToHandleExceptions() {
  435. const MCAsmInfo *MCAI = TM->getMCAsmInfo();
  436. assert(MCAI && "No MCAsmInfo");
  437. switch (MCAI->getExceptionHandlingType()) {
  438. case ExceptionHandling::SjLj:
  439. // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
  440. // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
  441. // catch info can get misplaced when a selector ends up more than one block
  442. // removed from the parent invoke(s). This could happen when a landing
  443. // pad is shared by multiple invokes and is also a target of a normal
  444. // edge from elsewhere.
  445. addPass(createSjLjEHPreparePass());
  446. LLVM_FALLTHROUGH;
  447. case ExceptionHandling::DwarfCFI:
  448. case ExceptionHandling::ARM:
  449. addPass(createDwarfEHPass());
  450. break;
  451. case ExceptionHandling::WinEH:
  452. // We support using both GCC-style and MSVC-style exceptions on Windows, so
  453. // add both preparation passes. Each pass will only actually run if it
  454. // recognizes the personality function.
  455. addPass(createWinEHPass());
  456. addPass(createDwarfEHPass());
  457. break;
  458. case ExceptionHandling::None:
  459. addPass(createLowerInvokePass());
  460. // The lower invoke pass may create unreachable code. Remove it.
  461. addPass(createUnreachableBlockEliminationPass());
  462. break;
  463. }
  464. }
  465. /// Add pass to prepare the LLVM IR for code generation. This should be done
  466. /// before exception handling preparation passes.
  467. void TargetPassConfig::addCodeGenPrepare() {
  468. if (getOptLevel() != CodeGenOpt::None && !DisableCGP)
  469. addPass(createCodeGenPreparePass());
  470. addPass(createRewriteSymbolsPass());
  471. }
  472. /// Add common passes that perform LLVM IR to IR transforms in preparation for
  473. /// instruction selection.
  474. void TargetPassConfig::addISelPrepare() {
  475. addPreISel();
  476. // Force codegen to run according to the callgraph.
  477. if (requiresCodeGenSCCOrder())
  478. addPass(new DummyCGSCCPass);
  479. // Add both the safe stack and the stack protection passes: each of them will
  480. // only protect functions that have corresponding attributes.
  481. addPass(createSafeStackPass());
  482. addPass(createStackProtectorPass());
  483. if (PrintISelInput)
  484. addPass(createPrintFunctionPass(
  485. dbgs(), "\n\n*** Final LLVM Code input to ISel ***\n"));
  486. // All passes which modify the LLVM IR are now complete; run the verifier
  487. // to ensure that the IR is valid.
  488. if (!DisableVerify)
  489. addPass(createVerifierPass());
  490. }
  491. /// -regalloc=... command line option.
  492. static FunctionPass *useDefaultRegisterAllocator() { return nullptr; }
  493. static cl::opt<RegisterRegAlloc::FunctionPassCtor, false,
  494. RegisterPassParser<RegisterRegAlloc> >
  495. RegAlloc("regalloc",
  496. cl::init(&useDefaultRegisterAllocator),
  497. cl::desc("Register allocator to use"));
  498. /// Add the complete set of target-independent postISel code generator passes.
  499. ///
  500. /// This can be read as the standard order of major LLVM CodeGen stages. Stages
  501. /// with nontrivial configuration or multiple passes are broken out below in
  502. /// add%Stage routines.
  503. ///
  504. /// Any TargetPassConfig::addXX routine may be overriden by the Target. The
  505. /// addPre/Post methods with empty header implementations allow injecting
  506. /// target-specific fixups just before or after major stages. Additionally,
  507. /// targets have the flexibility to change pass order within a stage by
  508. /// overriding default implementation of add%Stage routines below. Each
  509. /// technique has maintainability tradeoffs because alternate pass orders are
  510. /// not well supported. addPre/Post works better if the target pass is easily
  511. /// tied to a common pass. But if it has subtle dependencies on multiple passes,
  512. /// the target should override the stage instead.
  513. ///
  514. /// TODO: We could use a single addPre/Post(ID) hook to allow pass injection
  515. /// before/after any target-independent pass. But it's currently overkill.
  516. void TargetPassConfig::addMachinePasses() {
  517. AddingMachinePasses = true;
  518. // Insert a machine instr printer pass after the specified pass.
  519. if (!StringRef(PrintMachineInstrs.getValue()).equals("") &&
  520. !StringRef(PrintMachineInstrs.getValue()).equals("option-unspecified")) {
  521. const PassRegistry *PR = PassRegistry::getPassRegistry();
  522. const PassInfo *TPI = PR->getPassInfo(PrintMachineInstrs.getValue());
  523. const PassInfo *IPI = PR->getPassInfo(StringRef("machineinstr-printer"));
  524. assert (TPI && IPI && "Pass ID not registered!");
  525. const char *TID = (const char *)(TPI->getTypeInfo());
  526. const char *IID = (const char *)(IPI->getTypeInfo());
  527. insertPass(TID, IID);
  528. }
  529. // Print the instruction selected machine code...
  530. printAndVerify("After Instruction Selection");
  531. if (TM->Options.EnableIPRA)
  532. addPass(createRegUsageInfoPropPass());
  533. // Expand pseudo-instructions emitted by ISel.
  534. addPass(&ExpandISelPseudosID);
  535. // Add passes that optimize machine instructions in SSA form.
  536. if (getOptLevel() != CodeGenOpt::None) {
  537. addMachineSSAOptimization();
  538. } else {
  539. // If the target requests it, assign local variables to stack slots relative
  540. // to one another and simplify frame index references where possible.
  541. addPass(&LocalStackSlotAllocationID, false);
  542. }
  543. // Run pre-ra passes.
  544. addPreRegAlloc();
  545. // Run register allocation and passes that are tightly coupled with it,
  546. // including phi elimination and scheduling.
  547. if (getOptimizeRegAlloc())
  548. addOptimizedRegAlloc(createRegAllocPass(true));
  549. else {
  550. if (RegAlloc != &useDefaultRegisterAllocator &&
  551. RegAlloc != &createFastRegisterAllocator)
  552. report_fatal_error("Must use fast (default) register allocator for unoptimized regalloc.");
  553. addFastRegAlloc(createRegAllocPass(false));
  554. }
  555. // Run post-ra passes.
  556. addPostRegAlloc();
  557. // Insert prolog/epilog code. Eliminate abstract frame index references...
  558. if (getOptLevel() != CodeGenOpt::None)
  559. addPass(&ShrinkWrapID);
  560. // Prolog/Epilog inserter needs a TargetMachine to instantiate. But only
  561. // do so if it hasn't been disabled, substituted, or overridden.
  562. if (!isPassSubstitutedOrOverridden(&PrologEpilogCodeInserterID))
  563. addPass(createPrologEpilogInserterPass());
  564. /// Add passes that optimize machine instructions after register allocation.
  565. if (getOptLevel() != CodeGenOpt::None)
  566. addMachineLateOptimization();
  567. // Expand pseudo instructions before second scheduling pass.
  568. addPass(&ExpandPostRAPseudosID);
  569. // Run pre-sched2 passes.
  570. addPreSched2();
  571. if (EnableImplicitNullChecks)
  572. addPass(&ImplicitNullChecksID);
  573. // Second pass scheduler.
  574. // Let Target optionally insert this pass by itself at some other
  575. // point.
  576. if (getOptLevel() != CodeGenOpt::None &&
  577. !TM->targetSchedulesPostRAScheduling()) {
  578. if (MISchedPostRA)
  579. addPass(&PostMachineSchedulerID);
  580. else
  581. addPass(&PostRASchedulerID);
  582. }
  583. // GC
  584. if (addGCPasses()) {
  585. if (PrintGCInfo)
  586. addPass(createGCInfoPrinter(dbgs()), false, false);
  587. }
  588. // Basic block placement.
  589. if (getOptLevel() != CodeGenOpt::None)
  590. addBlockPlacement();
  591. addPreEmitPass();
  592. if (TM->Options.EnableIPRA)
  593. // Collect register usage information and produce a register mask of
  594. // clobbered registers, to be used to optimize call sites.
  595. addPass(createRegUsageInfoCollector());
  596. addPass(&FuncletLayoutID, false);
  597. addPass(&StackMapLivenessID, false);
  598. addPass(&LiveDebugValuesID, false);
  599. // Insert before XRay Instrumentation.
  600. addPass(&FEntryInserterID, false);
  601. addPass(&XRayInstrumentationID, false);
  602. addPass(&PatchableFunctionID, false);
  603. if (EnableMachineOutliner)
  604. PM->add(createMachineOutlinerPass());
  605. AddingMachinePasses = false;
  606. }
  607. /// Add passes that optimize machine instructions in SSA form.
  608. void TargetPassConfig::addMachineSSAOptimization() {
  609. // Pre-ra tail duplication.
  610. addPass(&EarlyTailDuplicateID);
  611. // Optimize PHIs before DCE: removing dead PHI cycles may make more
  612. // instructions dead.
  613. addPass(&OptimizePHIsID, false);
  614. // This pass merges large allocas. StackSlotColoring is a different pass
  615. // which merges spill slots.
  616. addPass(&StackColoringID, false);
  617. // If the target requests it, assign local variables to stack slots relative
  618. // to one another and simplify frame index references where possible.
  619. addPass(&LocalStackSlotAllocationID, false);
  620. // With optimization, dead code should already be eliminated. However
  621. // there is one known exception: lowered code for arguments that are only
  622. // used by tail calls, where the tail calls reuse the incoming stack
  623. // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
  624. addPass(&DeadMachineInstructionElimID);
  625. // Allow targets to insert passes that improve instruction level parallelism,
  626. // like if-conversion. Such passes will typically need dominator trees and
  627. // loop info, just like LICM and CSE below.
  628. addILPOpts();
  629. addPass(&MachineLICMID, false);
  630. addPass(&MachineCSEID, false);
  631. // Coalesce basic blocks with the same branch condition
  632. addPass(&BranchCoalescingID);
  633. addPass(&MachineSinkingID);
  634. addPass(&PeepholeOptimizerID);
  635. // Clean-up the dead code that may have been generated by peephole
  636. // rewriting.
  637. addPass(&DeadMachineInstructionElimID);
  638. }
  639. //===---------------------------------------------------------------------===//
  640. /// Register Allocation Pass Configuration
  641. //===---------------------------------------------------------------------===//
  642. bool TargetPassConfig::getOptimizeRegAlloc() const {
  643. switch (OptimizeRegAlloc) {
  644. case cl::BOU_UNSET: return getOptLevel() != CodeGenOpt::None;
  645. case cl::BOU_TRUE: return true;
  646. case cl::BOU_FALSE: return false;
  647. }
  648. llvm_unreachable("Invalid optimize-regalloc state");
  649. }
  650. /// RegisterRegAlloc's global Registry tracks allocator registration.
  651. MachinePassRegistry RegisterRegAlloc::Registry;
  652. /// A dummy default pass factory indicates whether the register allocator is
  653. /// overridden on the command line.
  654. static llvm::once_flag InitializeDefaultRegisterAllocatorFlag;
  655. static RegisterRegAlloc
  656. defaultRegAlloc("default",
  657. "pick register allocator based on -O option",
  658. useDefaultRegisterAllocator);
  659. static void initializeDefaultRegisterAllocatorOnce() {
  660. RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
  661. if (!Ctor) {
  662. Ctor = RegAlloc;
  663. RegisterRegAlloc::setDefault(RegAlloc);
  664. }
  665. }
  666. /// Instantiate the default register allocator pass for this target for either
  667. /// the optimized or unoptimized allocation path. This will be added to the pass
  668. /// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
  669. /// in the optimized case.
  670. ///
  671. /// A target that uses the standard regalloc pass order for fast or optimized
  672. /// allocation may still override this for per-target regalloc
  673. /// selection. But -regalloc=... always takes precedence.
  674. FunctionPass *TargetPassConfig::createTargetRegisterAllocator(bool Optimized) {
  675. if (Optimized)
  676. return createGreedyRegisterAllocator();
  677. else
  678. return createFastRegisterAllocator();
  679. }
  680. /// Find and instantiate the register allocation pass requested by this target
  681. /// at the current optimization level. Different register allocators are
  682. /// defined as separate passes because they may require different analysis.
  683. ///
  684. /// This helper ensures that the regalloc= option is always available,
  685. /// even for targets that override the default allocator.
  686. ///
  687. /// FIXME: When MachinePassRegistry register pass IDs instead of function ptrs,
  688. /// this can be folded into addPass.
  689. FunctionPass *TargetPassConfig::createRegAllocPass(bool Optimized) {
  690. // Initialize the global default.
  691. llvm::call_once(InitializeDefaultRegisterAllocatorFlag,
  692. initializeDefaultRegisterAllocatorOnce);
  693. RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
  694. if (Ctor != useDefaultRegisterAllocator)
  695. return Ctor();
  696. // With no -regalloc= override, ask the target for a regalloc pass.
  697. return createTargetRegisterAllocator(Optimized);
  698. }
  699. /// Return true if the default global register allocator is in use and
  700. /// has not be overriden on the command line with '-regalloc=...'
  701. bool TargetPassConfig::usingDefaultRegAlloc() const {
  702. return RegAlloc.getNumOccurrences() == 0;
  703. }
  704. /// Add the minimum set of target-independent passes that are required for
  705. /// register allocation. No coalescing or scheduling.
  706. void TargetPassConfig::addFastRegAlloc(FunctionPass *RegAllocPass) {
  707. addPass(&PHIEliminationID, false);
  708. addPass(&TwoAddressInstructionPassID, false);
  709. if (RegAllocPass)
  710. addPass(RegAllocPass);
  711. }
  712. /// Add standard target-independent passes that are tightly coupled with
  713. /// optimized register allocation, including coalescing, machine instruction
  714. /// scheduling, and register allocation itself.
  715. void TargetPassConfig::addOptimizedRegAlloc(FunctionPass *RegAllocPass) {
  716. addPass(&DetectDeadLanesID, false);
  717. addPass(&ProcessImplicitDefsID, false);
  718. // LiveVariables currently requires pure SSA form.
  719. //
  720. // FIXME: Once TwoAddressInstruction pass no longer uses kill flags,
  721. // LiveVariables can be removed completely, and LiveIntervals can be directly
  722. // computed. (We still either need to regenerate kill flags after regalloc, or
  723. // preferably fix the scavenger to not depend on them).
  724. addPass(&LiveVariablesID, false);
  725. // Edge splitting is smarter with machine loop info.
  726. addPass(&MachineLoopInfoID, false);
  727. addPass(&PHIEliminationID, false);
  728. // Eventually, we want to run LiveIntervals before PHI elimination.
  729. if (EarlyLiveIntervals)
  730. addPass(&LiveIntervalsID, false);
  731. addPass(&TwoAddressInstructionPassID, false);
  732. addPass(&RegisterCoalescerID);
  733. // The machine scheduler may accidentally create disconnected components
  734. // when moving subregister definitions around, avoid this by splitting them to
  735. // separate vregs before. Splitting can also improve reg. allocation quality.
  736. addPass(&RenameIndependentSubregsID);
  737. // PreRA instruction scheduling.
  738. addPass(&MachineSchedulerID);
  739. if (RegAllocPass) {
  740. // Add the selected register allocation pass.
  741. addPass(RegAllocPass);
  742. // Allow targets to change the register assignments before rewriting.
  743. addPreRewrite();
  744. // Finally rewrite virtual registers.
  745. addPass(&VirtRegRewriterID);
  746. // Perform stack slot coloring and post-ra machine LICM.
  747. //
  748. // FIXME: Re-enable coloring with register when it's capable of adding
  749. // kill markers.
  750. addPass(&StackSlotColoringID);
  751. // Run post-ra machine LICM to hoist reloads / remats.
  752. //
  753. // FIXME: can this move into MachineLateOptimization?
  754. addPass(&PostRAMachineLICMID);
  755. }
  756. }
  757. //===---------------------------------------------------------------------===//
  758. /// Post RegAlloc Pass Configuration
  759. //===---------------------------------------------------------------------===//
  760. /// Add passes that optimize machine instructions after register allocation.
  761. void TargetPassConfig::addMachineLateOptimization() {
  762. // Branch folding must be run after regalloc and prolog/epilog insertion.
  763. addPass(&BranchFolderPassID);
  764. // Tail duplication.
  765. // Note that duplicating tail just increases code size and degrades
  766. // performance for targets that require Structured Control Flow.
  767. // In addition it can also make CFG irreducible. Thus we disable it.
  768. if (!TM->requiresStructuredCFG())
  769. addPass(&TailDuplicateID);
  770. // Copy propagation.
  771. addPass(&MachineCopyPropagationID);
  772. }
  773. /// Add standard GC passes.
  774. bool TargetPassConfig::addGCPasses() {
  775. addPass(&GCMachineCodeAnalysisID, false);
  776. return true;
  777. }
  778. /// Add standard basic block placement passes.
  779. void TargetPassConfig::addBlockPlacement() {
  780. if (addPass(&MachineBlockPlacementID)) {
  781. // Run a separate pass to collect block placement statistics.
  782. if (EnableBlockPlacementStats)
  783. addPass(&MachineBlockPlacementStatsID);
  784. }
  785. }
  786. //===---------------------------------------------------------------------===//
  787. /// GlobalISel Configuration
  788. //===---------------------------------------------------------------------===//
  789. bool TargetPassConfig::isGlobalISelEnabled() const {
  790. return false;
  791. }
  792. bool TargetPassConfig::isGlobalISelAbortEnabled() const {
  793. return EnableGlobalISelAbort == 1;
  794. }
  795. bool TargetPassConfig::reportDiagnosticWhenGlobalISelFallback() const {
  796. return EnableGlobalISelAbort == 2;
  797. }