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());
197 if (CmpInst::isIntPredicate(Pred))
198 MIRBuilder.buildICmp(Pred, Res, Op0, Op1);
200 MIRBuilder.buildFCmp(Pred, Res, Op0, Op1);
205 bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) {
206 const ReturnInst &RI = cast<ReturnInst>(U);
207 const Value *Ret = RI.getReturnValue();
208 // The target may mess up with the insertion point, but
209 // this is not important as a return is the last instruction
210 // of the block anyway.
211 return CLI->lowerReturn(MIRBuilder, Ret, !Ret ? 0 : getOrCreateVReg(*Ret));
214 bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) {
215 const BranchInst &BrInst = cast<BranchInst>(U);
217 if (!BrInst.isUnconditional()) {
218 // We want a G_BRCOND to the true BB followed by an unconditional branch.
219 unsigned Tst = getOrCreateVReg(*BrInst.getCondition());
220 const BasicBlock &TrueTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ++));
221 MachineBasicBlock &TrueBB = getOrCreateBB(TrueTgt);
222 MIRBuilder.buildBrCond(Tst, TrueBB);
225 const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ));
226 MachineBasicBlock &TgtBB = getOrCreateBB(BrTgt);
227 MIRBuilder.buildBr(TgtBB);
230 MachineBasicBlock &CurBB = MIRBuilder.getMBB();
231 for (const BasicBlock *Succ : BrInst.successors())
232 CurBB.addSuccessor(&getOrCreateBB(*Succ));
236 bool IRTranslator::translateSwitch(const User &U,
237 MachineIRBuilder &MIRBuilder) {
238 // For now, just translate as a chain of conditional branches.
239 // FIXME: could we share most of the logic/code in
240 // SelectionDAGBuilder::visitSwitch between SelectionDAG and GlobalISel?
241 // At first sight, it seems most of the logic in there is independent of
242 // SelectionDAG-specifics and a lot of work went in to optimize switch
243 // lowering in there.
245 const SwitchInst &SwInst = cast<SwitchInst>(U);
246 const unsigned SwCondValue = getOrCreateVReg(*SwInst.getCondition());
247 const BasicBlock *OrigBB = SwInst.getParent();
249 LLT LLTi1 = getLLTForType(*Type::getInt1Ty(U.getContext()), *DL);
250 for (auto &CaseIt : SwInst.cases()) {
251 const unsigned CaseValueReg = getOrCreateVReg(*CaseIt.getCaseValue());
252 const unsigned Tst = MRI->createGenericVirtualRegister(LLTi1);
253 MIRBuilder.buildICmp(CmpInst::ICMP_EQ, Tst, CaseValueReg, SwCondValue);
254 MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
255 const BasicBlock *TrueBB = CaseIt.getCaseSuccessor();
256 MachineBasicBlock &TrueMBB = getOrCreateBB(*TrueBB);
258 MIRBuilder.buildBrCond(Tst, TrueMBB);
259 CurMBB.addSuccessor(&TrueMBB);
260 addMachineCFGPred({OrigBB, TrueBB}, &CurMBB);
262 MachineBasicBlock *FalseMBB =
263 MF->CreateMachineBasicBlock(SwInst.getParent());
264 MF->push_back(FalseMBB);
265 MIRBuilder.buildBr(*FalseMBB);
266 CurMBB.addSuccessor(FalseMBB);
268 MIRBuilder.setMBB(*FalseMBB);
270 // handle default case
271 const BasicBlock *DefaultBB = SwInst.getDefaultDest();
272 MachineBasicBlock &DefaultMBB = getOrCreateBB(*DefaultBB);
273 MIRBuilder.buildBr(DefaultMBB);
274 MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
275 CurMBB.addSuccessor(&DefaultMBB);
276 addMachineCFGPred({OrigBB, DefaultBB}, &CurMBB);
281 bool IRTranslator::translateIndirectBr(const User &U,
282 MachineIRBuilder &MIRBuilder) {
283 const IndirectBrInst &BrInst = cast<IndirectBrInst>(U);
285 const unsigned Tgt = getOrCreateVReg(*BrInst.getAddress());
286 MIRBuilder.buildBrIndirect(Tgt);
289 MachineBasicBlock &CurBB = MIRBuilder.getMBB();
290 for (const BasicBlock *Succ : BrInst.successors())
291 CurBB.addSuccessor(&getOrCreateBB(*Succ));
296 bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) {
297 const LoadInst &LI = cast<LoadInst>(U);
299 auto Flags = LI.isVolatile() ? MachineMemOperand::MOVolatile
300 : MachineMemOperand::MONone;
301 Flags |= MachineMemOperand::MOLoad;
303 unsigned Res = getOrCreateVReg(LI);
304 unsigned Addr = getOrCreateVReg(*LI.getPointerOperand());
306 MIRBuilder.buildLoad(
308 *MF->getMachineMemOperand(MachinePointerInfo(LI.getPointerOperand()),
309 Flags, DL->getTypeStoreSize(LI.getType()),
310 getMemOpAlignment(LI), AAMDNodes(), nullptr,
311 LI.getSynchScope(), LI.getOrdering()));
315 bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) {
316 const StoreInst &SI = cast<StoreInst>(U);
317 auto Flags = SI.isVolatile() ? MachineMemOperand::MOVolatile
318 : MachineMemOperand::MONone;
319 Flags |= MachineMemOperand::MOStore;
321 unsigned Val = getOrCreateVReg(*SI.getValueOperand());
322 unsigned Addr = getOrCreateVReg(*SI.getPointerOperand());
324 MIRBuilder.buildStore(
326 *MF->getMachineMemOperand(
327 MachinePointerInfo(SI.getPointerOperand()), Flags,
328 DL->getTypeStoreSize(SI.getValueOperand()->getType()),
329 getMemOpAlignment(SI), AAMDNodes(), nullptr, SI.getSynchScope(),
334 bool IRTranslator::translateExtractValue(const User &U,
335 MachineIRBuilder &MIRBuilder) {
336 const Value *Src = U.getOperand(0);
337 Type *Int32Ty = Type::getInt32Ty(U.getContext());
338 SmallVector<Value *, 1> Indices;
340 // getIndexedOffsetInType is designed for GEPs, so the first index is the
341 // usual array element rather than looking into the actual aggregate.
342 Indices.push_back(ConstantInt::get(Int32Ty, 0));
344 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) {
345 for (auto Idx : EVI->indices())
346 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
348 for (unsigned i = 1; i < U.getNumOperands(); ++i)
349 Indices.push_back(U.getOperand(i));
352 uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices);
354 unsigned Res = getOrCreateVReg(U);
355 MIRBuilder.buildExtract(Res, getOrCreateVReg(*Src), Offset);
360 bool IRTranslator::translateInsertValue(const User &U,
361 MachineIRBuilder &MIRBuilder) {
362 const Value *Src = U.getOperand(0);
363 Type *Int32Ty = Type::getInt32Ty(U.getContext());
364 SmallVector<Value *, 1> Indices;
366 // getIndexedOffsetInType is designed for GEPs, so the first index is the
367 // usual array element rather than looking into the actual aggregate.
368 Indices.push_back(ConstantInt::get(Int32Ty, 0));
370 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) {
371 for (auto Idx : IVI->indices())
372 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
374 for (unsigned i = 2; i < U.getNumOperands(); ++i)
375 Indices.push_back(U.getOperand(i));
378 uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices);
380 unsigned Res = getOrCreateVReg(U);
381 const Value &Inserted = *U.getOperand(1);
382 MIRBuilder.buildInsert(Res, getOrCreateVReg(*Src), getOrCreateVReg(Inserted),
388 bool IRTranslator::translateSelect(const User &U,
389 MachineIRBuilder &MIRBuilder) {
390 MIRBuilder.buildSelect(getOrCreateVReg(U), getOrCreateVReg(*U.getOperand(0)),
391 getOrCreateVReg(*U.getOperand(1)),
392 getOrCreateVReg(*U.getOperand(2)));
396 bool IRTranslator::translateBitCast(const User &U,
397 MachineIRBuilder &MIRBuilder) {
398 // If we're bitcasting to the source type, we can reuse the source vreg.
399 if (getLLTForType(*U.getOperand(0)->getType(), *DL) ==
400 getLLTForType(*U.getType(), *DL)) {
401 // Get the source vreg now, to avoid invalidating ValToVReg.
402 unsigned SrcReg = getOrCreateVReg(*U.getOperand(0));
403 unsigned &Reg = ValToVReg[&U];
404 // If we already assigned a vreg for this bitcast, we can't change that.
405 // Emit a copy to satisfy the users we already emitted.
407 MIRBuilder.buildCopy(Reg, SrcReg);
412 return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder);
415 bool IRTranslator::translateCast(unsigned Opcode, const User &U,
416 MachineIRBuilder &MIRBuilder) {
417 unsigned Op = getOrCreateVReg(*U.getOperand(0));
418 unsigned Res = getOrCreateVReg(U);
419 MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op);
423 bool IRTranslator::translateGetElementPtr(const User &U,
424 MachineIRBuilder &MIRBuilder) {
425 // FIXME: support vector GEPs.
426 if (U.getType()->isVectorTy())
429 Value &Op0 = *U.getOperand(0);
430 unsigned BaseReg = getOrCreateVReg(Op0);
431 LLT PtrTy = getLLTForType(*Op0.getType(), *DL);
432 unsigned PtrSize = DL->getPointerSizeInBits(PtrTy.getAddressSpace());
433 LLT OffsetTy = LLT::scalar(PtrSize);
436 for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U);
438 const Value *Idx = GTI.getOperand();
439 if (StructType *StTy = GTI.getStructTypeOrNull()) {
440 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
441 Offset += DL->getStructLayout(StTy)->getElementOffset(Field);
444 uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
446 // If this is a scalar constant or a splat vector of constants,
447 // handle it quickly.
448 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
449 Offset += ElementSize * CI->getSExtValue();
454 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
455 unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
456 MIRBuilder.buildConstant(OffsetReg, Offset);
457 MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg);
459 BaseReg = NewBaseReg;
463 // N = N + Idx * ElementSize;
464 unsigned ElementSizeReg = MRI->createGenericVirtualRegister(OffsetTy);
465 MIRBuilder.buildConstant(ElementSizeReg, ElementSize);
467 unsigned IdxReg = getOrCreateVReg(*Idx);
468 if (MRI->getType(IdxReg) != OffsetTy) {
469 unsigned NewIdxReg = MRI->createGenericVirtualRegister(OffsetTy);
470 MIRBuilder.buildSExtOrTrunc(NewIdxReg, IdxReg);
474 unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
475 MIRBuilder.buildMul(OffsetReg, ElementSizeReg, IdxReg);
477 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
478 MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg);
479 BaseReg = NewBaseReg;
484 unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
485 MIRBuilder.buildConstant(OffsetReg, Offset);
486 MIRBuilder.buildGEP(getOrCreateVReg(U), BaseReg, OffsetReg);
490 MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg);
494 bool IRTranslator::translateMemfunc(const CallInst &CI,
495 MachineIRBuilder &MIRBuilder,
497 LLT SizeTy = getLLTForType(*CI.getArgOperand(2)->getType(), *DL);
498 Type *DstTy = CI.getArgOperand(0)->getType();
499 if (cast<PointerType>(DstTy)->getAddressSpace() != 0 ||
500 SizeTy.getSizeInBits() != DL->getPointerSizeInBits(0))
503 SmallVector<CallLowering::ArgInfo, 8> Args;
504 for (int i = 0; i < 3; ++i) {
505 const auto &Arg = CI.getArgOperand(i);
506 Args.emplace_back(getOrCreateVReg(*Arg), Arg->getType());
511 case Intrinsic::memmove:
512 case Intrinsic::memcpy: {
513 Type *SrcTy = CI.getArgOperand(1)->getType();
514 if(cast<PointerType>(SrcTy)->getAddressSpace() != 0)
516 Callee = ID == Intrinsic::memcpy ? "memcpy" : "memmove";
519 case Intrinsic::memset:
526 return CLI->lowerCall(MIRBuilder, MachineOperand::CreateES(Callee),
527 CallLowering::ArgInfo(0, CI.getType()), Args);
530 void IRTranslator::getStackGuard(unsigned DstReg,
531 MachineIRBuilder &MIRBuilder) {
532 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
533 MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF));
534 auto MIB = MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD);
537 auto &TLI = *MF->getSubtarget().getTargetLowering();
538 Value *Global = TLI.getSDagStackGuard(*MF->getFunction()->getParent());
542 MachinePointerInfo MPInfo(Global);
543 MachineInstr::mmo_iterator MemRefs = MF->allocateMemRefsArray(1);
544 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
545 MachineMemOperand::MODereferenceable;
547 MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8,
548 DL->getPointerABIAlignment());
549 MIB.setMemRefs(MemRefs, MemRefs + 1);
552 bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op,
553 MachineIRBuilder &MIRBuilder) {
554 LLT Ty = getLLTForType(*CI.getOperand(0)->getType(), *DL);
555 LLT s1 = LLT::scalar(1);
556 unsigned Width = Ty.getSizeInBits();
557 unsigned Res = MRI->createGenericVirtualRegister(Ty);
558 unsigned Overflow = MRI->createGenericVirtualRegister(s1);
559 auto MIB = MIRBuilder.buildInstr(Op)
562 .addUse(getOrCreateVReg(*CI.getOperand(0)))
563 .addUse(getOrCreateVReg(*CI.getOperand(1)));
565 if (Op == TargetOpcode::G_UADDE || Op == TargetOpcode::G_USUBE) {
566 unsigned Zero = MRI->createGenericVirtualRegister(s1);
567 EntryBuilder.buildConstant(Zero, 0);
571 MIRBuilder.buildSequence(getOrCreateVReg(CI), Res, 0, Overflow, Width);
575 bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID,
576 MachineIRBuilder &MIRBuilder) {
580 case Intrinsic::lifetime_start:
581 case Intrinsic::lifetime_end:
582 // Stack coloring is not enabled in O0 (which we care about now) so we can
583 // drop these. Make sure someone notices when we start compiling at higher
585 if (MF->getTarget().getOptLevel() != CodeGenOpt::None)
588 case Intrinsic::dbg_declare: {
589 const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI);
590 assert(DI.getVariable() && "Missing variable");
592 const Value *Address = DI.getAddress();
593 if (!Address || isa<UndefValue>(Address)) {
594 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
598 unsigned Reg = getOrCreateVReg(*Address);
599 auto RegDef = MRI->def_instr_begin(Reg);
600 assert(DI.getVariable()->isValidLocationForIntrinsic(
601 MIRBuilder.getDebugLoc()) &&
602 "Expected inlined-at fields to agree");
604 if (RegDef != MRI->def_instr_end() &&
605 RegDef->getOpcode() == TargetOpcode::G_FRAME_INDEX) {
606 MIRBuilder.buildFIDbgValue(RegDef->getOperand(1).getIndex(),
607 DI.getVariable(), DI.getExpression());
609 MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(), DI.getExpression());
612 case Intrinsic::vaend:
613 // No target I know of cares about va_end. Certainly no in-tree target
614 // does. Simplest intrinsic ever!
616 case Intrinsic::vastart: {
617 auto &TLI = *MF->getSubtarget().getTargetLowering();
618 Value *Ptr = CI.getArgOperand(0);
619 unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8;
621 MIRBuilder.buildInstr(TargetOpcode::G_VASTART)
622 .addUse(getOrCreateVReg(*Ptr))
623 .addMemOperand(MF->getMachineMemOperand(
624 MachinePointerInfo(Ptr), MachineMemOperand::MOStore, ListSize, 0));
627 case Intrinsic::dbg_value: {
628 // This form of DBG_VALUE is target-independent.
629 const DbgValueInst &DI = cast<DbgValueInst>(CI);
630 const Value *V = DI.getValue();
631 assert(DI.getVariable()->isValidLocationForIntrinsic(
632 MIRBuilder.getDebugLoc()) &&
633 "Expected inlined-at fields to agree");
635 // Currently the optimizer can produce this; insert an undef to
636 // help debugging. Probably the optimizer should not do this.
637 MIRBuilder.buildIndirectDbgValue(0, DI.getOffset(), DI.getVariable(),
639 } else if (const auto *CI = dyn_cast<Constant>(V)) {
640 MIRBuilder.buildConstDbgValue(*CI, DI.getOffset(), DI.getVariable(),
643 unsigned Reg = getOrCreateVReg(*V);
644 // FIXME: This does not handle register-indirect values at offset 0. The
645 // direct/indirect thing shouldn't really be handled by something as
646 // implicit as reg+noreg vs reg+imm in the first palce, but it seems
647 // pretty baked in right now.
648 if (DI.getOffset() != 0)
649 MIRBuilder.buildIndirectDbgValue(Reg, DI.getOffset(), DI.getVariable(),
652 MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(),
657 case Intrinsic::uadd_with_overflow:
658 return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDE, MIRBuilder);
659 case Intrinsic::sadd_with_overflow:
660 return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder);
661 case Intrinsic::usub_with_overflow:
662 return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBE, MIRBuilder);
663 case Intrinsic::ssub_with_overflow:
664 return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder);
665 case Intrinsic::umul_with_overflow:
666 return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder);
667 case Intrinsic::smul_with_overflow:
668 return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder);
670 MIRBuilder.buildInstr(TargetOpcode::G_FPOW)
671 .addDef(getOrCreateVReg(CI))
672 .addUse(getOrCreateVReg(*CI.getArgOperand(0)))
673 .addUse(getOrCreateVReg(*CI.getArgOperand(1)));
675 case Intrinsic::memcpy:
676 case Intrinsic::memmove:
677 case Intrinsic::memset:
678 return translateMemfunc(CI, MIRBuilder, ID);
679 case Intrinsic::eh_typeid_for: {
680 GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0));
681 unsigned Reg = getOrCreateVReg(CI);
682 unsigned TypeID = MF->getTypeIDFor(GV);
683 MIRBuilder.buildConstant(Reg, TypeID);
686 case Intrinsic::objectsize: {
687 // If we don't know by now, we're never going to know.
688 const ConstantInt *Min = cast<ConstantInt>(CI.getArgOperand(1));
690 MIRBuilder.buildConstant(getOrCreateVReg(CI), Min->isZero() ? -1ULL : 0);
693 case Intrinsic::stackguard:
694 getStackGuard(getOrCreateVReg(CI), MIRBuilder);
696 case Intrinsic::stackprotector: {
697 LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
698 unsigned GuardVal = MRI->createGenericVirtualRegister(PtrTy);
699 getStackGuard(GuardVal, MIRBuilder);
701 AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1));
702 MIRBuilder.buildStore(
703 GuardVal, getOrCreateVReg(*Slot),
704 *MF->getMachineMemOperand(
705 MachinePointerInfo::getFixedStack(*MF,
706 getOrCreateFrameIndex(*Slot)),
707 MachineMemOperand::MOStore | MachineMemOperand::MOVolatile,
708 PtrTy.getSizeInBits() / 8, 8));
715 bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) {
716 const CallInst &CI = cast<CallInst>(U);
717 auto TII = MF->getTarget().getIntrinsicInfo();
718 const Function *F = CI.getCalledFunction();
720 if (CI.isInlineAsm())
723 if (!F || !F->isIntrinsic()) {
724 unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI);
725 SmallVector<unsigned, 8> Args;
726 for (auto &Arg: CI.arg_operands())
727 Args.push_back(getOrCreateVReg(*Arg));
729 return CLI->lowerCall(MIRBuilder, CI, Res, Args, [&]() {
730 return getOrCreateVReg(*CI.getCalledValue());
734 Intrinsic::ID ID = F->getIntrinsicID();
735 if (TII && ID == Intrinsic::not_intrinsic)
736 ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F));
738 assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
740 if (translateKnownIntrinsic(CI, ID, MIRBuilder))
743 unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI);
744 MachineInstrBuilder MIB =
745 MIRBuilder.buildIntrinsic(ID, Res, !CI.doesNotAccessMemory());
747 for (auto &Arg : CI.arg_operands()) {
748 // Some intrinsics take metadata parameters. Reject them.
749 if (isa<MetadataAsValue>(Arg))
751 if (ConstantInt *CI = dyn_cast<ConstantInt>(Arg))
752 MIB.addImm(CI->getSExtValue());
754 MIB.addUse(getOrCreateVReg(*Arg));
759 bool IRTranslator::translateInvoke(const User &U,
760 MachineIRBuilder &MIRBuilder) {
761 const InvokeInst &I = cast<InvokeInst>(U);
762 MCContext &Context = MF->getContext();
764 const BasicBlock *ReturnBB = I.getSuccessor(0);
765 const BasicBlock *EHPadBB = I.getSuccessor(1);
767 const Value *Callee(I.getCalledValue());
768 const Function *Fn = dyn_cast<Function>(Callee);
769 if (isa<InlineAsm>(Callee))
772 // FIXME: support invoking patchpoint and statepoint intrinsics.
773 if (Fn && Fn->isIntrinsic())
776 // FIXME: support whatever these are.
777 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
780 // FIXME: support Windows exception handling.
781 if (!isa<LandingPadInst>(EHPadBB->front()))
785 // Emit the actual call, bracketed by EH_LABELs so that the MF knows about
786 // the region covered by the try.
787 MCSymbol *BeginSymbol = Context.createTempSymbol();
788 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol);
790 unsigned Res = I.getType()->isVoidTy() ? 0 : getOrCreateVReg(I);
791 SmallVector<unsigned, 8> Args;
792 for (auto &Arg: I.arg_operands())
793 Args.push_back(getOrCreateVReg(*Arg));
795 CLI->lowerCall(MIRBuilder, I, Res, Args,
796 [&]() { return getOrCreateVReg(*I.getCalledValue()); });
798 MCSymbol *EndSymbol = Context.createTempSymbol();
799 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol);
801 // FIXME: track probabilities.
802 MachineBasicBlock &EHPadMBB = getOrCreateBB(*EHPadBB),
803 &ReturnMBB = getOrCreateBB(*ReturnBB);
804 MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
805 MIRBuilder.getMBB().addSuccessor(&ReturnMBB);
806 MIRBuilder.getMBB().addSuccessor(&EHPadMBB);
807 MIRBuilder.buildBr(ReturnMBB);
812 bool IRTranslator::translateLandingPad(const User &U,
813 MachineIRBuilder &MIRBuilder) {
814 const LandingPadInst &LP = cast<LandingPadInst>(U);
816 MachineBasicBlock &MBB = MIRBuilder.getMBB();
817 addLandingPadInfo(LP, MBB);
821 // If there aren't registers to copy the values into (e.g., during SjLj
822 // exceptions), then don't bother.
823 auto &TLI = *MF->getSubtarget().getTargetLowering();
824 const Constant *PersonalityFn = MF->getFunction()->getPersonalityFn();
825 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
826 TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
829 // If landingpad's return type is token type, we don't create DAG nodes
830 // for its exception pointer and selector value. The extraction of exception
831 // pointer or selector value from token type landingpads is not currently
833 if (LP.getType()->isTokenTy())
836 // Add a label to mark the beginning of the landing pad. Deletion of the
837 // landing pad can thus be detected via the MachineModuleInfo.
838 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL)
839 .addSym(MF->addLandingPad(&MBB));
841 LLT Ty = getLLTForType(*LP.getType(), *DL);
842 unsigned Undef = MRI->createGenericVirtualRegister(Ty);
843 MIRBuilder.buildUndef(Undef);
845 SmallVector<LLT, 2> Tys;
846 for (Type *Ty : cast<StructType>(LP.getType())->elements())
847 Tys.push_back(getLLTForType(*Ty, *DL));
848 assert(Tys.size() == 2 && "Only two-valued landingpads are supported");
850 // Mark exception register as live in.
851 unsigned ExceptionReg = TLI.getExceptionPointerRegister(PersonalityFn);
855 MBB.addLiveIn(ExceptionReg);
856 unsigned VReg = MRI->createGenericVirtualRegister(Tys[0]),
857 Tmp = MRI->createGenericVirtualRegister(Ty);
858 MIRBuilder.buildCopy(VReg, ExceptionReg);
859 MIRBuilder.buildInsert(Tmp, Undef, VReg, 0);
861 unsigned SelectorReg = TLI.getExceptionSelectorRegister(PersonalityFn);
865 MBB.addLiveIn(SelectorReg);
867 // N.b. the exception selector register always has pointer type and may not
868 // match the actual IR-level type in the landingpad so an extra cast is
870 unsigned PtrVReg = MRI->createGenericVirtualRegister(Tys[0]);
871 MIRBuilder.buildCopy(PtrVReg, SelectorReg);
873 VReg = MRI->createGenericVirtualRegister(Tys[1]);
874 MIRBuilder.buildInstr(TargetOpcode::G_PTRTOINT).addDef(VReg).addUse(PtrVReg);
875 MIRBuilder.buildInsert(getOrCreateVReg(LP), Tmp, VReg,
876 Tys[0].getSizeInBits());
880 bool IRTranslator::translateAlloca(const User &U,
881 MachineIRBuilder &MIRBuilder) {
882 auto &AI = cast<AllocaInst>(U);
884 if (AI.isStaticAlloca()) {
885 unsigned Res = getOrCreateVReg(AI);
886 int FI = getOrCreateFrameIndex(AI);
887 MIRBuilder.buildFrameIndex(Res, FI);
891 // Now we're in the harder dynamic case.
892 Type *Ty = AI.getAllocatedType();
894 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI.getAlignment());
896 unsigned NumElts = getOrCreateVReg(*AI.getArraySize());
898 LLT IntPtrTy = LLT::scalar(DL->getPointerSizeInBits());
899 if (MRI->getType(NumElts) != IntPtrTy) {
900 unsigned ExtElts = MRI->createGenericVirtualRegister(IntPtrTy);
901 MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts);
905 unsigned AllocSize = MRI->createGenericVirtualRegister(IntPtrTy);
906 unsigned TySize = MRI->createGenericVirtualRegister(IntPtrTy);
907 MIRBuilder.buildConstant(TySize, -DL->getTypeAllocSize(Ty));
908 MIRBuilder.buildMul(AllocSize, NumElts, TySize);
910 LLT PtrTy = getLLTForType(*AI.getType(), *DL);
911 auto &TLI = *MF->getSubtarget().getTargetLowering();
912 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
914 unsigned SPTmp = MRI->createGenericVirtualRegister(PtrTy);
915 MIRBuilder.buildCopy(SPTmp, SPReg);
917 unsigned AllocTmp = MRI->createGenericVirtualRegister(PtrTy);
918 MIRBuilder.buildGEP(AllocTmp, SPTmp, AllocSize);
920 // Handle alignment. We have to realign if the allocation granule was smaller
921 // than stack alignment, or the specific alloca requires more than stack
923 unsigned StackAlign =
924 MF->getSubtarget().getFrameLowering()->getStackAlignment();
925 Align = std::max(Align, StackAlign);
926 if (Align > StackAlign || DL->getTypeAllocSize(Ty) % StackAlign != 0) {
927 // Round the size of the allocation up to the stack alignment size
928 // by add SA-1 to the size. This doesn't overflow because we're computing
929 // an address inside an alloca.
930 unsigned AlignedAlloc = MRI->createGenericVirtualRegister(PtrTy);
931 MIRBuilder.buildPtrMask(AlignedAlloc, AllocTmp, Log2_32(Align));
932 AllocTmp = AlignedAlloc;
935 MIRBuilder.buildCopy(SPReg, AllocTmp);
936 MIRBuilder.buildCopy(getOrCreateVReg(AI), AllocTmp);
938 MF->getFrameInfo().CreateVariableSizedObject(Align ? Align : 1, &AI);
939 assert(MF->getFrameInfo().hasVarSizedObjects());
943 bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) {
944 // FIXME: We may need more info about the type. Because of how LLT works,
945 // we're completely discarding the i64/double distinction here (amongst
946 // others). Fortunately the ABIs I know of where that matters don't use va_arg
947 // anyway but that's not guaranteed.
948 MIRBuilder.buildInstr(TargetOpcode::G_VAARG)
949 .addDef(getOrCreateVReg(U))
950 .addUse(getOrCreateVReg(*U.getOperand(0)))
951 .addImm(DL->getABITypeAlignment(U.getType()));
955 bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) {
956 const PHINode &PI = cast<PHINode>(U);
957 auto MIB = MIRBuilder.buildInstr(TargetOpcode::PHI);
958 MIB.addDef(getOrCreateVReg(PI));
960 PendingPHIs.emplace_back(&PI, MIB.getInstr());
964 void IRTranslator::finishPendingPhis() {
965 for (std::pair<const PHINode *, MachineInstr *> &Phi : PendingPHIs) {
966 const PHINode *PI = Phi.first;
967 MachineInstrBuilder MIB(*MF, Phi.second);
969 // All MachineBasicBlocks exist, add them to the PHI. We assume IRTranslator
970 // won't create extra control flow here, otherwise we need to find the
971 // dominating predecessor here (or perhaps force the weirder IRTranslators
972 // to provide a simple boundary).
973 SmallSet<const BasicBlock *, 4> HandledPreds;
975 for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
976 auto IRPred = PI->getIncomingBlock(i);
977 if (HandledPreds.count(IRPred))
980 HandledPreds.insert(IRPred);
981 unsigned ValReg = getOrCreateVReg(*PI->getIncomingValue(i));
982 for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) {
983 assert(Pred->isSuccessor(MIB->getParent()) &&
984 "incorrect CFG at MachineBasicBlock level");
992 bool IRTranslator::translate(const Instruction &Inst) {
993 CurBuilder.setDebugLoc(Inst.getDebugLoc());
994 switch(Inst.getOpcode()) {
995 #define HANDLE_INST(NUM, OPCODE, CLASS) \
996 case Instruction::OPCODE: return translate##OPCODE(Inst, CurBuilder);
997 #include "llvm/IR/Instruction.def"
999 if (!TPC->isGlobalISelAbortEnabled())
1001 llvm_unreachable("unknown opcode");
1005 bool IRTranslator::translate(const Constant &C, unsigned Reg) {
1006 if (auto CI = dyn_cast<ConstantInt>(&C))
1007 EntryBuilder.buildConstant(Reg, *CI);
1008 else if (auto CF = dyn_cast<ConstantFP>(&C))
1009 EntryBuilder.buildFConstant(Reg, *CF);
1010 else if (isa<UndefValue>(C))
1011 EntryBuilder.buildUndef(Reg);
1012 else if (isa<ConstantPointerNull>(C))
1013 EntryBuilder.buildConstant(Reg, 0);
1014 else if (auto GV = dyn_cast<GlobalValue>(&C))
1015 EntryBuilder.buildGlobalValue(Reg, GV);
1016 else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
1017 switch(CE->getOpcode()) {
1018 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1019 case Instruction::OPCODE: return translate##OPCODE(*CE, EntryBuilder);
1020 #include "llvm/IR/Instruction.def"
1022 if (!TPC->isGlobalISelAbortEnabled())
1024 llvm_unreachable("unknown opcode");
1026 } else if (!TPC->isGlobalISelAbortEnabled())
1029 llvm_unreachable("unhandled constant kind");
1034 void IRTranslator::finalizeFunction() {
1035 // Release the memory used by the different maps we
1036 // needed during the translation.
1037 PendingPHIs.clear();
1039 FrameIndices.clear();
1041 MachinePreds.clear();
1044 bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) {
1046 const Function &F = *MF->getFunction();
1049 CLI = MF->getSubtarget().getCallLowering();
1050 CurBuilder.setMF(*MF);
1051 EntryBuilder.setMF(*MF);
1052 MRI = &MF->getRegInfo();
1053 DL = &F.getParent()->getDataLayout();
1054 TPC = &getAnalysis<TargetPassConfig>();
1055 ORE = make_unique<OptimizationRemarkEmitter>(&F);
1057 assert(PendingPHIs.empty() && "stale PHIs");
1059 // Release the per-function state when we return, whether we succeeded or not.
1060 auto FinalizeOnReturn = make_scope_exit([this]() { finalizeFunction(); });
1062 // Setup a separate basic-block for the arguments and constants, falling
1063 // through to the IR-level Function's entry block.
1064 MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock();
1065 MF->push_back(EntryBB);
1066 EntryBB->addSuccessor(&getOrCreateBB(F.front()));
1067 EntryBuilder.setMBB(*EntryBB);
1069 // Lower the actual args into this basic block.
1070 SmallVector<unsigned, 8> VRegArgs;
1071 for (const Argument &Arg: F.args())
1072 VRegArgs.push_back(getOrCreateVReg(Arg));
1073 if (!CLI->lowerFormalArguments(EntryBuilder, F, VRegArgs)) {
1074 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1075 MF->getFunction()->getSubprogram(),
1076 &MF->getFunction()->getEntryBlock());
1077 R << "unable to lower arguments: " << ore::NV("Prototype", F.getType());
1078 reportTranslationError(*MF, *TPC, *ORE, R);
1082 // And translate the function!
1083 for (const BasicBlock &BB: F) {
1084 MachineBasicBlock &MBB = getOrCreateBB(BB);
1085 // Set the insertion point of all the following translations to
1086 // the end of this basic block.
1087 CurBuilder.setMBB(MBB);
1089 for (const Instruction &Inst: BB) {
1090 if (translate(Inst))
1093 std::string InstStrStorage;
1094 raw_string_ostream InstStr(InstStrStorage);
1097 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1098 Inst.getDebugLoc(), &BB);
1099 R << "unable to translate instruction: " << ore::NV("Opcode", &Inst)
1100 << ": '" << InstStr.str() << "'";
1101 reportTranslationError(*MF, *TPC, *ORE, R);
1106 finishPendingPhis();
1108 // Now that the MachineFrameInfo has been configured, no further changes to
1109 // the reserved registers are possible.
1110 MRI->freezeReservedRegs(*MF);
1112 // Merge the argument lowering and constants block with its single
1113 // successor, the LLVM-IR entry block. We want the basic block to
1115 assert(EntryBB->succ_size() == 1 &&
1116 "Custom BB used for lowering should have only one successor");
1117 // Get the successor of the current entry block.
1118 MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin();
1119 assert(NewEntryBB.pred_size() == 1 &&
1120 "LLVM-IR entry block has a predecessor!?");
1121 // Move all the instruction from the current entry block to the
1123 NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(),
1126 // Update the live-in information for the new entry block.
1127 for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins())
1128 NewEntryBB.addLiveIn(LiveIn);
1129 NewEntryBB.sortUniqueLiveIns();
1131 // Get rid of the now empty basic block.
1132 EntryBB->removeSuccessor(&NewEntryBB);
1133 MF->remove(EntryBB);
1134 MF->DeleteMachineBasicBlock(EntryBB);
1136 assert(&MF->front() == &NewEntryBB &&
1137 "New entry wasn't next in the list of basic block!");