1 //===-- llvm/CodeGen/GlobalISel/IRTranslator.cpp - IRTranslator --*- C++ -*-==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 /// This file implements the IRTranslator class.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
15 #include "llvm/ADT/ScopeExit.h"
16 #include "llvm/ADT/SmallSet.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/Analysis/OptimizationDiagnosticInfo.h"
19 #include "llvm/CodeGen/GlobalISel/CallLowering.h"
20 #include "llvm/CodeGen/Analysis.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/TargetPassConfig.h"
26 #include "llvm/IR/Constant.h"
27 #include "llvm/IR/DebugInfo.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/GetElementPtrTypeIterator.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 #include "llvm/IR/Type.h"
32 #include "llvm/IR/Value.h"
33 #include "llvm/Target/TargetFrameLowering.h"
34 #include "llvm/Target/TargetIntrinsicInfo.h"
35 #include "llvm/Target/TargetLowering.h"
37 #define DEBUG_TYPE "irtranslator"
41 char IRTranslator::ID = 0;
42 INITIALIZE_PASS_BEGIN(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
44 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
45 INITIALIZE_PASS_END(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
48 static void reportTranslationError(MachineFunction &MF,
49 const TargetPassConfig &TPC,
50 OptimizationRemarkEmitter &ORE,
51 OptimizationRemarkMissed &R) {
52 MF.getProperties().set(MachineFunctionProperties::Property::FailedISel);
54 // Print the function name explicitly if we don't have a debug location (which
55 // makes the diagnostic less useful) or if we're going to emit a raw error.
56 if (!R.getLocation().isValid() || TPC.isGlobalISelAbortEnabled())
57 R << (" (in function: " + MF.getName() + ")").str();
59 if (TPC.isGlobalISelAbortEnabled())
60 report_fatal_error(R.getMsg());
65 IRTranslator::IRTranslator() : MachineFunctionPass(ID), MRI(nullptr) {
66 initializeIRTranslatorPass(*PassRegistry::getPassRegistry());
69 void IRTranslator::getAnalysisUsage(AnalysisUsage &AU) const {
70 AU.addRequired<TargetPassConfig>();
71 MachineFunctionPass::getAnalysisUsage(AU);
75 unsigned IRTranslator::getOrCreateVReg(const Value &Val) {
76 unsigned &ValReg = ValToVReg[&Val];
81 // Fill ValRegsSequence with the sequence of registers
82 // we need to concat together to produce the value.
83 assert(Val.getType()->isSized() &&
84 "Don't know how to create an empty vreg");
86 MRI->createGenericVirtualRegister(getLLTForType(*Val.getType(), *DL));
89 if (auto CV = dyn_cast<Constant>(&Val)) {
90 bool Success = translate(*CV, VReg);
92 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
93 MF->getFunction()->getSubprogram(),
94 &MF->getFunction()->getEntryBlock());
95 R << "unable to translate constant: " << ore::NV("Type", Val.getType());
96 reportTranslationError(*MF, *TPC, *ORE, R);
104 int IRTranslator::getOrCreateFrameIndex(const AllocaInst &AI) {
105 if (FrameIndices.find(&AI) != FrameIndices.end())
106 return FrameIndices[&AI];
108 unsigned ElementSize = DL->getTypeStoreSize(AI.getAllocatedType());
110 ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue();
112 // Always allocate at least one byte.
113 Size = std::max(Size, 1u);
115 unsigned Alignment = AI.getAlignment();
117 Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
119 int &FI = FrameIndices[&AI];
120 FI = MF->getFrameInfo().CreateStackObject(Size, Alignment, false, &AI);
124 unsigned IRTranslator::getMemOpAlignment(const Instruction &I) {
125 unsigned Alignment = 0;
126 Type *ValTy = nullptr;
127 if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
128 Alignment = SI->getAlignment();
129 ValTy = SI->getValueOperand()->getType();
130 } else if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
131 Alignment = LI->getAlignment();
132 ValTy = LI->getType();
134 OptimizationRemarkMissed R("gisel-irtranslator", "", &I);
135 R << "unable to translate memop: " << ore::NV("Opcode", &I);
136 reportTranslationError(*MF, *TPC, *ORE, R);
140 return Alignment ? Alignment : DL->getABITypeAlignment(ValTy);
143 MachineBasicBlock &IRTranslator::getOrCreateBB(const BasicBlock &BB) {
144 MachineBasicBlock *&MBB = BBToMBB[&BB];
146 MBB = MF->CreateMachineBasicBlock(&BB);
149 if (BB.hasAddressTaken())
150 MBB->setHasAddressTaken();
155 void IRTranslator::addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred) {
156 assert(NewPred && "new predecessor must be a real MachineBasicBlock");
157 MachinePreds[Edge].push_back(NewPred);
160 bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U,
161 MachineIRBuilder &MIRBuilder) {
162 // FIXME: handle signed/unsigned wrapping flags.
164 // Get or create a virtual register for each value.
165 // Unless the value is a Constant => loadimm cst?
166 // or inline constant each time?
167 // Creation of a virtual register needs to have a size.
168 unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
169 unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
170 unsigned Res = getOrCreateVReg(U);
171 MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op0).addUse(Op1);
175 bool IRTranslator::translateFSub(const User &U, MachineIRBuilder &MIRBuilder) {
176 // -0.0 - X --> G_FNEG
177 if (isa<Constant>(U.getOperand(0)) &&
178 U.getOperand(0) == ConstantFP::getZeroValueForNegation(U.getType())) {
179 MIRBuilder.buildInstr(TargetOpcode::G_FNEG)
180 .addDef(getOrCreateVReg(U))
181 .addUse(getOrCreateVReg(*U.getOperand(1)));
184 return translateBinaryOp(TargetOpcode::G_FSUB, U, MIRBuilder);
187 bool IRTranslator::translateCompare(const User &U,
188 MachineIRBuilder &MIRBuilder) {
189 const CmpInst *CI = dyn_cast<CmpInst>(&U);
190 unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
191 unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
192 unsigned Res = getOrCreateVReg(U);
193 CmpInst::Predicate Pred =
194 CI ? CI->getPredicate() : static_cast<CmpInst::Predicate>(
195 cast<ConstantExpr>(U).getPredicate());
196 if (CmpInst::isIntPredicate(Pred))
197 MIRBuilder.buildICmp(Pred, Res, Op0, Op1);
198 else if (Pred == CmpInst::FCMP_FALSE)
199 MIRBuilder.buildConstant(Res, 0);
200 else if (Pred == CmpInst::FCMP_TRUE)
201 MIRBuilder.buildConstant(Res, 1);
203 MIRBuilder.buildFCmp(Pred, Res, Op0, Op1);
208 bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) {
209 const ReturnInst &RI = cast<ReturnInst>(U);
210 const Value *Ret = RI.getReturnValue();
211 // The target may mess up with the insertion point, but
212 // this is not important as a return is the last instruction
213 // of the block anyway.
214 return CLI->lowerReturn(MIRBuilder, Ret, !Ret ? 0 : getOrCreateVReg(*Ret));
217 bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) {
218 const BranchInst &BrInst = cast<BranchInst>(U);
220 if (!BrInst.isUnconditional()) {
221 // We want a G_BRCOND to the true BB followed by an unconditional branch.
222 unsigned Tst = getOrCreateVReg(*BrInst.getCondition());
223 const BasicBlock &TrueTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ++));
224 MachineBasicBlock &TrueBB = getOrCreateBB(TrueTgt);
225 MIRBuilder.buildBrCond(Tst, TrueBB);
228 const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ));
229 MachineBasicBlock &TgtBB = getOrCreateBB(BrTgt);
230 MIRBuilder.buildBr(TgtBB);
233 MachineBasicBlock &CurBB = MIRBuilder.getMBB();
234 for (const BasicBlock *Succ : BrInst.successors())
235 CurBB.addSuccessor(&getOrCreateBB(*Succ));
239 bool IRTranslator::translateSwitch(const User &U,
240 MachineIRBuilder &MIRBuilder) {
241 // For now, just translate as a chain of conditional branches.
242 // FIXME: could we share most of the logic/code in
243 // SelectionDAGBuilder::visitSwitch between SelectionDAG and GlobalISel?
244 // At first sight, it seems most of the logic in there is independent of
245 // SelectionDAG-specifics and a lot of work went in to optimize switch
246 // lowering in there.
248 const SwitchInst &SwInst = cast<SwitchInst>(U);
249 const unsigned SwCondValue = getOrCreateVReg(*SwInst.getCondition());
250 const BasicBlock *OrigBB = SwInst.getParent();
252 LLT LLTi1 = getLLTForType(*Type::getInt1Ty(U.getContext()), *DL);
253 for (auto &CaseIt : SwInst.cases()) {
254 const unsigned CaseValueReg = getOrCreateVReg(*CaseIt.getCaseValue());
255 const unsigned Tst = MRI->createGenericVirtualRegister(LLTi1);
256 MIRBuilder.buildICmp(CmpInst::ICMP_EQ, Tst, CaseValueReg, SwCondValue);
257 MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
258 const BasicBlock *TrueBB = CaseIt.getCaseSuccessor();
259 MachineBasicBlock &TrueMBB = getOrCreateBB(*TrueBB);
261 MIRBuilder.buildBrCond(Tst, TrueMBB);
262 CurMBB.addSuccessor(&TrueMBB);
263 addMachineCFGPred({OrigBB, TrueBB}, &CurMBB);
265 MachineBasicBlock *FalseMBB =
266 MF->CreateMachineBasicBlock(SwInst.getParent());
267 MF->push_back(FalseMBB);
268 MIRBuilder.buildBr(*FalseMBB);
269 CurMBB.addSuccessor(FalseMBB);
271 MIRBuilder.setMBB(*FalseMBB);
273 // handle default case
274 const BasicBlock *DefaultBB = SwInst.getDefaultDest();
275 MachineBasicBlock &DefaultMBB = getOrCreateBB(*DefaultBB);
276 MIRBuilder.buildBr(DefaultMBB);
277 MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
278 CurMBB.addSuccessor(&DefaultMBB);
279 addMachineCFGPred({OrigBB, DefaultBB}, &CurMBB);
284 bool IRTranslator::translateIndirectBr(const User &U,
285 MachineIRBuilder &MIRBuilder) {
286 const IndirectBrInst &BrInst = cast<IndirectBrInst>(U);
288 const unsigned Tgt = getOrCreateVReg(*BrInst.getAddress());
289 MIRBuilder.buildBrIndirect(Tgt);
292 MachineBasicBlock &CurBB = MIRBuilder.getMBB();
293 for (const BasicBlock *Succ : BrInst.successors())
294 CurBB.addSuccessor(&getOrCreateBB(*Succ));
299 bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) {
300 const LoadInst &LI = cast<LoadInst>(U);
302 auto Flags = LI.isVolatile() ? MachineMemOperand::MOVolatile
303 : MachineMemOperand::MONone;
304 Flags |= MachineMemOperand::MOLoad;
306 unsigned Res = getOrCreateVReg(LI);
307 unsigned Addr = getOrCreateVReg(*LI.getPointerOperand());
309 MIRBuilder.buildLoad(
311 *MF->getMachineMemOperand(MachinePointerInfo(LI.getPointerOperand()),
312 Flags, DL->getTypeStoreSize(LI.getType()),
313 getMemOpAlignment(LI), AAMDNodes(), nullptr,
314 LI.getSynchScope(), LI.getOrdering()));
318 bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) {
319 const StoreInst &SI = cast<StoreInst>(U);
320 auto Flags = SI.isVolatile() ? MachineMemOperand::MOVolatile
321 : MachineMemOperand::MONone;
322 Flags |= MachineMemOperand::MOStore;
324 unsigned Val = getOrCreateVReg(*SI.getValueOperand());
325 unsigned Addr = getOrCreateVReg(*SI.getPointerOperand());
327 MIRBuilder.buildStore(
329 *MF->getMachineMemOperand(
330 MachinePointerInfo(SI.getPointerOperand()), Flags,
331 DL->getTypeStoreSize(SI.getValueOperand()->getType()),
332 getMemOpAlignment(SI), AAMDNodes(), nullptr, SI.getSynchScope(),
337 bool IRTranslator::translateExtractValue(const User &U,
338 MachineIRBuilder &MIRBuilder) {
339 const Value *Src = U.getOperand(0);
340 Type *Int32Ty = Type::getInt32Ty(U.getContext());
341 SmallVector<Value *, 1> Indices;
343 // getIndexedOffsetInType is designed for GEPs, so the first index is the
344 // usual array element rather than looking into the actual aggregate.
345 Indices.push_back(ConstantInt::get(Int32Ty, 0));
347 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) {
348 for (auto Idx : EVI->indices())
349 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
351 for (unsigned i = 1; i < U.getNumOperands(); ++i)
352 Indices.push_back(U.getOperand(i));
355 uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices);
357 unsigned Res = getOrCreateVReg(U);
358 MIRBuilder.buildExtract(Res, getOrCreateVReg(*Src), Offset);
363 bool IRTranslator::translateInsertValue(const User &U,
364 MachineIRBuilder &MIRBuilder) {
365 const Value *Src = U.getOperand(0);
366 Type *Int32Ty = Type::getInt32Ty(U.getContext());
367 SmallVector<Value *, 1> Indices;
369 // getIndexedOffsetInType is designed for GEPs, so the first index is the
370 // usual array element rather than looking into the actual aggregate.
371 Indices.push_back(ConstantInt::get(Int32Ty, 0));
373 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) {
374 for (auto Idx : IVI->indices())
375 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
377 for (unsigned i = 2; i < U.getNumOperands(); ++i)
378 Indices.push_back(U.getOperand(i));
381 uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices);
383 unsigned Res = getOrCreateVReg(U);
384 const Value &Inserted = *U.getOperand(1);
385 MIRBuilder.buildInsert(Res, getOrCreateVReg(*Src), getOrCreateVReg(Inserted),
391 bool IRTranslator::translateSelect(const User &U,
392 MachineIRBuilder &MIRBuilder) {
393 MIRBuilder.buildSelect(getOrCreateVReg(U), getOrCreateVReg(*U.getOperand(0)),
394 getOrCreateVReg(*U.getOperand(1)),
395 getOrCreateVReg(*U.getOperand(2)));
399 bool IRTranslator::translateBitCast(const User &U,
400 MachineIRBuilder &MIRBuilder) {
401 // If we're bitcasting to the source type, we can reuse the source vreg.
402 if (getLLTForType(*U.getOperand(0)->getType(), *DL) ==
403 getLLTForType(*U.getType(), *DL)) {
404 // Get the source vreg now, to avoid invalidating ValToVReg.
405 unsigned SrcReg = getOrCreateVReg(*U.getOperand(0));
406 unsigned &Reg = ValToVReg[&U];
407 // If we already assigned a vreg for this bitcast, we can't change that.
408 // Emit a copy to satisfy the users we already emitted.
410 MIRBuilder.buildCopy(Reg, SrcReg);
415 return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder);
418 bool IRTranslator::translateCast(unsigned Opcode, const User &U,
419 MachineIRBuilder &MIRBuilder) {
420 unsigned Op = getOrCreateVReg(*U.getOperand(0));
421 unsigned Res = getOrCreateVReg(U);
422 MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op);
426 bool IRTranslator::translateGetElementPtr(const User &U,
427 MachineIRBuilder &MIRBuilder) {
428 // FIXME: support vector GEPs.
429 if (U.getType()->isVectorTy())
432 Value &Op0 = *U.getOperand(0);
433 unsigned BaseReg = getOrCreateVReg(Op0);
434 LLT PtrTy = getLLTForType(*Op0.getType(), *DL);
435 unsigned PtrSize = DL->getPointerSizeInBits(PtrTy.getAddressSpace());
436 LLT OffsetTy = LLT::scalar(PtrSize);
439 for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U);
441 const Value *Idx = GTI.getOperand();
442 if (StructType *StTy = GTI.getStructTypeOrNull()) {
443 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
444 Offset += DL->getStructLayout(StTy)->getElementOffset(Field);
447 uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
449 // If this is a scalar constant or a splat vector of constants,
450 // handle it quickly.
451 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
452 Offset += ElementSize * CI->getSExtValue();
457 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
458 unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
459 MIRBuilder.buildConstant(OffsetReg, Offset);
460 MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg);
462 BaseReg = NewBaseReg;
466 // N = N + Idx * ElementSize;
467 unsigned ElementSizeReg = MRI->createGenericVirtualRegister(OffsetTy);
468 MIRBuilder.buildConstant(ElementSizeReg, ElementSize);
470 unsigned IdxReg = getOrCreateVReg(*Idx);
471 if (MRI->getType(IdxReg) != OffsetTy) {
472 unsigned NewIdxReg = MRI->createGenericVirtualRegister(OffsetTy);
473 MIRBuilder.buildSExtOrTrunc(NewIdxReg, IdxReg);
477 unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
478 MIRBuilder.buildMul(OffsetReg, ElementSizeReg, IdxReg);
480 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
481 MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg);
482 BaseReg = NewBaseReg;
487 unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
488 MIRBuilder.buildConstant(OffsetReg, Offset);
489 MIRBuilder.buildGEP(getOrCreateVReg(U), BaseReg, OffsetReg);
493 MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg);
497 bool IRTranslator::translateMemfunc(const CallInst &CI,
498 MachineIRBuilder &MIRBuilder,
500 LLT SizeTy = getLLTForType(*CI.getArgOperand(2)->getType(), *DL);
501 Type *DstTy = CI.getArgOperand(0)->getType();
502 if (cast<PointerType>(DstTy)->getAddressSpace() != 0 ||
503 SizeTy.getSizeInBits() != DL->getPointerSizeInBits(0))
506 SmallVector<CallLowering::ArgInfo, 8> Args;
507 for (int i = 0; i < 3; ++i) {
508 const auto &Arg = CI.getArgOperand(i);
509 Args.emplace_back(getOrCreateVReg(*Arg), Arg->getType());
514 case Intrinsic::memmove:
515 case Intrinsic::memcpy: {
516 Type *SrcTy = CI.getArgOperand(1)->getType();
517 if(cast<PointerType>(SrcTy)->getAddressSpace() != 0)
519 Callee = ID == Intrinsic::memcpy ? "memcpy" : "memmove";
522 case Intrinsic::memset:
529 return CLI->lowerCall(MIRBuilder, MachineOperand::CreateES(Callee),
530 CallLowering::ArgInfo(0, CI.getType()), Args);
533 void IRTranslator::getStackGuard(unsigned DstReg,
534 MachineIRBuilder &MIRBuilder) {
535 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
536 MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF));
537 auto MIB = MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD);
540 auto &TLI = *MF->getSubtarget().getTargetLowering();
541 Value *Global = TLI.getSDagStackGuard(*MF->getFunction()->getParent());
545 MachinePointerInfo MPInfo(Global);
546 MachineInstr::mmo_iterator MemRefs = MF->allocateMemRefsArray(1);
547 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
548 MachineMemOperand::MODereferenceable;
550 MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8,
551 DL->getPointerABIAlignment());
552 MIB.setMemRefs(MemRefs, MemRefs + 1);
555 bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op,
556 MachineIRBuilder &MIRBuilder) {
557 LLT Ty = getLLTForType(*CI.getOperand(0)->getType(), *DL);
558 LLT s1 = LLT::scalar(1);
559 unsigned Width = Ty.getSizeInBits();
560 unsigned Res = MRI->createGenericVirtualRegister(Ty);
561 unsigned Overflow = MRI->createGenericVirtualRegister(s1);
562 auto MIB = MIRBuilder.buildInstr(Op)
565 .addUse(getOrCreateVReg(*CI.getOperand(0)))
566 .addUse(getOrCreateVReg(*CI.getOperand(1)));
568 if (Op == TargetOpcode::G_UADDE || Op == TargetOpcode::G_USUBE) {
569 unsigned Zero = MRI->createGenericVirtualRegister(s1);
570 EntryBuilder.buildConstant(Zero, 0);
574 MIRBuilder.buildSequence(getOrCreateVReg(CI), Res, 0, Overflow, Width);
578 bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID,
579 MachineIRBuilder &MIRBuilder) {
583 case Intrinsic::lifetime_start:
584 case Intrinsic::lifetime_end:
585 // Stack coloring is not enabled in O0 (which we care about now) so we can
586 // drop these. Make sure someone notices when we start compiling at higher
588 if (MF->getTarget().getOptLevel() != CodeGenOpt::None)
591 case Intrinsic::dbg_declare: {
592 const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI);
593 assert(DI.getVariable() && "Missing variable");
595 const Value *Address = DI.getAddress();
596 if (!Address || isa<UndefValue>(Address)) {
597 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
601 assert(DI.getVariable()->isValidLocationForIntrinsic(
602 MIRBuilder.getDebugLoc()) &&
603 "Expected inlined-at fields to agree");
604 auto AI = dyn_cast<AllocaInst>(Address);
605 if (AI && AI->isStaticAlloca()) {
606 // Static allocas are tracked at the MF level, no need for DBG_VALUE
607 // instructions (in fact, they get ignored if they *do* exist).
608 MF->setVariableDbgInfo(DI.getVariable(), DI.getExpression(),
609 getOrCreateFrameIndex(*AI), DI.getDebugLoc());
611 MIRBuilder.buildDirectDbgValue(getOrCreateVReg(*Address),
612 DI.getVariable(), DI.getExpression());
615 case Intrinsic::vaend:
616 // No target I know of cares about va_end. Certainly no in-tree target
617 // does. Simplest intrinsic ever!
619 case Intrinsic::vastart: {
620 auto &TLI = *MF->getSubtarget().getTargetLowering();
621 Value *Ptr = CI.getArgOperand(0);
622 unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8;
624 MIRBuilder.buildInstr(TargetOpcode::G_VASTART)
625 .addUse(getOrCreateVReg(*Ptr))
626 .addMemOperand(MF->getMachineMemOperand(
627 MachinePointerInfo(Ptr), MachineMemOperand::MOStore, ListSize, 0));
630 case Intrinsic::dbg_value: {
631 // This form of DBG_VALUE is target-independent.
632 const DbgValueInst &DI = cast<DbgValueInst>(CI);
633 const Value *V = DI.getValue();
634 assert(DI.getVariable()->isValidLocationForIntrinsic(
635 MIRBuilder.getDebugLoc()) &&
636 "Expected inlined-at fields to agree");
638 // Currently the optimizer can produce this; insert an undef to
639 // help debugging. Probably the optimizer should not do this.
640 MIRBuilder.buildIndirectDbgValue(0, DI.getOffset(), DI.getVariable(),
642 } else if (const auto *CI = dyn_cast<Constant>(V)) {
643 MIRBuilder.buildConstDbgValue(*CI, DI.getOffset(), DI.getVariable(),
646 unsigned Reg = getOrCreateVReg(*V);
647 // FIXME: This does not handle register-indirect values at offset 0. The
648 // direct/indirect thing shouldn't really be handled by something as
649 // implicit as reg+noreg vs reg+imm in the first palce, but it seems
650 // pretty baked in right now.
651 if (DI.getOffset() != 0)
652 MIRBuilder.buildIndirectDbgValue(Reg, DI.getOffset(), DI.getVariable(),
655 MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(),
660 case Intrinsic::uadd_with_overflow:
661 return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDE, MIRBuilder);
662 case Intrinsic::sadd_with_overflow:
663 return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder);
664 case Intrinsic::usub_with_overflow:
665 return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBE, MIRBuilder);
666 case Intrinsic::ssub_with_overflow:
667 return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder);
668 case Intrinsic::umul_with_overflow:
669 return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder);
670 case Intrinsic::smul_with_overflow:
671 return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder);
673 MIRBuilder.buildInstr(TargetOpcode::G_FPOW)
674 .addDef(getOrCreateVReg(CI))
675 .addUse(getOrCreateVReg(*CI.getArgOperand(0)))
676 .addUse(getOrCreateVReg(*CI.getArgOperand(1)));
678 case Intrinsic::memcpy:
679 case Intrinsic::memmove:
680 case Intrinsic::memset:
681 return translateMemfunc(CI, MIRBuilder, ID);
682 case Intrinsic::eh_typeid_for: {
683 GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0));
684 unsigned Reg = getOrCreateVReg(CI);
685 unsigned TypeID = MF->getTypeIDFor(GV);
686 MIRBuilder.buildConstant(Reg, TypeID);
689 case Intrinsic::objectsize: {
690 // If we don't know by now, we're never going to know.
691 const ConstantInt *Min = cast<ConstantInt>(CI.getArgOperand(1));
693 MIRBuilder.buildConstant(getOrCreateVReg(CI), Min->isZero() ? -1ULL : 0);
696 case Intrinsic::stackguard:
697 getStackGuard(getOrCreateVReg(CI), MIRBuilder);
699 case Intrinsic::stackprotector: {
700 LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
701 unsigned GuardVal = MRI->createGenericVirtualRegister(PtrTy);
702 getStackGuard(GuardVal, MIRBuilder);
704 AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1));
705 MIRBuilder.buildStore(
706 GuardVal, getOrCreateVReg(*Slot),
707 *MF->getMachineMemOperand(
708 MachinePointerInfo::getFixedStack(*MF,
709 getOrCreateFrameIndex(*Slot)),
710 MachineMemOperand::MOStore | MachineMemOperand::MOVolatile,
711 PtrTy.getSizeInBits() / 8, 8));
718 bool IRTranslator::translateInlineAsm(const CallInst &CI,
719 MachineIRBuilder &MIRBuilder) {
720 const InlineAsm &IA = cast<InlineAsm>(*CI.getCalledValue());
721 if (!IA.getConstraintString().empty())
724 unsigned ExtraInfo = 0;
725 if (IA.hasSideEffects())
726 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
727 if (IA.getDialect() == InlineAsm::AD_Intel)
728 ExtraInfo |= InlineAsm::Extra_AsmDialect;
730 MIRBuilder.buildInstr(TargetOpcode::INLINEASM)
731 .addExternalSymbol(IA.getAsmString().c_str())
737 bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) {
738 const CallInst &CI = cast<CallInst>(U);
739 auto TII = MF->getTarget().getIntrinsicInfo();
740 const Function *F = CI.getCalledFunction();
742 if (CI.isInlineAsm())
743 return translateInlineAsm(CI, MIRBuilder);
745 if (!F || !F->isIntrinsic()) {
746 unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI);
747 SmallVector<unsigned, 8> Args;
748 for (auto &Arg: CI.arg_operands())
749 Args.push_back(getOrCreateVReg(*Arg));
751 MF->getFrameInfo().setHasCalls(true);
752 return CLI->lowerCall(MIRBuilder, &CI, Res, Args, [&]() {
753 return getOrCreateVReg(*CI.getCalledValue());
757 Intrinsic::ID ID = F->getIntrinsicID();
758 if (TII && ID == Intrinsic::not_intrinsic)
759 ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F));
761 assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
763 if (translateKnownIntrinsic(CI, ID, MIRBuilder))
766 unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI);
767 MachineInstrBuilder MIB =
768 MIRBuilder.buildIntrinsic(ID, Res, !CI.doesNotAccessMemory());
770 for (auto &Arg : CI.arg_operands()) {
771 // Some intrinsics take metadata parameters. Reject them.
772 if (isa<MetadataAsValue>(Arg))
774 if (ConstantInt *CI = dyn_cast<ConstantInt>(Arg))
775 MIB.addImm(CI->getSExtValue());
777 MIB.addUse(getOrCreateVReg(*Arg));
782 bool IRTranslator::translateInvoke(const User &U,
783 MachineIRBuilder &MIRBuilder) {
784 const InvokeInst &I = cast<InvokeInst>(U);
785 MCContext &Context = MF->getContext();
787 const BasicBlock *ReturnBB = I.getSuccessor(0);
788 const BasicBlock *EHPadBB = I.getSuccessor(1);
790 const Value *Callee = I.getCalledValue();
791 const Function *Fn = dyn_cast<Function>(Callee);
792 if (isa<InlineAsm>(Callee))
795 // FIXME: support invoking patchpoint and statepoint intrinsics.
796 if (Fn && Fn->isIntrinsic())
799 // FIXME: support whatever these are.
800 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
803 // FIXME: support Windows exception handling.
804 if (!isa<LandingPadInst>(EHPadBB->front()))
808 // Emit the actual call, bracketed by EH_LABELs so that the MF knows about
809 // the region covered by the try.
810 MCSymbol *BeginSymbol = Context.createTempSymbol();
811 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol);
813 unsigned Res = I.getType()->isVoidTy() ? 0 : getOrCreateVReg(I);
814 SmallVector<unsigned, 8> Args;
815 for (auto &Arg: I.arg_operands())
816 Args.push_back(getOrCreateVReg(*Arg));
818 if (!CLI->lowerCall(MIRBuilder, &I, Res, Args,
819 [&]() { return getOrCreateVReg(*I.getCalledValue()); }))
822 MCSymbol *EndSymbol = Context.createTempSymbol();
823 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol);
825 // FIXME: track probabilities.
826 MachineBasicBlock &EHPadMBB = getOrCreateBB(*EHPadBB),
827 &ReturnMBB = getOrCreateBB(*ReturnBB);
828 MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
829 MIRBuilder.getMBB().addSuccessor(&ReturnMBB);
830 MIRBuilder.getMBB().addSuccessor(&EHPadMBB);
831 MIRBuilder.buildBr(ReturnMBB);
836 bool IRTranslator::translateLandingPad(const User &U,
837 MachineIRBuilder &MIRBuilder) {
838 const LandingPadInst &LP = cast<LandingPadInst>(U);
840 MachineBasicBlock &MBB = MIRBuilder.getMBB();
841 addLandingPadInfo(LP, MBB);
845 // If there aren't registers to copy the values into (e.g., during SjLj
846 // exceptions), then don't bother.
847 auto &TLI = *MF->getSubtarget().getTargetLowering();
848 const Constant *PersonalityFn = MF->getFunction()->getPersonalityFn();
849 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
850 TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
853 // If landingpad's return type is token type, we don't create DAG nodes
854 // for its exception pointer and selector value. The extraction of exception
855 // pointer or selector value from token type landingpads is not currently
857 if (LP.getType()->isTokenTy())
860 // Add a label to mark the beginning of the landing pad. Deletion of the
861 // landing pad can thus be detected via the MachineModuleInfo.
862 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL)
863 .addSym(MF->addLandingPad(&MBB));
865 LLT Ty = getLLTForType(*LP.getType(), *DL);
866 unsigned Undef = MRI->createGenericVirtualRegister(Ty);
867 MIRBuilder.buildUndef(Undef);
869 SmallVector<LLT, 2> Tys;
870 for (Type *Ty : cast<StructType>(LP.getType())->elements())
871 Tys.push_back(getLLTForType(*Ty, *DL));
872 assert(Tys.size() == 2 && "Only two-valued landingpads are supported");
874 // Mark exception register as live in.
875 unsigned ExceptionReg = TLI.getExceptionPointerRegister(PersonalityFn);
879 MBB.addLiveIn(ExceptionReg);
880 unsigned VReg = MRI->createGenericVirtualRegister(Tys[0]),
881 Tmp = MRI->createGenericVirtualRegister(Ty);
882 MIRBuilder.buildCopy(VReg, ExceptionReg);
883 MIRBuilder.buildInsert(Tmp, Undef, VReg, 0);
885 unsigned SelectorReg = TLI.getExceptionSelectorRegister(PersonalityFn);
889 MBB.addLiveIn(SelectorReg);
891 // N.b. the exception selector register always has pointer type and may not
892 // match the actual IR-level type in the landingpad so an extra cast is
894 unsigned PtrVReg = MRI->createGenericVirtualRegister(Tys[0]);
895 MIRBuilder.buildCopy(PtrVReg, SelectorReg);
897 VReg = MRI->createGenericVirtualRegister(Tys[1]);
898 MIRBuilder.buildInstr(TargetOpcode::G_PTRTOINT).addDef(VReg).addUse(PtrVReg);
899 MIRBuilder.buildInsert(getOrCreateVReg(LP), Tmp, VReg,
900 Tys[0].getSizeInBits());
904 bool IRTranslator::translateAlloca(const User &U,
905 MachineIRBuilder &MIRBuilder) {
906 auto &AI = cast<AllocaInst>(U);
908 if (AI.isStaticAlloca()) {
909 unsigned Res = getOrCreateVReg(AI);
910 int FI = getOrCreateFrameIndex(AI);
911 MIRBuilder.buildFrameIndex(Res, FI);
915 // Now we're in the harder dynamic case.
916 Type *Ty = AI.getAllocatedType();
918 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI.getAlignment());
920 unsigned NumElts = getOrCreateVReg(*AI.getArraySize());
922 LLT IntPtrTy = LLT::scalar(DL->getPointerSizeInBits());
923 if (MRI->getType(NumElts) != IntPtrTy) {
924 unsigned ExtElts = MRI->createGenericVirtualRegister(IntPtrTy);
925 MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts);
929 unsigned AllocSize = MRI->createGenericVirtualRegister(IntPtrTy);
930 unsigned TySize = MRI->createGenericVirtualRegister(IntPtrTy);
931 MIRBuilder.buildConstant(TySize, -DL->getTypeAllocSize(Ty));
932 MIRBuilder.buildMul(AllocSize, NumElts, TySize);
934 LLT PtrTy = getLLTForType(*AI.getType(), *DL);
935 auto &TLI = *MF->getSubtarget().getTargetLowering();
936 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
938 unsigned SPTmp = MRI->createGenericVirtualRegister(PtrTy);
939 MIRBuilder.buildCopy(SPTmp, SPReg);
941 unsigned AllocTmp = MRI->createGenericVirtualRegister(PtrTy);
942 MIRBuilder.buildGEP(AllocTmp, SPTmp, AllocSize);
944 // Handle alignment. We have to realign if the allocation granule was smaller
945 // than stack alignment, or the specific alloca requires more than stack
947 unsigned StackAlign =
948 MF->getSubtarget().getFrameLowering()->getStackAlignment();
949 Align = std::max(Align, StackAlign);
950 if (Align > StackAlign || DL->getTypeAllocSize(Ty) % StackAlign != 0) {
951 // Round the size of the allocation up to the stack alignment size
952 // by add SA-1 to the size. This doesn't overflow because we're computing
953 // an address inside an alloca.
954 unsigned AlignedAlloc = MRI->createGenericVirtualRegister(PtrTy);
955 MIRBuilder.buildPtrMask(AlignedAlloc, AllocTmp, Log2_32(Align));
956 AllocTmp = AlignedAlloc;
959 MIRBuilder.buildCopy(SPReg, AllocTmp);
960 MIRBuilder.buildCopy(getOrCreateVReg(AI), AllocTmp);
962 MF->getFrameInfo().CreateVariableSizedObject(Align ? Align : 1, &AI);
963 assert(MF->getFrameInfo().hasVarSizedObjects());
967 bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) {
968 // FIXME: We may need more info about the type. Because of how LLT works,
969 // we're completely discarding the i64/double distinction here (amongst
970 // others). Fortunately the ABIs I know of where that matters don't use va_arg
971 // anyway but that's not guaranteed.
972 MIRBuilder.buildInstr(TargetOpcode::G_VAARG)
973 .addDef(getOrCreateVReg(U))
974 .addUse(getOrCreateVReg(*U.getOperand(0)))
975 .addImm(DL->getABITypeAlignment(U.getType()));
979 bool IRTranslator::translateInsertElement(const User &U,
980 MachineIRBuilder &MIRBuilder) {
981 // If it is a <1 x Ty> vector, use the scalar as it is
982 // not a legal vector type in LLT.
983 if (U.getType()->getVectorNumElements() == 1) {
984 unsigned Elt = getOrCreateVReg(*U.getOperand(1));
988 MIRBuilder.buildInsertVectorElement(
989 getOrCreateVReg(U), getOrCreateVReg(*U.getOperand(0)),
990 getOrCreateVReg(*U.getOperand(1)), getOrCreateVReg(*U.getOperand(2)));
994 bool IRTranslator::translateExtractElement(const User &U,
995 MachineIRBuilder &MIRBuilder) {
996 // If it is a <1 x Ty> vector, use the scalar as it is
997 // not a legal vector type in LLT.
998 if (U.getOperand(0)->getType()->getVectorNumElements() == 1) {
999 unsigned Elt = getOrCreateVReg(*U.getOperand(0));
1000 ValToVReg[&U] = Elt;
1003 MIRBuilder.buildExtractVectorElement(getOrCreateVReg(U),
1004 getOrCreateVReg(*U.getOperand(0)),
1005 getOrCreateVReg(*U.getOperand(1)));
1009 bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) {
1010 const PHINode &PI = cast<PHINode>(U);
1011 auto MIB = MIRBuilder.buildInstr(TargetOpcode::PHI);
1012 MIB.addDef(getOrCreateVReg(PI));
1014 PendingPHIs.emplace_back(&PI, MIB.getInstr());
1018 void IRTranslator::finishPendingPhis() {
1019 for (std::pair<const PHINode *, MachineInstr *> &Phi : PendingPHIs) {
1020 const PHINode *PI = Phi.first;
1021 MachineInstrBuilder MIB(*MF, Phi.second);
1023 // All MachineBasicBlocks exist, add them to the PHI. We assume IRTranslator
1024 // won't create extra control flow here, otherwise we need to find the
1025 // dominating predecessor here (or perhaps force the weirder IRTranslators
1026 // to provide a simple boundary).
1027 SmallSet<const BasicBlock *, 4> HandledPreds;
1029 for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
1030 auto IRPred = PI->getIncomingBlock(i);
1031 if (HandledPreds.count(IRPred))
1034 HandledPreds.insert(IRPred);
1035 unsigned ValReg = getOrCreateVReg(*PI->getIncomingValue(i));
1036 for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) {
1037 assert(Pred->isSuccessor(MIB->getParent()) &&
1038 "incorrect CFG at MachineBasicBlock level");
1046 bool IRTranslator::translate(const Instruction &Inst) {
1047 CurBuilder.setDebugLoc(Inst.getDebugLoc());
1048 switch(Inst.getOpcode()) {
1049 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1050 case Instruction::OPCODE: return translate##OPCODE(Inst, CurBuilder);
1051 #include "llvm/IR/Instruction.def"
1057 bool IRTranslator::translate(const Constant &C, unsigned Reg) {
1058 if (auto CI = dyn_cast<ConstantInt>(&C))
1059 EntryBuilder.buildConstant(Reg, *CI);
1060 else if (auto CF = dyn_cast<ConstantFP>(&C))
1061 EntryBuilder.buildFConstant(Reg, *CF);
1062 else if (isa<UndefValue>(C))
1063 EntryBuilder.buildUndef(Reg);
1064 else if (isa<ConstantPointerNull>(C))
1065 EntryBuilder.buildConstant(Reg, 0);
1066 else if (auto GV = dyn_cast<GlobalValue>(&C))
1067 EntryBuilder.buildGlobalValue(Reg, GV);
1068 else if (auto CAZ = dyn_cast<ConstantAggregateZero>(&C)) {
1069 if (!CAZ->getType()->isVectorTy())
1071 // Return the scalar if it is a <1 x Ty> vector.
1072 if (CAZ->getNumElements() == 1)
1073 return translate(*CAZ->getElementValue(0u), Reg);
1074 std::vector<unsigned> Ops;
1075 for (unsigned i = 0; i < CAZ->getNumElements(); ++i) {
1076 Constant &Elt = *CAZ->getElementValue(i);
1077 Ops.push_back(getOrCreateVReg(Elt));
1079 EntryBuilder.buildMerge(Reg, Ops);
1080 } else if (auto CV = dyn_cast<ConstantDataVector>(&C)) {
1081 // Return the scalar if it is a <1 x Ty> vector.
1082 if (CV->getNumElements() == 1)
1083 return translate(*CV->getElementAsConstant(0), Reg);
1084 std::vector<unsigned> Ops;
1085 for (unsigned i = 0; i < CV->getNumElements(); ++i) {
1086 Constant &Elt = *CV->getElementAsConstant(i);
1087 Ops.push_back(getOrCreateVReg(Elt));
1089 EntryBuilder.buildMerge(Reg, Ops);
1090 } else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
1091 switch(CE->getOpcode()) {
1092 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1093 case Instruction::OPCODE: return translate##OPCODE(*CE, EntryBuilder);
1094 #include "llvm/IR/Instruction.def"
1104 void IRTranslator::finalizeFunction() {
1105 // Release the memory used by the different maps we
1106 // needed during the translation.
1107 PendingPHIs.clear();
1109 FrameIndices.clear();
1111 MachinePreds.clear();
1114 bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) {
1116 const Function &F = *MF->getFunction();
1119 CLI = MF->getSubtarget().getCallLowering();
1120 CurBuilder.setMF(*MF);
1121 EntryBuilder.setMF(*MF);
1122 MRI = &MF->getRegInfo();
1123 DL = &F.getParent()->getDataLayout();
1124 TPC = &getAnalysis<TargetPassConfig>();
1125 ORE = make_unique<OptimizationRemarkEmitter>(&F);
1127 assert(PendingPHIs.empty() && "stale PHIs");
1129 // Release the per-function state when we return, whether we succeeded or not.
1130 auto FinalizeOnReturn = make_scope_exit([this]() { finalizeFunction(); });
1132 // Setup a separate basic-block for the arguments and constants, falling
1133 // through to the IR-level Function's entry block.
1134 MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock();
1135 MF->push_back(EntryBB);
1136 EntryBB->addSuccessor(&getOrCreateBB(F.front()));
1137 EntryBuilder.setMBB(*EntryBB);
1139 // Lower the actual args into this basic block.
1140 SmallVector<unsigned, 8> VRegArgs;
1141 for (const Argument &Arg: F.args())
1142 VRegArgs.push_back(getOrCreateVReg(Arg));
1143 if (!CLI->lowerFormalArguments(EntryBuilder, F, VRegArgs)) {
1144 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1145 MF->getFunction()->getSubprogram(),
1146 &MF->getFunction()->getEntryBlock());
1147 R << "unable to lower arguments: " << ore::NV("Prototype", F.getType());
1148 reportTranslationError(*MF, *TPC, *ORE, R);
1152 // And translate the function!
1153 for (const BasicBlock &BB: F) {
1154 MachineBasicBlock &MBB = getOrCreateBB(BB);
1155 // Set the insertion point of all the following translations to
1156 // the end of this basic block.
1157 CurBuilder.setMBB(MBB);
1159 for (const Instruction &Inst: BB) {
1160 if (translate(Inst))
1163 std::string InstStrStorage;
1164 raw_string_ostream InstStr(InstStrStorage);
1167 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1168 Inst.getDebugLoc(), &BB);
1169 R << "unable to translate instruction: " << ore::NV("Opcode", &Inst)
1170 << ": '" << InstStr.str() << "'";
1171 reportTranslationError(*MF, *TPC, *ORE, R);
1176 finishPendingPhis();
1178 // Now that the MachineFrameInfo has been configured, no further changes to
1179 // the reserved registers are possible.
1180 MRI->freezeReservedRegs(*MF);
1182 // Merge the argument lowering and constants block with its single
1183 // successor, the LLVM-IR entry block. We want the basic block to
1185 assert(EntryBB->succ_size() == 1 &&
1186 "Custom BB used for lowering should have only one successor");
1187 // Get the successor of the current entry block.
1188 MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin();
1189 assert(NewEntryBB.pred_size() == 1 &&
1190 "LLVM-IR entry block has a predecessor!?");
1191 // Move all the instruction from the current entry block to the
1193 NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(),
1196 // Update the live-in information for the new entry block.
1197 for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins())
1198 NewEntryBB.addLiveIn(LiveIn);
1199 NewEntryBB.sortUniqueLiveIns();
1201 // Get rid of the now empty basic block.
1202 EntryBB->removeSuccessor(&NewEntryBB);
1203 MF->remove(EntryBB);
1204 MF->DeleteMachineBasicBlock(EntryBB);
1206 assert(&MF->front() == &NewEntryBB &&
1207 "New entry wasn't next in the list of basic block!");