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