TargetPassConfig.cpp 59 KB

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