LLVM 22.0.0git
CodeGenPassBuilder.h
Go to the documentation of this file.
1//===- Construction of codegen pass pipelines ------------------*- C++ -*--===//
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/// \file
9///
10/// Interfaces for producing common pass manager configurations.
11///
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_PASSES_CODEGENPASSBUILDER_H
15#define LLVM_PASSES_CODEGENPASSBUILDER_H
16
18#include "llvm/ADT/StringRef.h"
69#include "llvm/CodeGen/PEI.h"
106#include "llvm/IR/PassManager.h"
107#include "llvm/IR/Verifier.h"
109#include "llvm/MC/MCAsmInfo.h"
111#include "llvm/Support/CodeGen.h"
112#include "llvm/Support/Debug.h"
113#include "llvm/Support/Error.h"
130#include <cassert>
131#include <type_traits>
132#include <utility>
133
134namespace llvm {
135
136// FIXME: Dummy target independent passes definitions that have not yet been
137// ported to new pass manager. Once they do, remove these.
138#define DUMMY_FUNCTION_PASS(NAME, PASS_NAME) \
139 struct PASS_NAME : public PassInfoMixin<PASS_NAME> { \
140 template <typename... Ts> PASS_NAME(Ts &&...) {} \
141 PreservedAnalyses run(Function &, FunctionAnalysisManager &) { \
142 return PreservedAnalyses::all(); \
143 } \
144 };
145#define DUMMY_MACHINE_MODULE_PASS(NAME, PASS_NAME) \
146 struct PASS_NAME : public PassInfoMixin<PASS_NAME> { \
147 template <typename... Ts> PASS_NAME(Ts &&...) {} \
148 PreservedAnalyses run(Module &, ModuleAnalysisManager &) { \
149 return PreservedAnalyses::all(); \
150 } \
151 };
152#define DUMMY_MACHINE_FUNCTION_PASS(NAME, PASS_NAME) \
153 struct PASS_NAME : public PassInfoMixin<PASS_NAME> { \
154 template <typename... Ts> PASS_NAME(Ts &&...) {} \
155 PreservedAnalyses run(MachineFunction &, \
156 MachineFunctionAnalysisManager &) { \
157 return PreservedAnalyses::all(); \
158 } \
159 };
160#include "llvm/Passes/MachinePassRegistry.def"
161
162/// This class provides access to building LLVM's passes.
163///
164/// Its members provide the baseline state available to passes during their
165/// construction. The \c MachinePassRegistry.def file specifies how to construct
166/// all of the built-in passes, and those may reference these members during
167/// construction.
168template <typename DerivedT, typename TargetMachineT> class CodeGenPassBuilder {
169public:
170 explicit CodeGenPassBuilder(TargetMachineT &TM,
171 const CGPassBuilderOption &Opts,
173 : TM(TM), Opt(Opts), PIC(PIC) {
174 // Target could set CGPassBuilderOption::MISchedPostRA to true to achieve
175 // substitutePass(&PostRASchedulerID, &PostMachineSchedulerID)
176
177 // Target should override TM.Options.EnableIPRA in their target-specific
178 // LLVMTM ctor. See TargetMachine::setGlobalISel for example.
179 if (Opt.EnableIPRA) {
180 TM.Options.EnableIPRA = *Opt.EnableIPRA;
181 } else {
182 // If not explicitly specified, use target default.
183 TM.Options.EnableIPRA |= TM.useIPRA();
184 }
185
186 if (Opt.EnableGlobalISelAbort)
187 TM.Options.GlobalISelAbort = *Opt.EnableGlobalISelAbort;
188
189 if (!Opt.OptimizeRegAlloc)
190 Opt.OptimizeRegAlloc = getOptLevel() != CodeGenOptLevel::None;
191 }
192
194 raw_pwrite_stream *DwoOut,
195 CodeGenFileType FileType) const;
196
200
201protected:
202 template <typename PassT>
203 using is_module_pass_t = decltype(std::declval<PassT &>().run(
204 std::declval<Module &>(), std::declval<ModuleAnalysisManager &>()));
205
206 template <typename PassT>
207 using is_function_pass_t = decltype(std::declval<PassT &>().run(
208 std::declval<Function &>(), std::declval<FunctionAnalysisManager &>()));
209
210 template <typename PassT>
211 using is_machine_function_pass_t = decltype(std::declval<PassT &>().run(
212 std::declval<MachineFunction &>(),
213 std::declval<MachineFunctionAnalysisManager &>()));
214
215 // Function object to maintain state while adding codegen IR passes.
216 // TODO: add a Function -> MachineFunction adaptor and merge
217 // AddIRPass/AddMachinePass so we can have a function pipeline that runs both
218 // function passes and machine function passes.
219 class AddIRPass {
220 public:
221 AddIRPass(ModulePassManager &MPM, const DerivedT &PB) : MPM(MPM), PB(PB) {}
222 ~AddIRPass() { flushFPMToMPM(); }
223
224 template <typename PassT>
225 void operator()(PassT &&Pass, bool Force = false,
226 StringRef Name = PassT::name()) {
229 "Only module pass and function pass are supported.");
230 if (!Force && !PB.runBeforeAdding(Name))
231 return;
232
233 // Add Function Pass
235 FPM.addPass(std::forward<PassT>(Pass));
236 } else {
237 // Add Module Pass
238 flushFPMToMPM();
239 MPM.addPass(std::forward<PassT>(Pass));
240 }
241 }
242
243 /// Setting this will add passes to the CGSCC pass manager.
245 if (PB.AddInCGSCCOrder)
246 return;
247 flushFPMToMPM();
248 PB.AddInCGSCCOrder = true;
249 }
250
251 /// Stop adding passes to the CGSCC pass manager.
252 /// Existing passes won't be removed.
254 if (!PB.AddInCGSCCOrder)
255 return;
256 flushFPMToMPM();
257 PB.AddInCGSCCOrder = false;
258 }
259
260 private:
261 void flushFPMToMPM() {
262 if (FPM.isEmpty())
263 return;
264 if (PB.AddInCGSCCOrder) {
266 createCGSCCToFunctionPassAdaptor(std::move(FPM))));
267 } else {
268 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
269 }
270 FPM = FunctionPassManager();
271 }
274 const DerivedT &PB;
275 };
276
277 // Function object to maintain state while adding codegen machine passes.
279 public:
280 AddMachinePass(ModulePassManager &MPM, const DerivedT &PB)
281 : MPM(MPM), PB(PB) {}
283 if (MFPM.isEmpty())
284 return;
285
289 if (this->PB.AddInCGSCCOrder) {
291 createCGSCCToFunctionPassAdaptor(std::move(FPM))));
292 } else
293 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
294 }
295
296 template <typename PassT>
297 void operator()(PassT &&Pass, bool Force = false,
298 StringRef Name = PassT::name()) {
301 "Only module pass and function pass are supported.");
302
303 if (!Force && !PB.runBeforeAdding(Name))
304 return;
305
306 // Add Function Pass
308 MFPM.addPass(std::forward<PassT>(Pass));
309 } else {
310 // Add Module Pass
311 flushMFPMToMPM();
312 MPM.addPass(std::forward<PassT>(Pass));
313 }
314
315 for (auto &C : PB.AfterCallbacks)
316 C(Name, MFPM);
317 }
318
319 /// Setting this will add passes to the CGSCC pass manager.
321 if (PB.AddInCGSCCOrder)
322 return;
323 flushMFPMToMPM();
324 PB.AddInCGSCCOrder = true;
325 }
326
327 /// Stop adding passes to the CGSCC pass manager.
328 /// Existing passes won't be removed.
330 if (!PB.AddInCGSCCOrder)
331 return;
332 flushMFPMToMPM();
333 PB.AddInCGSCCOrder = false;
334 }
335
336 private:
337 void flushMFPMToMPM() {
338 if (MFPM.isEmpty())
339 return;
340
341 if (PB.AddInCGSCCOrder) {
345 } else {
348 }
350 }
351
354 const DerivedT &PB;
355 };
356
357 TargetMachineT &TM;
360
361 template <typename TMC> TMC &getTM() const { return static_cast<TMC &>(TM); }
362 CodeGenOptLevel getOptLevel() const { return TM.getOptLevel(); }
363
364 /// Check whether or not GlobalISel should abort on error.
365 /// When this is disabled, GlobalISel will fall back on SDISel instead of
366 /// erroring out.
368 return TM.Options.GlobalISelAbort == GlobalISelAbortMode::Enable;
369 }
370
371 /// Check whether or not a diagnostic should be emitted when GlobalISel
372 /// uses the fallback path. In other words, it will emit a diagnostic
373 /// when GlobalISel failed and isGlobalISelAbortEnabled is false.
375 return TM.Options.GlobalISelAbort == GlobalISelAbortMode::DisableWithDiag;
376 }
377
378 /// addInstSelector - This method should install an instruction selector pass,
379 /// which converts from LLVM code to machine instructions.
380 Error addInstSelector(AddMachinePass &) const {
381 return make_error<StringError>("addInstSelector is not overridden",
383 }
384
385 /// Target can override this to add GlobalMergePass before all IR passes.
386 void addGlobalMergePass(AddIRPass &) const {}
387
388 /// Add passes that optimize instruction level parallelism for out-of-order
389 /// targets. These passes are run while the machine code is still in SSA
390 /// form, so they can use MachineTraceMetrics to control their heuristics.
391 ///
392 /// All passes added here should preserve the MachineDominatorTree,
393 /// MachineLoopInfo, and MachineTraceMetrics analyses.
394 void addILPOpts(AddMachinePass &) const {}
395
396 /// This method may be implemented by targets that want to run passes
397 /// immediately before register allocation.
398 void addPreRegAlloc(AddMachinePass &) const {}
399
400 /// addPreRewrite - Add passes to the optimized register allocation pipeline
401 /// after register allocation is complete, but before virtual registers are
402 /// rewritten to physical registers.
403 ///
404 /// These passes must preserve VirtRegMap and LiveIntervals, and when running
405 /// after RABasic or RAGreedy, they should take advantage of LiveRegMatrix.
406 /// When these passes run, VirtRegMap contains legal physreg assignments for
407 /// all virtual registers.
408 ///
409 /// Note if the target overloads addRegAssignAndRewriteOptimized, this may not
410 /// be honored. This is also not generally used for the fast variant,
411 /// where the allocation and rewriting are done in one pass.
412 void addPreRewrite(AddMachinePass &) const {}
413
414 /// Add passes to be run immediately after virtual registers are rewritten
415 /// to physical registers.
416 void addPostRewrite(AddMachinePass &) const {}
417
418 /// This method may be implemented by targets that want to run passes after
419 /// register allocation pass pipeline but before prolog-epilog insertion.
420 void addPostRegAlloc(AddMachinePass &) const {}
421
422 /// This method may be implemented by targets that want to run passes after
423 /// prolog-epilog insertion and before the second instruction scheduling pass.
424 void addPreSched2(AddMachinePass &) const {}
425
426 /// This pass may be implemented by targets that want to run passes
427 /// immediately before machine code is emitted.
428 void addPreEmitPass(AddMachinePass &) const {}
429
430 /// Targets may add passes immediately before machine code is emitted in this
431 /// callback. This is called even later than `addPreEmitPass`.
432 // FIXME: Rename `addPreEmitPass` to something more sensible given its actual
433 // position and remove the `2` suffix here as this callback is what
434 // `addPreEmitPass` *should* be but in reality isn't.
435 void addPreEmitPass2(AddMachinePass &) const {}
436
437 /// {{@ For GlobalISel
438 ///
439
440 /// addPreISel - This method should add any "last minute" LLVM->LLVM
441 /// passes (which are run just before instruction selector).
442 void addPreISel(AddIRPass &) const {
443 llvm_unreachable("addPreISel is not overridden");
444 }
445
446 /// This method should install an IR translator pass, which converts from
447 /// LLVM code to machine instructions with possibly generic opcodes.
448 Error addIRTranslator(AddMachinePass &) const {
449 return make_error<StringError>("addIRTranslator is not overridden",
451 }
452
453 /// This method may be implemented by targets that want to run passes
454 /// immediately before legalization.
455 void addPreLegalizeMachineIR(AddMachinePass &) const {}
456
457 /// This method should install a legalize pass, which converts the instruction
458 /// sequence into one that can be selected by the target.
459 Error addLegalizeMachineIR(AddMachinePass &) const {
460 return make_error<StringError>("addLegalizeMachineIR is not overridden",
462 }
463
464 /// This method may be implemented by targets that want to run passes
465 /// immediately before the register bank selection.
466 void addPreRegBankSelect(AddMachinePass &) const {}
467
468 /// This method should install a register bank selector pass, which
469 /// assigns register banks to virtual registers without a register
470 /// class or register banks.
471 Error addRegBankSelect(AddMachinePass &) const {
472 return make_error<StringError>("addRegBankSelect is not overridden",
474 }
475
476 /// This method may be implemented by targets that want to run passes
477 /// immediately before the (global) instruction selection.
478 void addPreGlobalInstructionSelect(AddMachinePass &) const {}
479
480 /// This method should install a (global) instruction selector pass, which
481 /// converts possibly generic instructions to fully target-specific
482 /// instructions, thereby constraining all generic virtual registers to
483 /// register classes.
484 Error addGlobalInstructionSelect(AddMachinePass &) const {
486 "addGlobalInstructionSelect is not overridden",
488 }
489 /// @}}
490
491 /// High level function that adds all passes necessary to go from llvm IR
492 /// representation to the MI representation.
493 /// Adds IR based lowering and target specific optimization passes and finally
494 /// the core instruction selection passes.
495 void addISelPasses(AddIRPass &) const;
496
497 /// Add the actual instruction selection passes. This does not include
498 /// preparation passes on IR.
499 Error addCoreISelPasses(AddMachinePass &) const;
500
501 /// Add the complete, standard set of LLVM CodeGen passes.
502 /// Fully developed targets will not generally override this.
503 Error addMachinePasses(AddMachinePass &) const;
504
505 /// Add passes to lower exception handling for the code generator.
506 void addPassesToHandleExceptions(AddIRPass &) const;
507
508 /// Add common target configurable passes that perform LLVM IR to IR
509 /// transforms following machine independent optimization.
510 void addIRPasses(AddIRPass &) const;
511
512 /// Add pass to prepare the LLVM IR for code generation. This should be done
513 /// before exception handling preparation passes.
514 void addCodeGenPrepare(AddIRPass &) const;
515
516 /// Add common passes that perform LLVM IR to IR transforms in preparation for
517 /// instruction selection.
518 void addISelPrepare(AddIRPass &) const;
519
520 /// Methods with trivial inline returns are convenient points in the common
521 /// codegen pass pipeline where targets may insert passes. Methods with
522 /// out-of-line standard implementations are major CodeGen stages called by
523 /// addMachinePasses. Some targets may override major stages when inserting
524 /// passes is insufficient, but maintaining overriden stages is more work.
525 ///
526
527 /// addMachineSSAOptimization - Add standard passes that optimize machine
528 /// instructions in SSA form.
529 void addMachineSSAOptimization(AddMachinePass &) const;
530
531 /// addFastRegAlloc - Add the minimum set of target-independent passes that
532 /// are required for fast register allocation.
533 Error addFastRegAlloc(AddMachinePass &) const;
534
535 /// addOptimizedRegAlloc - Add passes related to register allocation.
536 /// CodeGenTargetMachineImpl provides standard regalloc passes for most
537 /// targets.
538 void addOptimizedRegAlloc(AddMachinePass &) const;
539
540 /// Add passes that optimize machine instructions after register allocation.
541 void addMachineLateOptimization(AddMachinePass &) const;
542
543 /// addGCPasses - Add late codegen passes that analyze code for garbage
544 /// collection. This should return true if GC info should be printed after
545 /// these passes.
546 void addGCPasses(AddMachinePass &) const {}
547
548 /// Add standard basic block placement passes.
549 void addBlockPlacement(AddMachinePass &) const;
550
552 std::function<Expected<std::unique_ptr<MCStreamer>>(MCContext &)>;
553 void addAsmPrinter(AddMachinePass &, CreateMCStreamer) const {
554 llvm_unreachable("addAsmPrinter is not overridden");
555 }
556
557 /// Utilities for targets to add passes to the pass manager.
558 ///
559
560 /// createTargetRegisterAllocator - Create the register allocator pass for
561 /// this target at the current optimization level.
562 void addTargetRegisterAllocator(AddMachinePass &, bool Optimized) const;
563
564 /// addMachinePasses helper to create the target-selected or overriden
565 /// regalloc pass.
566 void addRegAllocPass(AddMachinePass &, bool Optimized) const;
567
568 /// Add core register alloator passes which do the actual register assignment
569 /// and rewriting. \returns true if any passes were added.
570 Error addRegAssignmentFast(AddMachinePass &) const;
571 Error addRegAssignmentOptimized(AddMachinePass &) const;
572
573 /// Allow the target to disable a specific pass by default.
574 /// Backend can declare unwanted passes in constructor.
575 template <typename... PassTs> void disablePass() {
576 BeforeCallbacks.emplace_back(
577 [](StringRef Name) { return ((Name != PassTs::name()) && ...); });
578 }
579
580 /// Insert InsertedPass pass after TargetPass pass.
581 /// Only machine function passes are supported.
582 template <typename TargetPassT, typename InsertedPassT>
583 void insertPass(InsertedPassT &&Pass) const {
584 AfterCallbacks.emplace_back(
585 [&](StringRef Name, MachineFunctionPassManager &MFPM) mutable {
586 if (Name == TargetPassT::name() &&
587 runBeforeAdding(InsertedPassT::name())) {
588 MFPM.addPass(std::forward<InsertedPassT>(Pass));
589 }
590 });
591 }
592
593private:
594 DerivedT &derived() { return static_cast<DerivedT &>(*this); }
595 const DerivedT &derived() const {
596 return static_cast<const DerivedT &>(*this);
597 }
598
599 bool runBeforeAdding(StringRef Name) const {
600 bool ShouldAdd = true;
601 for (auto &C : BeforeCallbacks)
602 ShouldAdd &= C(Name);
603 return ShouldAdd;
604 }
605
606 void setStartStopPasses(const TargetPassConfig::StartStopInfo &Info) const;
607
608 Error verifyStartStop(const TargetPassConfig::StartStopInfo &Info) const;
609
610 mutable SmallVector<llvm::unique_function<bool(StringRef)>, 4>
611 BeforeCallbacks;
612 mutable SmallVector<
613 llvm::unique_function<void(StringRef, MachineFunctionPassManager &)>, 4>
614 AfterCallbacks;
615
616 /// Helper variable for `-start-before/-start-after/-stop-before/-stop-after`
617 mutable bool Started = true;
618 mutable bool Stopped = true;
619 mutable bool AddInCGSCCOrder = false;
620};
621
622template <typename Derived, typename TargetMachineT>
625 CodeGenFileType FileType) const {
626 auto StartStopInfo = TargetPassConfig::getStartStopInfo(*PIC);
627 if (!StartStopInfo)
628 return StartStopInfo.takeError();
629 setStartStopPasses(*StartStopInfo);
630
632 bool PrintMIR = !PrintAsm && FileType != CodeGenFileType::Null;
633
634 {
635 AddIRPass addIRPass(MPM, derived());
637 /*Force=*/true);
639 /*Force=*/true);
641 /*Force=*/true);
643 /*Force=*/true);
644 addISelPasses(addIRPass);
645 }
646
647 AddMachinePass addPass(MPM, derived());
648
649 if (PrintMIR)
650 addPass(PrintMIRPreparePass(Out), /*Force=*/true);
651
652 if (auto Err = addCoreISelPasses(addPass))
653 return std::move(Err);
654
655 if (auto Err = derived().addMachinePasses(addPass))
656 return std::move(Err);
657
658 if (!Opt.DisableVerify)
659 addPass(MachineVerifierPass());
660
661 if (PrintAsm) {
662 derived().addAsmPrinter(
663 addPass, [this, &Out, DwoOut, FileType](MCContext &Ctx) {
664 return this->TM.createMCStreamer(Out, DwoOut, FileType, Ctx);
665 });
666 }
667
668 if (PrintMIR)
669 addPass(PrintMIRPass(Out), /*Force=*/true);
670
671 return verifyStartStop(*StartStopInfo);
672}
673
674template <typename Derived, typename TargetMachineT>
675void CodeGenPassBuilder<Derived, TargetMachineT>::setStartStopPasses(
676 const TargetPassConfig::StartStopInfo &Info) const {
677 if (!Info.StartPass.empty()) {
678 Started = false;
679 BeforeCallbacks.emplace_back([this, &Info, AfterFlag = Info.StartAfter,
680 Count = 0u](StringRef ClassName) mutable {
681 if (Count == Info.StartInstanceNum) {
682 if (AfterFlag) {
683 AfterFlag = false;
684 Started = true;
685 }
686 return Started;
687 }
688
689 auto PassName = PIC->getPassNameForClassName(ClassName);
690 if (Info.StartPass == PassName && ++Count == Info.StartInstanceNum)
691 Started = !Info.StartAfter;
692
693 return Started;
694 });
695 }
696
697 if (!Info.StopPass.empty()) {
698 Stopped = false;
699 BeforeCallbacks.emplace_back([this, &Info, AfterFlag = Info.StopAfter,
700 Count = 0u](StringRef ClassName) mutable {
701 if (Count == Info.StopInstanceNum) {
702 if (AfterFlag) {
703 AfterFlag = false;
704 Stopped = true;
705 }
706 return !Stopped;
707 }
708
709 auto PassName = PIC->getPassNameForClassName(ClassName);
710 if (Info.StopPass == PassName && ++Count == Info.StopInstanceNum)
711 Stopped = !Info.StopAfter;
712 return !Stopped;
713 });
714 }
715}
716
717template <typename Derived, typename TargetMachineT>
718Error CodeGenPassBuilder<Derived, TargetMachineT>::verifyStartStop(
720 if (Started && Stopped)
721 return Error::success();
722
723 if (!Started)
725 "Can't find start pass \"" + Info.StartPass + "\".",
726 std::make_error_code(std::errc::invalid_argument));
727 if (!Stopped)
729 "Can't find stop pass \"" + Info.StopPass + "\".",
730 std::make_error_code(std::errc::invalid_argument));
731 return Error::success();
732}
733
734template <typename Derived, typename TargetMachineT>
736 AddIRPass &addPass) const {
737 derived().addGlobalMergePass(addPass);
738 if (TM.useEmulatedTLS())
739 addPass(LowerEmuTLSPass());
740
742 addPass(ExpandLargeDivRemPass(TM));
743 addPass(ExpandFpPass(TM, getOptLevel()));
744
745 derived().addIRPasses(addPass);
746 derived().addCodeGenPrepare(addPass);
748 derived().addISelPrepare(addPass);
749}
750
751/// Add common target configurable passes that perform LLVM IR to IR transforms
752/// following machine independent optimization.
753template <typename Derived, typename TargetMachineT>
755 AddIRPass &addPass) const {
756 // Before running any passes, run the verifier to determine if the input
757 // coming from the front-end and/or optimizer is valid.
758 if (!Opt.DisableVerify)
759 addPass(VerifierPass(), /*Force=*/true);
760
761 // Run loop strength reduction before anything else.
762 if (getOptLevel() != CodeGenOptLevel::None && !Opt.DisableLSR) {
763 LoopPassManager LPM;
764 LPM.addPass(CanonicalizeFreezeInLoopsPass());
765 LPM.addPass(LoopStrengthReducePass());
766 if (Opt.EnableLoopTermFold)
767 LPM.addPass(LoopTermFoldPass());
768 addPass(createFunctionToLoopPassAdaptor(std::move(LPM),
769 /*UseMemorySSA=*/true));
770 }
771
773 // The MergeICmpsPass tries to create memcmp calls by grouping sequences of
774 // loads and compares. ExpandMemCmpPass then tries to expand those calls
775 // into optimally-sized loads and compares. The transforms are enabled by a
776 // target lowering hook.
777 if (!Opt.DisableMergeICmps)
778 addPass(MergeICmpsPass());
779 addPass(ExpandMemCmpPass(TM));
780 }
781
782 // Run GC lowering passes for builtin collectors
783 // TODO: add a pass insertion point here
784 addPass(GCLoweringPass());
785 addPass(ShadowStackGCLoweringPass());
787
788 // Make sure that no unreachable blocks are instruction selected.
789 addPass(UnreachableBlockElimPass());
790
791 // Prepare expensive constants for SelectionDAG.
792 if (getOptLevel() != CodeGenOptLevel::None && !Opt.DisableConstantHoisting)
793 addPass(ConstantHoistingPass());
794
795 // Replace calls to LLVM intrinsics (e.g., exp, log) operating on vector
796 // operands with calls to the corresponding functions in a vector library.
798 addPass(ReplaceWithVeclib());
799
801 !Opt.DisablePartialLibcallInlining)
803
804 // Instrument function entry and exit, e.g. with calls to mcount().
805 addPass(EntryExitInstrumenterPass(/*PostInlining=*/true));
806
807 // Add scalarization of target's unsupported masked memory intrinsics pass.
808 // the unsupported intrinsic will be replaced with a chain of basic blocks,
809 // that stores/loads element one-by-one if the appropriate mask bit is set.
811
812 // Expand reduction intrinsics into shuffle sequences if the target wants to.
813 if (!Opt.DisableExpandReductions)
814 addPass(ExpandReductionsPass());
815
816 // Convert conditional moves to conditional jumps when profitable.
817 if (getOptLevel() != CodeGenOptLevel::None && !Opt.DisableSelectOptimize)
818 addPass(SelectOptimizePass(TM));
819
820 if (Opt.EnableGlobalMergeFunc)
821 addPass(GlobalMergeFuncPass());
822}
823
824/// Turn exception handling constructs into something the code generators can
825/// handle.
826template <typename Derived, typename TargetMachineT>
828 AddIRPass &addPass) const {
829 const MCAsmInfo *MCAI = TM.getMCAsmInfo();
830 assert(MCAI && "No MCAsmInfo");
831 switch (MCAI->getExceptionHandlingType()) {
833 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
834 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
835 // catch info can get misplaced when a selector ends up more than one block
836 // removed from the parent invoke(s). This could happen when a landing
837 // pad is shared by multiple invokes and is also a target of a normal
838 // edge from elsewhere.
839 addPass(SjLjEHPreparePass(&TM));
840 [[fallthrough]];
845 addPass(DwarfEHPreparePass(TM));
846 break;
848 // We support using both GCC-style and MSVC-style exceptions on Windows, so
849 // add both preparation passes. Each pass will only actually run if it
850 // recognizes the personality function.
851 addPass(WinEHPreparePass());
852 addPass(DwarfEHPreparePass(TM));
853 break;
855 // Wasm EH uses Windows EH instructions, but it does not need to demote PHIs
856 // on catchpads and cleanuppads because it does not outline them into
857 // funclets. Catchswitch blocks are not lowered in SelectionDAG, so we
858 // should remove PHIs there.
859 addPass(WinEHPreparePass(/*DemoteCatchSwitchPHIOnly=*/false));
860 addPass(WasmEHPreparePass());
861 break;
863 addPass(LowerInvokePass());
864
865 // The lower invoke pass may create unreachable code. Remove it.
866 addPass(UnreachableBlockElimPass());
867 break;
868 }
869}
870
871/// Add pass to prepare the LLVM IR for code generation. This should be done
872/// before exception handling preparation passes.
873template <typename Derived, typename TargetMachineT>
875 AddIRPass &addPass) const {
876 if (getOptLevel() != CodeGenOptLevel::None && !Opt.DisableCGP)
877 addPass(CodeGenPreparePass(TM));
878 // TODO: Default ctor'd RewriteSymbolPass is no-op.
879 // addPass(RewriteSymbolPass());
880}
881
882/// Add common passes that perform LLVM IR to IR transforms in preparation for
883/// instruction selection.
884template <typename Derived, typename TargetMachineT>
886 AddIRPass &addPass) const {
887 derived().addPreISel(addPass);
888
889 if (Opt.RequiresCodeGenSCCOrder)
890 addPass.requireCGSCCOrder();
891
893 addPass(ObjCARCContractPass());
894
895 addPass(CallBrPreparePass());
896 // Add both the safe stack and the stack protection passes: each of them will
897 // only protect functions that have corresponding attributes.
898 addPass(SafeStackPass(TM));
899 addPass(StackProtectorPass(TM));
900
901 if (Opt.PrintISelInput)
902 addPass(PrintFunctionPass(dbgs(),
903 "\n\n*** Final LLVM Code input to ISel ***\n"));
904
905 // All passes which modify the LLVM IR are now complete; run the verifier
906 // to ensure that the IR is valid.
907 if (!Opt.DisableVerify)
908 addPass(VerifierPass(), /*Force=*/true);
909}
910
911template <typename Derived, typename TargetMachineT>
913 AddMachinePass &addPass) const {
914 // Enable FastISel with -fast-isel, but allow that to be overridden.
915 TM.setO0WantsFastISel(Opt.EnableFastISelOption.value_or(true));
916
917 // Determine an instruction selector.
918 enum class SelectorType { SelectionDAG, FastISel, GlobalISel };
919 SelectorType Selector;
920
921 if (Opt.EnableFastISelOption && *Opt.EnableFastISelOption == true)
922 Selector = SelectorType::FastISel;
923 else if ((Opt.EnableGlobalISelOption &&
924 *Opt.EnableGlobalISelOption == true) ||
925 (TM.Options.EnableGlobalISel &&
926 (!Opt.EnableGlobalISelOption ||
927 *Opt.EnableGlobalISelOption == false)))
928 Selector = SelectorType::GlobalISel;
929 else if (TM.getOptLevel() == CodeGenOptLevel::None && TM.getO0WantsFastISel())
930 Selector = SelectorType::FastISel;
931 else
932 Selector = SelectorType::SelectionDAG;
933
934 // Set consistently TM.Options.EnableFastISel and EnableGlobalISel.
935 if (Selector == SelectorType::FastISel) {
936 TM.setFastISel(true);
937 TM.setGlobalISel(false);
938 } else if (Selector == SelectorType::GlobalISel) {
939 TM.setFastISel(false);
940 TM.setGlobalISel(true);
941 }
942
943 // Add instruction selector passes.
944 if (Selector == SelectorType::GlobalISel) {
945 if (auto Err = derived().addIRTranslator(addPass))
946 return std::move(Err);
947
948 derived().addPreLegalizeMachineIR(addPass);
949
950 if (auto Err = derived().addLegalizeMachineIR(addPass))
951 return std::move(Err);
952
953 // Before running the register bank selector, ask the target if it
954 // wants to run some passes.
955 derived().addPreRegBankSelect(addPass);
956
957 if (auto Err = derived().addRegBankSelect(addPass))
958 return std::move(Err);
959
960 derived().addPreGlobalInstructionSelect(addPass);
961
962 if (auto Err = derived().addGlobalInstructionSelect(addPass))
963 return std::move(Err);
964
965 // Pass to reset the MachineFunction if the ISel failed.
966 addPass(ResetMachineFunctionPass(reportDiagnosticWhenGlobalISelFallback(),
968
969 // Provide a fallback path when we do not want to abort on
970 // not-yet-supported input.
972 if (auto Err = derived().addInstSelector(addPass))
973 return std::move(Err);
974
975 } else if (auto Err = derived().addInstSelector(addPass))
976 return std::move(Err);
977
978 // Expand pseudo-instructions emitted by ISel. Don't run the verifier before
979 // FinalizeISel.
980 addPass(FinalizeISelPass());
981
982 // // Print the instruction selected machine code...
983 // printAndVerify("After Instruction Selection");
984
985 return Error::success();
986}
987
988/// Add the complete set of target-independent postISel code generator passes.
989///
990/// This can be read as the standard order of major LLVM CodeGen stages. Stages
991/// with nontrivial configuration or multiple passes are broken out below in
992/// add%Stage routines.
993///
994/// Any CodeGenPassBuilder<Derived, TargetMachine>::addXX routine may be
995/// overriden by the Target. The addPre/Post methods with empty header
996/// implementations allow injecting target-specific fixups just before or after
997/// major stages. Additionally, targets have the flexibility to change pass
998/// order within a stage by overriding default implementation of add%Stage
999/// routines below. Each technique has maintainability tradeoffs because
1000/// alternate pass orders are not well supported. addPre/Post works better if
1001/// the target pass is easily tied to a common pass. But if it has subtle
1002/// dependencies on multiple passes, the target should override the stage
1003/// instead.
1004template <typename Derived, typename TargetMachineT>
1006 AddMachinePass &addPass) const {
1007 // Add passes that optimize machine instructions in SSA form.
1009 derived().addMachineSSAOptimization(addPass);
1010 } else {
1011 // If the target requests it, assign local variables to stack slots relative
1012 // to one another and simplify frame index references where possible.
1014 }
1015
1016 if (TM.Options.EnableIPRA) {
1018 addPass(RegUsageInfoPropagationPass());
1019 }
1020 // Run pre-ra passes.
1021 derived().addPreRegAlloc(addPass);
1022
1023 // Run register allocation and passes that are tightly coupled with it,
1024 // including phi elimination and scheduling.
1025 if (*Opt.OptimizeRegAlloc) {
1026 derived().addOptimizedRegAlloc(addPass);
1027 } else {
1028 if (auto Err = derived().addFastRegAlloc(addPass))
1029 return Err;
1030 }
1031
1032 // Run post-ra passes.
1033 derived().addPostRegAlloc(addPass);
1034
1037
1038 // Insert prolog/epilog code. Eliminate abstract frame index references...
1040 addPass(PostRAMachineSinkingPass());
1041 addPass(ShrinkWrapPass());
1042 }
1043
1044 addPass(PrologEpilogInserterPass());
1045
1046 /// Add passes that optimize machine instructions after register allocation.
1048 derived().addMachineLateOptimization(addPass);
1049
1050 // Expand pseudo instructions before second scheduling pass.
1051 addPass(ExpandPostRAPseudosPass());
1052
1053 // Run pre-sched2 passes.
1054 derived().addPreSched2(addPass);
1055
1056 if (Opt.EnableImplicitNullChecks)
1057 addPass(ImplicitNullChecksPass());
1058
1059 // Second pass scheduler.
1060 // Let Target optionally insert this pass by itself at some other
1061 // point.
1063 !TM.targetSchedulesPostRAScheduling()) {
1064 if (Opt.MISchedPostRA)
1065 addPass(PostMachineSchedulerPass(&TM));
1066 else
1067 addPass(PostRASchedulerPass(&TM));
1068 }
1069
1070 // GC
1071 derived().addGCPasses(addPass);
1072
1073 // Basic block placement.
1075 derived().addBlockPlacement(addPass);
1076
1077 // Insert before XRay Instrumentation.
1078 addPass(FEntryInserterPass());
1079
1080 addPass(XRayInstrumentationPass());
1081 addPass(PatchableFunctionPass());
1082
1083 derived().addPreEmitPass(addPass);
1084
1085 if (TM.Options.EnableIPRA)
1086 // Collect register usage information and produce a register mask of
1087 // clobbered registers, to be used to optimize call sites.
1088 addPass(RegUsageInfoCollectorPass());
1089
1090 addPass(FuncletLayoutPass());
1091
1092 addPass(RemoveLoadsIntoFakeUsesPass());
1093 addPass(StackMapLivenessPass());
1094 addPass(LiveDebugValuesPass(
1095 getTM<TargetMachine>().Options.ShouldEmitDebugEntryValues()));
1097
1098 if (TM.Options.EnableMachineOutliner &&
1100 Opt.EnableMachineOutliner != RunOutliner::NeverOutline) {
1101 if (Opt.EnableMachineOutliner != RunOutliner::TargetDefault ||
1102 TM.Options.SupportsDefaultOutlining)
1103 addPass(MachineOutlinerPass(Opt.EnableMachineOutliner));
1104 }
1105
1107
1108 // Add passes that directly emit MI after all other MI passes.
1109 derived().addPreEmitPass2(addPass);
1110
1111 return Error::success();
1112}
1113
1114/// Add passes that optimize machine instructions in SSA form.
1115template <typename Derived, typename TargetMachineT>
1117 AddMachinePass &addPass) const {
1118 // Pre-ra tail duplication.
1119 addPass(EarlyTailDuplicatePass());
1120
1121 // Optimize PHIs before DCE: removing dead PHI cycles may make more
1122 // instructions dead.
1123 addPass(OptimizePHIsPass());
1124
1125 // This pass merges large allocas. StackSlotColoring is a different pass
1126 // which merges spill slots.
1127 addPass(StackColoringPass());
1128
1129 // If the target requests it, assign local variables to stack slots relative
1130 // to one another and simplify frame index references where possible.
1132
1133 // With optimization, dead code should already be eliminated. However
1134 // there is one known exception: lowered code for arguments that are only
1135 // used by tail calls, where the tail calls reuse the incoming stack
1136 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
1138
1139 // Allow targets to insert passes that improve instruction level parallelism,
1140 // like if-conversion. Such passes will typically need dominator trees and
1141 // loop info, just like LICM and CSE below.
1142 derived().addILPOpts(addPass);
1143
1144 addPass(EarlyMachineLICMPass());
1145 addPass(MachineCSEPass());
1146
1147 addPass(MachineSinkingPass(Opt.EnableSinkAndFold));
1148
1149 addPass(PeepholeOptimizerPass());
1150 // Clean-up the dead code that may have been generated by peephole
1151 // rewriting.
1153}
1154
1155//===---------------------------------------------------------------------===//
1156/// Register Allocation Pass Configuration
1157//===---------------------------------------------------------------------===//
1158
1159/// Instantiate the default register allocator pass for this target for either
1160/// the optimized or unoptimized allocation path. This will be added to the pass
1161/// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
1162/// in the optimized case.
1163///
1164/// A target that uses the standard regalloc pass order for fast or optimized
1165/// allocation may still override this for per-target regalloc
1166/// selection. But -regalloc-npm=... always takes precedence.
1167/// If a target does not want to allow users to set -regalloc-npm=... at all,
1168/// check if Opt.RegAlloc == RegAllocType::Unset.
1169template <typename Derived, typename TargetMachineT>
1171 AddMachinePass &addPass, bool Optimized) const {
1172 if (Optimized)
1173 addPass(RAGreedyPass());
1174 else
1175 addPass(RegAllocFastPass());
1176}
1177
1178/// Find and instantiate the register allocation pass requested by this target
1179/// at the current optimization level. Different register allocators are
1180/// defined as separate passes because they may require different analysis.
1181///
1182/// This helper ensures that the -regalloc-npm= option is always available,
1183/// even for targets that override the default allocator.
1184template <typename Derived, typename TargetMachineT>
1186 AddMachinePass &addPass, bool Optimized) const {
1187 // Use the specified -regalloc-npm={basic|greedy|fast|pbqp}
1188 if (Opt.RegAlloc > RegAllocType::Default) {
1189 switch (Opt.RegAlloc) {
1190 case RegAllocType::Fast:
1191 addPass(RegAllocFastPass());
1192 break;
1194 addPass(RAGreedyPass());
1195 break;
1196 default:
1197 reportFatalUsageError("register allocator not supported yet");
1198 }
1199 return;
1200 }
1201 // -regalloc=default or unspecified, so pick based on the optimization level
1202 // or ask the target for the regalloc pass.
1203 derived().addTargetRegisterAllocator(addPass, Optimized);
1204}
1205
1206template <typename Derived, typename TargetMachineT>
1208 AddMachinePass &addPass) const {
1209 // TODO: Ensure allocator is default or fast.
1210 addRegAllocPass(addPass, false);
1211 return Error::success();
1212}
1213
1214template <typename Derived, typename TargetMachineT>
1216 AddMachinePass &addPass) const {
1217 // Add the selected register allocation pass.
1218 addRegAllocPass(addPass, true);
1219
1220 // Allow targets to change the register assignments before rewriting.
1221 derived().addPreRewrite(addPass);
1222
1223 // Finally rewrite virtual registers.
1224 addPass(VirtRegRewriterPass());
1225 // Perform stack slot coloring and post-ra machine LICM.
1226 //
1227 // FIXME: Re-enable coloring with register when it's capable of adding
1228 // kill markers.
1229 addPass(StackSlotColoringPass());
1230
1231 return Error::success();
1232}
1233
1234/// Add the minimum set of target-independent passes that are required for
1235/// register allocation. No coalescing or scheduling.
1236template <typename Derived, typename TargetMachineT>
1238 AddMachinePass &addPass) const {
1239 addPass(PHIEliminationPass());
1240 addPass(TwoAddressInstructionPass());
1241 return derived().addRegAssignmentFast(addPass);
1242}
1243
1244/// Add standard target-independent passes that are tightly coupled with
1245/// optimized register allocation, including coalescing, machine instruction
1246/// scheduling, and register allocation itself.
1247template <typename Derived, typename TargetMachineT>
1249 AddMachinePass &addPass) const {
1250 addPass(DetectDeadLanesPass());
1251
1252 addPass(InitUndefPass());
1253
1254 addPass(ProcessImplicitDefsPass());
1255
1256 // LiveVariables currently requires pure SSA form.
1257 //
1258 // FIXME: Once TwoAddressInstruction pass no longer uses kill flags,
1259 // LiveVariables can be removed completely, and LiveIntervals can be directly
1260 // computed. (We still either need to regenerate kill flags after regalloc, or
1261 // preferably fix the scavenger to not depend on them).
1262 // FIXME: UnreachableMachineBlockElim is a dependant pass of LiveVariables.
1263 // When LiveVariables is removed this has to be removed/moved either.
1264 // Explicit addition of UnreachableMachineBlockElim allows stopping before or
1265 // after it with -stop-before/-stop-after.
1268
1269 // Edge splitting is smarter with machine loop info.
1271 addPass(PHIEliminationPass());
1272
1273 // Eventually, we want to run LiveIntervals before PHI elimination.
1274 if (Opt.EarlyLiveIntervals)
1276
1277 addPass(TwoAddressInstructionPass());
1278 addPass(RegisterCoalescerPass());
1279
1280 // The machine scheduler may accidentally create disconnected components
1281 // when moving subregister definitions around, avoid this by splitting them to
1282 // separate vregs before. Splitting can also improve reg. allocation quality.
1284
1285 // PreRA instruction scheduling.
1286 addPass(MachineSchedulerPass(&TM));
1287
1288 if (auto E = derived().addRegAssignmentOptimized(addPass)) {
1289 // addRegAssignmentOptimized did not add a reg alloc pass, so do nothing.
1290 return;
1291 }
1292 // Allow targets to expand pseudo instructions depending on the choice of
1293 // registers before MachineCopyPropagation.
1294 derived().addPostRewrite(addPass);
1295
1296 // Copy propagate to forward register uses and try to eliminate COPYs that
1297 // were not coalesced.
1298 addPass(MachineCopyPropagationPass());
1299
1300 // Run post-ra machine LICM to hoist reloads / remats.
1301 //
1302 // FIXME: can this move into MachineLateOptimization?
1303 addPass(MachineLICMPass());
1304}
1305
1306//===---------------------------------------------------------------------===//
1307/// Post RegAlloc Pass Configuration
1308//===---------------------------------------------------------------------===//
1309
1310/// Add passes that optimize machine instructions after register allocation.
1311template <typename Derived, typename TargetMachineT>
1313 AddMachinePass &addPass) const {
1314 // Branch folding must be run after regalloc and prolog/epilog insertion.
1315 addPass(BranchFolderPass(Opt.EnableTailMerge));
1316
1317 // Tail duplication.
1318 // Note that duplicating tail just increases code size and degrades
1319 // performance for targets that require Structured Control Flow.
1320 // In addition it can also make CFG irreducible. Thus we disable it.
1321 if (!TM.requiresStructuredCFG())
1322 addPass(TailDuplicatePass());
1323
1324 // Cleanup of redundant (identical) address/immediate loads.
1326
1327 // Copy propagation.
1328 addPass(MachineCopyPropagationPass());
1329}
1330
1331/// Add standard basic block placement passes.
1332template <typename Derived, typename TargetMachineT>
1334 AddMachinePass &addPass) const {
1335 addPass(MachineBlockPlacementPass(Opt.EnableTailMerge));
1336 // Run a separate pass to collect block placement statistics.
1337 if (Opt.EnableBlockPlacementStats)
1339}
1340
1341} // namespace llvm
1342
1343#endif // LLVM_PASSES_CODEGENPASSBUILDER_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This is the interface for LLVM's primary stateless and local alias analysis.
This header provides classes for managing passes over SCCs of the call graph.
Analysis containing CSE Info
Definition CSEInfo.cpp:27
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...
static LVOptions Options
Definition LVOptions.cpp:25
This header provides classes for managing a pipeline of passes over loops in LLVM IR.
The header file for the LowerConstantIntrinsics pass as used by the new pass manager.
if(PassOpts->AAPipeline)
PassInstrumentationCallbacks PIC
PassBuilder PB(Machine, PassOpts->PTO, std::nullopt, &PIC)
This pass is required to take advantage of the interprocedural register allocation infrastructure.
This is the interface for a metadata-based scoped no-alias analysis.
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.
This pass exposes codegen information to IR-level passes.
This is the interface for a metadata-based TBAA.
static const char PassName[]
A pass that canonicalizes freeze instructions in a loop.
AddIRPass(ModulePassManager &MPM, const DerivedT &PB)
void operator()(PassT &&Pass, bool Force=false, StringRef Name=PassT::name())
void requireCGSCCOrder()
Setting this will add passes to the CGSCC pass manager.
void stopAddingInCGSCCOrder()
Stop adding passes to the CGSCC pass manager.
void stopAddingInCGSCCOrder()
Stop adding passes to the CGSCC pass manager.
AddMachinePass(ModulePassManager &MPM, const DerivedT &PB)
void operator()(PassT &&Pass, bool Force=false, StringRef Name=PassT::name())
void requireCGSCCOrder()
Setting this will add passes to the CGSCC pass manager.
void addPreRewrite(AddMachinePass &) const
addPreRewrite - Add passes to the optimized register allocation pipeline after register allocation is...
void addPostRegAlloc(AddMachinePass &) const
This method may be implemented by targets that want to run passes after register allocation pass pipe...
void addPreGlobalInstructionSelect(AddMachinePass &) const
This method may be implemented by targets that want to run passes immediately before the (global) ins...
Error addRegAssignmentFast(AddMachinePass &) const
Add core register alloator passes which do the actual register assignment and rewriting.
decltype(std::declval< PassT & >().run( std::declval< Function & >(), std::declval< FunctionAnalysisManager & >())) is_function_pass_t
Error addFastRegAlloc(AddMachinePass &) const
addFastRegAlloc - Add the minimum set of target-independent passes that are required for fast registe...
Error addIRTranslator(AddMachinePass &) const
This method should install an IR translator pass, which converts from LLVM code to machine instructio...
void addILPOpts(AddMachinePass &) const
Add passes that optimize instruction level parallelism for out-of-order targets.
void addRegAllocPass(AddMachinePass &, bool Optimized) const
addMachinePasses helper to create the target-selected or overriden regalloc pass.
void addPreSched2(AddMachinePass &) const
This method may be implemented by targets that want to run passes after prolog-epilog insertion and b...
Error addRegBankSelect(AddMachinePass &) const
This method should install a register bank selector pass, which assigns register banks to virtual reg...
bool isGlobalISelAbortEnabled() const
Check whether or not GlobalISel should abort on error.
void addPreRegAlloc(AddMachinePass &) const
This method may be implemented by targets that want to run passes immediately before register allocat...
void insertPass(InsertedPassT &&Pass) const
Insert InsertedPass pass after TargetPass pass.
void addGCPasses(AddMachinePass &) const
addGCPasses - Add late codegen passes that analyze code for garbage collection.
Error buildPipeline(ModulePassManager &MPM, raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut, CodeGenFileType FileType) const
void addGlobalMergePass(AddIRPass &) const
Target can override this to add GlobalMergePass before all IR passes.
Error addLegalizeMachineIR(AddMachinePass &) const
This method should install a legalize pass, which converts the instruction sequence into one that can...
Error addCoreISelPasses(AddMachinePass &) const
Add the actual instruction selection passes.
std::function< Expected< std::unique_ptr< MCStreamer > >(MCContext &)> CreateMCStreamer
void addOptimizedRegAlloc(AddMachinePass &) const
addOptimizedRegAlloc - Add passes related to register allocation.
void addISelPasses(AddIRPass &) const
High level function that adds all passes necessary to go from llvm IR representation to the MI repres...
decltype(std::declval< PassT & >().run( std::declval< MachineFunction & >(), std::declval< MachineFunctionAnalysisManager & >())) is_machine_function_pass_t
void addMachineSSAOptimization(AddMachinePass &) const
Methods with trivial inline returns are convenient points in the common codegen pass pipeline where t...
CodeGenPassBuilder(TargetMachineT &TM, const CGPassBuilderOption &Opts, PassInstrumentationCallbacks *PIC)
Error addRegAssignmentOptimized(AddMachinePass &) const
void addCodeGenPrepare(AddIRPass &) const
Add pass to prepare the LLVM IR for code generation.
Error addMachinePasses(AddMachinePass &) const
Add the complete, standard set of LLVM CodeGen passes.
void addISelPrepare(AddIRPass &) const
Add common passes that perform LLVM IR to IR transforms in preparation for instruction selection.
void disablePass()
Allow the target to disable a specific pass by default.
void addBlockPlacement(AddMachinePass &) const
Add standard basic block placement passes.
Error addInstSelector(AddMachinePass &) const
addInstSelector - This method should install an instruction selector pass, which converts from LLVM c...
void addTargetRegisterAllocator(AddMachinePass &, bool Optimized) const
Utilities for targets to add passes to the pass manager.
void addPreEmitPass2(AddMachinePass &) const
Targets may add passes immediately before machine code is emitted in this callback.
void addPostRewrite(AddMachinePass &) const
Add passes to be run immediately after virtual registers are rewritten to physical registers.
void addPreRegBankSelect(AddMachinePass &) const
This method may be implemented by targets that want to run passes immediately before the register ban...
void addPreEmitPass(AddMachinePass &) const
This pass may be implemented by targets that want to run passes immediately before machine code is em...
Error addGlobalInstructionSelect(AddMachinePass &) const
This method should install a (global) instruction selector pass, which converts possibly generic inst...
void addMachineLateOptimization(AddMachinePass &) const
Add passes that optimize machine instructions after register allocation.
void addIRPasses(AddIRPass &) const
Add common target configurable passes that perform LLVM IR to IR transforms following machine indepen...
decltype(std::declval< PassT & >().run( std::declval< Module & >(), std::declval< ModuleAnalysisManager & >())) is_module_pass_t
void addPreLegalizeMachineIR(AddMachinePass &) const
This method may be implemented by targets that want to run passes immediately before legalization.
void addPassesToHandleExceptions(AddIRPass &) const
Add passes to lower exception handling for the code generator.
PassInstrumentationCallbacks * getPassInstrumentationCallbacks() const
bool reportDiagnosticWhenGlobalISelFallback() const
Check whether or not a diagnostic should be emitted when GlobalISel uses the fallback path.
void addPreISel(AddIRPass &) const
{{@ For GlobalISel
void addAsmPrinter(AddMachinePass &, CreateMCStreamer) const
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
This is a fast-path instruction selection class that generates poor code and doesn't support illegal ...
Definition FastISel.h:66
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:64
ExceptionHandling getExceptionHandlingType() const
Definition MCAsmInfo.h:633
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 interface - Implemented by all 'passes'.
Definition Pass.h:99
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...
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
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:134
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.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
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:98
@ SjLj
setjmp/longjmp based exceptions
Definition CodeGen.h:56
@ ZOS
z/OS MVS Exception Handling.
Definition CodeGen.h:61
@ None
No exception support.
Definition CodeGen.h:54
@ AIX
AIX Exception Handling.
Definition CodeGen.h:60
@ DwarfCFI
DWARF-like instruction based exceptions.
Definition CodeGen.h:55
@ WinEH
Windows Exception Handling.
Definition CodeGen.h:58
@ Wasm
WebAssembly Exception Handling.
Definition CodeGen.h:59
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:111
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:207
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:82
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
PassManager< Function > FunctionPassManager
Convenience typedef for a pass manager over functions.
typename detail::detector< void, Op, Args... >::value_t is_detected
Detects if a given trait holds for some set of arguments 'Args'.
PassManager< MachineFunction > MachineFunctionPassManager
Convenience typedef for a pass manager over functions.
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:180
Global function merging pass for new pass manager.
A utility pass template to force an analysis result to be available.