#include "llvm/CodeGen/TargetPassConfig.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Analysis/BasicAliasAnalysis.h"
#include "llvm/Analysis/CFLAndersAliasAnalysis.h"
#include "llvm/Analysis/CFLSteensAliasAnalysis.h"
#include "llvm/Analysis/CallGraphSCCPass.h"
#include "llvm/Analysis/ScopedNoAliasAA.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/Analysis/TypeBasedAliasAnalysis.h"
#include "llvm/CodeGen/BasicBlockSectionsProfileReader.h"
#include "llvm/CodeGen/CSEConfigBase.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachinePassRegistry.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/RegAllocRegistry.h"
#include "llvm/IR/IRPrintingPasses.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/PassInstrumentation.h"
#include "llvm/IR/Verifier.h"
#include "llvm/InitializePasses.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCTargetOptions.h"
#include "llvm/Pass.h"
#include "llvm/Support/CodeGen.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Discriminator.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/SaveAndRestore.h"
#include "llvm/Support/Threading.h"
#include "llvm/Target/CGPassBuilderOption.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils.h"
#include <cassert>
#include <string>
using namespace llvm;
static cl::opt<bool>
EnableIPRA("enable-ipra", cl::init(false), cl::Hidden,
cl::desc("Enable interprocedural register allocation "
"to reduce load/store at procedure calls."));
static cl::opt<bool> DisablePostRASched("disable-post-ra", cl::Hidden,
cl::desc("Disable Post Regalloc Scheduler"));
static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
cl::desc("Disable branch folding"));
static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
cl::desc("Disable tail duplication"));
static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
cl::desc("Disable pre-register allocation tail duplication"));
static cl::opt<bool> DisableBlockPlacement("disable-block-placement",
cl::Hidden, cl::desc("Disable probability-driven block placement"));
static cl::opt<bool> EnableBlockPlacementStats("enable-block-placement-stats",
cl::Hidden, cl::desc("Collect probability-driven block placement stats"));
static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
cl::desc("Disable Stack Slot Coloring"));
static cl::opt<bool> DisableMachineDCE("disable-machine-dce", cl::Hidden,
cl::desc("Disable Machine Dead Code Elimination"));
static cl::opt<bool> DisableEarlyIfConversion("disable-early-ifcvt", cl::Hidden,
cl::desc("Disable Early If-conversion"));
static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
cl::desc("Disable Machine LICM"));
static cl::opt<bool> DisableMachineCSE("disable-machine-cse", cl::Hidden,
cl::desc("Disable Machine Common Subexpression Elimination"));
static cl::opt<cl::boolOrDefault> OptimizeRegAlloc(
"optimize-regalloc", cl::Hidden,
cl::desc("Enable optimized register allocation compilation path."));
static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm",
cl::Hidden,
cl::desc("Disable Machine LICM"));
static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
cl::desc("Disable Machine Sinking"));
static cl::opt<bool> DisablePostRAMachineSink("disable-postra-machine-sink",
cl::Hidden,
cl::desc("Disable PostRA Machine Sinking"));
static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
cl::desc("Disable Loop Strength Reduction Pass"));
static cl::opt<bool> DisableConstantHoisting("disable-constant-hoisting",
cl::Hidden, cl::desc("Disable ConstantHoisting"));
static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
cl::desc("Disable Codegen Prepare"));
static cl::opt<bool> DisableCopyProp("disable-copyprop", cl::Hidden,
cl::desc("Disable Copy Propagation pass"));
static cl::opt<bool> DisablePartialLibcallInlining("disable-partial-libcall-inlining",
cl::Hidden, cl::desc("Disable Partial Libcall Inlining"));
static cl::opt<bool> EnableImplicitNullChecks(
"enable-implicit-null-checks",
cl::desc("Fold null checks into faulting memory operations"),
cl::init(false), cl::Hidden);
static cl::opt<bool> DisableMergeICmps("disable-mergeicmps",
cl::desc("Disable MergeICmps Pass"),
cl::init(false), cl::Hidden);
static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
cl::desc("Print LLVM IR produced by the loop-reduce pass"));
static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
cl::desc("Print LLVM IR input to isel pass"));
static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
cl::desc("Dump garbage collector data"));
static cl::opt<cl::boolOrDefault>
VerifyMachineCode("verify-machineinstrs", cl::Hidden,
cl::desc("Verify generated machine code"));
static cl::opt<cl::boolOrDefault>
DebugifyAndStripAll("debugify-and-strip-all-safe", cl::Hidden,
cl::desc("Debugify MIR before and Strip debug after "
"each pass except those known to be unsafe "
"when debug info is present"));
static cl::opt<cl::boolOrDefault> DebugifyCheckAndStripAll(
"debugify-check-and-strip-all-safe", cl::Hidden,
cl::desc(
"Debugify MIR before, by checking and stripping the debug info after, "
"each pass except those known to be unsafe when debug info is "
"present"));
static cl::opt<RunOutliner> EnableMachineOutliner(
"enable-machine-outliner", cl::desc("Enable the machine outliner"),
cl::Hidden, cl::ValueOptional, cl::init(RunOutliner::TargetDefault),
cl::values(clEnumValN(RunOutliner::AlwaysOutline, "always",
"Run on all functions guaranteed to be beneficial"),
clEnumValN(RunOutliner::NeverOutline, "never",
"Disable all outlining"),
clEnumValN(RunOutliner::AlwaysOutline, "", "")));
static cl::opt<bool> DisableCFIFixup("disable-cfi-fixup", cl::Hidden,
cl::desc("Disable the CFI fixup pass"));
static cl::opt<cl::boolOrDefault>
EnableFastISelOption("fast-isel", cl::Hidden,
cl::desc("Enable the \"fast\" instruction selector"));
static cl::opt<cl::boolOrDefault> EnableGlobalISelOption(
"global-isel", cl::Hidden,
cl::desc("Enable the \"global\" instruction selector"));
static cl::opt<bool>
PrintAfterISel("print-after-isel", cl::init(false), cl::Hidden,
cl::desc("Print machine instrs after ISel"));
static cl::opt<GlobalISelAbortMode> EnableGlobalISelAbort(
"global-isel-abort", cl::Hidden,
cl::desc("Enable abort calls when \"global\" instruction selection "
"fails to lower/select an instruction"),
cl::values(
clEnumValN(GlobalISelAbortMode::Disable, "0", "Disable the abort"),
clEnumValN(GlobalISelAbortMode::Enable, "1", "Enable the abort"),
clEnumValN(GlobalISelAbortMode::DisableWithDiag, "2",
"Disable the abort but emit a diagnostic on failure")));
static cl::opt<bool>
FSNoFinalDiscrim("fs-no-final-discrim", cl::init(false), cl::Hidden,
cl::desc("Do not insert FS-AFDO discriminators before "
"emit."));
static cl::opt<bool> DisableRAFSProfileLoader(
"disable-ra-fsprofile-loader", cl::init(false), cl::Hidden,
cl::desc("Disable MIRProfileLoader before RegAlloc"));
static cl::opt<bool> DisableLayoutFSProfileLoader(
"disable-layout-fsprofile-loader", cl::init(false), cl::Hidden,
cl::desc("Disable MIRProfileLoader before BlockPlacement"));
static cl::opt<std::string>
FSProfileFile("fs-profile-file", cl::init(""), cl::value_desc("filename"),
cl::desc("Flow Sensitive profile file name."), cl::Hidden);
static cl::opt<std::string> FSRemappingFile(
"fs-remapping-file", cl::init(""), cl::value_desc("filename"),
cl::desc("Flow Sensitive profile remapping file name."), cl::Hidden);
static cl::opt<bool> MISchedPostRA(
"misched-postra", cl::Hidden,
cl::desc(
"Run MachineScheduler post regalloc (independent of preRA sched)"));
static cl::opt<bool> EarlyLiveIntervals("early-live-intervals", cl::Hidden,
cl::desc("Run live interval analysis earlier in the pipeline"));
static cl::opt<CFLAAType> UseCFLAA(
"use-cfl-aa-in-codegen", cl::init(CFLAAType::None), cl::Hidden,
cl::desc("Enable the new, experimental CFL alias analysis in CodeGen"),
cl::values(clEnumValN(CFLAAType::None, "none", "Disable CFL-AA"),
clEnumValN(CFLAAType::Steensgaard, "steens",
"Enable unification-based CFL-AA"),
clEnumValN(CFLAAType::Andersen, "anders",
"Enable inclusion-based CFL-AA"),
clEnumValN(CFLAAType::Both, "both",
"Enable both variants of CFL-AA")));
static const char StartAfterOptName[] = "start-after";
static const char StartBeforeOptName[] = "start-before";
static const char StopAfterOptName[] = "stop-after";
static const char StopBeforeOptName[] = "stop-before";
static cl::opt<std::string>
StartAfterOpt(StringRef(StartAfterOptName),
cl::desc("Resume compilation after a specific pass"),
cl::value_desc("pass-name"), cl::init(""), cl::Hidden);
static cl::opt<std::string>
StartBeforeOpt(StringRef(StartBeforeOptName),
cl::desc("Resume compilation before a specific pass"),
cl::value_desc("pass-name"), cl::init(""), cl::Hidden);
static cl::opt<std::string>
StopAfterOpt(StringRef(StopAfterOptName),
cl::desc("Stop compilation after a specific pass"),
cl::value_desc("pass-name"), cl::init(""), cl::Hidden);
static cl::opt<std::string>
StopBeforeOpt(StringRef(StopBeforeOptName),
cl::desc("Stop compilation before a specific pass"),
cl::value_desc("pass-name"), cl::init(""), cl::Hidden);
static cl::opt<bool> EnableMachineFunctionSplitter(
"enable-split-machine-functions", cl::Hidden,
cl::desc("Split out cold blocks from machine functions based on profile "
"information."));
static cl::opt<bool> DisableExpandReductions(
"disable-expand-reductions", cl::init(false), cl::Hidden,
cl::desc("Disable the expand reduction intrinsics pass from running"));
static cl::opt<bool> DisableSelectOptimize(
"disable-select-optimize", cl::init(true), cl::Hidden,
cl::desc("Disable the select-optimization pass from running"));
static IdentifyingPassPtr applyDisable(IdentifyingPassPtr PassID,
bool Override) {
if (Override)
return IdentifyingPassPtr();
return PassID;
}
static IdentifyingPassPtr overridePass(AnalysisID StandardID,
IdentifyingPassPtr TargetID) {
if (StandardID == &PostRASchedulerID)
return applyDisable(TargetID, DisablePostRASched);
if (StandardID == &BranchFolderPassID)
return applyDisable(TargetID, DisableBranchFold);
if (StandardID == &TailDuplicateID)
return applyDisable(TargetID, DisableTailDuplicate);
if (StandardID == &EarlyTailDuplicateID)
return applyDisable(TargetID, DisableEarlyTailDup);
if (StandardID == &MachineBlockPlacementID)
return applyDisable(TargetID, DisableBlockPlacement);
if (StandardID == &StackSlotColoringID)
return applyDisable(TargetID, DisableSSC);
if (StandardID == &DeadMachineInstructionElimID)
return applyDisable(TargetID, DisableMachineDCE);
if (StandardID == &EarlyIfConverterID)
return applyDisable(TargetID, DisableEarlyIfConversion);
if (StandardID == &EarlyMachineLICMID)
return applyDisable(TargetID, DisableMachineLICM);
if (StandardID == &MachineCSEID)
return applyDisable(TargetID, DisableMachineCSE);
if (StandardID == &MachineLICMID)
return applyDisable(TargetID, DisablePostRAMachineLICM);
if (StandardID == &MachineSinkingID)
return applyDisable(TargetID, DisableMachineSink);
if (StandardID == &PostRAMachineSinkingID)
return applyDisable(TargetID, DisablePostRAMachineSink);
if (StandardID == &MachineCopyPropagationID)
return applyDisable(TargetID, DisableCopyProp);
return TargetID;
}
static std::string getFSProfileFile(const TargetMachine *TM) {
if (!FSProfileFile.empty())
return FSProfileFile.getValue();
const Optional<PGOOptions> &PGOOpt = TM->getPGOOption();
if (PGOOpt == None || PGOOpt->Action != PGOOptions::SampleUse)
return std::string();
return PGOOpt->ProfileFile;
}
static std::string getFSRemappingFile(const TargetMachine *TM) {
if (!FSRemappingFile.empty())
return FSRemappingFile.getValue();
const Optional<PGOOptions> &PGOOpt = TM->getPGOOption();
if (PGOOpt == None || PGOOpt->Action != PGOOptions::SampleUse)
return std::string();
return PGOOpt->ProfileRemappingFile;
}
INITIALIZE_PASS(TargetPassConfig, "targetpassconfig",
"Target Pass Configuration", false, false)
char TargetPassConfig::ID = 0;
namespace {
struct InsertedPass {
AnalysisID TargetPassID;
IdentifyingPassPtr InsertedPassID;
InsertedPass(AnalysisID TargetPassID, IdentifyingPassPtr InsertedPassID)
: TargetPassID(TargetPassID), InsertedPassID(InsertedPassID) {}
Pass *getInsertedPass() const {
assert(InsertedPassID.isValid() && "Illegal Pass ID!");
if (InsertedPassID.isInstance())
return InsertedPassID.getInstance();
Pass *NP = Pass::createPass(InsertedPassID.getID());
assert(NP && "Pass ID not registered");
return NP;
}
};
}
namespace llvm {
extern cl::opt<bool> EnableFSDiscriminator;
class PassConfigImpl {
public:
DenseMap<AnalysisID,IdentifyingPassPtr> TargetPasses;
SmallVector<InsertedPass, 4> InsertedPasses;
};
}
TargetPassConfig::~TargetPassConfig() {
delete Impl;
}
static const PassInfo *getPassInfo(StringRef PassName) {
if (PassName.empty())
return nullptr;
const PassRegistry &PR = *PassRegistry::getPassRegistry();
const PassInfo *PI = PR.getPassInfo(PassName);
if (!PI)
report_fatal_error(Twine('\"') + Twine(PassName) +
Twine("\" pass is not registered."));
return PI;
}
static AnalysisID getPassIDFromName(StringRef PassName) {
const PassInfo *PI = getPassInfo(PassName);
return PI ? PI->getTypeInfo() : nullptr;
}
static std::pair<StringRef, unsigned>
getPassNameAndInstanceNum(StringRef PassName) {
StringRef Name, InstanceNumStr;
std::tie(Name, InstanceNumStr) = PassName.split(',');
unsigned InstanceNum = 0;
if (!InstanceNumStr.empty() && InstanceNumStr.getAsInteger(10, InstanceNum))
report_fatal_error("invalid pass instance specifier " + PassName);
return std::make_pair(Name, InstanceNum);
}
void TargetPassConfig::setStartStopPasses() {
StringRef StartBeforeName;
std::tie(StartBeforeName, StartBeforeInstanceNum) =
getPassNameAndInstanceNum(StartBeforeOpt);
StringRef StartAfterName;
std::tie(StartAfterName, StartAfterInstanceNum) =
getPassNameAndInstanceNum(StartAfterOpt);
StringRef StopBeforeName;
std::tie(StopBeforeName, StopBeforeInstanceNum)
= getPassNameAndInstanceNum(StopBeforeOpt);
StringRef StopAfterName;
std::tie(StopAfterName, StopAfterInstanceNum)
= getPassNameAndInstanceNum(StopAfterOpt);
StartBefore = getPassIDFromName(StartBeforeName);
StartAfter = getPassIDFromName(StartAfterName);
StopBefore = getPassIDFromName(StopBeforeName);
StopAfter = getPassIDFromName(StopAfterName);
if (StartBefore && StartAfter)
report_fatal_error(Twine(StartBeforeOptName) + Twine(" and ") +
Twine(StartAfterOptName) + Twine(" specified!"));
if (StopBefore && StopAfter)
report_fatal_error(Twine(StopBeforeOptName) + Twine(" and ") +
Twine(StopAfterOptName) + Twine(" specified!"));
Started = (StartAfter == nullptr) && (StartBefore == nullptr);
}
CGPassBuilderOption llvm::getCGPassBuilderOption() {
CGPassBuilderOption Opt;
#define SET_OPTION(Option) \
if (Option.getNumOccurrences()) \
Opt.Option = Option;
SET_OPTION(EnableFastISelOption)
SET_OPTION(EnableGlobalISelAbort)
SET_OPTION(EnableGlobalISelOption)
SET_OPTION(EnableIPRA)
SET_OPTION(OptimizeRegAlloc)
SET_OPTION(VerifyMachineCode)
#define SET_BOOLEAN_OPTION(Option) Opt.Option = Option;
SET_BOOLEAN_OPTION(EarlyLiveIntervals)
SET_BOOLEAN_OPTION(EnableBlockPlacementStats)
SET_BOOLEAN_OPTION(EnableImplicitNullChecks)
SET_BOOLEAN_OPTION(EnableMachineOutliner)
SET_BOOLEAN_OPTION(MISchedPostRA)
SET_BOOLEAN_OPTION(UseCFLAA)
SET_BOOLEAN_OPTION(DisableMergeICmps)
SET_BOOLEAN_OPTION(DisableLSR)
SET_BOOLEAN_OPTION(DisableConstantHoisting)
SET_BOOLEAN_OPTION(DisableCGP)
SET_BOOLEAN_OPTION(DisablePartialLibcallInlining)
SET_BOOLEAN_OPTION(DisableSelectOptimize)
SET_BOOLEAN_OPTION(PrintLSR)
SET_BOOLEAN_OPTION(PrintISelInput)
SET_BOOLEAN_OPTION(PrintGCInfo)
return Opt;
}
static void registerPartialPipelineCallback(PassInstrumentationCallbacks &PIC,
LLVMTargetMachine &LLVMTM) {
StringRef StartBefore;
StringRef StartAfter;
StringRef StopBefore;
StringRef StopAfter;
unsigned StartBeforeInstanceNum = 0;
unsigned StartAfterInstanceNum = 0;
unsigned StopBeforeInstanceNum = 0;
unsigned StopAfterInstanceNum = 0;
std::tie(StartBefore, StartBeforeInstanceNum) =
getPassNameAndInstanceNum(StartBeforeOpt);
std::tie(StartAfter, StartAfterInstanceNum) =
getPassNameAndInstanceNum(StartAfterOpt);
std::tie(StopBefore, StopBeforeInstanceNum) =
getPassNameAndInstanceNum(StopBeforeOpt);
std::tie(StopAfter, StopAfterInstanceNum) =
getPassNameAndInstanceNum(StopAfterOpt);
if (StartBefore.empty() && StartAfter.empty() && StopBefore.empty() &&
StopAfter.empty())
return;
std::tie(StartBefore, std::ignore) =
LLVMTM.getPassNameFromLegacyName(StartBefore);
std::tie(StartAfter, std::ignore) =
LLVMTM.getPassNameFromLegacyName(StartAfter);
std::tie(StopBefore, std::ignore) =
LLVMTM.getPassNameFromLegacyName(StopBefore);
std::tie(StopAfter, std::ignore) =
LLVMTM.getPassNameFromLegacyName(StopAfter);
if (!StartBefore.empty() && !StartAfter.empty())
report_fatal_error(Twine(StartBeforeOptName) + Twine(" and ") +
Twine(StartAfterOptName) + Twine(" specified!"));
if (!StopBefore.empty() && !StopAfter.empty())
report_fatal_error(Twine(StopBeforeOptName) + Twine(" and ") +
Twine(StopAfterOptName) + Twine(" specified!"));
PIC.registerShouldRunOptionalPassCallback(
[=, EnableCurrent = StartBefore.empty() && StartAfter.empty(),
EnableNext = Optional<bool>(), StartBeforeCount = 0u,
StartAfterCount = 0u, StopBeforeCount = 0u,
StopAfterCount = 0u](StringRef P, Any) mutable {
bool StartBeforePass = !StartBefore.empty() && P.contains(StartBefore);
bool StartAfterPass = !StartAfter.empty() && P.contains(StartAfter);
bool StopBeforePass = !StopBefore.empty() && P.contains(StopBefore);
bool StopAfterPass = !StopAfter.empty() && P.contains(StopAfter);
if (EnableNext) {
EnableCurrent = *EnableNext;
EnableNext.reset();
}
if (StartAfterPass && StartAfterCount++ == StartAfterInstanceNum) {
assert(!EnableNext && "Error: assign to EnableNext more than once");
EnableNext = true;
}
if (StopAfterPass && StopAfterCount++ == StopAfterInstanceNum) {
assert(!EnableNext && "Error: assign to EnableNext more than once");
EnableNext = false;
}
if (StartBeforePass && StartBeforeCount++ == StartBeforeInstanceNum)
EnableCurrent = true;
if (StopBeforePass && StopBeforeCount++ == StopBeforeInstanceNum)
EnableCurrent = false;
return EnableCurrent;
});
}
void llvm::registerCodeGenCallback(PassInstrumentationCallbacks &PIC,
LLVMTargetMachine &LLVMTM) {
PIC.registerShouldRunOptionalPassCallback([](StringRef P, Any) {
#define DISABLE_PASS(Option, Name) \
if (Option && P.contains(#Name)) \
return false;
DISABLE_PASS(DisableBlockPlacement, MachineBlockPlacementPass)
DISABLE_PASS(DisableBranchFold, BranchFolderPass)
DISABLE_PASS(DisableCopyProp, MachineCopyPropagationPass)
DISABLE_PASS(DisableEarlyIfConversion, EarlyIfConverterPass)
DISABLE_PASS(DisableEarlyTailDup, EarlyTailDuplicatePass)
DISABLE_PASS(DisableMachineCSE, MachineCSEPass)
DISABLE_PASS(DisableMachineDCE, DeadMachineInstructionElimPass)
DISABLE_PASS(DisableMachineLICM, EarlyMachineLICMPass)
DISABLE_PASS(DisableMachineSink, MachineSinkingPass)
DISABLE_PASS(DisablePostRAMachineLICM, MachineLICMPass)
DISABLE_PASS(DisablePostRAMachineSink, PostRAMachineSinkingPass)
DISABLE_PASS(DisablePostRASched, PostRASchedulerPass)
DISABLE_PASS(DisableSSC, StackSlotColoringPass)
DISABLE_PASS(DisableTailDuplicate, TailDuplicatePass)
return true;
});
registerPartialPipelineCallback(PIC, LLVMTM);
}
TargetPassConfig::TargetPassConfig(LLVMTargetMachine &TM, PassManagerBase &pm)
: ImmutablePass(ID), PM(&pm), TM(&TM) {
Impl = new PassConfigImpl();
initializeCodeGen(*PassRegistry::getPassRegistry());
initializeBasicAAWrapperPassPass(*PassRegistry::getPassRegistry());
initializeAAResultsWrapperPassPass(*PassRegistry::getPassRegistry());
if (EnableIPRA.getNumOccurrences())
TM.Options.EnableIPRA = EnableIPRA;
else {
TM.Options.EnableIPRA |= TM.useIPRA();
}
if (TM.Options.EnableIPRA)
setRequiresCodeGenSCCOrder();
if (EnableGlobalISelAbort.getNumOccurrences())
TM.Options.GlobalISelAbort = EnableGlobalISelAbort;
setStartStopPasses();
}
CodeGenOpt::Level TargetPassConfig::getOptLevel() const {
return TM->getOptLevel();
}
void TargetPassConfig::insertPass(AnalysisID TargetPassID,
IdentifyingPassPtr InsertedPassID) {
assert(((!InsertedPassID.isInstance() &&
TargetPassID != InsertedPassID.getID()) ||
(InsertedPassID.isInstance() &&
TargetPassID != InsertedPassID.getInstance()->getPassID())) &&
"Insert a pass after itself!");
Impl->InsertedPasses.emplace_back(TargetPassID, InsertedPassID);
}
TargetPassConfig *LLVMTargetMachine::createPassConfig(PassManagerBase &PM) {
return new TargetPassConfig(*this, PM);
}
TargetPassConfig::TargetPassConfig()
: ImmutablePass(ID) {
report_fatal_error("Trying to construct TargetPassConfig without a target "
"machine. Scheduling a CodeGen pass without a target "
"triple set?");
}
bool TargetPassConfig::willCompleteCodeGenPipeline() {
return StopBeforeOpt.empty() && StopAfterOpt.empty();
}
bool TargetPassConfig::hasLimitedCodeGenPipeline() {
return !StartBeforeOpt.empty() || !StartAfterOpt.empty() ||
!willCompleteCodeGenPipeline();
}
std::string
TargetPassConfig::getLimitedCodeGenPipelineReason(const char *Separator) {
if (!hasLimitedCodeGenPipeline())
return std::string();
std::string Res;
static cl::opt<std::string> *PassNames[] = {&StartAfterOpt, &StartBeforeOpt,
&StopAfterOpt, &StopBeforeOpt};
static const char *OptNames[] = {StartAfterOptName, StartBeforeOptName,
StopAfterOptName, StopBeforeOptName};
bool IsFirst = true;
for (int Idx = 0; Idx < 4; ++Idx)
if (!PassNames[Idx]->empty()) {
if (!IsFirst)
Res += Separator;
IsFirst = false;
Res += OptNames[Idx];
}
return Res;
}
void TargetPassConfig::setOpt(bool &Opt, bool Val) {
assert(!Initialized && "PassConfig is immutable");
Opt = Val;
}
void TargetPassConfig::substitutePass(AnalysisID StandardID,
IdentifyingPassPtr TargetID) {
Impl->TargetPasses[StandardID] = TargetID;
}
IdentifyingPassPtr TargetPassConfig::getPassSubstitution(AnalysisID ID) const {
DenseMap<AnalysisID, IdentifyingPassPtr>::const_iterator
I = Impl->TargetPasses.find(ID);
if (I == Impl->TargetPasses.end())
return ID;
return I->second;
}
bool TargetPassConfig::isPassSubstitutedOrOverridden(AnalysisID ID) const {
IdentifyingPassPtr TargetID = getPassSubstitution(ID);
IdentifyingPassPtr FinalPtr = overridePass(ID, TargetID);
return !FinalPtr.isValid() || FinalPtr.isInstance() ||
FinalPtr.getID() != ID;
}
void TargetPassConfig::addPass(Pass *P) {
assert(!Initialized && "PassConfig is immutable");
AnalysisID PassID = P->getPassID();
if (StartBefore == PassID && StartBeforeCount++ == StartBeforeInstanceNum)
Started = true;
if (StopBefore == PassID && StopBeforeCount++ == StopBeforeInstanceNum)
Stopped = true;
if (Started && !Stopped) {
if (AddingMachinePasses) {
std::string Banner =
std::string("After ") + std::string(P->getPassName());
addMachinePrePasses();
PM->add(P);
addMachinePostPasses(Banner);
} else {
PM->add(P);
}
for (const auto &IP : Impl->InsertedPasses)
if (IP.TargetPassID == PassID)
addPass(IP.getInsertedPass());
} else {
delete P;
}
if (StopAfter == PassID && StopAfterCount++ == StopAfterInstanceNum)
Stopped = true;
if (StartAfter == PassID && StartAfterCount++ == StartAfterInstanceNum)
Started = true;
if (Stopped && !Started)
report_fatal_error("Cannot stop compilation after pass that is not run");
}
AnalysisID TargetPassConfig::addPass(AnalysisID PassID) {
IdentifyingPassPtr TargetID = getPassSubstitution(PassID);
IdentifyingPassPtr FinalPtr = overridePass(PassID, TargetID);
if (!FinalPtr.isValid())
return nullptr;
Pass *P;
if (FinalPtr.isInstance())
P = FinalPtr.getInstance();
else {
P = Pass::createPass(FinalPtr.getID());
if (!P)
llvm_unreachable("Pass ID not registered");
}
AnalysisID FinalID = P->getPassID();
addPass(P);
return FinalID;
}
void TargetPassConfig::printAndVerify(const std::string &Banner) {
addPrintPass(Banner);
addVerifyPass(Banner);
}
void TargetPassConfig::addPrintPass(const std::string &Banner) {
if (PrintAfterISel)
PM->add(createMachineFunctionPrinterPass(dbgs(), Banner));
}
void TargetPassConfig::addVerifyPass(const std::string &Banner) {
bool Verify = VerifyMachineCode == cl::BOU_TRUE;
#ifdef EXPENSIVE_CHECKS
if (VerifyMachineCode == cl::BOU_UNSET)
Verify = TM->isMachineVerifierClean();
#endif
if (Verify)
PM->add(createMachineVerifierPass(Banner));
}
void TargetPassConfig::addDebugifyPass() {
PM->add(createDebugifyMachineModulePass());
}
void TargetPassConfig::addStripDebugPass() {
PM->add(createStripDebugMachineModulePass(true));
}
void TargetPassConfig::addCheckDebugPass() {
PM->add(createCheckDebugMachineModulePass());
}
void TargetPassConfig::addMachinePrePasses(bool AllowDebugify) {
if (AllowDebugify && DebugifyIsSafe &&
(DebugifyAndStripAll == cl::BOU_TRUE ||
DebugifyCheckAndStripAll == cl::BOU_TRUE))
addDebugifyPass();
}
void TargetPassConfig::addMachinePostPasses(const std::string &Banner) {
if (DebugifyIsSafe) {
if (DebugifyCheckAndStripAll == cl::BOU_TRUE) {
addCheckDebugPass();
addStripDebugPass();
} else if (DebugifyAndStripAll == cl::BOU_TRUE)
addStripDebugPass();
}
addVerifyPass(Banner);
}
void TargetPassConfig::addIRPasses() {
if (!DisableVerify)
addPass(createVerifierPass());
if (getOptLevel() != CodeGenOpt::None) {
switch (UseCFLAA) {
case CFLAAType::Steensgaard:
addPass(createCFLSteensAAWrapperPass());
break;
case CFLAAType::Andersen:
addPass(createCFLAndersAAWrapperPass());
break;
case CFLAAType::Both:
addPass(createCFLAndersAAWrapperPass());
addPass(createCFLSteensAAWrapperPass());
break;
default:
break;
}
addPass(createTypeBasedAAWrapperPass());
addPass(createScopedNoAliasAAWrapperPass());
addPass(createBasicAAWrapperPass());
if (!DisableLSR) {
addPass(createCanonicalizeFreezeInLoopsPass());
addPass(createLoopStrengthReducePass());
if (PrintLSR)
addPass(createPrintFunctionPass(dbgs(),
"\n\n*** Code after LSR ***\n"));
}
if (!DisableMergeICmps)
addPass(createMergeICmpsLegacyPass());
addPass(createExpandMemCmpPass());
}
addPass(&GCLoweringID);
addPass(&ShadowStackGCLoweringID);
addPass(createLowerConstantIntrinsicsPass());
if (TM->getTargetTriple().isOSBinFormatMachO() &&
TM->Options.LowerGlobalDtorsViaCxaAtExit)
addPass(createLowerGlobalDtorsLegacyPass());
addPass(createUnreachableBlockEliminationPass());
if (getOptLevel() != CodeGenOpt::None && !DisableConstantHoisting)
addPass(createConstantHoistingPass());
if (getOptLevel() != CodeGenOpt::None)
addPass(createReplaceWithVeclibLegacyPass());
if (getOptLevel() != CodeGenOpt::None && !DisablePartialLibcallInlining)
addPass(createPartiallyInlineLibCallsPass());
addPass(createExpandVectorPredicationPass());
addPass(createScalarizeMaskedMemIntrinLegacyPass());
if (!DisableExpandReductions)
addPass(createExpandReductionsPass());
if (getOptLevel() != CodeGenOpt::None)
addPass(createTLSVariableHoistPass());
if (getOptLevel() != CodeGenOpt::None && !DisableSelectOptimize)
addPass(createSelectOptimizePass());
}
void TargetPassConfig::addPassesToHandleExceptions() {
const MCAsmInfo *MCAI = TM->getMCAsmInfo();
assert(MCAI && "No MCAsmInfo");
switch (MCAI->getExceptionHandlingType()) {
case ExceptionHandling::SjLj:
addPass(createSjLjEHPreparePass(TM));
LLVM_FALLTHROUGH;
case ExceptionHandling::DwarfCFI:
case ExceptionHandling::ARM:
case ExceptionHandling::AIX:
addPass(createDwarfEHPass(getOptLevel()));
break;
case ExceptionHandling::WinEH:
addPass(createWinEHPass());
addPass(createDwarfEHPass(getOptLevel()));
break;
case ExceptionHandling::Wasm:
addPass(createWinEHPass(false));
addPass(createWasmEHPass());
break;
case ExceptionHandling::None:
addPass(createLowerInvokePass());
addPass(createUnreachableBlockEliminationPass());
break;
}
}
void TargetPassConfig::addCodeGenPrepare() {
if (getOptLevel() != CodeGenOpt::None && !DisableCGP)
addPass(createCodeGenPreparePass());
}
void TargetPassConfig::addISelPrepare() {
addPreISel();
if (requiresCodeGenSCCOrder())
addPass(new DummyCGSCCPass);
addPass(createSafeStackPass());
addPass(createStackProtectorPass());
if (PrintISelInput)
addPass(createPrintFunctionPass(
dbgs(), "\n\n*** Final LLVM Code input to ISel ***\n"));
if (!DisableVerify)
addPass(createVerifierPass());
}
bool TargetPassConfig::addCoreISelPasses() {
TM->setO0WantsFastISel(EnableFastISelOption != cl::BOU_FALSE);
enum class SelectorType { SelectionDAG, FastISel, GlobalISel };
SelectorType Selector;
if (EnableFastISelOption == cl::BOU_TRUE)
Selector = SelectorType::FastISel;
else if (EnableGlobalISelOption == cl::BOU_TRUE ||
(TM->Options.EnableGlobalISel &&
EnableGlobalISelOption != cl::BOU_FALSE))
Selector = SelectorType::GlobalISel;
else if (TM->getOptLevel() == CodeGenOpt::None && TM->getO0WantsFastISel())
Selector = SelectorType::FastISel;
else
Selector = SelectorType::SelectionDAG;
if (Selector == SelectorType::FastISel) {
TM->setFastISel(true);
TM->setGlobalISel(false);
} else if (Selector == SelectorType::GlobalISel) {
TM->setFastISel(false);
TM->setGlobalISel(true);
}
SaveAndRestore<bool> SavedDebugifyIsSafe(DebugifyIsSafe);
if (Selector != SelectorType::GlobalISel || !isGlobalISelAbortEnabled())
DebugifyIsSafe = false;
if (Selector == SelectorType::GlobalISel) {
SaveAndRestore<bool> SavedAddingMachinePasses(AddingMachinePasses, true);
if (addIRTranslator())
return true;
addPreLegalizeMachineIR();
if (addLegalizeMachineIR())
return true;
addPreRegBankSelect();
if (addRegBankSelect())
return true;
addPreGlobalInstructionSelect();
if (addGlobalInstructionSelect())
return true;
addPass(createResetMachineFunctionPass(
reportDiagnosticWhenGlobalISelFallback(), isGlobalISelAbortEnabled()));
if (!isGlobalISelAbortEnabled() && addInstSelector())
return true;
} else if (addInstSelector())
return true;
addPass(&FinalizeISelID);
printAndVerify("After Instruction Selection");
return false;
}
bool TargetPassConfig::addISelPasses() {
if (TM->useEmulatedTLS())
addPass(createLowerEmuTLSPass());
addPass(createPreISelIntrinsicLoweringPass());
PM->add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
addIRPasses();
addCodeGenPrepare();
addPassesToHandleExceptions();
addISelPrepare();
return addCoreISelPasses();
}
static FunctionPass *useDefaultRegisterAllocator() { return nullptr; }
static cl::opt<RegisterRegAlloc::FunctionPassCtor, false,
RegisterPassParser<RegisterRegAlloc>>
RegAlloc("regalloc", cl::Hidden, cl::init(&useDefaultRegisterAllocator),
cl::desc("Register allocator to use"));
void TargetPassConfig::addMachinePasses() {
AddingMachinePasses = true;
if (getOptLevel() != CodeGenOpt::None) {
addMachineSSAOptimization();
} else {
addPass(&LocalStackSlotAllocationID);
}
if (TM->Options.EnableIPRA)
addPass(createRegUsageInfoPropPass());
addPreRegAlloc();
DebugifyIsSafe = false;
if (EnableFSDiscriminator) {
addPass(createMIRAddFSDiscriminatorsPass(
sampleprof::FSDiscriminatorPass::Pass1));
const std::string ProfileFile = getFSProfileFile(TM);
if (!ProfileFile.empty() && !DisableRAFSProfileLoader)
addPass(
createMIRProfileLoaderPass(ProfileFile, getFSRemappingFile(TM),
sampleprof::FSDiscriminatorPass::Pass1));
}
if (getOptimizeRegAlloc())
addOptimizedRegAlloc();
else
addFastRegAlloc();
addPostRegAlloc();
addPass(&RemoveRedundantDebugValuesID);
addPass(&FixupStatepointCallerSavedID);
if (getOptLevel() != CodeGenOpt::None) {
addPass(&PostRAMachineSinkingID);
addPass(&ShrinkWrapID);
}
if (!isPassSubstitutedOrOverridden(&PrologEpilogCodeInserterID))
addPass(createPrologEpilogInserterPass());
if (getOptLevel() != CodeGenOpt::None)
addMachineLateOptimization();
addPass(&ExpandPostRAPseudosID);
addPreSched2();
if (EnableImplicitNullChecks)
addPass(&ImplicitNullChecksID);
if (getOptLevel() != CodeGenOpt::None &&
!TM->targetSchedulesPostRAScheduling()) {
if (MISchedPostRA)
addPass(&PostMachineSchedulerID);
else
addPass(&PostRASchedulerID);
}
if (addGCPasses()) {
if (PrintGCInfo)
addPass(createGCInfoPrinter(dbgs()));
}
if (getOptLevel() != CodeGenOpt::None)
addBlockPlacement();
addPass(&FEntryInserterID);
addPass(&XRayInstrumentationID);
addPass(&PatchableFunctionID);
if (EnableFSDiscriminator && !FSNoFinalDiscrim)
addPass(createMIRAddFSDiscriminatorsPass(
sampleprof::FSDiscriminatorPass::PassLast));
addPreEmitPass();
if (TM->Options.EnableIPRA)
addPass(createRegUsageInfoCollector());
addPass(&FuncletLayoutID);
addPass(&StackMapLivenessID);
addPass(&LiveDebugValuesID);
if (TM->Options.EnableMachineOutliner && getOptLevel() != CodeGenOpt::None &&
EnableMachineOutliner != RunOutliner::NeverOutline) {
bool RunOnAllFunctions =
(EnableMachineOutliner == RunOutliner::AlwaysOutline);
bool AddOutliner =
RunOnAllFunctions || TM->Options.SupportsDefaultOutlining;
if (AddOutliner)
addPass(createMachineOutlinerPass(RunOnAllFunctions));
}
if (TM->getBBSectionsType() != llvm::BasicBlockSection::None) {
if (TM->getBBSectionsType() == llvm::BasicBlockSection::List) {
addPass(llvm::createBasicBlockSectionsProfileReaderPass(
TM->getBBSectionsFuncListBuf()));
}
addPass(llvm::createBasicBlockSectionsPass());
} else if (TM->Options.EnableMachineFunctionSplitter ||
EnableMachineFunctionSplitter) {
addPass(createMachineFunctionSplitterPass());
}
if (!DisableCFIFixup && TM->Options.EnableCFIFixup)
addPass(createCFIFixup());
addPreEmitPass2();
AddingMachinePasses = false;
}
void TargetPassConfig::addMachineSSAOptimization() {
addPass(&EarlyTailDuplicateID);
addPass(&OptimizePHIsID);
addPass(&StackColoringID);
addPass(&LocalStackSlotAllocationID);
addPass(&DeadMachineInstructionElimID);
addILPOpts();
addPass(&EarlyMachineLICMID);
addPass(&MachineCSEID);
addPass(&MachineSinkingID);
addPass(&PeepholeOptimizerID);
addPass(&DeadMachineInstructionElimID);
}
bool TargetPassConfig::getOptimizeRegAlloc() const {
switch (OptimizeRegAlloc) {
case cl::BOU_UNSET: return getOptLevel() != CodeGenOpt::None;
case cl::BOU_TRUE: return true;
case cl::BOU_FALSE: return false;
}
llvm_unreachable("Invalid optimize-regalloc state");
}
static llvm::once_flag InitializeDefaultRegisterAllocatorFlag;
static RegisterRegAlloc
defaultRegAlloc("default",
"pick register allocator based on -O option",
useDefaultRegisterAllocator);
static void initializeDefaultRegisterAllocatorOnce() {
if (!RegisterRegAlloc::getDefault())
RegisterRegAlloc::setDefault(RegAlloc);
}
FunctionPass *TargetPassConfig::createTargetRegisterAllocator(bool Optimized) {
if (Optimized)
return createGreedyRegisterAllocator();
else
return createFastRegisterAllocator();
}
FunctionPass *TargetPassConfig::createRegAllocPass(bool Optimized) {
llvm::call_once(InitializeDefaultRegisterAllocatorFlag,
initializeDefaultRegisterAllocatorOnce);
RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
if (Ctor != useDefaultRegisterAllocator)
return Ctor();
return createTargetRegisterAllocator(Optimized);
}
bool TargetPassConfig::isCustomizedRegAlloc() {
return RegAlloc !=
(RegisterRegAlloc::FunctionPassCtor)&useDefaultRegisterAllocator;
}
bool TargetPassConfig::addRegAssignAndRewriteFast() {
if (RegAlloc != (RegisterRegAlloc::FunctionPassCtor)&useDefaultRegisterAllocator &&
RegAlloc != (RegisterRegAlloc::FunctionPassCtor)&createFastRegisterAllocator &&
RegAlloc != (RegisterRegAlloc::FunctionPassCtor)&createSimpleRegisterAllocator)
report_fatal_error("Must use fast (default) register allocator for unoptimized regalloc.");
addPass(createRegAllocPass(false));
addPostFastRegAllocRewrite();
return true;
}
bool TargetPassConfig::addRegAssignAndRewriteOptimized() {
addPass(createRegAllocPass(true));
addPreRewrite();
addPass(&VirtRegRewriterID);
addPass(createRegAllocScoringPass());
return true;
}
bool TargetPassConfig::usingDefaultRegAlloc() const {
return RegAlloc.getNumOccurrences() == 0;
}
void TargetPassConfig::addFastRegAlloc() {
addPass(&PHIEliminationID);
addPass(&TwoAddressInstructionPassID);
addRegAssignAndRewriteFast();
}
void TargetPassConfig::addOptimizedRegAlloc() {
addPass(&DetectDeadLanesID);
addPass(&ProcessImplicitDefsID);
addPass(&UnreachableMachineBlockElimID);
addPass(&LiveVariablesID);
addPass(&MachineLoopInfoID);
addPass(&PHIEliminationID);
if (EarlyLiveIntervals)
addPass(&LiveIntervalsID);
addPass(&TwoAddressInstructionPassID);
addPass(&RegisterCoalescerID);
addPass(&RenameIndependentSubregsID);
addPass(&MachineSchedulerID);
if (addRegAssignAndRewriteOptimized()) {
addPass(&StackSlotColoringID);
addPostRewrite();
addPass(&MachineCopyPropagationID);
addPass(&MachineLICMID);
}
}
void TargetPassConfig::addMachineLateOptimization() {
addPass(&BranchFolderPassID);
if (!TM->requiresStructuredCFG())
addPass(&TailDuplicateID);
addPass(&MachineCopyPropagationID);
}
bool TargetPassConfig::addGCPasses() {
addPass(&GCMachineCodeAnalysisID);
return true;
}
void TargetPassConfig::addBlockPlacement() {
if (EnableFSDiscriminator) {
addPass(createMIRAddFSDiscriminatorsPass(
sampleprof::FSDiscriminatorPass::Pass2));
const std::string ProfileFile = getFSProfileFile(TM);
if (!ProfileFile.empty() && !DisableLayoutFSProfileLoader)
addPass(
createMIRProfileLoaderPass(ProfileFile, getFSRemappingFile(TM),
sampleprof::FSDiscriminatorPass::Pass2));
}
if (addPass(&MachineBlockPlacementID)) {
if (EnableBlockPlacementStats)
addPass(&MachineBlockPlacementStatsID);
}
}
bool TargetPassConfig::isGlobalISelAbortEnabled() const {
return TM->Options.GlobalISelAbort == GlobalISelAbortMode::Enable;
}
bool TargetPassConfig::reportDiagnosticWhenGlobalISelFallback() const {
return TM->Options.GlobalISelAbort == GlobalISelAbortMode::DisableWithDiag;
}
bool TargetPassConfig::isGISelCSEEnabled() const {
return true;
}
std::unique_ptr<CSEConfigBase> TargetPassConfig::getCSEConfig() const {
return std::make_unique<CSEConfigBase>();
}