#include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
#include "llvm/ADT/PostOrderIterator.h"
#include "llvm/ADT/ScopeExit.h"
#include "llvm/Analysis/LazyBlockFrequencyInfo.h"
#include "llvm/Analysis/ProfileSummaryInfo.h"
#include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
#include "llvm/CodeGen/GlobalISel/InstructionSelector.h"
#include "llvm/CodeGen/GlobalISel/LegalizerInfo.h"
#include "llvm/CodeGen/GlobalISel/Utils.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/TargetLowering.h"
#include "llvm/CodeGen/TargetPassConfig.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/Config/config.h"
#include "llvm/IR/Function.h"
#include "llvm/MC/TargetRegistry.h"
#include "llvm/Support/CodeGenCoverage.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Target/TargetMachine.h"
#define DEBUG_TYPE "instruction-select"
using namespace llvm;
#ifdef LLVM_GISEL_COV_PREFIX
static cl::opt<std::string>
CoveragePrefix("gisel-coverage-prefix", cl::init(LLVM_GISEL_COV_PREFIX),
cl::desc("Record GlobalISel rule coverage files of this "
"prefix if instrumentation was generated"));
#else
static const std::string CoveragePrefix;
#endif
char InstructionSelect::ID = 0;
INITIALIZE_PASS_BEGIN(InstructionSelect, DEBUG_TYPE,
"Select target instructions out of generic instructions",
false, false)
INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
INITIALIZE_PASS_DEPENDENCY(GISelKnownBitsAnalysis)
INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
INITIALIZE_PASS_DEPENDENCY(LazyBlockFrequencyInfoPass)
INITIALIZE_PASS_END(InstructionSelect, DEBUG_TYPE,
"Select target instructions out of generic instructions",
false, false)
InstructionSelect::InstructionSelect(CodeGenOpt::Level OL)
: MachineFunctionPass(ID), OptLevel(OL) {}
InstructionSelect::InstructionSelect()
: MachineFunctionPass(ID), OptLevel(CodeGenOpt::Default) {}
void InstructionSelect::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<TargetPassConfig>();
AU.addRequired<GISelKnownBitsAnalysis>();
AU.addPreserved<GISelKnownBitsAnalysis>();
if (OptLevel != CodeGenOpt::None) {
AU.addRequired<ProfileSummaryInfoWrapperPass>();
LazyBlockFrequencyInfoPass::getLazyBFIAnalysisUsage(AU);
}
getSelectionDAGFallbackAnalysisUsage(AU);
MachineFunctionPass::getAnalysisUsage(AU);
}
bool InstructionSelect::runOnMachineFunction(MachineFunction &MF) {
if (MF.getProperties().hasProperty(
MachineFunctionProperties::Property::FailedISel))
return false;
LLVM_DEBUG(dbgs() << "Selecting function: " << MF.getName() << '\n');
const TargetPassConfig &TPC = getAnalysis<TargetPassConfig>();
InstructionSelector *ISel = MF.getSubtarget().getInstructionSelector();
CodeGenOpt::Level OldOptLevel = OptLevel;
auto RestoreOptLevel = make_scope_exit([=]() { OptLevel = OldOptLevel; });
OptLevel = MF.getFunction().hasOptNone() ? CodeGenOpt::None
: MF.getTarget().getOptLevel();
GISelKnownBits *KB = &getAnalysis<GISelKnownBitsAnalysis>().get(MF);
if (OptLevel != CodeGenOpt::None) {
PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
if (PSI && PSI->hasProfileSummary())
BFI = &getAnalysis<LazyBlockFrequencyInfoPass>().getBFI();
}
CodeGenCoverage CoverageInfo;
assert(ISel && "Cannot work without InstructionSelector");
ISel->setupMF(MF, KB, CoverageInfo, PSI, BFI);
MachineOptimizationRemarkEmitter MORE(MF, nullptr);
MachineRegisterInfo &MRI = MF.getRegInfo();
#ifndef NDEBUG
if (!DisableGISelLegalityCheck)
if (const MachineInstr *MI = machineFunctionIsIllegal(MF)) {
reportGISelFailure(MF, TPC, MORE, "gisel-select",
"instruction is not legal", *MI);
return false;
}
const size_t NumBlocks = MF.size();
#endif
DenseSet<MachineBasicBlock *> SelectedBlocks;
for (MachineBasicBlock *MBB : post_order(&MF)) {
ISel->CurMBB = MBB;
SelectedBlocks.insert(MBB);
if (MBB->empty())
continue;
bool ReachedBegin = false;
for (auto MII = std::prev(MBB->end()), Begin = MBB->begin();
!ReachedBegin;) {
#ifndef NDEBUG
const auto AfterIt = std::next(MII);
#endif
MachineInstr &MI = *MII;
if (MII == Begin)
ReachedBegin = true;
else
--MII;
LLVM_DEBUG(dbgs() << "Selecting: \n " << MI);
if (isTriviallyDead(MI, MRI)) {
LLVM_DEBUG(dbgs() << "Is dead; erasing.\n");
MI.eraseFromParent();
continue;
}
if (isPreISelGenericOptimizationHint(MI.getOpcode())) {
Register DstReg = MI.getOperand(0).getReg();
Register SrcReg = MI.getOperand(1).getReg();
const TargetRegisterClass *DstRC = MRI.getRegClassOrNull(DstReg);
if (DstRC)
MRI.setRegClass(SrcReg, DstRC);
assert(canReplaceReg(DstReg, SrcReg, MRI) &&
"Must be able to replace dst with src!");
MI.eraseFromParent();
MRI.replaceRegWith(DstReg, SrcReg);
continue;
}
if (!ISel->select(MI)) {
reportGISelFailure(MF, TPC, MORE, "gisel-select", "cannot select", MI);
return false;
}
LLVM_DEBUG({
auto InsertedBegin = ReachedBegin ? MBB->begin() : std::next(MII);
dbgs() << "Into:\n";
for (auto &InsertedMI : make_range(InsertedBegin, AfterIt))
dbgs() << " " << InsertedMI;
dbgs() << '\n';
});
}
}
for (MachineBasicBlock &MBB : MF) {
if (MBB.empty())
continue;
if (!SelectedBlocks.contains(&MBB)) {
MBB.clear();
continue;
}
bool ReachedBegin = false;
for (auto MII = std::prev(MBB.end()), Begin = MBB.begin(); !ReachedBegin;) {
MachineInstr &MI = *MII;
if (MII == Begin)
ReachedBegin = true;
else
--MII;
if (MI.getOpcode() != TargetOpcode::COPY)
continue;
Register SrcReg = MI.getOperand(1).getReg();
Register DstReg = MI.getOperand(0).getReg();
if (Register::isVirtualRegister(SrcReg) &&
Register::isVirtualRegister(DstReg)) {
auto SrcRC = MRI.getRegClass(SrcReg);
auto DstRC = MRI.getRegClass(DstReg);
if (SrcRC == DstRC) {
MRI.replaceRegWith(DstReg, SrcReg);
MI.eraseFromParent();
}
}
}
}
#ifndef NDEBUG
const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
unsigned VReg = Register::index2VirtReg(I);
MachineInstr *MI = nullptr;
if (!MRI.def_empty(VReg))
MI = &*MRI.def_instr_begin(VReg);
else if (!MRI.use_empty(VReg)) {
MI = &*MRI.use_instr_begin(VReg);
if (MI->isDebugValue())
continue;
}
if (!MI)
continue;
const TargetRegisterClass *RC = MRI.getRegClassOrNull(VReg);
if (!RC) {
reportGISelFailure(MF, TPC, MORE, "gisel-select",
"VReg has no regclass after selection", *MI);
return false;
}
const LLT Ty = MRI.getType(VReg);
if (Ty.isValid() && Ty.getSizeInBits() > TRI.getRegSizeInBits(*RC)) {
reportGISelFailure(
MF, TPC, MORE, "gisel-select",
"VReg's low-level type and register class have different sizes", *MI);
return false;
}
}
if (MF.size() != NumBlocks) {
MachineOptimizationRemarkMissed R("gisel-select", "GISelFailure",
MF.getFunction().getSubprogram(),
nullptr);
R << "inserting blocks is not supported yet";
reportGISelFailure(MF, TPC, MORE, R);
return false;
}
#endif
MachineFrameInfo &MFI = MF.getFrameInfo();
for (const auto &MBB : MF) {
if (MFI.hasCalls() && MF.hasInlineAsm())
break;
for (const auto &MI : MBB) {
if ((MI.isCall() && !MI.isReturn()) || MI.isStackAligningInlineAsm())
MFI.setHasCalls(true);
if (MI.isInlineAsm())
MF.setHasInlineAsm(true);
}
}
auto &TLI = *MF.getSubtarget().getTargetLowering();
TLI.finalizeLowering(MF);
LLVM_DEBUG({
dbgs() << "Rules covered by selecting function: " << MF.getName() << ":";
for (auto RuleID : CoverageInfo.covered())
dbgs() << " id" << RuleID;
dbgs() << "\n\n";
});
CoverageInfo.emit(CoveragePrefix,
TLI.getTargetMachine().getTarget().getBackendName());
MRI.clearVirtRegTypes();
return true;
}