LLVM 24.0.0git
CodeGenPassBuilder.cpp
Go to the documentation of this file.
1//===--- CodeGenPassBuilder.cpp --------------------------------------- ---===//
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
16#include "llvm/ADT/StringRef.h"
62#include "llvm/CodeGen/PEI.h"
99#include "llvm/IR/PassManager.h"
100#include "llvm/IR/Verifier.h"
102#include "llvm/MC/MCAsmInfo.h"
103#include "llvm/MC/MCStreamer.h"
107#include "llvm/Support/CodeGen.h"
108#include "llvm/Support/Debug.h"
109#include "llvm/Support/Error.h"
123#include <cassert>
124#include <utility>
125
126using namespace llvm;
127
128namespace llvm {
129#define DUMMY_MACHINE_FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
130 AnalysisKey PASS_NAME::Key;
131#include "llvm/Passes/MachinePassRegistry.def"
132} // namespace llvm
133
135 const CGPassBuilderOption &Opts,
137 : TM(TM), Opt(Opts), PIC(PIC) {
138 // Target could set CGPassBuilderOption::MISchedPostRA to true to achieve
139 // substitutePass(&PostRASchedulerID, &PostMachineSchedulerID)
140
141 // Target should override TM.Options.EnableIPRA in their target-specific
142 // LLVMTM ctor. See TargetMachine::setGlobalISel for example.
143 if (Opt.EnableIPRA) {
144 TM.Options.EnableIPRA = *Opt.EnableIPRA;
145 } else {
146 // If not explicitly specified, use target default.
147 TM.Options.EnableIPRA |= TM.useIPRA();
148 }
149
150 if (Opt.EnableGlobalISelAbort)
151 TM.Options.GlobalISelAbort = *Opt.EnableGlobalISelAbort;
152
153 // An explicit RegAlloc choice implies its pipeline: only the fast
154 // allocator uses the unoptimized one.
155 if (Opt.OptimizeRegAlloc == cl::boolOrDefault::BOU_UNSET) {
156 bool Optimized = Opt.RegAlloc > RegAllocType::Default
157 ? Opt.RegAlloc != RegAllocType::Fast
158 : getOptLevel() != CodeGenOptLevel::None;
159 Opt.OptimizeRegAlloc =
160 Optimized ? cl::boolOrDefault::BOU_TRUE : cl::boolOrDefault::BOU_FALSE;
161 }
162}
163
164// Out-of-line to anchor the vtable in this translation unit.
166
168 return make_error<StringError>("addInstSelector is not overridden",
170}
171
173 return make_error<StringError>("addIRTranslator is not overridden",
175}
176
178 return make_error<StringError>("addLegalizeMachineIR is not overridden",
180}
181
183 return make_error<StringError>("addRegBankSelect is not overridden",
185}
186
188 return make_error<StringError>("addGlobalInstructionSelect is not overridden",
190}
191
193 llvm_unreachable("addAsmPrinterBegin is not overriden");
194}
195
197 llvm_unreachable("addAsmPrinter is not overridden");
198}
199
201 llvm_unreachable("addAsmPrinterEnd is not overriden");
202}
203
205 bool FreeMachineFunctions) {
206 if (PMW.FPM.isEmpty() && PMW.MFPM.isEmpty())
207 return;
208 if (!PMW.MFPM.isEmpty()) {
209 PMW.FPM.addPass(
210 createFunctionToMachineFunctionPassAdaptor(std::move(PMW.MFPM)));
211 PMW.MFPM = MachineFunctionPassManager();
212 }
213 if (FreeMachineFunctions)
215 if (AddInCGSCCOrder) {
217 createCGSCCToFunctionPassAdaptor(std::move(PMW.FPM))));
218 } else {
219 PMW.MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PMW.FPM)));
220 }
221 PMW.FPM = FunctionPassManager();
222}
223
226 raw_pwrite_stream *DwoOut, CodeGenFileType FileType, MCContext &Ctx) {
227 auto StartStopInfo = TargetPassConfig::getStartStopInfo(*PIC);
228 if (!StartStopInfo)
229 return StartStopInfo.takeError();
230 setStartStopPasses(*StartStopInfo);
231
233 bool PrintMIR = !PrintAsm && FileType != CodeGenFileType::Null;
234
235 PassManagerWrapper PMW(MPM);
236
238 /*Force=*/true);
240 /*Force=*/true);
242 /*Force=*/true);
244 /*Force=*/true);
246 PMW,
247 /*Force=*/true);
248 addISelPasses(PMW);
249 flushFPMsToMPM(PMW);
250
251 if (PrintAsm) {
252 Expected<std::unique_ptr<MCStreamer>> MCStreamerOrErr =
253 TM.createMCStreamer(Out, DwoOut, FileType, Ctx);
254 if (!MCStreamerOrErr)
255 return MCStreamerOrErr.takeError();
256 std::unique_ptr<AsmPrinter> Printer(
257 TM.getTarget().createAsmPrinter(TM, std::move(*MCStreamerOrErr)));
258 if (!Printer)
259 return createStringError("failed to create AsmPrinter");
260 MAM.registerPass([&] { return AsmPrinterAnalysis(std::move(Printer)); });
262 }
263
264 if (PrintMIR)
265 addModulePass(PrintMIRPreparePass(Out), PMW, /*Force=*/true);
266
267 if (auto Err = addCoreISelPasses(PMW))
268 return Err;
269
270 if (auto Err = addMachinePasses(PMW))
271 return Err;
272
273 if (!Opt.DisableVerify && TM.Options.EnableDefaultMachineVerifier)
275
276 // We add AsmPrinter regardless if we are emitting MIR or Assembly as the
277 // final output so that -stop-before=<target>-asm-printer works. When printing
278 // MIR as the final output, we never end up running AsmPrinter.
279 addAsmPrinter(PMW);
280
281 if (PrintAsm) {
282 flushFPMsToMPM(PMW, /*FreeMachineFunctions=*/true);
283 addAsmPrinterEnd(PMW);
284 } else {
285 if (PrintMIR)
286 addMachineFunctionPass(PrintMIRPass(Out), PMW, /*Force=*/true);
287 flushFPMsToMPM(PMW, /*FreeMachineFunctions=*/true);
288 }
289
290 return verifyStartStop(*StartStopInfo);
291}
292
293void CodeGenPassBuilder::setStartStopPasses(
295 if (!Info.StartPass.empty()) {
296 Started = false;
297 BeforeCallbacks.emplace_back([this, &Info, AfterFlag = Info.StartAfter,
298 Count = 0u](StringRef ClassName) mutable {
299 if (Count == Info.StartInstanceNum) {
300 if (AfterFlag) {
301 AfterFlag = false;
302 Started = true;
303 }
304 return Started;
305 }
306
307 auto PassName = PIC->getPassNameForClassName(ClassName);
308 if (Info.StartPass == PassName && ++Count == Info.StartInstanceNum)
309 Started = !Info.StartAfter;
310
311 return Started;
312 });
313 }
314
315 if (!Info.StopPass.empty()) {
316 Stopped = false;
317 BeforeCallbacks.emplace_back([this, &Info, AfterFlag = Info.StopAfter,
318 Count = 0u](StringRef ClassName) mutable {
319 if (Count == Info.StopInstanceNum) {
320 if (AfterFlag) {
321 AfterFlag = false;
322 Stopped = true;
323 }
324 return !Stopped;
325 }
326
327 auto PassName = PIC->getPassNameForClassName(ClassName);
328 if (Info.StopPass == PassName && ++Count == Info.StopInstanceNum)
329 Stopped = !Info.StopAfter;
330 return !Stopped;
331 });
332 }
333}
334
335Error CodeGenPassBuilder::verifyStartStop(
336 const TargetPassConfig::StartStopInfo &Info) const {
337 if (Started && Stopped)
338 return Error::success();
339
340 if (!Started)
342 "Can't find start pass \"" + Info.StartPass + "\".",
343 std::make_error_code(std::errc::invalid_argument));
344 if (!Stopped)
346 "Can't find stop pass \"" + Info.StopPass + "\".",
347 std::make_error_code(std::errc::invalid_argument));
348 return Error::success();
349}
350
353 if (TM.useEmulatedTLS())
355
356 // ObjCARCContract operates on ObjC intrinsics and must run before
357 // PreISelIntrinsicLowering.
360 flushFPMsToMPM(PMW);
361 }
364
365 addIRPasses(PMW);
368 addISelPrepare(PMW);
369}
370
371/// Add common target configurable passes that perform LLVM IR to IR transforms
372/// following machine independent optimization.
374 // Before running any passes, run the verifier to determine if the input
375 // coming from the front-end and/or optimizer is valid.
376 if (!Opt.DisableVerify)
377 addFunctionPass(VerifierPass(), PMW, /*Force=*/true);
378
379 // Run loop strength reduction before anything else.
380 if (getOptLevel() != CodeGenOptLevel::None && !Opt.DisableLSR) {
381 // These passes do not use MSSA.
382 LoopPassManager LPM;
383 LPM.addPass(CanonicalizeFreezeInLoopsPass());
384 LPM.addPass(LoopStrengthReducePass());
385 if (Opt.EnableLoopTermFold)
386 LPM.addPass(LoopTermFoldPass());
388 /*UseMemorySSA=*/false),
389 PMW);
390 }
391
392 // Run GC lowering passes for builtin collectors
393 // TODO: add a pass insertion point here
395 // Explicitly check to see if we should add ShadowStackGCLowering to avoid
396 // splitting the function pipeline if we do not have to.
397 if (runBeforeAdding(ShadowStackGCLoweringPass::name())) {
398 flushFPMsToMPM(PMW);
400 }
401
402 // Make sure that no unreachable blocks are instruction selected.
404
405 // Prepare expensive constants for SelectionDAG.
406 if (getOptLevel() != CodeGenOptLevel::None && !Opt.DisableConstantHoisting)
408
409 // Replace calls to LLVM intrinsics (e.g., exp, log) operating on vector
410 // operands with calls to the corresponding functions in a vector library.
413
415 !Opt.DisablePartialLibcallInlining)
417
418 // Instrument function entry and exit, e.g. with calls to mcount().
419 addFunctionPass(EntryExitInstrumenterPass(/*PostInlining=*/true), PMW);
420
421 // Add scalarization of target's unsupported masked memory intrinsics pass.
422 // the unsupported intrinsic will be replaced with a chain of basic blocks,
423 // that stores/loads element one-by-one if the appropriate mask bit is set.
425
426 // Expand reduction intrinsics into shuffle sequences if the target wants to.
427 if (!Opt.DisableExpandReductions)
429
430 // Convert conditional moves to conditional jumps when profitable.
431 if (getOptLevel() != CodeGenOptLevel::None && !Opt.DisableSelectOptimize)
433
434 if (Opt.EnableGlobalMergeFunc) {
435 flushFPMsToMPM(PMW);
437 }
438}
439
440/// Turn exception handling constructs into something the code generators can
441/// handle.
443 const MCAsmInfo &MCAI = TM.getMCAsmInfo();
444 switch (MCAI.getExceptionHandlingType()) {
446 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
447 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
448 // catch info can get misplaced when a selector ends up more than one block
449 // removed from the parent invoke(s). This could happen when a landing
450 // pad is shared by multiple invokes and is also a target of a normal
451 // edge from elsewhere.
453 [[fallthrough]];
459 break;
461 // We support using both GCC-style and MSVC-style exceptions on Windows, so
462 // add both preparation passes. Each pass will only actually run if it
463 // recognizes the personality function.
466 break;
468 // Wasm EH uses Windows EH instructions, but it does not need to demote PHIs
469 // on catchpads and cleanuppads because it does not outline them into
470 // funclets. Catchswitch blocks are not lowered in SelectionDAG, so we
471 // should remove PHIs there.
472 addFunctionPass(WinEHPreparePass(/*DemoteCatchSwitchPHIOnly=*/false), PMW);
474 break;
478 // Emscripten EH is lowered earlier by WebAssemblyLowerEmscriptenEHSjLj, so
479 // by this point it needs no generic EH preparation, like the None case.
481
482 // The lower invoke pass may create unreachable code. Remove it.
484 break;
485 }
486}
487
488/// Add pass to prepare the LLVM IR for code generation. This should be done
489/// before exception handling preparation passes.
491 if (getOptLevel() != CodeGenOptLevel::None && !Opt.DisableCGP)
493 // TODO: Default ctor'd RewriteSymbolPass is no-op.
494 // addPass(RewriteSymbolPass());
495}
496
497/// Add common passes that perform LLVM IR to IR transforms in preparation for
498/// instruction selection.
500 addPreISel(PMW);
501
502 if (Opt.RequiresCodeGenSCCOrder && !AddInCGSCCOrder)
504
506 // Add both the safe stack and the stack protection passes: each of them will
507 // only protect functions that have corresponding attributes.
510
511 if (Opt.PrintISelInput)
513 dbgs(), "\n\n*** Final LLVM Code input to ISel ***\n"),
514 PMW);
515
516 // All passes which modify the LLVM IR are now complete; run the verifier
517 // to ensure that the IR is valid.
518 if (!Opt.DisableVerify)
519 addFunctionPass(VerifierPass(), PMW, /*Force=*/true);
520}
521
523 // Enable FastISel with -fast-isel, but allow that to be overridden.
524 TM.setO0WantsFastISel(Opt.EnableFastISelOption !=
526
527 // Determine an instruction selector.
528 enum class SelectorType { SelectionDAG, FastISel, GlobalISel };
529 SelectorType Selector;
530
531 if (Opt.EnableFastISelOption == cl::boolOrDefault::BOU_TRUE)
532 Selector = SelectorType::FastISel;
533 else if (Opt.EnableGlobalISelOption == cl::boolOrDefault::BOU_TRUE ||
534 (TM.Options.EnableGlobalISel &&
535 Opt.EnableGlobalISelOption != cl::boolOrDefault::BOU_FALSE))
536 Selector = SelectorType::GlobalISel;
537 else if (TM.getOptLevel() == CodeGenOptLevel::None && TM.getO0WantsFastISel())
538 Selector = SelectorType::FastISel;
539 else
540 Selector = SelectorType::SelectionDAG;
541
542 // Set consistently TM.Options.EnableFastISel and EnableGlobalISel.
543 if (Selector == SelectorType::FastISel) {
544 TM.setFastISel(true);
545 TM.setGlobalISel(false);
546 } else if (Selector == SelectorType::GlobalISel) {
547 TM.setFastISel(false);
548 TM.setGlobalISel(true);
549 }
550
551 // Add instruction selector passes.
552 if (Selector == SelectorType::GlobalISel) {
553 if (auto Err = addIRTranslator(PMW))
554 return Err;
555
557
558 if (auto Err = addLegalizeMachineIR(PMW))
559 return Err;
560
561 // Before running the register bank selector, ask the target if it
562 // wants to run some passes.
564
565 if (auto Err = addRegBankSelect(PMW))
566 return Err;
567
569
570 if (auto Err = addGlobalInstructionSelect(PMW))
571 return Err;
572
573 // Pass to reset the MachineFunction if the ISel failed.
575 ResetMachineFunctionPass(reportDiagnosticWhenGlobalISelFallback(),
577 PMW);
578
579 // Provide a fallback path when we do not want to abort on
580 // not-yet-supported input.
582 if (auto Err = addInstSelector(PMW))
583 return Err;
584
585 } else if (auto Err = addInstSelector(PMW))
586 return Err;
587
588 // Expand pseudo-instructions emitted by ISel. Don't run the verifier before
589 // FinalizeISel.
591
592 // // Print the instruction selected machine code...
593 // printAndVerify("After Instruction Selection");
594
595 return Error::success();
596}
597
598/// Add the complete set of target-independent postISel code generator passes.
599///
600/// This can be read as the standard order of major LLVM CodeGen stages. Stages
601/// with nontrivial configuration or multiple passes are broken out below in
602/// add%Stage routines.
603///
604/// Any CodeGenPassBuilder::addXX routine may be overriden by the Target. The
605/// addPre/Post methods with empty header implementations allow injecting
606/// target-specific fixups just before or after major stages. Additionally,
607/// targets have the flexibility to change pass order within a stage by
608/// overriding default implementation of add%Stage routines below. Each
609/// technique has maintainability tradeoffs because alternate pass orders are
610/// not well supported. addPre/Post works better if the target pass is easily
611/// tied to a common pass. But if it has subtle dependencies on multiple passes,
612/// the target should override the stage instead.
614 // Add passes that optimize machine instructions in SSA form.
617 } else {
618 // If the target requests it, assign local variables to stack slots relative
619 // to one another and simplify frame index references where possible.
621 }
622
623 if (TM.Options.EnableIPRA) {
624 flushFPMsToMPM(PMW);
626 PMW, /*Force=*/true);
628 }
629 // Run pre-ra passes.
630 addPreRegAlloc(PMW);
631
632 // Run register allocation and passes that are tightly coupled with it,
633 // including phi elimination and scheduling.
634 if (auto Err = Opt.OptimizeRegAlloc == cl::boolOrDefault::BOU_TRUE
636 : addFastRegAlloc(PMW))
637 return Err;
638
639 // Run post-ra passes.
640 addPostRegAlloc(PMW);
641
644
645 // Insert prolog/epilog code. Eliminate abstract frame index references...
649 }
650
652
653 /// Add passes that optimize machine instructions after register allocation.
656
657 // Expand pseudo instructions before second scheduling pass.
659
660 // Run pre-sched2 passes.
661 addPreSched2(PMW);
662
663 if (Opt.EnableImplicitNullChecks)
665
666 // Second pass scheduler.
667 // Let Target optionally insert this pass by itself at some other
668 // point.
670 !TM.targetSchedulesPostRAScheduling()) {
671 if (Opt.MISchedPostRA)
673 else
675 }
676
677 // GC
678 addGCPasses(PMW);
679
680 // Basic block placement.
683
684 // Insert before XRay Instrumentation.
686
689
690 addPreEmitPass(PMW);
691
692 if (TM.Options.EnableIPRA) {
693 // Collect register usage information and produce a register mask of
694 // clobbered registers, to be used to optimize call sites.
696 // If -print-regusage is specified, print the collected register usage info.
697 if (Opt.PrintRegUsage) {
698 flushFPMsToMPM(PMW);
700 }
701 }
702
704
706 addMachineFunctionPass(StackMapLivenessPass(), PMW);
708 LiveDebugValuesPass(TM.Options.ShouldEmitDebugEntryValues()), PMW);
710
711 if (TM.Options.EnableMachineOutliner &&
713 Opt.EnableMachineOutliner != RunOutliner::NeverOutline) {
714 if (Opt.EnableMachineOutliner != RunOutliner::TargetDefault ||
715 TM.Options.SupportsDefaultOutlining) {
716 flushFPMsToMPM(PMW);
717 addModulePass(MachineOutlinerPass(Opt.EnableMachineOutliner), PMW);
718 }
719 }
720
721 if (Opt.EnableGCEmptyBlocks)
723
725
727
728 // Add passes that directly emit MI after all other MI passes.
729 addPreEmitPass2(PMW);
730
731 return Error::success();
732}
733
734/// Add passes that optimize machine instructions in SSA form.
736 // Pre-ra tail duplication.
738
739 // Optimize PHIs before DCE: removing dead PHI cycles may make more
740 // instructions dead.
742
743 // This pass merges large allocas. StackSlotColoring is a different pass
744 // which merges spill slots.
746
747 // If the target requests it, assign local variables to stack slots relative
748 // to one another and simplify frame index references where possible.
750
751 // With optimization, dead code should already be eliminated. However
752 // there is one known exception: lowered code for arguments that are only
753 // used by tail calls, where the tail calls reuse the incoming stack
754 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
756
757 // Allow targets to insert passes that improve instruction level parallelism,
758 // like if-conversion. Such passes will typically need dominator trees and
759 // loop info, just like LICM and CSE below.
760 addILPOpts(PMW);
761
764
765 addMachineFunctionPass(MachineSinkingPass(Opt.EnableSinkAndFold), PMW);
766
768 // Clean-up the dead code that may have been generated by peephole
769 // rewriting.
771}
772
773//===---------------------------------------------------------------------===//
774/// Register Allocation Pass Configuration
775//===---------------------------------------------------------------------===//
776
777/// Instantiate the default register allocator pass for this target for either
778/// the optimized or unoptimized allocation path. This will be added to the pass
779/// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
780/// in the optimized case.
781///
782/// A target that uses the standard regalloc pass order for fast or optimized
783/// allocation may still override this for per-target regalloc
784/// selection. But -regalloc-npm=... always takes precedence.
785/// If a target does not want to allow users to set -regalloc-npm=... at all,
786/// check if Opt.RegAlloc == RegAllocType::Unset.
788 bool Optimized) {
789 if (Optimized)
791 else
793}
794
795/// Find and instantiate the register allocation pass requested by this target
796/// at the current optimization level. Different register allocators are
797/// defined as separate passes because they may require different analysis.
798///
799/// This helper ensures that the -regalloc-npm= option is always available,
800/// even for targets that override the default allocator.
802 bool Optimized) {
803 // Use the specified -regalloc-npm={basic|greedy|fast|pbqp}
804 if (Opt.RegAlloc > RegAllocType::Default) {
805 switch (Opt.RegAlloc) {
808 break;
811 break;
812 default:
813 reportFatalUsageError("register allocator not supported yet");
814 }
815 return;
816 }
817 // -regalloc=default or unspecified, so pick based on the optimization level
818 // or ask the target for the regalloc pass.
819 addTargetRegisterAllocator(PMW, Optimized);
820}
821
823 // TODO: Ensure allocator is default or fast.
824 addRegAllocPass(PMW, false);
825 return Error::success();
826}
827
830 // Add the selected register allocation pass.
831 addRegAllocPass(PMW, true);
832
833 // Allow targets to change the register assignments before rewriting.
834 addPreRewrite(PMW);
835
836 // Finally rewrite virtual registers.
838
839 return true;
840}
841
842/// Add the minimum set of target-independent passes that are required for
843/// register allocation. No coalescing or scheduling.
849
850/// Add standard target-independent passes that are tightly coupled with
851/// optimized register allocation, including coalescing, machine instruction
852/// scheduling, and register allocation itself.
855
857
859
860 // LiveVariables currently requires pure SSA form.
861 //
862 // FIXME: Once TwoAddressInstruction pass no longer uses kill flags,
863 // LiveVariables can be removed completely, and LiveIntervals can be directly
864 // computed. (We still either need to regenerate kill flags after regalloc, or
865 // preferably fix the scavenger to not depend on them).
866 // FIXME: UnreachableMachineBlockElim is a dependant pass of LiveVariables.
867 // When LiveVariables is removed this has to be removed/moved either.
868 // Explicit addition of UnreachableMachineBlockElim allows stopping before or
869 // after it with -stop-before/-stop-after.
873
874 // Edge splitting is smarter with machine loop info.
878
879 // Eventually, we want to run LiveIntervals before PHI elimination.
880 if (Opt.EarlyLiveIntervals)
883
886
887 // The machine scheduler may accidentally create disconnected components
888 // when moving subregister definitions around, avoid this by splitting them to
889 // separate vregs before. Splitting can also improve reg. allocation quality.
891
892 // PreRA instruction scheduling.
894
896 if (!AddedPasses)
897 return AddedPasses.takeError();
898 if (!AddedPasses.get())
899 return Error::success();
900
902
903 // Allow targets to expand pseudo instructions depending on the choice of
904 // registers before MachineCopyPropagation.
905 addPostRewrite(PMW);
906
907 // Copy propagate to forward register uses and try to eliminate COPYs that
908 // were not coalesced.
910
911 // Run post-ra machine LICM to hoist reloads / remats.
912 //
913 // FIXME: can this move into MachineLateOptimization?
915
916 return Error::success();
917}
918
919//===---------------------------------------------------------------------===//
920/// Post RegAlloc Pass Configuration
921//===---------------------------------------------------------------------===//
922
923/// Add passes that optimize machine instructions after register allocation.
925 // Cleanup of redundant (identical) address/immediate loads.
927
928 // Branch folding must be run after regalloc and prolog/epilog insertion.
929 addMachineFunctionPass(BranchFolderPass(Opt.EnableTailMerge), PMW);
930
931 // Tail duplication.
932 // Note that duplicating tail just increases code size and degrades
933 // performance for targets that require Structured Control Flow.
934 // In addition it can also make CFG irreducible. Thus we disable it.
935 if (!TM.requiresStructuredCFG())
937
938 // Copy propagation.
940}
941
942/// Add standard basic block placement passes.
945 // Run a separate pass to collect block placement statistics.
946 if (Opt.EnableBlockPlacementStats)
948}
amdgpu next use AMDGPU Next Use Analysis Printer
This header provides classes for managing passes over SCCs of the call graph.
Interfaces for producing common pass manager configurations.
Defines an IR pass for CodeGen Prepare.
Analysis that tracks defined/used subregister lanes across COPY instructions and instructions that ge...
This file defines passes to print out IR in various granularities.
This header defines various interfaces for pass management in LLVM.
This file contains the declaration of the InterleavedAccessPass class, its corresponding pass name is...
This header provides classes for managing a pipeline of passes over loops in LLVM IR.
ModuleAnalysisManager MAM
if(PassOpts->AAPipeline)
PassInstrumentationCallbacks PIC
This pass is required to take advantage of the interprocedural register allocation infrastructure.
This file contains the declaration of the SelectOptimizePass class, its corresponding pass name is se...
This file defines the SmallVector class.
Target-Independent Code Generator Pass Configuration Options pass.
static const char PassName[]
A pass that canonicalizes freeze instructions in a loop.
virtual void addPreEmitPass(PassManagerWrapper &PMW)
This pass may be implemented by targets that want to run passes immediately before machine code is em...
virtual void addMachineSSAOptimization(PassManagerWrapper &PMW)
Methods with trivial inline returns are convenient points in the common codegen pass pipeline where t...
void addRegAllocPass(PassManagerWrapper &PMW, bool Optimized)
addMachinePasses helper to create the target-selected or overriden regalloc pass.
void addMachineFunctionPass(PassT &&Pass, PassManagerWrapper &PMW, bool Force=false, StringRef Name=PassT::name())
CodeGenPassBuilder(TargetMachine &TM, const CGPassBuilderOption &Opts, PassInstrumentationCallbacks *PIC)
virtual Error addLegalizeMachineIR(PassManagerWrapper &PMW)
This method should install a legalize pass, which converts the instruction sequence into one that can...
virtual void addPreRewrite(PassManagerWrapper &PMW)
addPreRewrite - Add passes to the optimized register allocation pipeline after register allocation is...
virtual Error addMachinePasses(PassManagerWrapper &PMW)
Add the complete, standard set of LLVM CodeGen passes.
void flushFPMsToMPM(PassManagerWrapper &PMW, bool FreeMachineFunctions=false)
virtual void addAsmPrinter(PassManagerWrapper &PMW)
virtual Error addRegAssignAndRewriteFast(PassManagerWrapper &PMW)
Add core register allocator passes which do the actual register assignment and rewriting.
void addFunctionPass(PassT &&Pass, PassManagerWrapper &PMW, bool Force=false, StringRef Name=PassT::name())
virtual void addIRPasses(PassManagerWrapper &PMW)
Add common target configurable passes that perform LLVM IR to IR transforms following machine indepen...
virtual void addMachineLateOptimization(PassManagerWrapper &PMW)
Add passes that optimize machine instructions after register allocation.
Error buildPipeline(ModulePassManager &MPM, ModuleAnalysisManager &MAM, raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut, CodeGenFileType FileType, MCContext &Ctx)
virtual void addPreRegAlloc(PassManagerWrapper &PMW)
This method may be implemented by targets that want to run passes immediately before register allocat...
virtual void addPostRegAlloc(PassManagerWrapper &PMW)
This method may be implemented by targets that want to run passes after register allocation pass pipe...
bool isGlobalISelAbortEnabled() const
Check whether or not GlobalISel should abort on error.
virtual void addPreSched2(PassManagerWrapper &PMW)
This method may be implemented by targets that want to run passes after prolog-epilog insertion and b...
void addISelPasses(PassManagerWrapper &PMW)
High level function that adds all passes necessary to go from llvm IR representation to the MI repres...
virtual void addCodeGenPrepare(PassManagerWrapper &PMW)
Add pass to prepare the LLVM IR for code generation.
Error addCoreISelPasses(PassManagerWrapper &PMW)
Add the actual instruction selection passes.
virtual void addPreEmitPass2(PassManagerWrapper &PMW)
Targets may add passes immediately before machine code is emitted in this callback.
virtual void addPreRegBankSelect(PassManagerWrapper &PMW)
This method may be implemented by targets that want to run passes immediately before the register ban...
virtual void addGlobalMergePass(PassManagerWrapper &PMW)
Target can override this to add GlobalMergePass before all IR passes.
CodeGenOptLevel getOptLevel() const
virtual void addTargetRegisterAllocator(PassManagerWrapper &PMW, bool Optimized)
Utilities for targets to add passes to the pass manager.
virtual Error addGlobalInstructionSelect(PassManagerWrapper &PMW)
This method should install a (global) instruction selector pass, which converts possibly generic inst...
virtual void addAsmPrinterBegin(PassManagerWrapper &PMW)
virtual Error addIRTranslator(PassManagerWrapper &PMW)
This method should install an IR translator pass, which converts from LLVM code to machine instructio...
virtual void addPreLegalizeMachineIR(PassManagerWrapper &PMW)
This method may be implemented by targets that want to run passes immediately before legalization.
virtual Expected< bool > addRegAssignAndRewriteOptimized(PassManagerWrapper &PMW)
virtual void addISelPrepare(PassManagerWrapper &PMW)
Add common passes that perform LLVM IR to IR transforms in preparation for instruction selection.
virtual void addPreISel(PassManagerWrapper &PMW)
{{@ For GlobalISel
virtual Error addOptimizedRegAlloc(PassManagerWrapper &PMW)
addOptimizedRegAlloc - Add passes related to register allocation.
virtual void addPostBBSections(PassManagerWrapper &PMW)
void addModulePass(PassT &&Pass, PassManagerWrapper &PMW, bool Force=false, StringRef Name=PassT::name())
virtual Error addFastRegAlloc(PassManagerWrapper &PMW)
addFastRegAlloc - Add the minimum set of target-independent passes that are required for fast registe...
virtual void addPreGlobalInstructionSelect(PassManagerWrapper &PMW)
This method may be implemented by targets that want to run passes immediately before the (global) ins...
void addPassesToHandleExceptions(PassManagerWrapper &PMW)
Add passes to lower exception handling for the code generator.
virtual void addILPOpts(PassManagerWrapper &PMW)
Add passes that optimize instruction level parallelism for out-of-order targets.
PassInstrumentationCallbacks * PIC
virtual void addAsmPrinterEnd(PassManagerWrapper &PMW)
virtual Error addInstSelector(PassManagerWrapper &PMW)
addInstSelector - This method should install an instruction selector pass, which converts from LLVM c...
virtual void addBlockPlacement(PassManagerWrapper &PMW)
Add standard basic block placement passes.
virtual void addPostRewrite(PassManagerWrapper &PMW)
Add passes to be run immediately after virtual registers are rewritten to physical registers.
bool reportDiagnosticWhenGlobalISelFallback() const
Check whether or not a diagnostic should be emitted when GlobalISel uses the fallback path.
virtual void addGCPasses(PassManagerWrapper &PMW)
addGCPasses - Add late codegen passes that analyze code for garbage collection.
void requireCGSCCOrder(PassManagerWrapper &PMW)
virtual Error addRegBankSelect(PassManagerWrapper &PMW)
This method should install a register bank selector pass, which assigns register banks to virtual reg...
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
reference get()
Returns a reference to the stored T value.
Definition Error.h:582
This is a fast-path instruction selection class that generates poor code and doesn't support illegal ...
Definition FastISel.h:67
LowerIntrinsics - This pass rewrites calls to the llvm.gcread or llvm.gcwrite intrinsics,...
Definition GCMetadata.h:229
Performs Loop Strength Reduce Pass.
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition MCAsmInfo.h:67
ExceptionHandling getExceptionHandlingType() const
Definition MCAsmInfo.h:656
Context object for machine code objects.
Definition MCContext.h:83
This class manages callbacks registration, as well as provides a way for PassInstrumentation to pass ...
LLVM_ABI StringRef getPassNameForClassName(StringRef ClassName)
Get the pass name for a given pass class name. Empty if no match found.
LLVM_ATTRIBUTE_MINSIZE std::enable_if_t<!std::is_same_v< PassT, PassManager > > addPass(PassT &&Pass)
bool isEmpty() const
Returns if the pass manager contains any passes.
Pass (for the new pass manager) for printing a Function as LLVM's text IR assembly.
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Primary interface to the complete machine description for the target machine.
static Expected< StartStopInfo > getStartStopInfo(PassInstrumentationCallbacks &PIC)
Returns pass name in -stop-before or -stop-after NOTE: New pass manager migration only.
static bool willCompleteCodeGenPipeline()
Returns true if none of the -stop-before and -stop-after options is set.
Create a verifier pass.
Definition Verifier.h:133
An abstract base class for streams implementations that also support a pwrite operation.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This is an optimization pass for GlobalISel generic memory operations.
ModuleToFunctionPassAdaptor createModuleToFunctionPassAdaptor(FunctionPassT &&Pass, bool EagerlyInvalidate=false)
A function to deduce a function pass type and wrap it in the templated adaptor.
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:94
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1321
PassManager< Loop, LoopAnalysisManager, LoopStandardAnalysisResults &, LPMUpdater & > LoopPassManager
The Loop pass manager.
ModuleToPostOrderCGSCCPassAdaptor createModuleToPostOrderCGSCCPassAdaptor(CGSCCPassT &&Pass)
A function to deduce a function pass type and wrap it in the templated adaptor.
FunctionToLoopPassAdaptor createFunctionToLoopPassAdaptor(LoopPassT &&Pass, bool UseMemorySSA=false)
A function to deduce a loop pass type and wrap it in the templated adaptor.
CGSCCToFunctionPassAdaptor createCGSCCToFunctionPassAdaptor(FunctionPassT &&Pass, bool EagerlyInvalidate=false, bool NoRerun=false)
A function to deduce a function pass type and wrap it in the templated adaptor.
CodeGenFileType
These enums are meant to be passed into addPassesToEmitFile to indicate what type of file to emit,...
Definition CodeGen.h:256
FunctionToMachineFunctionPassAdaptor createFunctionToMachineFunctionPassAdaptor(MachineFunctionPassT &&Pass)
PassManager< Module > ModulePassManager
Convenience typedef for a pass manager over modules.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
PassManager< Function > FunctionPassManager
Convenience typedef for a pass manager over functions.
@ SjLj
setjmp/longjmp based exceptions
Definition CodeGen.h:58
@ ZOS
z/OS MVS Exception Handling.
Definition CodeGen.h:64
@ Emscripten
Emscripten JavaScript-based exception handling.
Definition CodeGen.h:62
@ None
No exception support.
Definition CodeGen.h:56
@ Default
Not specified; resolve to the target's default model.
Definition CodeGen.h:55
@ AIX
AIX Exception Handling.
Definition CodeGen.h:63
@ DwarfCFI
DWARF-like instruction based exceptions.
Definition CodeGen.h:57
@ WinEH
Windows Exception Handling.
Definition CodeGen.h:60
@ Wasm
WebAssembly Exception Handling.
Definition CodeGen.h:61
PassManager< MachineFunction > MachineFunctionPassManager
Convenience typedef for a pass manager over functions.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
Global function merging pass for new pass manager.
A utility pass template to force an analysis result to be available.