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