79 #define DEBUG_TYPE "irtranslator" 85 cl::desc(
"Should enable CSE in irtranslator"),
104 if (!R.getLocation().isValid() || TPC.isGlobalISelAbortEnabled())
105 R << (
" (in function: " + MF.getName() +
")").str();
107 if (TPC.isGlobalISelAbortEnabled())
123 DILocationVerifier() =
default;
124 ~DILocationVerifier() =
default;
126 const Instruction *getCurrentInst()
const {
return CurrInst; }
127 void setCurrentInst(
const Instruction *Inst) { CurrInst = Inst; }
134 assert(getCurrentInst() &&
"Inserted instruction without a current MI");
139 <<
" was copied to " << MI);
146 "Line info was not transferred to all instructions");
150 #endif // ifndef NDEBUG 162 IRTranslator::allocateVRegs(
const Value &Val) {
163 assert(!VMap.contains(Val) &&
"Value already allocated in VMap");
164 auto *Regs = VMap.getVRegs(Val);
165 auto *
Offsets = VMap.getOffsets(Val);
169 for (
unsigned i = 0; i < SplitTys.
size(); ++i)
175 auto VRegsIt = VMap.findVRegs(Val);
176 if (VRegsIt != VMap.vregs_end())
177 return *VRegsIt->second;
180 return *VMap.getVRegs(Val);
183 auto *VRegs = VMap.getVRegs(Val);
184 auto *
Offsets = VMap.getOffsets(Val);
187 "Don't know how to create an empty vreg");
193 if (!isa<Constant>(Val)) {
194 for (
auto Ty : SplitTys)
195 VRegs->push_back(
MRI->createGenericVirtualRegister(Ty));
201 auto &
C = cast<Constant>(Val);
203 while (
auto Elt =
C.getAggregateElement(Idx++)) {
204 auto EltRegs = getOrCreateVRegs(*Elt);
205 llvm::copy(EltRegs, std::back_inserter(*VRegs));
208 assert(SplitTys.size() == 1 &&
"unexpectedly split LLT");
209 VRegs->push_back(
MRI->createGenericVirtualRegister(SplitTys[0]));
210 bool Success = translate(cast<Constant>(Val), VRegs->front());
213 MF->getFunction().getSubprogram(),
214 &MF->getFunction().getEntryBlock());
215 R <<
"unable to translate constant: " <<
ore::NV(
"Type", Val.
getType());
224 int IRTranslator::getOrCreateFrameIndex(
const AllocaInst &AI) {
225 if (FrameIndices.find(&AI) != FrameIndices.end())
226 return FrameIndices[&AI];
230 ElementSize * cast<ConstantInt>(AI.
getArraySize())->getZExtValue();
233 Size = std::max<uint64_t>(
Size, 1u);
239 int &FI = FrameIndices[&AI];
240 FI = MF->getFrameInfo().CreateStackObject(Size, Alignment,
false, &AI);
244 unsigned IRTranslator::getMemOpAlignment(
const Instruction &
I) {
245 unsigned Alignment = 0;
246 Type *ValTy =
nullptr;
247 if (
const StoreInst *
SI = dyn_cast<StoreInst>(&I)) {
248 Alignment =
SI->getAlignment();
249 ValTy =
SI->getValueOperand()->getType();
250 }
else if (
const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
251 Alignment = LI->getAlignment();
252 ValTy = LI->getType();
259 ValTy = AI->getCompareOperand()->
getType();
260 }
else if (
const AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(&I)) {
269 R <<
"unable to translate memop: " <<
ore::NV(
"Opcode", &I);
274 return Alignment ? Alignment : DL->getABITypeAlignment(ValTy);
279 assert(MBB &&
"BasicBlock was not encountered before");
284 assert(NewPred &&
"new predecessor must be a real MachineBasicBlock");
285 MachinePreds[Edge].push_back(NewPred);
288 bool IRTranslator::translateBinaryOp(
unsigned Opcode,
const User &U,
298 if (isa<Instruction>(U)) {
303 MIRBuilder.
buildInstr(Opcode, {Res}, {Op0, Op1}, Flags);
314 if (isa<Instruction>(U)) {
319 MIRBuilder.
buildInstr(TargetOpcode::G_FNEG, {Res}, {Op1}, Flags);
322 return translateBinaryOp(TargetOpcode::G_FSUB, U, MIRBuilder);
329 if (isa<Instruction>(U)) {
333 MIRBuilder.
buildInstr(TargetOpcode::G_FNEG, {Res}, {Op0}, Flags);
337 bool IRTranslator::translateCompare(
const User &U,
347 MIRBuilder.
buildICmp(Pred, Res, Op0, Op1);
355 assert(CI &&
"Instruction should be CmpInst");
356 MIRBuilder.
buildInstr(TargetOpcode::G_FCMP, {Res}, {Pred, Op0, Op1},
366 if (Ret && DL->getTypeStoreSize(Ret->getType()) == 0)
371 VRegs = getOrCreateVRegs(*Ret);
374 if (CLI->supportSwiftError() && SwiftError.getFunctionArg()) {
375 SwiftErrorVReg = SwiftError.getOrCreateVRegUseAt(
376 &RI, &MIRBuilder.
getMBB(), SwiftError.getFunctionArg());
382 return CLI->lowerReturn(MIRBuilder, Ret, VRegs, SwiftErrorVReg);
386 const BranchInst &BrInst = cast<BranchInst>(U);
418 Prob = getEdgeProbability(Src, Dst);
430 auto SuccSize = std::max<uint32_t>(
succ_size(SrcBB), 1);
433 return FuncInfo.BPI->getEdgeProbability(SrcBB, DstBB);
443 for (
auto &I : SI.
cases()) {
445 assert(Succ &&
"Could not find successor mbb in mapping");
448 BPI ? BPI->getEdgeProbability(SI.
getParent(), I.getSuccessorIndex())
450 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
463 if (Clusters.empty()) {
470 SL->findJumpTables(Clusters, &SI, DefaultMBB,
nullptr,
nullptr);
473 dbgs() <<
"Case clusters: ";
474 for (
const CaseCluster &
C : Clusters) {
481 if (
C.Low !=
C.High) {
490 assert(!Clusters.empty());
494 auto DefaultProb = getEdgeProbability(SwitchMBB, DefaultMBB);
495 WorkList.push_back({SwitchMBB, First, Last,
nullptr,
nullptr, DefaultProb});
499 while (!WorkList.empty()) {
500 SwitchWorkListItem
W = WorkList.back();
502 if (!lowerSwitchWorkItem(W, SI.
getCondition(), SwitchMBB, DefaultMBB, MIB))
511 assert(JT.
Reg != -1U &&
"Should lower JT Header first!");
533 Register SwitchOpReg = getOrCreateVReg(SValue);
535 auto Sub = MIB.
buildSub({SwitchTy}, SwitchOpReg, FirstCst);
540 const LLT PtrScalarTy =
LLT::scalar(DL->getTypeSizeInBits(PtrIRTy));
543 JT.
Reg = Sub.getReg(0);
554 auto Cst = getOrCreateVReg(
595 "Can only handle SLE ranges");
597 const APInt& Low = cast<ConstantInt>(CB.
CmpLHS)->getValue();
601 if (cast<ConstantInt>(CB.
CmpLHS)->isMinValue(
true)) {
606 const LLT &CmpTy =
MRI->getType(CmpOpReg);
607 auto Sub = MIB.
buildSub({CmpTy}, CmpOpReg, CondLHS);
634 Cond = MIB.
buildInstr(TargetOpcode::G_XOR, {i1Ty}, {Cond, True},
None)
652 bool FallthroughUnreachable) {
656 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
662 CurMF->
insert(BBI, JumpMBB);
672 auto JumpProb = I->Prob;
673 auto FallthroughProb = UnhandledProbs;
681 if (*
SI == DefaultMBB) {
682 JumpProb += DefaultProb / 2;
683 FallthroughProb -= DefaultProb / 2;
688 addMachineCFGPred({SwitchMBB->
getBasicBlock(), (*SI)->getBasicBlock()},
694 if (FallthroughUnreachable)
695 JTH->OmitRangeCheck =
true;
697 if (!JTH->OmitRangeCheck)
698 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
699 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
704 JTH->HeaderBB = CurMBB;
708 if (CurMBB == SwitchMBB) {
709 if (!emitJumpTableHeader(*JT, *JTH, CurMBB))
718 bool FallthroughUnreachable,
724 const Value *RHS, *LHS, *MHS;
726 if (I->Low == I->High) {
742 CaseBlock CB(Pred, FallthroughUnreachable, LHS, RHS, MHS, I->MBB, Fallthrough,
743 CurMBB, MIB.
getDebugLoc(), I->Prob, UnhandledProbs);
745 emitSwitchCase(CB, SwitchMBB, MIB);
758 if (++BBI != FuncInfo.MF->end())
767 [](
const CaseCluster &a,
const CaseCluster &b) {
768 return a.Prob != b.Prob
770 : a.Low->getValue().slt(b.Low->getValue());
779 if (I->Kind ==
CC_Range && I->MBB == NextMBB) {
790 UnhandledProbs += I->Prob;
794 bool FallthroughUnreachable =
false;
798 Fallthrough = DefaultMBB;
799 FallthroughUnreachable = isa<UnreachableInst>(
803 CurMF->
insert(BBI, Fallthrough);
805 UnhandledProbs -= I->Prob;
809 LLVM_DEBUG(
dbgs() <<
"Switch to bit test optimization unimplemented");
813 if (!lowerJumpTableWorkItem(W, SwitchMBB, CurMBB, DefaultMBB, MIB, BBI,
814 UnhandledProbs, I, Fallthrough,
815 FallthroughUnreachable)) {
822 if (!lowerSwitchRangeWorkItem(I, Cond, Fallthrough,
823 FallthroughUnreachable, UnhandledProbs,
824 CurMBB, MIB, SwitchMBB)) {
831 CurMBB = Fallthrough;
837 bool IRTranslator::translateIndirectBr(
const User &U,
853 if (
auto Arg = dyn_cast<Argument>(V))
854 return Arg->hasSwiftErrorAttr();
855 if (
auto AI = dyn_cast<AllocaInst>(V))
861 const LoadInst &LI = cast<LoadInst>(U);
867 if (DL->getTypeStoreSize(LI.
getType()) == 0)
878 assert(Regs.
size() == 1 &&
"swifterror should be single pointer");
879 Register VReg = SwiftError.getOrCreateVRegUseAt(&LI, &MIRBuilder.
getMBB(),
887 for (
unsigned i = 0; i < Regs.
size(); ++i) {
892 unsigned BaseAlign = getMemOpAlignment(LI);
895 auto MMO = MF->getMachineMemOperand(
896 Ptr, Flags, (
MRI->getType(Regs[i]).getSizeInBits() + 7) / 8,
897 MinAlign(BaseAlign, Offsets[i] / 8), AAMetadata, Ranges,
899 MIRBuilder.
buildLoad(Regs[i], Addr, *MMO);
922 assert(Vals.
size() == 1 &&
"swifterror should be single pointer");
924 Register VReg = SwiftError.getOrCreateVRegDefAt(&SI, &MIRBuilder.
getMBB(),
930 for (
unsigned i = 0; i < Vals.
size(); ++i) {
935 unsigned BaseAlign = getMemOpAlignment(SI);
938 auto MMO = MF->getMachineMemOperand(
939 Ptr, Flags, (
MRI->getType(Vals[i]).getSizeInBits() + 7) / 8,
940 MinAlign(BaseAlign, Offsets[i] / 8), AAMetadata,
nullptr,
957 for (
auto Idx : EVI->indices())
959 }
else if (
const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) {
960 for (
auto Idx : IVI->indices())
967 return 8 *
static_cast<uint64_t
>(
971 bool IRTranslator::translateExtractValue(
const User &U,
978 auto &DstRegs = allocateVRegs(U);
980 for (
unsigned i = 0; i < DstRegs.size(); ++i)
981 DstRegs[i] = SrcRegs[Idx++];
986 bool IRTranslator::translateInsertValue(
const User &U,
990 auto &DstRegs = allocateVRegs(U);
994 auto InsertedIt = InsertedRegs.
begin();
996 for (
unsigned i = 0; i < DstRegs.size(); ++i) {
997 if (DstOffsets[i] >= Offset && InsertedIt != InsertedRegs.
end())
998 DstRegs[i] = *InsertedIt++;
1000 DstRegs[i] = SrcRegs[i];
1006 bool IRTranslator::translateSelect(
const User &U,
1015 if (
const CmpInst *Cmp = dyn_cast<CmpInst>(SI.getCondition()))
1018 for (
unsigned i = 0; i < ResRegs.size(); ++i) {
1019 MIRBuilder.
buildInstr(TargetOpcode::G_SELECT, {ResRegs[i]},
1020 {Tst, Op0Regs[i], Op1Regs[i]}, Flags);
1026 bool IRTranslator::translateBitCast(
const User &U,
1032 auto &Regs = *VMap.getVRegs(U);
1038 Regs.push_back(SrcReg);
1039 VMap.getOffsets(U)->push_back(0);
1043 return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder);
1046 bool IRTranslator::translateCast(
unsigned Opcode,
const User &U,
1054 bool IRTranslator::translateGetElementPtr(
const User &U,
1061 Register BaseReg = getOrCreateVReg(Op0);
1064 Type *OffsetIRTy = DL->getIntPtrType(PtrIRTy);
1070 const Value *Idx = GTI.getOperand();
1071 if (
StructType *StTy = GTI.getStructTypeOrNull()) {
1072 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
1073 Offset += DL->getStructLayout(StTy)->getElementOffset(Field);
1076 uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
1080 if (
const auto *CI = dyn_cast<ConstantInt>(Idx)) {
1081 Offset += ElementSize * CI->getSExtValue();
1088 BaseReg = MIRBuilder.
buildPtrAdd(PtrTy, BaseReg, OffsetMIB.getReg(0))
1093 Register IdxReg = getOrCreateVReg(*Idx);
1094 if (
MRI->getType(IdxReg) != OffsetTy)
1100 if (ElementSize != 1) {
1106 GepOffsetReg = IdxReg;
1115 MIRBuilder.
buildPtrAdd(getOrCreateVReg(U), BaseReg, OffsetMIB.getReg(0));
1119 MIRBuilder.
buildCopy(getOrCreateVReg(U), BaseReg);
1123 bool IRTranslator::translateMemFunc(
const CallInst &CI,
1133 for (
auto AI = CI.
arg_begin(), AE = CI.
arg_end(); std::next(AI) != AE; ++AI)
1134 ICall.
addUse(getOrCreateVReg(**AI));
1136 unsigned DstAlign = 0, SrcAlign = 0;
1141 if (
auto *MCI = dyn_cast<MemCpyInst>(&CI)) {
1142 DstAlign = std::max<unsigned>(MCI->getDestAlignment(), 1);
1143 SrcAlign = std::max<unsigned>(MCI->getSourceAlignment(), 1);
1144 }
else if (
auto *MMI = dyn_cast<MemMoveInst>(&CI)) {
1145 DstAlign = std::max<unsigned>(MMI->getDestAlignment(), 1);
1146 SrcAlign = std::max<unsigned>(MMI->getSourceAlignment(), 1);
1148 auto *MSI = cast<MemSetInst>(&CI);
1149 DstAlign = std::max<unsigned>(MSI->getDestAlignment(), 1);
1159 ICall.addMemOperand(MF->getMachineMemOperand(
1162 if (ID != Intrinsic::memset)
1163 ICall.addMemOperand(MF->getMachineMemOperand(
1170 void IRTranslator::getStackGuard(
Register DstReg,
1174 auto MIB = MIRBuilder.
buildInstr(TargetOpcode::LOAD_STACK_GUARD);
1177 auto &TLI = *MF->getSubtarget().getTargetLowering();
1178 Value *Global = TLI.getSDagStackGuard(*MF->getFunction().getParent());
1186 MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8,
1187 DL->getPointerABIAlignment(0).value());
1188 MIB.setMemRefs({MemRef});
1191 bool IRTranslator::translateOverflowIntrinsic(
const CallInst &CI,
unsigned Op,
1203 unsigned IRTranslator::getSimpleIntrinsicOpcode(
Intrinsic::ID ID) {
1207 case Intrinsic::bswap:
1208 return TargetOpcode::G_BSWAP;
1209 case Intrinsic::bitreverse:
1210 return TargetOpcode::G_BITREVERSE;
1211 case Intrinsic::ceil:
1212 return TargetOpcode::G_FCEIL;
1213 case Intrinsic::cos:
1214 return TargetOpcode::G_FCOS;
1215 case Intrinsic::ctpop:
1216 return TargetOpcode::G_CTPOP;
1217 case Intrinsic::exp:
1218 return TargetOpcode::G_FEXP;
1219 case Intrinsic::exp2:
1220 return TargetOpcode::G_FEXP2;
1221 case Intrinsic::fabs:
1222 return TargetOpcode::G_FABS;
1223 case Intrinsic::copysign:
1224 return TargetOpcode::G_FCOPYSIGN;
1226 return TargetOpcode::G_FMINNUM;
1228 return TargetOpcode::G_FMAXNUM;
1230 return TargetOpcode::G_FMINIMUM;
1232 return TargetOpcode::G_FMAXIMUM;
1233 case Intrinsic::canonicalize:
1234 return TargetOpcode::G_FCANONICALIZE;
1235 case Intrinsic::floor:
1236 return TargetOpcode::G_FFLOOR;
1237 case Intrinsic::fma:
1238 return TargetOpcode::G_FMA;
1239 case Intrinsic::log:
1240 return TargetOpcode::G_FLOG;
1242 return TargetOpcode::G_FLOG2;
1243 case Intrinsic::log10:
1244 return TargetOpcode::G_FLOG10;
1245 case Intrinsic::nearbyint:
1246 return TargetOpcode::G_FNEARBYINT;
1247 case Intrinsic::pow:
1248 return TargetOpcode::G_FPOW;
1249 case Intrinsic::rint:
1250 return TargetOpcode::G_FRINT;
1252 return TargetOpcode::G_INTRINSIC_ROUND;
1253 case Intrinsic::sin:
1254 return TargetOpcode::G_FSIN;
1255 case Intrinsic::sqrt:
1256 return TargetOpcode::G_FSQRT;
1257 case Intrinsic::trunc:
1258 return TargetOpcode::G_INTRINSIC_TRUNC;
1259 case Intrinsic::readcyclecounter:
1260 return TargetOpcode::G_READCYCLECOUNTER;
1265 bool IRTranslator::translateSimpleIntrinsic(
const CallInst &CI,
1269 unsigned Op = getSimpleIntrinsicOpcode(ID);
1280 MIRBuilder.
buildInstr(Op, {getOrCreateVReg(CI)}, VRegs,
1290 if (translateSimpleIntrinsic(CI, ID, MIRBuilder))
1296 case Intrinsic::lifetime_start:
1297 case Intrinsic::lifetime_end: {
1312 for (
const Value *V : Allocas) {
1324 case Intrinsic::dbg_declare: {
1329 if (!Address || isa<UndefValue>(Address)) {
1336 "Expected inlined-at fields to agree");
1351 case Intrinsic::dbg_label: {
1357 "Expected inlined-at fields to agree");
1362 case Intrinsic::vaend:
1366 case Intrinsic::vastart: {
1367 auto &TLI = *MF->getSubtarget().getTargetLowering();
1369 unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8;
1372 MIRBuilder.
buildInstr(TargetOpcode::G_VASTART)
1373 .
addUse(getOrCreateVReg(*Ptr))
1378 case Intrinsic::dbg_value: {
1384 "Expected inlined-at fields to agree");
1389 }
else if (
const auto *CI = dyn_cast<Constant>(V)) {
1402 case Intrinsic::uadd_with_overflow:
1403 return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDO, MIRBuilder);
1404 case Intrinsic::sadd_with_overflow:
1405 return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder);
1406 case Intrinsic::usub_with_overflow:
1407 return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBO, MIRBuilder);
1408 case Intrinsic::ssub_with_overflow:
1409 return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder);
1410 case Intrinsic::umul_with_overflow:
1411 return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder);
1412 case Intrinsic::smul_with_overflow:
1413 return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder);
1414 case Intrinsic::fmuladd: {
1416 const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
1417 Register Dst = getOrCreateVReg(CI);
1426 MIRBuilder.
buildInstr(TargetOpcode::G_FMA, {Dst}, {Op0, Op1, Op2},
1430 auto FMul = MIRBuilder.
buildInstr(TargetOpcode::G_FMUL, {Ty}, {Op0, Op1},
1432 MIRBuilder.
buildInstr(TargetOpcode::G_FADD, {Dst}, {FMul, Op2},
1437 case Intrinsic::memcpy:
1438 case Intrinsic::memmove:
1439 case Intrinsic::memset:
1440 return translateMemFunc(CI, MIRBuilder, ID);
1441 case Intrinsic::eh_typeid_for: {
1444 unsigned TypeID = MF->getTypeIDFor(GV);
1448 case Intrinsic::objectsize:
1451 case Intrinsic::is_constant:
1454 case Intrinsic::stackguard:
1455 getStackGuard(getOrCreateVReg(CI), MIRBuilder);
1457 case Intrinsic::stackprotector: {
1459 Register GuardVal =
MRI->createGenericVirtualRegister(PtrTy);
1460 getStackGuard(GuardVal, MIRBuilder);
1463 int FI = getOrCreateFrameIndex(*Slot);
1464 MF->getFrameInfo().setStackProtectorIndex(FI);
1467 GuardVal, getOrCreateVReg(*Slot),
1474 case Intrinsic::stacksave: {
1477 Register StackPtr = MF->getSubtarget()
1478 .getTargetLowering()
1479 ->getStackPointerRegisterToSaveRestore();
1488 case Intrinsic::stackrestore: {
1491 Register StackPtr = MF->getSubtarget()
1492 .getTargetLowering()
1493 ->getStackPointerRegisterToSaveRestore();
1502 case Intrinsic::cttz:
1503 case Intrinsic::ctlz: {
1505 bool isTrailing = ID == Intrinsic::cttz;
1506 unsigned Opcode = isTrailing
1507 ? Cst->
isZero() ? TargetOpcode::G_CTTZ
1508 : TargetOpcode::G_CTTZ_ZERO_UNDEF
1509 : Cst->
isZero() ? TargetOpcode::G_CTLZ
1510 : TargetOpcode::G_CTLZ_ZERO_UNDEF;
1512 .
addDef(getOrCreateVReg(CI))
1516 case Intrinsic::invariant_start: {
1522 case Intrinsic::invariant_end:
1524 case Intrinsic::assume:
1525 case Intrinsic::var_annotation:
1526 case Intrinsic::sideeffect:
1529 case Intrinsic::read_register: {
1531 MIRBuilder.
buildInstr(TargetOpcode::G_READ_REGISTER)
1532 .
addDef(getOrCreateVReg(CI))
1533 .
addMetadata(cast<MDNode>(cast<MetadataAsValue>(Arg)->getMetadata()));
1540 bool IRTranslator::translateInlineAsm(
const CallInst &CI,
1546 unsigned ExtraInfo = 0;
1569 assert(SwiftInVReg == 0 &&
"Expected only one swift error argument");
1571 SwiftInVReg =
MRI->createGenericVirtualRegister(Ty);
1572 MIRBuilder.
buildCopy(SwiftInVReg, SwiftError.getOrCreateVRegUseAt(
1576 SwiftError.getOrCreateVRegDefAt(&I, &MIRBuilder.
getMBB(),
Arg);
1586 CLI->lowerCall(MIRBuilder, CS, Res, Args, SwiftErrorVReg,
1591 assert(!HasTailCall &&
"Can't tail call return twice from block?");
1600 const CallInst &CI = cast<CallInst>(U);
1601 auto TII = MF->getTarget().getIntrinsicInfo();
1606 (MF->getTarget().getTargetTriple().isOSWindows() &&
1615 return translateInlineAsm(CI, MIRBuilder);
1625 return translateCallSite(&CI, MIRBuilder);
1629 if (translateKnownIntrinsic(CI, ID, MIRBuilder))
1634 ResultRegs = getOrCreateVRegs(CI);
1640 if (isa<FPMathOperator>(CI))
1645 if (isa<MetadataAsValue>(
Arg.value()))
1654 assert(CI->getBitWidth() <= 64 &&
1655 "large intrinsic immediates not handled");
1656 MIB.
addImm(CI->getSExtValue());
1662 if (VRegs.
size() > 1)
1669 const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
1670 TargetLowering::IntrinsicInfo
Info;
1676 DL->getABITypeAlignment(Info.memVT.getTypeForEVT(F->
getContext())));
1678 uint64_t
Size = Info.memVT.getStoreSize();
1686 bool IRTranslator::translateInvoke(
const User &U,
1696 if (isa<InlineAsm>(Callee))
1712 if (!isa<LandingPadInst>(EHPadBB->
front()))
1717 MCSymbol *BeginSymbol = Context.createTempSymbol();
1720 if (!translateCallSite(&I, MIRBuilder))
1723 MCSymbol *EndSymbol = Context.createTempSymbol();
1728 &ReturnMBB = getMBB(*ReturnBB);
1729 MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
1732 MIRBuilder.
buildBr(ReturnMBB);
1737 bool IRTranslator::translateCallBr(
const User &U,
1743 bool IRTranslator::translateLandingPad(
const User &U,
1753 auto &TLI = *MF->getSubtarget().getTargetLowering();
1754 const Constant *PersonalityFn = MF->getFunction().getPersonalityFn();
1755 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
1756 TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
1769 .
addSym(MF->addLandingPad(&MBB));
1776 for (
Type *Ty : cast<StructType>(LP.
getType())->elements())
1778 assert(Tys.
size() == 2 &&
"Only two-valued landingpads are supported");
1781 Register ExceptionReg = TLI.getExceptionPointerRegister(PersonalityFn);
1785 MBB.addLiveIn(ExceptionReg);
1787 MIRBuilder.
buildCopy(ResRegs[0], ExceptionReg);
1789 Register SelectorReg = TLI.getExceptionSelectorRegister(PersonalityFn);
1793 MBB.addLiveIn(SelectorReg);
1794 Register PtrVReg =
MRI->createGenericVirtualRegister(Tys[0]);
1795 MIRBuilder.
buildCopy(PtrVReg, SelectorReg);
1796 MIRBuilder.
buildCast(ResRegs[1], PtrVReg);
1801 bool IRTranslator::translateAlloca(
const User &U,
1803 auto &AI = cast<AllocaInst>(U);
1809 Register Res = getOrCreateVReg(AI);
1810 int FI = getOrCreateFrameIndex(AI);
1816 if (MF->getTarget().getTargetTriple().isOSWindows())
1826 Type *IntPtrIRTy = DL->getIntPtrType(AI.
getType());
1828 if (
MRI->getType(NumElts) != IntPtrTy) {
1829 Register ExtElts =
MRI->createGenericVirtualRegister(IntPtrTy);
1834 Register AllocSize =
MRI->createGenericVirtualRegister(IntPtrTy);
1837 MIRBuilder.
buildMul(AllocSize, NumElts, TySize);
1839 unsigned StackAlign =
1840 MF->getSubtarget().getFrameLowering()->getStackAlignment();
1841 if (Align <= StackAlign)
1847 auto SAMinusOne = MIRBuilder.
buildConstant(IntPtrTy, StackAlign - 1);
1848 auto AllocAdd = MIRBuilder.
buildAdd(IntPtrTy, AllocSize, SAMinusOne,
1851 MIRBuilder.
buildConstant(IntPtrTy, ~(uint64_t)(StackAlign - 1));
1852 auto AlignedAlloc = MIRBuilder.
buildAnd(IntPtrTy, AllocAdd, AlignCst);
1856 MF->getFrameInfo().CreateVariableSizedObject(Align ? Align : 1, &AI);
1857 assert(MF->getFrameInfo().hasVarSizedObjects());
1867 .
addDef(getOrCreateVReg(U))
1873 bool IRTranslator::translateInsertElement(
const User &U,
1879 auto &Regs = *VMap.getVRegs(U);
1881 Regs.push_back(Elt);
1882 VMap.getOffsets(U)->push_back(0);
1897 bool IRTranslator::translateExtractElement(
const User &U,
1903 auto &Regs = *VMap.getVRegs(U);
1905 Regs.push_back(Elt);
1906 VMap.getOffsets(U)->push_back(0);
1914 const auto &TLI = *MF->getSubtarget().getTargetLowering();
1915 unsigned PreferredVecIdxWidth = TLI.getVectorIdxTy(*DL).getSizeInBits();
1917 if (
auto *CI = dyn_cast<ConstantInt>(U.
getOperand(1))) {
1918 if (CI->getBitWidth() != PreferredVecIdxWidth) {
1919 APInt NewIdx = CI->getValue().sextOrTrunc(PreferredVecIdxWidth);
1921 Idx = getOrCreateVReg(*NewIdxCI);
1926 if (
MRI->getType(Idx).getSizeInBits() != PreferredVecIdxWidth) {
1934 bool IRTranslator::translateShuffleVector(
const User &U,
1939 MIRBuilder.
buildInstr(TargetOpcode::G_SHUFFLE_VECTOR)
1940 .
addDef(getOrCreateVReg(U))
1948 const PHINode &PI = cast<PHINode>(U);
1951 for (
auto Reg : getOrCreateVRegs(PI)) {
1952 auto MIB = MIRBuilder.
buildInstr(TargetOpcode::G_PHI, {
Reg}, {});
1953 Insts.push_back(MIB.getInstr());
1956 PendingPHIs.emplace_back(&PI, std::move(Insts));
1960 bool IRTranslator::translateAtomicCmpXchg(
const User &U,
1972 Type *
ValType = ResType->Type::getStructElementType(0);
1974 auto Res = getOrCreateVRegs(I);
1985 OldValRes, SuccessRes, Addr, Cmp, NewVal,
1987 Flags, DL->getTypeStoreSize(ValType),
1988 getMemOpAlignment(I), AAMetadata,
nullptr,
1994 bool IRTranslator::translateAtomicRMW(
const User &U,
2008 unsigned Opcode = 0;
2013 Opcode = TargetOpcode::G_ATOMICRMW_XCHG;
2016 Opcode = TargetOpcode::G_ATOMICRMW_ADD;
2019 Opcode = TargetOpcode::G_ATOMICRMW_SUB;
2022 Opcode = TargetOpcode::G_ATOMICRMW_AND;
2025 Opcode = TargetOpcode::G_ATOMICRMW_NAND;
2028 Opcode = TargetOpcode::G_ATOMICRMW_OR;
2031 Opcode = TargetOpcode::G_ATOMICRMW_XOR;
2034 Opcode = TargetOpcode::G_ATOMICRMW_MAX;
2037 Opcode = TargetOpcode::G_ATOMICRMW_MIN;
2040 Opcode = TargetOpcode::G_ATOMICRMW_UMAX;
2043 Opcode = TargetOpcode::G_ATOMICRMW_UMIN;
2046 Opcode = TargetOpcode::G_ATOMICRMW_FADD;
2049 Opcode = TargetOpcode::G_ATOMICRMW_FSUB;
2057 Opcode, Res, Addr, Val,
2059 Flags, DL->getTypeStoreSize(ResType),
2060 getMemOpAlignment(I), AAMetadata,
2065 bool IRTranslator::translateFence(
const User &U,
2067 const FenceInst &Fence = cast<FenceInst>(U);
2073 void IRTranslator::finishPendingPhis() {
2078 #endif // ifndef NDEBUG 2079 for (
auto &Phi : PendingPHIs) {
2080 const PHINode *PI = Phi.first;
2085 Verifier.setCurrentInst(PI);
2086 #endif // ifndef NDEBUG 2092 for (
auto Pred : getMachinePredBBs({IRPred, PI->
getParent()})) {
2096 for (
unsigned j = 0; j < ValRegs.
size(); ++j) {
2106 bool IRTranslator::valueIsSplit(
const Value &V,
2109 if (Offsets && !Offsets->
empty())
2112 return SplitTys.
size() > 1;
2115 bool IRTranslator::translate(
const Instruction &Inst) {
2120 EntryBuilder->setDebugLoc(
2123 EntryBuilder->setDebugLoc(
DebugLoc());
2126 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 2127 case Instruction::OPCODE: \ 2128 return translate##OPCODE(Inst, *CurBuilder.get()); 2129 #include "llvm/IR/Instruction.def" 2136 if (
auto CI = dyn_cast<ConstantInt>(&C))
2137 EntryBuilder->buildConstant(Reg, *CI);
2138 else if (
auto CF = dyn_cast<ConstantFP>(&C))
2139 EntryBuilder->buildFConstant(Reg, *CF);
2140 else if (isa<UndefValue>(C))
2141 EntryBuilder->buildUndef(Reg);
2142 else if (isa<ConstantPointerNull>(C)) {
2145 unsigned NullSize = DL->getTypeSizeInBits(C.
getType());
2148 Register ZeroReg = getOrCreateVReg(*ZeroVal);
2149 EntryBuilder->buildCast(Reg, ZeroReg);
2150 }
else if (
auto GV = dyn_cast<GlobalValue>(&C))
2151 EntryBuilder->buildGlobalValue(Reg, GV);
2152 else if (
auto CAZ = dyn_cast<ConstantAggregateZero>(&C)) {
2153 if (!CAZ->getType()->isVectorTy())
2156 if (CAZ->getNumElements() == 1)
2157 return translate(*CAZ->getElementValue(0u),
Reg);
2159 for (
unsigned i = 0; i < CAZ->getNumElements(); ++i) {
2160 Constant &Elt = *CAZ->getElementValue(i);
2163 EntryBuilder->buildBuildVector(Reg, Ops);
2164 }
else if (
auto CV = dyn_cast<ConstantDataVector>(&C)) {
2166 if (CV->getNumElements() == 1)
2167 return translate(*CV->getElementAsConstant(0),
Reg);
2169 for (
unsigned i = 0; i < CV->getNumElements(); ++i) {
2170 Constant &Elt = *CV->getElementAsConstant(i);
2173 EntryBuilder->buildBuildVector(Reg, Ops);
2174 }
else if (
auto CE = dyn_cast<ConstantExpr>(&C)) {
2175 switch(CE->getOpcode()) {
2176 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 2177 case Instruction::OPCODE: \ 2178 return translate##OPCODE(*CE, *EntryBuilder.get()); 2179 #include "llvm/IR/Instruction.def" 2183 }
else if (
auto CV = dyn_cast<ConstantVector>(&C)) {
2184 if (CV->getNumOperands() == 1)
2185 return translate(*CV->getOperand(0),
Reg);
2187 for (
unsigned i = 0; i < CV->getNumOperands(); ++i) {
2188 Ops.
push_back(getOrCreateVReg(*CV->getOperand(i)));
2190 EntryBuilder->buildBuildVector(Reg, Ops);
2191 }
else if (
auto *BA = dyn_cast<BlockAddress>(&C)) {
2192 EntryBuilder->buildBlockAddress(Reg, BA);
2199 void IRTranslator::finalizeBasicBlock() {
2200 for (
auto &JTCase : SL->JTCases) {
2202 if (!JTCase.first.Emitted)
2203 emitJumpTableHeader(JTCase.second, JTCase.first, JTCase.first.HeaderBB);
2205 emitJumpTable(JTCase.second, JTCase.second.MBB);
2207 SL->JTCases.clear();
2210 void IRTranslator::finalizeFunction() {
2213 PendingPHIs.clear();
2215 FrameIndices.clear();
2216 MachinePreds.clear();
2220 EntryBuilder.reset();
2245 getAnalysis<GISelCSEAnalysisWrapperPass>().getCSEWrapper();
2248 TPC = &getAnalysis<TargetPassConfig>();
2251 : TPC->isGISelCSEEnabled();
2254 EntryBuilder = std::make_unique<CSEMIRBuilder>(CurMF);
2255 CSEInfo = &Wrapper.
get(TPC->getCSEConfig());
2256 EntryBuilder->setCSEInfo(CSEInfo);
2257 CurBuilder = std::make_unique<CSEMIRBuilder>(CurMF);
2258 CurBuilder->setCSEInfo(CSEInfo);
2260 EntryBuilder = std::make_unique<MachineIRBuilder>();
2261 CurBuilder = std::make_unique<MachineIRBuilder>();
2263 CLI = MF->getSubtarget().getCallLowering();
2264 CurBuilder->
setMF(*MF);
2265 EntryBuilder->setMF(*MF);
2266 MRI = &MF->getRegInfo();
2268 ORE = std::make_unique<OptimizationRemarkEmitter>(&
F);
2270 FuncInfo.BPI =
nullptr;
2271 const auto &TLI = *MF->getSubtarget().getTargetLowering();
2273 SL = std::make_unique<GISelSwitchLowering>(
this, FuncInfo);
2274 SL->init(TLI, TM, *DL);
2278 assert(PendingPHIs.empty() &&
"stale PHIs");
2280 if (!DL->isLittleEndian()) {
2284 R <<
"unable to translate in big endian mode";
2289 auto FinalizeOnReturn =
make_scope_exit([
this]() { finalizeFunction(); });
2294 EntryBuilder->setMBB(*EntryBB);
2297 SwiftError.setFunction(CurMF);
2298 SwiftError.createEntriesInEntryBlock(DbgLoc);
2301 bool HasMustTailInVarArgFn =
false;
2305 auto *&MBB = BBToMBB[&BB];
2307 MBB = MF->CreateMachineBasicBlock(&BB);
2313 if (!HasMustTailInVarArgFn)
2317 MF->getFrameInfo().setHasMustTailInVarArgFunc(HasMustTailInVarArgFn);
2320 EntryBB->addSuccessor(&getMBB(F.front()));
2325 if (DL->getTypeStoreSize(
Arg.getType()) == 0)
2330 if (
Arg.hasSwiftErrorAttr()) {
2331 assert(VRegs.
size() == 1 &&
"Too many vregs for Swift error");
2332 SwiftError.setCurrentVReg(EntryBB, SwiftError.getFunctionArg(), VRegs[0]);
2336 if (!CLI->lowerFormalArguments(*EntryBuilder.get(),
F, VRegArgs)) {
2338 F.getSubprogram(), &F.getEntryBlock());
2339 R <<
"unable to lower arguments: " <<
ore::NV(
"Prototype", F.getType());
2346 if (EnableCSE && CSEInfo)
2353 #endif // ifndef NDEBUG 2359 CurBuilder->setMBB(MBB);
2360 HasTailCall =
false;
2370 Verifier.setCurrentInst(&Inst);
2371 #endif // ifndef NDEBUG 2372 if (translate(Inst))
2377 R <<
"unable to translate instruction: " <<
ore::NV(
"Opcode", &Inst);
2379 if (ORE->allowExtraAnalysis(
"gisel-irtranslator")) {
2380 std::string InstStrStorage;
2384 R <<
": '" << InstStr.
str() <<
"'";
2391 finalizeBasicBlock();
2398 finishPendingPhis();
2400 SwiftError.propagateVRegs();
2405 assert(EntryBB->succ_size() == 1 &&
2406 "Custom BB used for lowering should have only one successor");
2409 assert(NewEntryBB.pred_size() == 1 &&
2410 "LLVM-IR entry block has a predecessor!?");
2413 NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(),
2418 NewEntryBB.addLiveIn(LiveIn);
2419 NewEntryBB.sortUniqueLiveIns();
2422 EntryBB->removeSuccessor(&NewEntryBB);
2423 MF->remove(EntryBB);
2424 MF->DeleteMachineBasicBlock(EntryBB);
2426 assert(&MF->front() == &NewEntryBB &&
2427 "New entry wasn't next in the list of basic block!");
2431 SP.copyToMachineFrameInfo(MF->getFrameInfo());
auto lower_bound(R &&Range, T &&Value) -> decltype(adl_begin(Range))
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
MachineInstrBuilder buildDirectDbgValue(Register Reg, const MDNode *Variable, const MDNode *Expr)
Build and insert a DBG_VALUE instruction expressing the fact that the associated Variable lives in Re...
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
Return a value (possibly void), from a function.
Value * getValueOperand()
const MachineInstrBuilder & addMetadata(const MDNode *MD) const
unsigned getNumCases() const
Return the number of 'cases' in this switch instruction, excluding the default case.
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
A simple RAII based CSEInfo installer.
virtual MachineInstrBuilder buildConstant(const DstOp &Res, const ConstantInt &Val)
Build and insert Res = G_CONSTANT Val.
A parsed version of the target data layout string in and methods for querying it. ...
reference emplace_back(ArgTypes &&... Args)
MachineInstrBuilder buildJumpTable(const LLT PtrTy, unsigned JTI)
Build and insert Res = G_JUMP_TABLE JTI.
This class is the base class for the comparison instructions.
DILocation * get() const
Get the underlying DILocation.
MachineInstrBuilder buildZExtOrTrunc(const DstOp &Res, const SrcOp &Op)
Build and insert Res = G_ZEXT Op, Res = G_TRUNC Op, or Res = COPY Op depending on the differing sizes...
*p = old <signed v ? old : v
iterator_range< CaseIt > cases()
Iteration adapter for range-for loops.
This class represents an incoming formal argument to a Function.
DiagnosticInfoOptimizationBase::Argument NV
MachineBasicBlock * FalseBB
CaseClusterVector::iterator CaseClusterIt
This represents the llvm.dbg.label instruction.
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
MachineInstrBuilder buildBrCond(Register Tst, MachineBasicBlock &Dest)
Build and insert G_BRCOND Tst, Dest.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
This class represents lattice values for constants.
const MachineInstrBuilder & addShuffleMask(ArrayRef< int > Val) const
void getSelectionDAGFallbackAnalysisUsage(AnalysisUsage &AU)
Modify analysis usage so it preserves passes required for the SelectionDAG fallback.
MachineInstrBuilder buildSExtOrTrunc(const DstOp &Res, const SrcOp &Op)
Build and insert Res = G_SEXT Op, Res = G_TRUNC Op, or Res = COPY Op depending on the differing sizes...
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
bool isSized(SmallPtrSetImpl< Type *> *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Register getReg(unsigned Idx) const
Get the register for the operand index.
void setIsEHPad(bool V=true)
Indicates the block is a landing pad.
Optional< MachineInstrBuilder > materializePtrAdd(Register &Res, Register Op0, const LLT &ValueTy, uint64_t Value)
Materialize and insert Res = G_PTR_ADD Op0, (G_CONSTANT Value)
An instruction for ordering other memory operations.
An instruction that atomically checks whether a specified value is in a memory location, and, if it is, stores a new value there.
void push_back(const T &Elt)
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
MachineInstrBuilder buildCast(const DstOp &Dst, const SrcOp &Src)
Build and insert an appropriate cast between two registers of equal size.
MachineInstrBuilder buildPtrAdd(const DstOp &Res, const SrcOp &Op0, const SrcOp &Op1)
Build and insert Res = G_PTR_ADD Op0, Op1.
IRTranslator LLVM IR static false void reportTranslationError(MachineFunction &MF, const TargetPassConfig &TPC, OptimizationRemarkEmitter &ORE, OptimizationRemarkMissed &R)
This class represents a function call, abstracting a target machine's calling convention.
Value * getCondition() const
static uint64_t round(uint64_t Acc, uint64_t Input)
void setDebugLoc(const DebugLoc &DL)
Set the debug location to DL for all the next build instructions.
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this store instruction.
gep_type_iterator gep_type_end(const User *GEP)
const std::string & getAsmString() const
*p = old <unsigned v ? old : v
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
*p = old >unsigned v ? old : v
LLVM_NODISCARD detail::scope_exit< typename std::decay< Callable >::type > make_scope_exit(Callable &&F)
LLVMContext & getContext() const
All values hold a context through their type.
void addSuccessorWithoutProb(MachineBasicBlock *Succ)
Add Succ as a successor of this MachineBasicBlock.
Type * getPointerOperandType() const
bool hasDLLImportStorageClass() const
BasicBlock * getSuccessor(unsigned i) const
Value * getNewValOperand()
unsigned const TargetRegisterInfo * TRI
This structure is used to communicate between SelectionDAGBuilder and SDISel for the code generation ...
User::op_iterator arg_end()
Return the iterator pointing to the end of the argument list.
The actual analysis pass wrapper.
An instruction for reading from memory.
reverse_iterator rbegin()
void setMF(MachineFunction &MF)
MachineInstrBuilder buildAtomicRMW(unsigned Opcode, const DstOp &OldValRes, const SrcOp &Addr, const SrcOp &Val, MachineMemOperand &MMO)
Build and insert OldValRes<def> = G_ATOMICRMW_<Opcode> Addr, Val, MMO.
bool hasExternalWeakLinkage() const
an instruction that atomically reads a memory location, combines it with another value, and then stores the result back.
Value * getCondition() const
bool isVectorTy() const
True if this is an instance of VectorType.
LLVM_READONLY APFloat maximum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2018 maximum semantics.
bool isMustTailCall() const
MachineInstrBuilder buildDynStackAlloc(const DstOp &Res, const SrcOp &Size, unsigned Align)
Build and insert Res = G_DYN_STACKALLOC Size, Align.
GlobalValue * ExtractTypeInfo(Value *V)
ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
*p = old >signed v ? old : v
virtual bool getTgtMemIntrinsic(IntrinsicInfo &, const CallInst &, MachineFunction &, unsigned) const
Given an intrinsic, checks if on the target the intrinsic will need to map to a MemIntrinsicNode (tou...
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
MachineInstrBuilder buildBrJT(Register TablePtr, unsigned JTI, Register IndexReg)
Build and insert G_BRJT TablePtr, JTI, IndexReg.
BranchProbability TrueProb
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
AtomicOrdering getFailureOrdering() const
Returns the failure ordering constraint of this cmpxchg instruction.
bool hasSideEffects() const
Value * getArgOperand(unsigned i) const
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
bool isVolatile() const
Return true if this is a load from a volatile memory location.
A description of a memory reference used in the backend.
amdgpu aa AMDGPU Address space based Alias Analysis Wrapper
unsigned countOperandBundlesOfType(StringRef Name) const
Return the number of operand bundles with the tag Name attached to this instruction.
This class represents the LLVM 'select' instruction.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
unsigned getAlignment() const
Return the alignment of the memory that is being allocated by the instruction.
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
PointerType * getType() const
Overload to return most specific pointer type.
Class to represent struct types.
ValTy * getCalledValue() const
Return the pointer to function that is being called.
DILabel * getLabel() const
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
BinOp getOperation() const
bool isWeak() const
Return true if this cmpxchg may spuriously fail.
A cluster of cases suitable for jump table lowering.
TypeID
Definitions of all of the base types for the Type system.
LLVM_READONLY APFloat minimum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2018 minimum semantics.
The memory access is dereferenceable (i.e., doesn't trap).
std::vector< CaseCluster > CaseClusterVector
bool isVolatile() const
Return true if this is a cmpxchg from a volatile memory location.
const MachineInstrBuilder & addDef(Register RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a virtual register definition operand.
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
Target-Independent Code Generator Pass Configuration Options.
bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
BranchProbability FalseProb
INLINEASM - Represents an inline asm block.
MachineBasicBlock * ThisBB
Context object for machine code objects.
InstrTy * getInstruction() const
Value * getPointerOperand()
MachineBasicBlock * TrueBB
Type * getType() const
All values are typed, get the type of this value.
MachineInstrBuilder buildFence(unsigned Ordering, unsigned Scope)
Build and insert G_FENCE Ordering, Scope.
MachineInstrBuilder buildBrIndirect(Register Tgt)
Build and insert G_BRINDIRECT Tgt.
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type...
AtomicOrdering getSuccessOrdering() const
Returns the success ordering constraint of this cmpxchg instruction.
const MachineInstrBuilder & addFPImm(const ConstantFP *Val) const
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
iterator_range< User::op_iterator > arg_operands()
An instruction for storing to memory.
static LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
MachineInstrBuilder buildSub(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, Optional< unsigned > Flags=None)
Build and insert Res = G_SUB Op0, Op1.
void setSuccProbability(succ_iterator I, BranchProbability Prob)
Set successor probability of a given iterator.
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *bb=nullptr)
CreateMachineBasicBlock - Allocate a new MachineBasicBlock.
MachineInstrBuilder buildExtractVectorElement(const DstOp &Res, const SrcOp &Val, const SrcOp &Idx)
Build and insert Res = G_EXTRACT_VECTOR_ELT Val, Idx.
Value * getOperand(unsigned i) const
Analysis containing CSE Info
BasicBlockListType::iterator iterator
unsigned JTI
The JumpTableIndex for this jump table in the function.
void normalizeSuccProbs()
Normalize probabilities of all successors so that the sum of them becomes one.
TargetInstrInfo - Interface to description of machine instruction set.
This corresponds to the llvm.lifetime.
MachineBasicBlock::iterator getInsertPt()
Current insertion point for new instructions.
bool doesNotAccessMemory() const
Determine if the function does not access memory.
MachineInstrBuilder buildDbgLabel(const MDNode *Label)
Build and insert a DBG_LABEL instructions specifying that Label is given.
bool isVoidTy() const
Return true if this is 'void'.
The memory access is volatile.
bool isValidLocationForIntrinsic(const DILocation *DL) const
Check that a location is valid for this label.
const BasicBlock & getEntryBlock() const
constexpr uint64_t MinAlign(uint64_t A, uint64_t B)
A and B are either alignments or offsets.
void getAAMetadata(AAMDNodes &N, bool Merge=false) const
Fills the AAMDNodes structure with AA metadata from this instruction.
initializer< Ty > init(const Ty &Val)
const MachineInstrBuilder & addUse(Register RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a virtual register use operand.
Abstract class that contains various methods for clients to notify about changes. ...
FPOpFusion::FPOpFusionMode AllowFPOpFusion
AllowFPOpFusion - This flag is set by the -fuse-fp-ops=xxx option.
The landingpad instruction holds all of the information necessary to generate correct exception handl...
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
void GetUnderlyingObjects(const Value *V, SmallVectorImpl< const Value *> &Objects, const DataLayout &DL, LoopInfo *LI=nullptr, unsigned MaxLookup=6)
This method is similar to GetUnderlyingObject except that it can look through phi and select instruct...
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this rmw instruction.
CodeGenOpt::Level getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
unsigned const MachineRegisterInfo * MRI
Value * getCalledValue() const
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
DISubprogram * getSubprogram() const
Get the attached subprogram.
Conditional or Unconditional Branch instruction.
MachineInstrBuilder buildInstr(unsigned Opcode)
Build and insert <empty> = Opcode <empty>.
Value * getAddress() const
static bool checkForMustTailInVarArgFn(bool IsVarArg, const BasicBlock &BB)
Returns true if a BasicBlock BB within a variadic function contains a variadic musttail call...
size_t size() const
size - Get the array size.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
bool isInlineAsm() const
Check if this call is an inline asm statement.
Value * getCompareOperand()
MachineBasicBlock * MBB
The MBB into which to emit the code for the indirect jump.
void sortAndRangeify(CaseClusterVector &Clusters)
Sort Clusters and merge adjacent cases.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
const Instruction & front() const
void computeValueLLTs(const DataLayout &DL, Type &Ty, SmallVectorImpl< LLT > &ValueTys, SmallVectorImpl< uint64_t > *Offsets=nullptr, uint64_t StartingOffset=0)
computeValueLLTs - Given an LLVM IR type, compute a sequence of LLTs that represent all the individua...
Indirect Branch Instruction.
SmallVector< SwitchWorkListItem, 4 > SwitchWorkList
Helper class to build MachineInstr.
BranchProbability DefaultProb
BasicBlock * getDefaultDest() const
DIExpression * getExpression() const
bool isPredecessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a predecessor of this block.
bool isValidLocationForIntrinsic(const DILocation *DL) const
Check that a location is valid for this variable.
Represent the analysis usage information of a pass.
GISelCSEInfo & get(std::unique_ptr< CSEConfigBase > CSEOpt, bool ReCompute=false)
Takes a CSEConfigBase object that defines what opcodes get CSEd.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
void print(raw_ostream &O, bool IsForDebug=false) const
Implement operator<< on Value.
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
Value * getPointerOperand()
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
CaseClusterIt LastCluster
const MachineInstrBuilder & addSym(MCSymbol *Sym, unsigned char TargetFlags=0) const
const MachineInstrBuilder & addFrameIndex(int Idx) const
static double log2(double V)
static Constant * getAllOnesValue(Type *Ty)
1 1 1 1 Always true (always folded)
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
succ_iterator succ_begin()
MachineInstrBuilder buildCopy(const DstOp &Res, const SrcOp &Op)
Build and insert Res = COPY Op.
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this cmpxchg instruction.
BasicBlock * getSuccessor(unsigned i) const
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
const Value * getArraySize() const
Get the number of elements allocated.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
static uint16_t copyFlagsFromInstruction(const Instruction &I)
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
AtomicOrdering getOrdering() const
Returns the ordering constraint of this rmw instruction.
Simple wrapper that does the following.
This class contains a discriminated union of information about pointers in memory operands...
std::string & str()
Flushes the stream contents to the target string and returns the string's reference.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_READONLY APFloat maxnum(const APFloat &A, const APFloat &B)
Implements IEEE maxNum semantics.
EVT getValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the EVT corresponding to this LLVM type.
const std::string & getConstraintString() const
iterator_range< IterTy > args() const
This struct is a compact representation of a valid (non-zero power of two) alignment.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
EH_LABEL - Represents a label in mid basic block used to track locations needed for debug and excepti...
MachineInstrBuilder buildIntrinsic(Intrinsic::ID ID, ArrayRef< Register > Res, bool HasSideEffects)
Build and insert either a G_INTRINSIC (if HasSideEffects is false) or G_INTRINSIC_W_SIDE_EFFECTS inst...
void copyIRFlags(const Instruction &I)
Copy all flags to MachineInst MIFlags.
void sort(IteratorTy Start, IteratorTy End)
LLT getLLTForType(Type &Ty, const DataLayout &DL)
Construct a low-level type based on an LLVM type.
The memory access writes data.
MachineInstrBuilder buildBr(MachineBasicBlock &Dest)
Build and insert G_BR Dest.
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
MachineInstrBuilder buildConstDbgValue(const Constant &C, const MDNode *Variable, const MDNode *Expr)
Build and insert a DBG_VALUE instructions specifying that Variable is given by C (suitably modified b...
struct PredInfoPair PredInfo
Predicate getPredicate(unsigned Condition, unsigned Hint)
Return predicate consisting of specified condition and hint bits.
unsigned getNumOperands() const
MachineInstrBuilder buildLoad(const DstOp &Res, const SrcOp &Addr, MachineMemOperand &MMO)
Build and insert Res = G_LOAD Addr, MMO.
MachineInstrBuilder buildMul(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, Optional< unsigned > Flags=None)
Build and insert Res = G_MUL Op0, Op1.
void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
MachineInstrBuilder buildICmp(CmpInst::Predicate Pred, const DstOp &Res, const SrcOp &Op0, const SrcOp &Op1)
Build and insert a Res = G_ICMP Pred, Op0, Op1.
This is the shared class of boolean and integer constants.
Align max(MaybeAlign Lhs, Align Rhs)
This struct is a compact representation of a valid (power of two) or undefined (0) alignment...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
MachineInstrBuilder buildFrameIndex(const DstOp &Res, int Idx)
Build and insert Res = G_FRAME_INDEX Idx.
bool isAggregateType() const
Return true if the type is an aggregate type.
unsigned getSizeInBits() const
Returns the total size of the type. Must only be called on sized types.
static uint64_t getOffsetFromIndices(const User &U, const DataLayout &DL)
const MachineInstrBuilder & addMemOperand(MachineMemOperand *MMO) const
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
DebugLoc getDebugLoc()
Get the current instruction's debug location.
virtual bool isTailCall(const MachineInstr &Inst) const
Determines whether Inst is a tail call instruction.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
bool isLayoutSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB will be emitted immediately after this block, such that if this bloc...
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
MachineInstrBuilder buildInsertVectorElement(const DstOp &Res, const SrcOp &Val, const SrcOp &Elt, const SrcOp &Idx)
Build and insert Res = G_INSERT_VECTOR_ELT Val, Elt, Idx.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
unsigned getVectorNumElements() const
bool isIntPredicate() const
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Class for arbitrary precision integers.
virtual bool isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, EVT) const
Return true if an FMA operation is faster than a pair of fmul and fadd instructions.
amdgpu Simplify well known AMD library false FunctionCallee Callee
static unsigned getReg(const void *D, unsigned RC, unsigned RegNo)
unsigned Reg
The virtual register containing the index of the jump table entry to jump to.
void setHasAddressTaken()
Set this block to reflect that it potentially is the target of an indirect branch.
MachineInstrBuilder buildAtomicCmpXchgWithSuccess(Register OldValRes, Register SuccessRes, Register Addr, Register CmpVal, Register NewVal, MachineMemOperand &MMO)
Build and insert OldValRes<def>, SuccessRes<def> = G_ATOMIC_CMPXCHG_WITH_SUCCESS Addr, CmpVal, NewVal, MMO.
CaseClusterIt FirstCluster
The memory access reads data.
static MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
Representation of each machine instruction.
unsigned succ_size(const Instruction *I)
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
void addObserver(GISelChangeObserver *O)
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this fence instruction.
bool isVolatile() const
Return true if this is a store to a volatile memory location.
Analysis providing branch probability information.
unsigned getNumArgOperands() const
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
Type * getPointerOperandType() const
MachineBasicBlock * Default
The MBB of the default bb, which is a successor of the range check MBB.
static IntegerType * getInt32Ty(LLVMContext &C)
void removeObserver(GISelChangeObserver *O)
A cluster of adjacent case labels with the same destination, or just one case.
MachineInstrBuilder buildAdd(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, Optional< unsigned > Flags=None)
Build and insert Res = G_ADD Op0, Op1.
LLVM_NODISCARD bool empty() const
AtomicOrdering getOrdering() const
Returns the ordering constraint of this store instruction.
This represents the llvm.dbg.value instruction.
bool isTokenTy() const
Return true if this is 'token'.
verify safepoint Safepoint IR Verifier
Value * getPointerOperand()
MachineInstrBuilder buildIndirectDbgValue(Register Reg, const MDNode *Variable, const MDNode *Expr)
Build and insert a DBG_VALUE instruction expressing the fact that the associated Variable lives in me...
const MachineBasicBlock & getMBB() const
Getter for the basic block we currently build.
Establish a view to a call site for examination.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation.
static cl::opt< bool > EnableCSEInIRTranslator("enable-cse-in-irtranslator", cl::desc("Should enable CSE in irtranslator"), cl::Optional, cl::init(false))
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this load instruction.
void setMBB(MachineBasicBlock &MBB)
Set the insertion point to the end of MBB.
void push_back(MachineInstr *MI)
static Constant * getZeroValueForNegation(Type *Ty)
Floating point negation must be implemented with f(x) = -0.0 - x.
Pair of physical register and lane mask.
The memory access always returns the same value (or traps).
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
MachineInstrBuilder buildStore(const SrcOp &Val, const SrcOp &Addr, MachineMemOperand &MMO)
Build and insert G_STORE Val, Addr, MMO.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
DILocalVariable * getVariable() const
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
bool isUnconditional() const
AsmDialect getDialect() const
This file declares the IRTranslator pass.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
void insert(iterator MBBI, MachineBasicBlock *MBB)
SmallVector< int, 16 > getShuffleMask() const
A raw_ostream that writes to an std::string.
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
static bool isSwiftError(const Value *V)
succ_range successors(Instruction *I)
This file describes how to lower LLVM calls to machine code calls.
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
INITIALIZE_PASS_BEGIN(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI", false, false) INITIALIZE_PASS_END(IRTranslator
Primary interface to the complete machine description for the target machine.
MachineInstrBuilder buildAnd(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1)
Build and insert Res = G_AND Op0, Op1.
bool skipFunction(const Function &F) const
Optional passes call this function to check whether the pass should be skipped.
const Instruction * getFirstNonPHIOrDbg() const
Returns a pointer to the first instruction in this block that is not a PHINode or a debug intrinsic...
AtomicOrdering getOrdering() const
Returns the ordering constraint of this fence instruction.
MachineInstrBuilder buildUndef(const DstOp &Res)
Build and insert Res = IMPLICIT_DEF.
Simple wrapper observer that takes several observers, and calls each one for each event...
Register getReg() const
getReg - Returns the register number.
bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size...
A cluster of cases suitable for bit test lowering.
const MachineOperand & getOperand(unsigned i) const
OutputIt copy(R &&Range, OutputIt Out)
This represents the llvm.dbg.declare instruction.
Value * getPointerOperand()
Statically lint checks LLVM IR
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
LLVM_READONLY APFloat minnum(const APFloat &A, const APFloat &B)
Implements IEEE minNum semantics.
std::vector< MachineBasicBlock * >::iterator succ_iterator
int64_t getIndexedOffsetInType(Type *ElemTy, ArrayRef< Value *> Indices) const
Returns the offset from the beginning of the type for the specified indices.
bool isVolatile() const
Return true if this is a RMW on a volatile memory location.
const MachineInstrBuilder & addExternalSymbol(const char *FnName, unsigned TargetFlags=0) const
0 0 0 0 Always false (always folded)
Wrapper class representing virtual and physical registers.
detail::enumerator< R > enumerate(R &&TheRange)
Given an input range, returns a new range whose values are are pair (A,B) such that A is the 0-based ...
This file describes how to lower LLVM code to machine code.
const BasicBlock * getParent() const
virtual const TargetRegisterClass * getPointerRegClass(const MachineFunction &MF, unsigned Kind=0) const
Returns a TargetRegisterClass used for pointer values.
an instruction to allocate memory on the stack
This instruction inserts a struct field of array element value into an aggregate value.
gep_type_iterator gep_type_begin(const User *GEP)
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.