TargetPassConfig.cpp 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543
  1. //===- TargetPassConfig.cpp - Target independent code generation passes ---===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines interfaces to access the target independent code
  10. // generation passes provided by the LLVM backend.
  11. //
  12. //===---------------------------------------------------------------------===//
  13. #include "llvm/CodeGen/TargetPassConfig.h"
  14. #include "llvm/ADT/DenseMap.h"
  15. #include "llvm/ADT/SmallVector.h"
  16. #include "llvm/ADT/StringRef.h"
  17. #include "llvm/Analysis/BasicAliasAnalysis.h"
  18. #include "llvm/Analysis/CFLAndersAliasAnalysis.h"
  19. #include "llvm/Analysis/CFLSteensAliasAnalysis.h"
  20. #include "llvm/Analysis/CallGraphSCCPass.h"
  21. #include "llvm/Analysis/ScopedNoAliasAA.h"
  22. #include "llvm/Analysis/TargetTransformInfo.h"
  23. #include "llvm/Analysis/TypeBasedAliasAnalysis.h"
  24. #include "llvm/CodeGen/CSEConfigBase.h"
  25. #include "llvm/CodeGen/MachineFunctionPass.h"
  26. #include "llvm/CodeGen/MachinePassRegistry.h"
  27. #include "llvm/CodeGen/Passes.h"
  28. #include "llvm/CodeGen/RegAllocRegistry.h"
  29. #include "llvm/IR/IRPrintingPasses.h"
  30. #include "llvm/IR/LegacyPassManager.h"
  31. #include "llvm/IR/PassInstrumentation.h"
  32. #include "llvm/IR/Verifier.h"
  33. #include "llvm/InitializePasses.h"
  34. #include "llvm/MC/MCAsmInfo.h"
  35. #include "llvm/MC/MCTargetOptions.h"
  36. #include "llvm/Pass.h"
  37. #include "llvm/Support/CodeGen.h"
  38. #include "llvm/Support/CommandLine.h"
  39. #include "llvm/Support/Compiler.h"
  40. #include "llvm/Support/Debug.h"
  41. #include "llvm/Support/Discriminator.h"
  42. #include "llvm/Support/ErrorHandling.h"
  43. #include "llvm/Support/SaveAndRestore.h"
  44. #include "llvm/Support/Threading.h"
  45. #include "llvm/Target/CGPassBuilderOption.h"
  46. #include "llvm/Target/TargetMachine.h"
  47. #include "llvm/Transforms/Scalar.h"
  48. #include "llvm/Transforms/Utils.h"
  49. #include "llvm/Transforms/Utils/SymbolRewriter.h"
  50. #include <cassert>
  51. #include <string>
  52. using namespace llvm;
  53. static cl::opt<bool>
  54. EnableIPRA("enable-ipra", cl::init(false), cl::Hidden,
  55. cl::desc("Enable interprocedural register allocation "
  56. "to reduce load/store at procedure calls."));
  57. static cl::opt<bool> DisablePostRASched("disable-post-ra", cl::Hidden,
  58. cl::desc("Disable Post Regalloc Scheduler"));
  59. static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
  60. cl::desc("Disable branch folding"));
  61. static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
  62. cl::desc("Disable tail duplication"));
  63. static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
  64. cl::desc("Disable pre-register allocation tail duplication"));
  65. static cl::opt<bool> DisableBlockPlacement("disable-block-placement",
  66. cl::Hidden, cl::desc("Disable probability-driven block placement"));
  67. static cl::opt<bool> EnableBlockPlacementStats("enable-block-placement-stats",
  68. cl::Hidden, cl::desc("Collect probability-driven block placement stats"));
  69. static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
  70. cl::desc("Disable Stack Slot Coloring"));
  71. static cl::opt<bool> DisableMachineDCE("disable-machine-dce", cl::Hidden,
  72. cl::desc("Disable Machine Dead Code Elimination"));
  73. static cl::opt<bool> DisableEarlyIfConversion("disable-early-ifcvt", cl::Hidden,
  74. cl::desc("Disable Early If-conversion"));
  75. static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
  76. cl::desc("Disable Machine LICM"));
  77. static cl::opt<bool> DisableMachineCSE("disable-machine-cse", cl::Hidden,
  78. cl::desc("Disable Machine Common Subexpression Elimination"));
  79. static cl::opt<cl::boolOrDefault> OptimizeRegAlloc(
  80. "optimize-regalloc", cl::Hidden,
  81. cl::desc("Enable optimized register allocation compilation path."));
  82. static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm",
  83. cl::Hidden,
  84. cl::desc("Disable Machine LICM"));
  85. static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
  86. cl::desc("Disable Machine Sinking"));
  87. static cl::opt<bool> DisablePostRAMachineSink("disable-postra-machine-sink",
  88. cl::Hidden,
  89. cl::desc("Disable PostRA Machine Sinking"));
  90. static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
  91. cl::desc("Disable Loop Strength Reduction Pass"));
  92. static cl::opt<bool> DisableConstantHoisting("disable-constant-hoisting",
  93. cl::Hidden, cl::desc("Disable ConstantHoisting"));
  94. static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
  95. cl::desc("Disable Codegen Prepare"));
  96. static cl::opt<bool> DisableCopyProp("disable-copyprop", cl::Hidden,
  97. cl::desc("Disable Copy Propagation pass"));
  98. static cl::opt<bool> DisablePartialLibcallInlining("disable-partial-libcall-inlining",
  99. cl::Hidden, cl::desc("Disable Partial Libcall Inlining"));
  100. static cl::opt<bool> EnableImplicitNullChecks(
  101. "enable-implicit-null-checks",
  102. cl::desc("Fold null checks into faulting memory operations"),
  103. cl::init(false), cl::Hidden);
  104. static cl::opt<bool> DisableMergeICmps("disable-mergeicmps",
  105. cl::desc("Disable MergeICmps Pass"),
  106. cl::init(false), cl::Hidden);
  107. static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
  108. cl::desc("Print LLVM IR produced by the loop-reduce pass"));
  109. static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
  110. cl::desc("Print LLVM IR input to isel pass"));
  111. static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
  112. cl::desc("Dump garbage collector data"));
  113. static cl::opt<cl::boolOrDefault>
  114. VerifyMachineCode("verify-machineinstrs", cl::Hidden,
  115. cl::desc("Verify generated machine code"),
  116. cl::ZeroOrMore);
  117. static cl::opt<cl::boolOrDefault> DebugifyAndStripAll(
  118. "debugify-and-strip-all-safe", cl::Hidden,
  119. cl::desc(
  120. "Debugify MIR before and Strip debug after "
  121. "each pass except those known to be unsafe when debug info is present"),
  122. cl::ZeroOrMore);
  123. static cl::opt<cl::boolOrDefault> DebugifyCheckAndStripAll(
  124. "debugify-check-and-strip-all-safe", cl::Hidden,
  125. cl::desc(
  126. "Debugify MIR before, by checking and stripping the debug info after, "
  127. "each pass except those known to be unsafe when debug info is present"),
  128. cl::ZeroOrMore);
  129. // Enable or disable the MachineOutliner.
  130. static cl::opt<RunOutliner> EnableMachineOutliner(
  131. "enable-machine-outliner", cl::desc("Enable the machine outliner"),
  132. cl::Hidden, cl::ValueOptional, cl::init(RunOutliner::TargetDefault),
  133. cl::values(clEnumValN(RunOutliner::AlwaysOutline, "always",
  134. "Run on all functions guaranteed to be beneficial"),
  135. clEnumValN(RunOutliner::NeverOutline, "never",
  136. "Disable all outlining"),
  137. // Sentinel value for unspecified option.
  138. clEnumValN(RunOutliner::AlwaysOutline, "", "")));
  139. // Enable or disable FastISel. Both options are needed, because
  140. // FastISel is enabled by default with -fast, and we wish to be
  141. // able to enable or disable fast-isel independently from -O0.
  142. static cl::opt<cl::boolOrDefault>
  143. EnableFastISelOption("fast-isel", cl::Hidden,
  144. cl::desc("Enable the \"fast\" instruction selector"));
  145. static cl::opt<cl::boolOrDefault> EnableGlobalISelOption(
  146. "global-isel", cl::Hidden,
  147. cl::desc("Enable the \"global\" instruction selector"));
  148. // FIXME: remove this after switching to NPM or GlobalISel, whichever gets there
  149. // first...
  150. static cl::opt<bool>
  151. PrintAfterISel("print-after-isel", cl::init(false), cl::Hidden,
  152. cl::desc("Print machine instrs after ISel"));
  153. static cl::opt<GlobalISelAbortMode> EnableGlobalISelAbort(
  154. "global-isel-abort", cl::Hidden,
  155. cl::desc("Enable abort calls when \"global\" instruction selection "
  156. "fails to lower/select an instruction"),
  157. cl::values(
  158. clEnumValN(GlobalISelAbortMode::Disable, "0", "Disable the abort"),
  159. clEnumValN(GlobalISelAbortMode::Enable, "1", "Enable the abort"),
  160. clEnumValN(GlobalISelAbortMode::DisableWithDiag, "2",
  161. "Disable the abort but emit a diagnostic on failure")));
  162. // An option that disables inserting FS-AFDO discriminators before emit.
  163. // This is mainly for debugging and tuning purpose.
  164. static cl::opt<bool>
  165. FSNoFinalDiscrim("fs-no-final-discrim", cl::init(false), cl::Hidden,
  166. cl::desc("Do not insert FS-AFDO discriminators before "
  167. "emit."));
  168. // Disable MIRProfileLoader before RegAlloc. This is for for debugging and
  169. // tuning purpose.
  170. static cl::opt<bool> DisableRAFSProfileLoader(
  171. "disable-ra-fsprofile-loader", cl::init(true), cl::Hidden,
  172. cl::desc("Disable MIRProfileLoader before RegAlloc"));
  173. // Disable MIRProfileLoader before BloackPlacement. This is for for debugging
  174. // and tuning purpose.
  175. static cl::opt<bool> DisableLayoutFSProfileLoader(
  176. "disable-layout-fsprofile-loader", cl::init(true), cl::Hidden,
  177. cl::desc("Disable MIRProfileLoader before BlockPlacement"));
  178. // Specify FSProfile file name.
  179. static cl::opt<std::string>
  180. FSProfileFile("fs-profile-file", cl::init(""), cl::value_desc("filename"),
  181. cl::desc("Flow Sensitive profile file name."), cl::Hidden);
  182. // Specify Remapping file for FSProfile.
  183. static cl::opt<std::string> FSRemappingFile(
  184. "fs-remapping-file", cl::init(""), cl::value_desc("filename"),
  185. cl::desc("Flow Sensitive profile remapping file name."), cl::Hidden);
  186. // Temporary option to allow experimenting with MachineScheduler as a post-RA
  187. // scheduler. Targets can "properly" enable this with
  188. // substitutePass(&PostRASchedulerID, &PostMachineSchedulerID).
  189. // Targets can return true in targetSchedulesPostRAScheduling() and
  190. // insert a PostRA scheduling pass wherever it wants.
  191. static cl::opt<bool> MISchedPostRA(
  192. "misched-postra", cl::Hidden,
  193. cl::desc(
  194. "Run MachineScheduler post regalloc (independent of preRA sched)"));
  195. // Experimental option to run live interval analysis early.
  196. static cl::opt<bool> EarlyLiveIntervals("early-live-intervals", cl::Hidden,
  197. cl::desc("Run live interval analysis earlier in the pipeline"));
  198. // Experimental option to use CFL-AA in codegen
  199. static cl::opt<CFLAAType> UseCFLAA(
  200. "use-cfl-aa-in-codegen", cl::init(CFLAAType::None), cl::Hidden,
  201. cl::desc("Enable the new, experimental CFL alias analysis in CodeGen"),
  202. cl::values(clEnumValN(CFLAAType::None, "none", "Disable CFL-AA"),
  203. clEnumValN(CFLAAType::Steensgaard, "steens",
  204. "Enable unification-based CFL-AA"),
  205. clEnumValN(CFLAAType::Andersen, "anders",
  206. "Enable inclusion-based CFL-AA"),
  207. clEnumValN(CFLAAType::Both, "both",
  208. "Enable both variants of CFL-AA")));
  209. /// Option names for limiting the codegen pipeline.
  210. /// Those are used in error reporting and we didn't want
  211. /// to duplicate their names all over the place.
  212. static const char StartAfterOptName[] = "start-after";
  213. static const char StartBeforeOptName[] = "start-before";
  214. static const char StopAfterOptName[] = "stop-after";
  215. static const char StopBeforeOptName[] = "stop-before";
  216. static cl::opt<std::string>
  217. StartAfterOpt(StringRef(StartAfterOptName),
  218. cl::desc("Resume compilation after a specific pass"),
  219. cl::value_desc("pass-name"), cl::init(""), cl::Hidden);
  220. static cl::opt<std::string>
  221. StartBeforeOpt(StringRef(StartBeforeOptName),
  222. cl::desc("Resume compilation before a specific pass"),
  223. cl::value_desc("pass-name"), cl::init(""), cl::Hidden);
  224. static cl::opt<std::string>
  225. StopAfterOpt(StringRef(StopAfterOptName),
  226. cl::desc("Stop compilation after a specific pass"),
  227. cl::value_desc("pass-name"), cl::init(""), cl::Hidden);
  228. static cl::opt<std::string>
  229. StopBeforeOpt(StringRef(StopBeforeOptName),
  230. cl::desc("Stop compilation before a specific pass"),
  231. cl::value_desc("pass-name"), cl::init(""), cl::Hidden);
  232. /// Enable the machine function splitter pass.
  233. static cl::opt<bool> EnableMachineFunctionSplitter(
  234. "enable-split-machine-functions", cl::Hidden,
  235. cl::desc("Split out cold blocks from machine functions based on profile "
  236. "information."));
  237. /// Disable the expand reductions pass for testing.
  238. static cl::opt<bool> DisableExpandReductions(
  239. "disable-expand-reductions", cl::init(false), cl::Hidden,
  240. cl::desc("Disable the expand reduction intrinsics pass from running"));
  241. /// Allow standard passes to be disabled by command line options. This supports
  242. /// simple binary flags that either suppress the pass or do nothing.
  243. /// i.e. -disable-mypass=false has no effect.
  244. /// These should be converted to boolOrDefault in order to use applyOverride.
  245. static IdentifyingPassPtr applyDisable(IdentifyingPassPtr PassID,
  246. bool Override) {
  247. if (Override)
  248. return IdentifyingPassPtr();
  249. return PassID;
  250. }
  251. /// Allow standard passes to be disabled by the command line, regardless of who
  252. /// is adding the pass.
  253. ///
  254. /// StandardID is the pass identified in the standard pass pipeline and provided
  255. /// to addPass(). It may be a target-specific ID in the case that the target
  256. /// directly adds its own pass, but in that case we harmlessly fall through.
  257. ///
  258. /// TargetID is the pass that the target has configured to override StandardID.
  259. ///
  260. /// StandardID may be a pseudo ID. In that case TargetID is the name of the real
  261. /// pass to run. This allows multiple options to control a single pass depending
  262. /// on where in the pipeline that pass is added.
  263. static IdentifyingPassPtr overridePass(AnalysisID StandardID,
  264. IdentifyingPassPtr TargetID) {
  265. if (StandardID == &PostRASchedulerID)
  266. return applyDisable(TargetID, DisablePostRASched);
  267. if (StandardID == &BranchFolderPassID)
  268. return applyDisable(TargetID, DisableBranchFold);
  269. if (StandardID == &TailDuplicateID)
  270. return applyDisable(TargetID, DisableTailDuplicate);
  271. if (StandardID == &EarlyTailDuplicateID)
  272. return applyDisable(TargetID, DisableEarlyTailDup);
  273. if (StandardID == &MachineBlockPlacementID)
  274. return applyDisable(TargetID, DisableBlockPlacement);
  275. if (StandardID == &StackSlotColoringID)
  276. return applyDisable(TargetID, DisableSSC);
  277. if (StandardID == &DeadMachineInstructionElimID)
  278. return applyDisable(TargetID, DisableMachineDCE);
  279. if (StandardID == &EarlyIfConverterID)
  280. return applyDisable(TargetID, DisableEarlyIfConversion);
  281. if (StandardID == &EarlyMachineLICMID)
  282. return applyDisable(TargetID, DisableMachineLICM);
  283. if (StandardID == &MachineCSEID)
  284. return applyDisable(TargetID, DisableMachineCSE);
  285. if (StandardID == &MachineLICMID)
  286. return applyDisable(TargetID, DisablePostRAMachineLICM);
  287. if (StandardID == &MachineSinkingID)
  288. return applyDisable(TargetID, DisableMachineSink);
  289. if (StandardID == &PostRAMachineSinkingID)
  290. return applyDisable(TargetID, DisablePostRAMachineSink);
  291. if (StandardID == &MachineCopyPropagationID)
  292. return applyDisable(TargetID, DisableCopyProp);
  293. return TargetID;
  294. }
  295. // Find the FSProfile file name. The internal option takes the precedence
  296. // before getting from TargetMachine.
  297. static std::string getFSProfileFile(const TargetMachine *TM) {
  298. if (!FSProfileFile.empty())
  299. return FSProfileFile.getValue();
  300. const Optional<PGOOptions> &PGOOpt = TM->getPGOOption();
  301. if (PGOOpt == None || PGOOpt->Action != PGOOptions::SampleUse)
  302. return std::string();
  303. return PGOOpt->ProfileFile;
  304. }
  305. // Find the Profile remapping file name. The internal option takes the
  306. // precedence before getting from TargetMachine.
  307. static std::string getFSRemappingFile(const TargetMachine *TM) {
  308. if (!FSRemappingFile.empty())
  309. return FSRemappingFile.getValue();
  310. const Optional<PGOOptions> &PGOOpt = TM->getPGOOption();
  311. if (PGOOpt == None || PGOOpt->Action != PGOOptions::SampleUse)
  312. return std::string();
  313. return PGOOpt->ProfileRemappingFile;
  314. }
  315. //===---------------------------------------------------------------------===//
  316. /// TargetPassConfig
  317. //===---------------------------------------------------------------------===//
  318. INITIALIZE_PASS(TargetPassConfig, "targetpassconfig",
  319. "Target Pass Configuration", false, false)
  320. char TargetPassConfig::ID = 0;
  321. namespace {
  322. struct InsertedPass {
  323. AnalysisID TargetPassID;
  324. IdentifyingPassPtr InsertedPassID;
  325. InsertedPass(AnalysisID TargetPassID, IdentifyingPassPtr InsertedPassID)
  326. : TargetPassID(TargetPassID), InsertedPassID(InsertedPassID) {}
  327. Pass *getInsertedPass() const {
  328. assert(InsertedPassID.isValid() && "Illegal Pass ID!");
  329. if (InsertedPassID.isInstance())
  330. return InsertedPassID.getInstance();
  331. Pass *NP = Pass::createPass(InsertedPassID.getID());
  332. assert(NP && "Pass ID not registered");
  333. return NP;
  334. }
  335. };
  336. } // end anonymous namespace
  337. namespace llvm {
  338. extern cl::opt<bool> EnableFSDiscriminator;
  339. class PassConfigImpl {
  340. public:
  341. // List of passes explicitly substituted by this target. Normally this is
  342. // empty, but it is a convenient way to suppress or replace specific passes
  343. // that are part of a standard pass pipeline without overridding the entire
  344. // pipeline. This mechanism allows target options to inherit a standard pass's
  345. // user interface. For example, a target may disable a standard pass by
  346. // default by substituting a pass ID of zero, and the user may still enable
  347. // that standard pass with an explicit command line option.
  348. DenseMap<AnalysisID,IdentifyingPassPtr> TargetPasses;
  349. /// Store the pairs of <AnalysisID, AnalysisID> of which the second pass
  350. /// is inserted after each instance of the first one.
  351. SmallVector<InsertedPass, 4> InsertedPasses;
  352. };
  353. } // end namespace llvm
  354. // Out of line virtual method.
  355. TargetPassConfig::~TargetPassConfig() {
  356. delete Impl;
  357. }
  358. static const PassInfo *getPassInfo(StringRef PassName) {
  359. if (PassName.empty())
  360. return nullptr;
  361. const PassRegistry &PR = *PassRegistry::getPassRegistry();
  362. const PassInfo *PI = PR.getPassInfo(PassName);
  363. if (!PI)
  364. report_fatal_error(Twine('\"') + Twine(PassName) +
  365. Twine("\" pass is not registered."));
  366. return PI;
  367. }
  368. static AnalysisID getPassIDFromName(StringRef PassName) {
  369. const PassInfo *PI = getPassInfo(PassName);
  370. return PI ? PI->getTypeInfo() : nullptr;
  371. }
  372. static std::pair<StringRef, unsigned>
  373. getPassNameAndInstanceNum(StringRef PassName) {
  374. StringRef Name, InstanceNumStr;
  375. std::tie(Name, InstanceNumStr) = PassName.split(',');
  376. unsigned InstanceNum = 0;
  377. if (!InstanceNumStr.empty() && InstanceNumStr.getAsInteger(10, InstanceNum))
  378. report_fatal_error("invalid pass instance specifier " + PassName);
  379. return std::make_pair(Name, InstanceNum);
  380. }
  381. void TargetPassConfig::setStartStopPasses() {
  382. StringRef StartBeforeName;
  383. std::tie(StartBeforeName, StartBeforeInstanceNum) =
  384. getPassNameAndInstanceNum(StartBeforeOpt);
  385. StringRef StartAfterName;
  386. std::tie(StartAfterName, StartAfterInstanceNum) =
  387. getPassNameAndInstanceNum(StartAfterOpt);
  388. StringRef StopBeforeName;
  389. std::tie(StopBeforeName, StopBeforeInstanceNum)
  390. = getPassNameAndInstanceNum(StopBeforeOpt);
  391. StringRef StopAfterName;
  392. std::tie(StopAfterName, StopAfterInstanceNum)
  393. = getPassNameAndInstanceNum(StopAfterOpt);
  394. StartBefore = getPassIDFromName(StartBeforeName);
  395. StartAfter = getPassIDFromName(StartAfterName);
  396. StopBefore = getPassIDFromName(StopBeforeName);
  397. StopAfter = getPassIDFromName(StopAfterName);
  398. if (StartBefore && StartAfter)
  399. report_fatal_error(Twine(StartBeforeOptName) + Twine(" and ") +
  400. Twine(StartAfterOptName) + Twine(" specified!"));
  401. if (StopBefore && StopAfter)
  402. report_fatal_error(Twine(StopBeforeOptName) + Twine(" and ") +
  403. Twine(StopAfterOptName) + Twine(" specified!"));
  404. Started = (StartAfter == nullptr) && (StartBefore == nullptr);
  405. }
  406. CGPassBuilderOption llvm::getCGPassBuilderOption() {
  407. CGPassBuilderOption Opt;
  408. #define SET_OPTION(Option) \
  409. if (Option.getNumOccurrences()) \
  410. Opt.Option = Option;
  411. SET_OPTION(EnableFastISelOption)
  412. SET_OPTION(EnableGlobalISelAbort)
  413. SET_OPTION(EnableGlobalISelOption)
  414. SET_OPTION(EnableIPRA)
  415. SET_OPTION(OptimizeRegAlloc)
  416. SET_OPTION(VerifyMachineCode)
  417. #define SET_BOOLEAN_OPTION(Option) Opt.Option = Option;
  418. SET_BOOLEAN_OPTION(EarlyLiveIntervals)
  419. SET_BOOLEAN_OPTION(EnableBlockPlacementStats)
  420. SET_BOOLEAN_OPTION(EnableImplicitNullChecks)
  421. SET_BOOLEAN_OPTION(EnableMachineOutliner)
  422. SET_BOOLEAN_OPTION(MISchedPostRA)
  423. SET_BOOLEAN_OPTION(UseCFLAA)
  424. SET_BOOLEAN_OPTION(DisableMergeICmps)
  425. SET_BOOLEAN_OPTION(DisableLSR)
  426. SET_BOOLEAN_OPTION(DisableConstantHoisting)
  427. SET_BOOLEAN_OPTION(DisableCGP)
  428. SET_BOOLEAN_OPTION(DisablePartialLibcallInlining)
  429. SET_BOOLEAN_OPTION(PrintLSR)
  430. SET_BOOLEAN_OPTION(PrintISelInput)
  431. SET_BOOLEAN_OPTION(PrintGCInfo)
  432. return Opt;
  433. }
  434. static void registerPartialPipelineCallback(PassInstrumentationCallbacks &PIC,
  435. LLVMTargetMachine &LLVMTM) {
  436. StringRef StartBefore;
  437. StringRef StartAfter;
  438. StringRef StopBefore;
  439. StringRef StopAfter;
  440. unsigned StartBeforeInstanceNum = 0;
  441. unsigned StartAfterInstanceNum = 0;
  442. unsigned StopBeforeInstanceNum = 0;
  443. unsigned StopAfterInstanceNum = 0;
  444. std::tie(StartBefore, StartBeforeInstanceNum) =
  445. getPassNameAndInstanceNum(StartBeforeOpt);
  446. std::tie(StartAfter, StartAfterInstanceNum) =
  447. getPassNameAndInstanceNum(StartAfterOpt);
  448. std::tie(StopBefore, StopBeforeInstanceNum) =
  449. getPassNameAndInstanceNum(StopBeforeOpt);
  450. std::tie(StopAfter, StopAfterInstanceNum) =
  451. getPassNameAndInstanceNum(StopAfterOpt);
  452. if (StartBefore.empty() && StartAfter.empty() && StopBefore.empty() &&
  453. StopAfter.empty())
  454. return;
  455. std::tie(StartBefore, std::ignore) =
  456. LLVMTM.getPassNameFromLegacyName(StartBefore);
  457. std::tie(StartAfter, std::ignore) =
  458. LLVMTM.getPassNameFromLegacyName(StartAfter);
  459. std::tie(StopBefore, std::ignore) =
  460. LLVMTM.getPassNameFromLegacyName(StopBefore);
  461. std::tie(StopAfter, std::ignore) =
  462. LLVMTM.getPassNameFromLegacyName(StopAfter);
  463. if (!StartBefore.empty() && !StartAfter.empty())
  464. report_fatal_error(Twine(StartBeforeOptName) + Twine(" and ") +
  465. Twine(StartAfterOptName) + Twine(" specified!"));
  466. if (!StopBefore.empty() && !StopAfter.empty())
  467. report_fatal_error(Twine(StopBeforeOptName) + Twine(" and ") +
  468. Twine(StopAfterOptName) + Twine(" specified!"));
  469. PIC.registerShouldRunOptionalPassCallback(
  470. [=, EnableCurrent = StartBefore.empty() && StartAfter.empty(),
  471. EnableNext = Optional<bool>(), StartBeforeCount = 0u,
  472. StartAfterCount = 0u, StopBeforeCount = 0u,
  473. StopAfterCount = 0u](StringRef P, Any) mutable {
  474. bool StartBeforePass = !StartBefore.empty() && P.contains(StartBefore);
  475. bool StartAfterPass = !StartAfter.empty() && P.contains(StartAfter);
  476. bool StopBeforePass = !StopBefore.empty() && P.contains(StopBefore);
  477. bool StopAfterPass = !StopAfter.empty() && P.contains(StopAfter);
  478. // Implement -start-after/-stop-after
  479. if (EnableNext) {
  480. EnableCurrent = *EnableNext;
  481. EnableNext.reset();
  482. }
  483. // Using PIC.registerAfterPassCallback won't work because if this
  484. // callback returns false, AfterPassCallback is also skipped.
  485. if (StartAfterPass && StartAfterCount++ == StartAfterInstanceNum) {
  486. assert(!EnableNext && "Error: assign to EnableNext more than once");
  487. EnableNext = true;
  488. }
  489. if (StopAfterPass && StopAfterCount++ == StopAfterInstanceNum) {
  490. assert(!EnableNext && "Error: assign to EnableNext more than once");
  491. EnableNext = false;
  492. }
  493. if (StartBeforePass && StartBeforeCount++ == StartBeforeInstanceNum)
  494. EnableCurrent = true;
  495. if (StopBeforePass && StopBeforeCount++ == StopBeforeInstanceNum)
  496. EnableCurrent = false;
  497. return EnableCurrent;
  498. });
  499. }
  500. void llvm::registerCodeGenCallback(PassInstrumentationCallbacks &PIC,
  501. LLVMTargetMachine &LLVMTM) {
  502. // Register a callback for disabling passes.
  503. PIC.registerShouldRunOptionalPassCallback([](StringRef P, Any) {
  504. #define DISABLE_PASS(Option, Name) \
  505. if (Option && P.contains(#Name)) \
  506. return false;
  507. DISABLE_PASS(DisableBlockPlacement, MachineBlockPlacementPass)
  508. DISABLE_PASS(DisableBranchFold, BranchFolderPass)
  509. DISABLE_PASS(DisableCopyProp, MachineCopyPropagationPass)
  510. DISABLE_PASS(DisableEarlyIfConversion, EarlyIfConverterPass)
  511. DISABLE_PASS(DisableEarlyTailDup, EarlyTailDuplicatePass)
  512. DISABLE_PASS(DisableMachineCSE, MachineCSEPass)
  513. DISABLE_PASS(DisableMachineDCE, DeadMachineInstructionElimPass)
  514. DISABLE_PASS(DisableMachineLICM, EarlyMachineLICMPass)
  515. DISABLE_PASS(DisableMachineSink, MachineSinkingPass)
  516. DISABLE_PASS(DisablePostRAMachineLICM, MachineLICMPass)
  517. DISABLE_PASS(DisablePostRAMachineSink, PostRAMachineSinkingPass)
  518. DISABLE_PASS(DisablePostRASched, PostRASchedulerPass)
  519. DISABLE_PASS(DisableSSC, StackSlotColoringPass)
  520. DISABLE_PASS(DisableTailDuplicate, TailDuplicatePass)
  521. return true;
  522. });
  523. registerPartialPipelineCallback(PIC, LLVMTM);
  524. }
  525. // Out of line constructor provides default values for pass options and
  526. // registers all common codegen passes.
  527. TargetPassConfig::TargetPassConfig(LLVMTargetMachine &TM, PassManagerBase &pm)
  528. : ImmutablePass(ID), PM(&pm), TM(&TM) {
  529. Impl = new PassConfigImpl();
  530. // Register all target independent codegen passes to activate their PassIDs,
  531. // including this pass itself.
  532. initializeCodeGen(*PassRegistry::getPassRegistry());
  533. // Also register alias analysis passes required by codegen passes.
  534. initializeBasicAAWrapperPassPass(*PassRegistry::getPassRegistry());
  535. initializeAAResultsWrapperPassPass(*PassRegistry::getPassRegistry());
  536. if (EnableIPRA.getNumOccurrences())
  537. TM.Options.EnableIPRA = EnableIPRA;
  538. else {
  539. // If not explicitly specified, use target default.
  540. TM.Options.EnableIPRA |= TM.useIPRA();
  541. }
  542. if (TM.Options.EnableIPRA)
  543. setRequiresCodeGenSCCOrder();
  544. if (EnableGlobalISelAbort.getNumOccurrences())
  545. TM.Options.GlobalISelAbort = EnableGlobalISelAbort;
  546. setStartStopPasses();
  547. }
  548. CodeGenOpt::Level TargetPassConfig::getOptLevel() const {
  549. return TM->getOptLevel();
  550. }
  551. /// Insert InsertedPassID pass after TargetPassID.
  552. void TargetPassConfig::insertPass(AnalysisID TargetPassID,
  553. IdentifyingPassPtr InsertedPassID) {
  554. assert(((!InsertedPassID.isInstance() &&
  555. TargetPassID != InsertedPassID.getID()) ||
  556. (InsertedPassID.isInstance() &&
  557. TargetPassID != InsertedPassID.getInstance()->getPassID())) &&
  558. "Insert a pass after itself!");
  559. Impl->InsertedPasses.emplace_back(TargetPassID, InsertedPassID);
  560. }
  561. /// createPassConfig - Create a pass configuration object to be used by
  562. /// addPassToEmitX methods for generating a pipeline of CodeGen passes.
  563. ///
  564. /// Targets may override this to extend TargetPassConfig.
  565. TargetPassConfig *LLVMTargetMachine::createPassConfig(PassManagerBase &PM) {
  566. return new TargetPassConfig(*this, PM);
  567. }
  568. TargetPassConfig::TargetPassConfig()
  569. : ImmutablePass(ID) {
  570. report_fatal_error("Trying to construct TargetPassConfig without a target "
  571. "machine. Scheduling a CodeGen pass without a target "
  572. "triple set?");
  573. }
  574. bool TargetPassConfig::willCompleteCodeGenPipeline() {
  575. return StopBeforeOpt.empty() && StopAfterOpt.empty();
  576. }
  577. bool TargetPassConfig::hasLimitedCodeGenPipeline() {
  578. return !StartBeforeOpt.empty() || !StartAfterOpt.empty() ||
  579. !willCompleteCodeGenPipeline();
  580. }
  581. std::string
  582. TargetPassConfig::getLimitedCodeGenPipelineReason(const char *Separator) {
  583. if (!hasLimitedCodeGenPipeline())
  584. return std::string();
  585. std::string Res;
  586. static cl::opt<std::string> *PassNames[] = {&StartAfterOpt, &StartBeforeOpt,
  587. &StopAfterOpt, &StopBeforeOpt};
  588. static const char *OptNames[] = {StartAfterOptName, StartBeforeOptName,
  589. StopAfterOptName, StopBeforeOptName};
  590. bool IsFirst = true;
  591. for (int Idx = 0; Idx < 4; ++Idx)
  592. if (!PassNames[Idx]->empty()) {
  593. if (!IsFirst)
  594. Res += Separator;
  595. IsFirst = false;
  596. Res += OptNames[Idx];
  597. }
  598. return Res;
  599. }
  600. // Helper to verify the analysis is really immutable.
  601. void TargetPassConfig::setOpt(bool &Opt, bool Val) {
  602. assert(!Initialized && "PassConfig is immutable");
  603. Opt = Val;
  604. }
  605. void TargetPassConfig::substitutePass(AnalysisID StandardID,
  606. IdentifyingPassPtr TargetID) {
  607. Impl->TargetPasses[StandardID] = TargetID;
  608. }
  609. IdentifyingPassPtr TargetPassConfig::getPassSubstitution(AnalysisID ID) const {
  610. DenseMap<AnalysisID, IdentifyingPassPtr>::const_iterator
  611. I = Impl->TargetPasses.find(ID);
  612. if (I == Impl->TargetPasses.end())
  613. return ID;
  614. return I->second;
  615. }
  616. bool TargetPassConfig::isPassSubstitutedOrOverridden(AnalysisID ID) const {
  617. IdentifyingPassPtr TargetID = getPassSubstitution(ID);
  618. IdentifyingPassPtr FinalPtr = overridePass(ID, TargetID);
  619. return !FinalPtr.isValid() || FinalPtr.isInstance() ||
  620. FinalPtr.getID() != ID;
  621. }
  622. /// Add a pass to the PassManager if that pass is supposed to be run. If the
  623. /// Started/Stopped flags indicate either that the compilation should start at
  624. /// a later pass or that it should stop after an earlier pass, then do not add
  625. /// the pass. Finally, compare the current pass against the StartAfter
  626. /// and StopAfter options and change the Started/Stopped flags accordingly.
  627. void TargetPassConfig::addPass(Pass *P) {
  628. assert(!Initialized && "PassConfig is immutable");
  629. // Cache the Pass ID here in case the pass manager finds this pass is
  630. // redundant with ones already scheduled / available, and deletes it.
  631. // Fundamentally, once we add the pass to the manager, we no longer own it
  632. // and shouldn't reference it.
  633. AnalysisID PassID = P->getPassID();
  634. if (StartBefore == PassID && StartBeforeCount++ == StartBeforeInstanceNum)
  635. Started = true;
  636. if (StopBefore == PassID && StopBeforeCount++ == StopBeforeInstanceNum)
  637. Stopped = true;
  638. if (Started && !Stopped) {
  639. if (AddingMachinePasses)
  640. addMachinePrePasses();
  641. std::string Banner;
  642. // Construct banner message before PM->add() as that may delete the pass.
  643. if (AddingMachinePasses)
  644. Banner = std::string("After ") + std::string(P->getPassName());
  645. PM->add(P);
  646. if (AddingMachinePasses)
  647. addMachinePostPasses(Banner);
  648. // Add the passes after the pass P if there is any.
  649. for (const auto &IP : Impl->InsertedPasses) {
  650. if (IP.TargetPassID == PassID)
  651. addPass(IP.getInsertedPass());
  652. }
  653. } else {
  654. delete P;
  655. }
  656. if (StopAfter == PassID && StopAfterCount++ == StopAfterInstanceNum)
  657. Stopped = true;
  658. if (StartAfter == PassID && StartAfterCount++ == StartAfterInstanceNum)
  659. Started = true;
  660. if (Stopped && !Started)
  661. report_fatal_error("Cannot stop compilation after pass that is not run");
  662. }
  663. /// Add a CodeGen pass at this point in the pipeline after checking for target
  664. /// and command line overrides.
  665. ///
  666. /// addPass cannot return a pointer to the pass instance because is internal the
  667. /// PassManager and the instance we create here may already be freed.
  668. AnalysisID TargetPassConfig::addPass(AnalysisID PassID) {
  669. IdentifyingPassPtr TargetID = getPassSubstitution(PassID);
  670. IdentifyingPassPtr FinalPtr = overridePass(PassID, TargetID);
  671. if (!FinalPtr.isValid())
  672. return nullptr;
  673. Pass *P;
  674. if (FinalPtr.isInstance())
  675. P = FinalPtr.getInstance();
  676. else {
  677. P = Pass::createPass(FinalPtr.getID());
  678. if (!P)
  679. llvm_unreachable("Pass ID not registered");
  680. }
  681. AnalysisID FinalID = P->getPassID();
  682. addPass(P); // Ends the lifetime of P.
  683. return FinalID;
  684. }
  685. void TargetPassConfig::printAndVerify(const std::string &Banner) {
  686. addPrintPass(Banner);
  687. addVerifyPass(Banner);
  688. }
  689. void TargetPassConfig::addPrintPass(const std::string &Banner) {
  690. if (PrintAfterISel)
  691. PM->add(createMachineFunctionPrinterPass(dbgs(), Banner));
  692. }
  693. void TargetPassConfig::addVerifyPass(const std::string &Banner) {
  694. bool Verify = VerifyMachineCode == cl::BOU_TRUE;
  695. #ifdef EXPENSIVE_CHECKS
  696. if (VerifyMachineCode == cl::BOU_UNSET)
  697. Verify = TM->isMachineVerifierClean();
  698. #endif
  699. if (Verify)
  700. PM->add(createMachineVerifierPass(Banner));
  701. }
  702. void TargetPassConfig::addDebugifyPass() {
  703. PM->add(createDebugifyMachineModulePass());
  704. }
  705. void TargetPassConfig::addStripDebugPass() {
  706. PM->add(createStripDebugMachineModulePass(/*OnlyDebugified=*/true));
  707. }
  708. void TargetPassConfig::addCheckDebugPass() {
  709. PM->add(createCheckDebugMachineModulePass());
  710. }
  711. void TargetPassConfig::addMachinePrePasses(bool AllowDebugify) {
  712. if (AllowDebugify && DebugifyIsSafe &&
  713. (DebugifyAndStripAll == cl::BOU_TRUE ||
  714. DebugifyCheckAndStripAll == cl::BOU_TRUE))
  715. addDebugifyPass();
  716. }
  717. void TargetPassConfig::addMachinePostPasses(const std::string &Banner) {
  718. if (DebugifyIsSafe) {
  719. if (DebugifyCheckAndStripAll == cl::BOU_TRUE) {
  720. addCheckDebugPass();
  721. addStripDebugPass();
  722. } else if (DebugifyAndStripAll == cl::BOU_TRUE)
  723. addStripDebugPass();
  724. }
  725. addVerifyPass(Banner);
  726. }
  727. /// Add common target configurable passes that perform LLVM IR to IR transforms
  728. /// following machine independent optimization.
  729. void TargetPassConfig::addIRPasses() {
  730. // Before running any passes, run the verifier to determine if the input
  731. // coming from the front-end and/or optimizer is valid.
  732. if (!DisableVerify)
  733. addPass(createVerifierPass());
  734. if (getOptLevel() != CodeGenOpt::None) {
  735. switch (UseCFLAA) {
  736. case CFLAAType::Steensgaard:
  737. addPass(createCFLSteensAAWrapperPass());
  738. break;
  739. case CFLAAType::Andersen:
  740. addPass(createCFLAndersAAWrapperPass());
  741. break;
  742. case CFLAAType::Both:
  743. addPass(createCFLAndersAAWrapperPass());
  744. addPass(createCFLSteensAAWrapperPass());
  745. break;
  746. default:
  747. break;
  748. }
  749. // Basic AliasAnalysis support.
  750. // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
  751. // BasicAliasAnalysis wins if they disagree. This is intended to help
  752. // support "obvious" type-punning idioms.
  753. addPass(createTypeBasedAAWrapperPass());
  754. addPass(createScopedNoAliasAAWrapperPass());
  755. addPass(createBasicAAWrapperPass());
  756. // Run loop strength reduction before anything else.
  757. if (!DisableLSR) {
  758. addPass(createCanonicalizeFreezeInLoopsPass());
  759. addPass(createLoopStrengthReducePass());
  760. if (PrintLSR)
  761. addPass(createPrintFunctionPass(dbgs(),
  762. "\n\n*** Code after LSR ***\n"));
  763. }
  764. // The MergeICmpsPass tries to create memcmp calls by grouping sequences of
  765. // loads and compares. ExpandMemCmpPass then tries to expand those calls
  766. // into optimally-sized loads and compares. The transforms are enabled by a
  767. // target lowering hook.
  768. if (!DisableMergeICmps)
  769. addPass(createMergeICmpsLegacyPass());
  770. addPass(createExpandMemCmpPass());
  771. }
  772. // Run GC lowering passes for builtin collectors
  773. // TODO: add a pass insertion point here
  774. addPass(&GCLoweringID);
  775. addPass(&ShadowStackGCLoweringID);
  776. addPass(createLowerConstantIntrinsicsPass());
  777. // Make sure that no unreachable blocks are instruction selected.
  778. addPass(createUnreachableBlockEliminationPass());
  779. // Prepare expensive constants for SelectionDAG.
  780. if (getOptLevel() != CodeGenOpt::None && !DisableConstantHoisting)
  781. addPass(createConstantHoistingPass());
  782. if (getOptLevel() != CodeGenOpt::None)
  783. addPass(createReplaceWithVeclibLegacyPass());
  784. if (getOptLevel() != CodeGenOpt::None && !DisablePartialLibcallInlining)
  785. addPass(createPartiallyInlineLibCallsPass());
  786. // Expand vector predication intrinsics into standard IR instructions.
  787. // This pass has to run before ScalarizeMaskedMemIntrin and ExpandReduction
  788. // passes since it emits those kinds of intrinsics.
  789. addPass(createExpandVectorPredicationPass());
  790. // Add scalarization of target's unsupported masked memory intrinsics pass.
  791. // the unsupported intrinsic will be replaced with a chain of basic blocks,
  792. // that stores/loads element one-by-one if the appropriate mask bit is set.
  793. addPass(createScalarizeMaskedMemIntrinLegacyPass());
  794. // Expand reduction intrinsics into shuffle sequences if the target wants to.
  795. // Allow disabling it for testing purposes.
  796. if (!DisableExpandReductions)
  797. addPass(createExpandReductionsPass());
  798. }
  799. /// Turn exception handling constructs into something the code generators can
  800. /// handle.
  801. void TargetPassConfig::addPassesToHandleExceptions() {
  802. const MCAsmInfo *MCAI = TM->getMCAsmInfo();
  803. assert(MCAI && "No MCAsmInfo");
  804. switch (MCAI->getExceptionHandlingType()) {
  805. case ExceptionHandling::SjLj:
  806. // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
  807. // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
  808. // catch info can get misplaced when a selector ends up more than one block
  809. // removed from the parent invoke(s). This could happen when a landing
  810. // pad is shared by multiple invokes and is also a target of a normal
  811. // edge from elsewhere.
  812. addPass(createSjLjEHPreparePass(TM));
  813. LLVM_FALLTHROUGH;
  814. case ExceptionHandling::DwarfCFI:
  815. case ExceptionHandling::ARM:
  816. case ExceptionHandling::AIX:
  817. addPass(createDwarfEHPass(getOptLevel()));
  818. break;
  819. case ExceptionHandling::WinEH:
  820. // We support using both GCC-style and MSVC-style exceptions on Windows, so
  821. // add both preparation passes. Each pass will only actually run if it
  822. // recognizes the personality function.
  823. addPass(createWinEHPass());
  824. addPass(createDwarfEHPass(getOptLevel()));
  825. break;
  826. case ExceptionHandling::Wasm:
  827. // Wasm EH uses Windows EH instructions, but it does not need to demote PHIs
  828. // on catchpads and cleanuppads because it does not outline them into
  829. // funclets. Catchswitch blocks are not lowered in SelectionDAG, so we
  830. // should remove PHIs there.
  831. addPass(createWinEHPass(/*DemoteCatchSwitchPHIOnly=*/false));
  832. addPass(createWasmEHPass());
  833. break;
  834. case ExceptionHandling::None:
  835. addPass(createLowerInvokePass());
  836. // The lower invoke pass may create unreachable code. Remove it.
  837. addPass(createUnreachableBlockEliminationPass());
  838. break;
  839. }
  840. }
  841. /// Add pass to prepare the LLVM IR for code generation. This should be done
  842. /// before exception handling preparation passes.
  843. void TargetPassConfig::addCodeGenPrepare() {
  844. if (getOptLevel() != CodeGenOpt::None && !DisableCGP)
  845. addPass(createCodeGenPreparePass());
  846. }
  847. /// Add common passes that perform LLVM IR to IR transforms in preparation for
  848. /// instruction selection.
  849. void TargetPassConfig::addISelPrepare() {
  850. addPreISel();
  851. // Force codegen to run according to the callgraph.
  852. if (requiresCodeGenSCCOrder())
  853. addPass(new DummyCGSCCPass);
  854. // Add both the safe stack and the stack protection passes: each of them will
  855. // only protect functions that have corresponding attributes.
  856. addPass(createSafeStackPass());
  857. addPass(createStackProtectorPass());
  858. if (PrintISelInput)
  859. addPass(createPrintFunctionPass(
  860. dbgs(), "\n\n*** Final LLVM Code input to ISel ***\n"));
  861. // All passes which modify the LLVM IR are now complete; run the verifier
  862. // to ensure that the IR is valid.
  863. if (!DisableVerify)
  864. addPass(createVerifierPass());
  865. }
  866. bool TargetPassConfig::addCoreISelPasses() {
  867. // Enable FastISel with -fast-isel, but allow that to be overridden.
  868. TM->setO0WantsFastISel(EnableFastISelOption != cl::BOU_FALSE);
  869. // Determine an instruction selector.
  870. enum class SelectorType { SelectionDAG, FastISel, GlobalISel };
  871. SelectorType Selector;
  872. if (EnableFastISelOption == cl::BOU_TRUE)
  873. Selector = SelectorType::FastISel;
  874. else if (EnableGlobalISelOption == cl::BOU_TRUE ||
  875. (TM->Options.EnableGlobalISel &&
  876. EnableGlobalISelOption != cl::BOU_FALSE))
  877. Selector = SelectorType::GlobalISel;
  878. else if (TM->getOptLevel() == CodeGenOpt::None && TM->getO0WantsFastISel())
  879. Selector = SelectorType::FastISel;
  880. else
  881. Selector = SelectorType::SelectionDAG;
  882. // Set consistently TM->Options.EnableFastISel and EnableGlobalISel.
  883. if (Selector == SelectorType::FastISel) {
  884. TM->setFastISel(true);
  885. TM->setGlobalISel(false);
  886. } else if (Selector == SelectorType::GlobalISel) {
  887. TM->setFastISel(false);
  888. TM->setGlobalISel(true);
  889. }
  890. // FIXME: Injecting into the DAGISel pipeline seems to cause issues with
  891. // analyses needing to be re-run. This can result in being unable to
  892. // schedule passes (particularly with 'Function Alias Analysis
  893. // Results'). It's not entirely clear why but AFAICT this seems to be
  894. // due to one FunctionPassManager not being able to use analyses from a
  895. // previous one. As we're injecting a ModulePass we break the usual
  896. // pass manager into two. GlobalISel with the fallback path disabled
  897. // and -run-pass seem to be unaffected. The majority of GlobalISel
  898. // testing uses -run-pass so this probably isn't too bad.
  899. SaveAndRestore<bool> SavedDebugifyIsSafe(DebugifyIsSafe);
  900. if (Selector != SelectorType::GlobalISel || !isGlobalISelAbortEnabled())
  901. DebugifyIsSafe = false;
  902. // Add instruction selector passes.
  903. if (Selector == SelectorType::GlobalISel) {
  904. SaveAndRestore<bool> SavedAddingMachinePasses(AddingMachinePasses, true);
  905. if (addIRTranslator())
  906. return true;
  907. addPreLegalizeMachineIR();
  908. if (addLegalizeMachineIR())
  909. return true;
  910. // Before running the register bank selector, ask the target if it
  911. // wants to run some passes.
  912. addPreRegBankSelect();
  913. if (addRegBankSelect())
  914. return true;
  915. addPreGlobalInstructionSelect();
  916. if (addGlobalInstructionSelect())
  917. return true;
  918. // Pass to reset the MachineFunction if the ISel failed.
  919. addPass(createResetMachineFunctionPass(
  920. reportDiagnosticWhenGlobalISelFallback(), isGlobalISelAbortEnabled()));
  921. // Provide a fallback path when we do not want to abort on
  922. // not-yet-supported input.
  923. if (!isGlobalISelAbortEnabled() && addInstSelector())
  924. return true;
  925. } else if (addInstSelector())
  926. return true;
  927. // Expand pseudo-instructions emitted by ISel. Don't run the verifier before
  928. // FinalizeISel.
  929. addPass(&FinalizeISelID);
  930. // Print the instruction selected machine code...
  931. printAndVerify("After Instruction Selection");
  932. return false;
  933. }
  934. bool TargetPassConfig::addISelPasses() {
  935. if (TM->useEmulatedTLS())
  936. addPass(createLowerEmuTLSPass());
  937. addPass(createPreISelIntrinsicLoweringPass());
  938. PM->add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
  939. addIRPasses();
  940. addCodeGenPrepare();
  941. addPassesToHandleExceptions();
  942. addISelPrepare();
  943. return addCoreISelPasses();
  944. }
  945. /// -regalloc=... command line option.
  946. static FunctionPass *useDefaultRegisterAllocator() { return nullptr; }
  947. static cl::opt<RegisterRegAlloc::FunctionPassCtor, false,
  948. RegisterPassParser<RegisterRegAlloc>>
  949. RegAlloc("regalloc", cl::Hidden, cl::init(&useDefaultRegisterAllocator),
  950. cl::desc("Register allocator to use"));
  951. /// Add the complete set of target-independent postISel code generator passes.
  952. ///
  953. /// This can be read as the standard order of major LLVM CodeGen stages. Stages
  954. /// with nontrivial configuration or multiple passes are broken out below in
  955. /// add%Stage routines.
  956. ///
  957. /// Any TargetPassConfig::addXX routine may be overriden by the Target. The
  958. /// addPre/Post methods with empty header implementations allow injecting
  959. /// target-specific fixups just before or after major stages. Additionally,
  960. /// targets have the flexibility to change pass order within a stage by
  961. /// overriding default implementation of add%Stage routines below. Each
  962. /// technique has maintainability tradeoffs because alternate pass orders are
  963. /// not well supported. addPre/Post works better if the target pass is easily
  964. /// tied to a common pass. But if it has subtle dependencies on multiple passes,
  965. /// the target should override the stage instead.
  966. ///
  967. /// TODO: We could use a single addPre/Post(ID) hook to allow pass injection
  968. /// before/after any target-independent pass. But it's currently overkill.
  969. void TargetPassConfig::addMachinePasses() {
  970. AddingMachinePasses = true;
  971. // Add passes that optimize machine instructions in SSA form.
  972. if (getOptLevel() != CodeGenOpt::None) {
  973. addMachineSSAOptimization();
  974. } else {
  975. // If the target requests it, assign local variables to stack slots relative
  976. // to one another and simplify frame index references where possible.
  977. addPass(&LocalStackSlotAllocationID);
  978. }
  979. if (TM->Options.EnableIPRA)
  980. addPass(createRegUsageInfoPropPass());
  981. // Run pre-ra passes.
  982. addPreRegAlloc();
  983. // Debugifying the register allocator passes seems to provoke some
  984. // non-determinism that affects CodeGen and there doesn't seem to be a point
  985. // where it becomes safe again so stop debugifying here.
  986. DebugifyIsSafe = false;
  987. // Add a FSDiscriminator pass right before RA, so that we could get
  988. // more precise SampleFDO profile for RA.
  989. if (EnableFSDiscriminator) {
  990. addPass(createMIRAddFSDiscriminatorsPass(
  991. sampleprof::FSDiscriminatorPass::Pass1));
  992. const std::string ProfileFile = getFSProfileFile(TM);
  993. if (!ProfileFile.empty() && !DisableRAFSProfileLoader)
  994. addPass(
  995. createMIRProfileLoaderPass(ProfileFile, getFSRemappingFile(TM),
  996. sampleprof::FSDiscriminatorPass::Pass1));
  997. }
  998. // Run register allocation and passes that are tightly coupled with it,
  999. // including phi elimination and scheduling.
  1000. if (getOptimizeRegAlloc())
  1001. addOptimizedRegAlloc();
  1002. else
  1003. addFastRegAlloc();
  1004. // Run post-ra passes.
  1005. addPostRegAlloc();
  1006. addPass(&RemoveRedundantDebugValuesID);
  1007. addPass(&FixupStatepointCallerSavedID);
  1008. // Insert prolog/epilog code. Eliminate abstract frame index references...
  1009. if (getOptLevel() != CodeGenOpt::None) {
  1010. addPass(&PostRAMachineSinkingID);
  1011. addPass(&ShrinkWrapID);
  1012. }
  1013. // Prolog/Epilog inserter needs a TargetMachine to instantiate. But only
  1014. // do so if it hasn't been disabled, substituted, or overridden.
  1015. if (!isPassSubstitutedOrOverridden(&PrologEpilogCodeInserterID))
  1016. addPass(createPrologEpilogInserterPass());
  1017. /// Add passes that optimize machine instructions after register allocation.
  1018. if (getOptLevel() != CodeGenOpt::None)
  1019. addMachineLateOptimization();
  1020. // Expand pseudo instructions before second scheduling pass.
  1021. addPass(&ExpandPostRAPseudosID);
  1022. // Run pre-sched2 passes.
  1023. addPreSched2();
  1024. if (EnableImplicitNullChecks)
  1025. addPass(&ImplicitNullChecksID);
  1026. // Second pass scheduler.
  1027. // Let Target optionally insert this pass by itself at some other
  1028. // point.
  1029. if (getOptLevel() != CodeGenOpt::None &&
  1030. !TM->targetSchedulesPostRAScheduling()) {
  1031. if (MISchedPostRA)
  1032. addPass(&PostMachineSchedulerID);
  1033. else
  1034. addPass(&PostRASchedulerID);
  1035. }
  1036. // GC
  1037. if (addGCPasses()) {
  1038. if (PrintGCInfo)
  1039. addPass(createGCInfoPrinter(dbgs()));
  1040. }
  1041. // Basic block placement.
  1042. if (getOptLevel() != CodeGenOpt::None)
  1043. addBlockPlacement();
  1044. // Insert before XRay Instrumentation.
  1045. addPass(&FEntryInserterID);
  1046. addPass(&XRayInstrumentationID);
  1047. addPass(&PatchableFunctionID);
  1048. if (EnableFSDiscriminator && !FSNoFinalDiscrim)
  1049. // Add FS discriminators here so that all the instruction duplicates
  1050. // in different BBs get their own discriminators. With this, we can "sum"
  1051. // the SampleFDO counters instead of using MAX. This will improve the
  1052. // SampleFDO profile quality.
  1053. addPass(createMIRAddFSDiscriminatorsPass(
  1054. sampleprof::FSDiscriminatorPass::PassLast));
  1055. addPreEmitPass();
  1056. if (TM->Options.EnableIPRA)
  1057. // Collect register usage information and produce a register mask of
  1058. // clobbered registers, to be used to optimize call sites.
  1059. addPass(createRegUsageInfoCollector());
  1060. // FIXME: Some backends are incompatible with running the verifier after
  1061. // addPreEmitPass. Maybe only pass "false" here for those targets?
  1062. addPass(&FuncletLayoutID);
  1063. addPass(&StackMapLivenessID);
  1064. addPass(&LiveDebugValuesID);
  1065. if (TM->Options.EnableMachineOutliner && getOptLevel() != CodeGenOpt::None &&
  1066. EnableMachineOutliner != RunOutliner::NeverOutline) {
  1067. bool RunOnAllFunctions =
  1068. (EnableMachineOutliner == RunOutliner::AlwaysOutline);
  1069. bool AddOutliner =
  1070. RunOnAllFunctions || TM->Options.SupportsDefaultOutlining;
  1071. if (AddOutliner)
  1072. addPass(createMachineOutlinerPass(RunOnAllFunctions));
  1073. }
  1074. // Machine function splitter uses the basic block sections feature. Both
  1075. // cannot be enabled at the same time. Basic block sections takes precedence.
  1076. // FIXME: In principle, BasicBlockSection::Labels and splitting can used
  1077. // together. Update this check once we have addressed any issues.
  1078. if (TM->getBBSectionsType() != llvm::BasicBlockSection::None) {
  1079. addPass(llvm::createBasicBlockSectionsPass(TM->getBBSectionsFuncListBuf()));
  1080. } else if (TM->Options.EnableMachineFunctionSplitter ||
  1081. EnableMachineFunctionSplitter) {
  1082. addPass(createMachineFunctionSplitterPass());
  1083. }
  1084. // Add passes that directly emit MI after all other MI passes.
  1085. addPreEmitPass2();
  1086. AddingMachinePasses = false;
  1087. }
  1088. /// Add passes that optimize machine instructions in SSA form.
  1089. void TargetPassConfig::addMachineSSAOptimization() {
  1090. // Pre-ra tail duplication.
  1091. addPass(&EarlyTailDuplicateID);
  1092. // Optimize PHIs before DCE: removing dead PHI cycles may make more
  1093. // instructions dead.
  1094. addPass(&OptimizePHIsID);
  1095. // This pass merges large allocas. StackSlotColoring is a different pass
  1096. // which merges spill slots.
  1097. addPass(&StackColoringID);
  1098. // If the target requests it, assign local variables to stack slots relative
  1099. // to one another and simplify frame index references where possible.
  1100. addPass(&LocalStackSlotAllocationID);
  1101. // With optimization, dead code should already be eliminated. However
  1102. // there is one known exception: lowered code for arguments that are only
  1103. // used by tail calls, where the tail calls reuse the incoming stack
  1104. // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
  1105. addPass(&DeadMachineInstructionElimID);
  1106. // Allow targets to insert passes that improve instruction level parallelism,
  1107. // like if-conversion. Such passes will typically need dominator trees and
  1108. // loop info, just like LICM and CSE below.
  1109. addILPOpts();
  1110. addPass(&EarlyMachineLICMID);
  1111. addPass(&MachineCSEID);
  1112. addPass(&MachineSinkingID);
  1113. addPass(&PeepholeOptimizerID);
  1114. // Clean-up the dead code that may have been generated by peephole
  1115. // rewriting.
  1116. addPass(&DeadMachineInstructionElimID);
  1117. }
  1118. //===---------------------------------------------------------------------===//
  1119. /// Register Allocation Pass Configuration
  1120. //===---------------------------------------------------------------------===//
  1121. bool TargetPassConfig::getOptimizeRegAlloc() const {
  1122. switch (OptimizeRegAlloc) {
  1123. case cl::BOU_UNSET: return getOptLevel() != CodeGenOpt::None;
  1124. case cl::BOU_TRUE: return true;
  1125. case cl::BOU_FALSE: return false;
  1126. }
  1127. llvm_unreachable("Invalid optimize-regalloc state");
  1128. }
  1129. /// A dummy default pass factory indicates whether the register allocator is
  1130. /// overridden on the command line.
  1131. static llvm::once_flag InitializeDefaultRegisterAllocatorFlag;
  1132. static RegisterRegAlloc
  1133. defaultRegAlloc("default",
  1134. "pick register allocator based on -O option",
  1135. useDefaultRegisterAllocator);
  1136. static void initializeDefaultRegisterAllocatorOnce() {
  1137. if (!RegisterRegAlloc::getDefault())
  1138. RegisterRegAlloc::setDefault(RegAlloc);
  1139. }
  1140. /// Instantiate the default register allocator pass for this target for either
  1141. /// the optimized or unoptimized allocation path. This will be added to the pass
  1142. /// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
  1143. /// in the optimized case.
  1144. ///
  1145. /// A target that uses the standard regalloc pass order for fast or optimized
  1146. /// allocation may still override this for per-target regalloc
  1147. /// selection. But -regalloc=... always takes precedence.
  1148. FunctionPass *TargetPassConfig::createTargetRegisterAllocator(bool Optimized) {
  1149. if (Optimized)
  1150. return createGreedyRegisterAllocator();
  1151. else
  1152. return createFastRegisterAllocator();
  1153. }
  1154. /// Find and instantiate the register allocation pass requested by this target
  1155. /// at the current optimization level. Different register allocators are
  1156. /// defined as separate passes because they may require different analysis.
  1157. ///
  1158. /// This helper ensures that the regalloc= option is always available,
  1159. /// even for targets that override the default allocator.
  1160. ///
  1161. /// FIXME: When MachinePassRegistry register pass IDs instead of function ptrs,
  1162. /// this can be folded into addPass.
  1163. FunctionPass *TargetPassConfig::createRegAllocPass(bool Optimized) {
  1164. // Initialize the global default.
  1165. llvm::call_once(InitializeDefaultRegisterAllocatorFlag,
  1166. initializeDefaultRegisterAllocatorOnce);
  1167. RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
  1168. if (Ctor != useDefaultRegisterAllocator)
  1169. return Ctor();
  1170. // With no -regalloc= override, ask the target for a regalloc pass.
  1171. return createTargetRegisterAllocator(Optimized);
  1172. }
  1173. bool TargetPassConfig::addRegAssignAndRewriteFast() {
  1174. if (RegAlloc != (RegisterRegAlloc::FunctionPassCtor)&useDefaultRegisterAllocator &&
  1175. RegAlloc != (RegisterRegAlloc::FunctionPassCtor)&createFastRegisterAllocator)
  1176. report_fatal_error("Must use fast (default) register allocator for unoptimized regalloc.");
  1177. addPass(createRegAllocPass(false));
  1178. // Allow targets to change the register assignments after
  1179. // fast register allocation.
  1180. addPostFastRegAllocRewrite();
  1181. return true;
  1182. }
  1183. bool TargetPassConfig::addRegAssignAndRewriteOptimized() {
  1184. // Add the selected register allocation pass.
  1185. addPass(createRegAllocPass(true));
  1186. // Allow targets to change the register assignments before rewriting.
  1187. addPreRewrite();
  1188. // Finally rewrite virtual registers.
  1189. addPass(&VirtRegRewriterID);
  1190. // Regalloc scoring for ML-driven eviction - noop except when learning a new
  1191. // eviction policy.
  1192. addPass(createRegAllocScoringPass());
  1193. return true;
  1194. }
  1195. /// Return true if the default global register allocator is in use and
  1196. /// has not be overriden on the command line with '-regalloc=...'
  1197. bool TargetPassConfig::usingDefaultRegAlloc() const {
  1198. return RegAlloc.getNumOccurrences() == 0;
  1199. }
  1200. /// Add the minimum set of target-independent passes that are required for
  1201. /// register allocation. No coalescing or scheduling.
  1202. void TargetPassConfig::addFastRegAlloc() {
  1203. addPass(&PHIEliminationID);
  1204. addPass(&TwoAddressInstructionPassID);
  1205. addRegAssignAndRewriteFast();
  1206. }
  1207. /// Add standard target-independent passes that are tightly coupled with
  1208. /// optimized register allocation, including coalescing, machine instruction
  1209. /// scheduling, and register allocation itself.
  1210. void TargetPassConfig::addOptimizedRegAlloc() {
  1211. addPass(&DetectDeadLanesID);
  1212. addPass(&ProcessImplicitDefsID);
  1213. // LiveVariables currently requires pure SSA form.
  1214. //
  1215. // FIXME: Once TwoAddressInstruction pass no longer uses kill flags,
  1216. // LiveVariables can be removed completely, and LiveIntervals can be directly
  1217. // computed. (We still either need to regenerate kill flags after regalloc, or
  1218. // preferably fix the scavenger to not depend on them).
  1219. // FIXME: UnreachableMachineBlockElim is a dependant pass of LiveVariables.
  1220. // When LiveVariables is removed this has to be removed/moved either.
  1221. // Explicit addition of UnreachableMachineBlockElim allows stopping before or
  1222. // after it with -stop-before/-stop-after.
  1223. addPass(&UnreachableMachineBlockElimID);
  1224. addPass(&LiveVariablesID);
  1225. // Edge splitting is smarter with machine loop info.
  1226. addPass(&MachineLoopInfoID);
  1227. addPass(&PHIEliminationID);
  1228. // Eventually, we want to run LiveIntervals before PHI elimination.
  1229. if (EarlyLiveIntervals)
  1230. addPass(&LiveIntervalsID);
  1231. addPass(&TwoAddressInstructionPassID);
  1232. addPass(&RegisterCoalescerID);
  1233. // The machine scheduler may accidentally create disconnected components
  1234. // when moving subregister definitions around, avoid this by splitting them to
  1235. // separate vregs before. Splitting can also improve reg. allocation quality.
  1236. addPass(&RenameIndependentSubregsID);
  1237. // PreRA instruction scheduling.
  1238. addPass(&MachineSchedulerID);
  1239. if (addRegAssignAndRewriteOptimized()) {
  1240. // Perform stack slot coloring and post-ra machine LICM.
  1241. addPass(&StackSlotColoringID);
  1242. // Allow targets to expand pseudo instructions depending on the choice of
  1243. // registers before MachineCopyPropagation.
  1244. addPostRewrite();
  1245. // Copy propagate to forward register uses and try to eliminate COPYs that
  1246. // were not coalesced.
  1247. addPass(&MachineCopyPropagationID);
  1248. // Run post-ra machine LICM to hoist reloads / remats.
  1249. //
  1250. // FIXME: can this move into MachineLateOptimization?
  1251. addPass(&MachineLICMID);
  1252. }
  1253. }
  1254. //===---------------------------------------------------------------------===//
  1255. /// Post RegAlloc Pass Configuration
  1256. //===---------------------------------------------------------------------===//
  1257. /// Add passes that optimize machine instructions after register allocation.
  1258. void TargetPassConfig::addMachineLateOptimization() {
  1259. // Branch folding must be run after regalloc and prolog/epilog insertion.
  1260. addPass(&BranchFolderPassID);
  1261. // Tail duplication.
  1262. // Note that duplicating tail just increases code size and degrades
  1263. // performance for targets that require Structured Control Flow.
  1264. // In addition it can also make CFG irreducible. Thus we disable it.
  1265. if (!TM->requiresStructuredCFG())
  1266. addPass(&TailDuplicateID);
  1267. // Copy propagation.
  1268. addPass(&MachineCopyPropagationID);
  1269. }
  1270. /// Add standard GC passes.
  1271. bool TargetPassConfig::addGCPasses() {
  1272. addPass(&GCMachineCodeAnalysisID);
  1273. return true;
  1274. }
  1275. /// Add standard basic block placement passes.
  1276. void TargetPassConfig::addBlockPlacement() {
  1277. if (EnableFSDiscriminator) {
  1278. addPass(createMIRAddFSDiscriminatorsPass(
  1279. sampleprof::FSDiscriminatorPass::Pass2));
  1280. const std::string ProfileFile = getFSProfileFile(TM);
  1281. if (!ProfileFile.empty() && !DisableLayoutFSProfileLoader)
  1282. addPass(
  1283. createMIRProfileLoaderPass(ProfileFile, getFSRemappingFile(TM),
  1284. sampleprof::FSDiscriminatorPass::Pass2));
  1285. }
  1286. if (addPass(&MachineBlockPlacementID)) {
  1287. // Run a separate pass to collect block placement statistics.
  1288. if (EnableBlockPlacementStats)
  1289. addPass(&MachineBlockPlacementStatsID);
  1290. }
  1291. }
  1292. //===---------------------------------------------------------------------===//
  1293. /// GlobalISel Configuration
  1294. //===---------------------------------------------------------------------===//
  1295. bool TargetPassConfig::isGlobalISelAbortEnabled() const {
  1296. return TM->Options.GlobalISelAbort == GlobalISelAbortMode::Enable;
  1297. }
  1298. bool TargetPassConfig::reportDiagnosticWhenGlobalISelFallback() const {
  1299. return TM->Options.GlobalISelAbort == GlobalISelAbortMode::DisableWithDiag;
  1300. }
  1301. bool TargetPassConfig::isGISelCSEEnabled() const {
  1302. return true;
  1303. }
  1304. std::unique_ptr<CSEConfigBase> TargetPassConfig::getCSEConfig() const {
  1305. return std::make_unique<CSEConfigBase>();
  1306. }