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/SmallSet.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/CodeGen/GlobalISel/CallLowering.h"
18 #include "llvm/CodeGen/Analysis.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineModuleInfo.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/TargetPassConfig.h"
24 #include "llvm/IR/Constant.h"
25 #include "llvm/IR/DebugInfo.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/GetElementPtrTypeIterator.h"
28 #include "llvm/IR/IntrinsicInst.h"
29 #include "llvm/IR/Type.h"
30 #include "llvm/IR/Value.h"
31 #include "llvm/Target/TargetIntrinsicInfo.h"
32 #include "llvm/Target/TargetLowering.h"
34 #define DEBUG_TYPE "irtranslator"
38 char IRTranslator::ID = 0;
39 INITIALIZE_PASS_BEGIN(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
41 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
42 INITIALIZE_PASS_END(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
45 static void reportTranslationError(const Value &V, const Twine &Message) {
46 std::string ErrStorage;
47 raw_string_ostream Err(ErrStorage);
48 Err << Message << ": " << V << '\n';
49 report_fatal_error(Err.str());
52 IRTranslator::IRTranslator() : MachineFunctionPass(ID), MRI(nullptr) {
53 initializeIRTranslatorPass(*PassRegistry::getPassRegistry());
56 void IRTranslator::getAnalysisUsage(AnalysisUsage &AU) const {
57 AU.addRequired<TargetPassConfig>();
58 MachineFunctionPass::getAnalysisUsage(AU);
62 unsigned IRTranslator::getOrCreateVReg(const Value &Val) {
63 unsigned &ValReg = ValToVReg[&Val];
68 // Fill ValRegsSequence with the sequence of registers
69 // we need to concat together to produce the value.
70 assert(Val.getType()->isSized() &&
71 "Don't know how to create an empty vreg");
72 unsigned VReg = MRI->createGenericVirtualRegister(LLT{*Val.getType(), *DL});
75 if (auto CV = dyn_cast<Constant>(&Val)) {
76 bool Success = translate(*CV, VReg);
78 if (!TPC->isGlobalISelAbortEnabled()) {
79 MF->getProperties().set(
80 MachineFunctionProperties::Property::FailedISel);
83 reportTranslationError(Val, "unable to translate constant");
90 int IRTranslator::getOrCreateFrameIndex(const AllocaInst &AI) {
91 if (FrameIndices.find(&AI) != FrameIndices.end())
92 return FrameIndices[&AI];
94 unsigned ElementSize = DL->getTypeStoreSize(AI.getAllocatedType());
96 ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue();
98 // Always allocate at least one byte.
99 Size = std::max(Size, 1u);
101 unsigned Alignment = AI.getAlignment();
103 Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
105 int &FI = FrameIndices[&AI];
106 FI = MF->getFrameInfo().CreateStackObject(Size, Alignment, false, &AI);
110 unsigned IRTranslator::getMemOpAlignment(const Instruction &I) {
111 unsigned Alignment = 0;
112 Type *ValTy = nullptr;
113 if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
114 Alignment = SI->getAlignment();
115 ValTy = SI->getValueOperand()->getType();
116 } else if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
117 Alignment = LI->getAlignment();
118 ValTy = LI->getType();
119 } else if (!TPC->isGlobalISelAbortEnabled()) {
120 MF->getProperties().set(
121 MachineFunctionProperties::Property::FailedISel);
124 llvm_unreachable("unhandled memory instruction");
126 return Alignment ? Alignment : DL->getABITypeAlignment(ValTy);
129 MachineBasicBlock &IRTranslator::getOrCreateBB(const BasicBlock &BB) {
130 MachineBasicBlock *&MBB = BBToMBB[&BB];
132 MBB = MF->CreateMachineBasicBlock(&BB);
135 if (BB.hasAddressTaken())
136 MBB->setHasAddressTaken();
141 void IRTranslator::addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred) {
142 assert(NewPred && "new predecessor must be a real MachineBasicBlock");
143 MachinePreds[Edge].push_back(NewPred);
146 bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U,
147 MachineIRBuilder &MIRBuilder) {
148 // FIXME: handle signed/unsigned wrapping flags.
150 // Get or create a virtual register for each value.
151 // Unless the value is a Constant => loadimm cst?
152 // or inline constant each time?
153 // Creation of a virtual register needs to have a size.
154 unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
155 unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
156 unsigned Res = getOrCreateVReg(U);
157 MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op0).addUse(Op1);
161 bool IRTranslator::translateCompare(const User &U,
162 MachineIRBuilder &MIRBuilder) {
163 const CmpInst *CI = dyn_cast<CmpInst>(&U);
164 unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
165 unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
166 unsigned Res = getOrCreateVReg(U);
167 CmpInst::Predicate Pred =
168 CI ? CI->getPredicate() : static_cast<CmpInst::Predicate>(
169 cast<ConstantExpr>(U).getPredicate());
171 if (CmpInst::isIntPredicate(Pred))
172 MIRBuilder.buildICmp(Pred, Res, Op0, Op1);
174 MIRBuilder.buildFCmp(Pred, Res, Op0, Op1);
179 bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) {
180 const ReturnInst &RI = cast<ReturnInst>(U);
181 const Value *Ret = RI.getReturnValue();
182 // The target may mess up with the insertion point, but
183 // this is not important as a return is the last instruction
184 // of the block anyway.
185 return CLI->lowerReturn(MIRBuilder, Ret, !Ret ? 0 : getOrCreateVReg(*Ret));
188 bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) {
189 const BranchInst &BrInst = cast<BranchInst>(U);
191 if (!BrInst.isUnconditional()) {
192 // We want a G_BRCOND to the true BB followed by an unconditional branch.
193 unsigned Tst = getOrCreateVReg(*BrInst.getCondition());
194 const BasicBlock &TrueTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ++));
195 MachineBasicBlock &TrueBB = getOrCreateBB(TrueTgt);
196 MIRBuilder.buildBrCond(Tst, TrueBB);
199 const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ));
200 MachineBasicBlock &TgtBB = getOrCreateBB(BrTgt);
201 MIRBuilder.buildBr(TgtBB);
204 MachineBasicBlock &CurBB = MIRBuilder.getMBB();
205 for (const BasicBlock *Succ : BrInst.successors())
206 CurBB.addSuccessor(&getOrCreateBB(*Succ));
210 bool IRTranslator::translateSwitch(const User &U,
211 MachineIRBuilder &MIRBuilder) {
212 // For now, just translate as a chain of conditional branches.
213 // FIXME: could we share most of the logic/code in
214 // SelectionDAGBuilder::visitSwitch between SelectionDAG and GlobalISel?
215 // At first sight, it seems most of the logic in there is independent of
216 // SelectionDAG-specifics and a lot of work went in to optimize switch
217 // lowering in there.
219 const SwitchInst &SwInst = cast<SwitchInst>(U);
220 const unsigned SwCondValue = getOrCreateVReg(*SwInst.getCondition());
221 const BasicBlock *OrigBB = SwInst.getParent();
223 LLT LLTi1 = LLT(*Type::getInt1Ty(U.getContext()), *DL);
224 for (auto &CaseIt : SwInst.cases()) {
225 const unsigned CaseValueReg = getOrCreateVReg(*CaseIt.getCaseValue());
226 const unsigned Tst = MRI->createGenericVirtualRegister(LLTi1);
227 MIRBuilder.buildICmp(CmpInst::ICMP_EQ, Tst, CaseValueReg, SwCondValue);
228 MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
229 const BasicBlock *TrueBB = CaseIt.getCaseSuccessor();
230 MachineBasicBlock &TrueMBB = getOrCreateBB(*TrueBB);
232 MIRBuilder.buildBrCond(Tst, TrueMBB);
233 CurMBB.addSuccessor(&TrueMBB);
234 addMachineCFGPred({OrigBB, TrueBB}, &CurMBB);
236 MachineBasicBlock *FalseMBB =
237 MF->CreateMachineBasicBlock(SwInst.getParent());
238 MF->push_back(FalseMBB);
239 MIRBuilder.buildBr(*FalseMBB);
240 CurMBB.addSuccessor(FalseMBB);
242 MIRBuilder.setMBB(*FalseMBB);
244 // handle default case
245 const BasicBlock *DefaultBB = SwInst.getDefaultDest();
246 MachineBasicBlock &DefaultMBB = getOrCreateBB(*DefaultBB);
247 MIRBuilder.buildBr(DefaultMBB);
248 MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
249 CurMBB.addSuccessor(&DefaultMBB);
250 addMachineCFGPred({OrigBB, DefaultBB}, &CurMBB);
255 bool IRTranslator::translateIndirectBr(const User &U,
256 MachineIRBuilder &MIRBuilder) {
257 const IndirectBrInst &BrInst = cast<IndirectBrInst>(U);
259 const unsigned Tgt = getOrCreateVReg(*BrInst.getAddress());
260 MIRBuilder.buildBrIndirect(Tgt);
263 MachineBasicBlock &CurBB = MIRBuilder.getMBB();
264 for (const BasicBlock *Succ : BrInst.successors())
265 CurBB.addSuccessor(&getOrCreateBB(*Succ));
270 bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) {
271 const LoadInst &LI = cast<LoadInst>(U);
273 if (!TPC->isGlobalISelAbortEnabled() && LI.isAtomic())
276 assert(!LI.isAtomic() && "only non-atomic loads are supported at the moment");
277 auto Flags = LI.isVolatile() ? MachineMemOperand::MOVolatile
278 : MachineMemOperand::MONone;
279 Flags |= MachineMemOperand::MOLoad;
281 unsigned Res = getOrCreateVReg(LI);
282 unsigned Addr = getOrCreateVReg(*LI.getPointerOperand());
283 LLT VTy{*LI.getType(), *DL}, PTy{*LI.getPointerOperand()->getType(), *DL};
284 MIRBuilder.buildLoad(
286 *MF->getMachineMemOperand(MachinePointerInfo(LI.getPointerOperand()),
287 Flags, DL->getTypeStoreSize(LI.getType()),
288 getMemOpAlignment(LI)));
292 bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) {
293 const StoreInst &SI = cast<StoreInst>(U);
295 if (!TPC->isGlobalISelAbortEnabled() && SI.isAtomic())
298 assert(!SI.isAtomic() && "only non-atomic stores supported at the moment");
299 auto Flags = SI.isVolatile() ? MachineMemOperand::MOVolatile
300 : MachineMemOperand::MONone;
301 Flags |= MachineMemOperand::MOStore;
303 unsigned Val = getOrCreateVReg(*SI.getValueOperand());
304 unsigned Addr = getOrCreateVReg(*SI.getPointerOperand());
305 LLT VTy{*SI.getValueOperand()->getType(), *DL},
306 PTy{*SI.getPointerOperand()->getType(), *DL};
308 MIRBuilder.buildStore(
310 *MF->getMachineMemOperand(
311 MachinePointerInfo(SI.getPointerOperand()), Flags,
312 DL->getTypeStoreSize(SI.getValueOperand()->getType()),
313 getMemOpAlignment(SI)));
317 bool IRTranslator::translateExtractValue(const User &U,
318 MachineIRBuilder &MIRBuilder) {
319 const Value *Src = U.getOperand(0);
320 Type *Int32Ty = Type::getInt32Ty(U.getContext());
321 SmallVector<Value *, 1> Indices;
323 // getIndexedOffsetInType is designed for GEPs, so the first index is the
324 // usual array element rather than looking into the actual aggregate.
325 Indices.push_back(ConstantInt::get(Int32Ty, 0));
327 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) {
328 for (auto Idx : EVI->indices())
329 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
331 for (unsigned i = 1; i < U.getNumOperands(); ++i)
332 Indices.push_back(U.getOperand(i));
335 uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices);
337 unsigned Res = getOrCreateVReg(U);
338 MIRBuilder.buildExtract(Res, Offset, getOrCreateVReg(*Src));
343 bool IRTranslator::translateInsertValue(const User &U,
344 MachineIRBuilder &MIRBuilder) {
345 const Value *Src = U.getOperand(0);
346 Type *Int32Ty = Type::getInt32Ty(U.getContext());
347 SmallVector<Value *, 1> Indices;
349 // getIndexedOffsetInType is designed for GEPs, so the first index is the
350 // usual array element rather than looking into the actual aggregate.
351 Indices.push_back(ConstantInt::get(Int32Ty, 0));
353 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) {
354 for (auto Idx : IVI->indices())
355 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
357 for (unsigned i = 2; i < U.getNumOperands(); ++i)
358 Indices.push_back(U.getOperand(i));
361 uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices);
363 unsigned Res = getOrCreateVReg(U);
364 const Value &Inserted = *U.getOperand(1);
365 MIRBuilder.buildInsert(Res, getOrCreateVReg(*Src), getOrCreateVReg(Inserted),
371 bool IRTranslator::translateSelect(const User &U,
372 MachineIRBuilder &MIRBuilder) {
373 MIRBuilder.buildSelect(getOrCreateVReg(U), getOrCreateVReg(*U.getOperand(0)),
374 getOrCreateVReg(*U.getOperand(1)),
375 getOrCreateVReg(*U.getOperand(2)));
379 bool IRTranslator::translateBitCast(const User &U,
380 MachineIRBuilder &MIRBuilder) {
381 if (LLT{*U.getOperand(0)->getType(), *DL} == LLT{*U.getType(), *DL}) {
382 unsigned &Reg = ValToVReg[&U];
384 MIRBuilder.buildCopy(Reg, getOrCreateVReg(*U.getOperand(0)));
386 Reg = getOrCreateVReg(*U.getOperand(0));
389 return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder);
392 bool IRTranslator::translateCast(unsigned Opcode, const User &U,
393 MachineIRBuilder &MIRBuilder) {
394 unsigned Op = getOrCreateVReg(*U.getOperand(0));
395 unsigned Res = getOrCreateVReg(U);
396 MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op);
400 bool IRTranslator::translateGetElementPtr(const User &U,
401 MachineIRBuilder &MIRBuilder) {
402 // FIXME: support vector GEPs.
403 if (U.getType()->isVectorTy())
406 Value &Op0 = *U.getOperand(0);
407 unsigned BaseReg = getOrCreateVReg(Op0);
408 LLT PtrTy{*Op0.getType(), *DL};
409 unsigned PtrSize = DL->getPointerSizeInBits(PtrTy.getAddressSpace());
410 LLT OffsetTy = LLT::scalar(PtrSize);
413 for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U);
415 const Value *Idx = GTI.getOperand();
416 if (StructType *StTy = GTI.getStructTypeOrNull()) {
417 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
418 Offset += DL->getStructLayout(StTy)->getElementOffset(Field);
421 uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
423 // If this is a scalar constant or a splat vector of constants,
424 // handle it quickly.
425 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
426 Offset += ElementSize * CI->getSExtValue();
431 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
432 unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
433 MIRBuilder.buildConstant(OffsetReg, Offset);
434 MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg);
436 BaseReg = NewBaseReg;
440 // N = N + Idx * ElementSize;
441 unsigned ElementSizeReg = MRI->createGenericVirtualRegister(OffsetTy);
442 MIRBuilder.buildConstant(ElementSizeReg, ElementSize);
444 unsigned IdxReg = getOrCreateVReg(*Idx);
445 if (MRI->getType(IdxReg) != OffsetTy) {
446 unsigned NewIdxReg = MRI->createGenericVirtualRegister(OffsetTy);
447 MIRBuilder.buildSExtOrTrunc(NewIdxReg, IdxReg);
451 unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
452 MIRBuilder.buildMul(OffsetReg, ElementSizeReg, IdxReg);
454 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
455 MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg);
456 BaseReg = NewBaseReg;
461 unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
462 MIRBuilder.buildConstant(OffsetReg, Offset);
463 MIRBuilder.buildGEP(getOrCreateVReg(U), BaseReg, OffsetReg);
467 MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg);
471 bool IRTranslator::translateMemfunc(const CallInst &CI,
472 MachineIRBuilder &MIRBuilder,
474 LLT SizeTy{*CI.getArgOperand(2)->getType(), *DL};
475 Type *DstTy = CI.getArgOperand(0)->getType();
476 if (cast<PointerType>(DstTy)->getAddressSpace() != 0 ||
477 SizeTy.getSizeInBits() != DL->getPointerSizeInBits(0))
480 SmallVector<CallLowering::ArgInfo, 8> Args;
481 for (int i = 0; i < 3; ++i) {
482 const auto &Arg = CI.getArgOperand(i);
483 Args.emplace_back(getOrCreateVReg(*Arg), Arg->getType());
488 case Intrinsic::memmove:
489 case Intrinsic::memcpy: {
490 Type *SrcTy = CI.getArgOperand(1)->getType();
491 if(cast<PointerType>(SrcTy)->getAddressSpace() != 0)
493 Callee = ID == Intrinsic::memcpy ? "memcpy" : "memmove";
496 case Intrinsic::memset:
503 return CLI->lowerCall(MIRBuilder, MachineOperand::CreateES(Callee),
504 CallLowering::ArgInfo(0, CI.getType()), Args);
507 void IRTranslator::getStackGuard(unsigned DstReg,
508 MachineIRBuilder &MIRBuilder) {
509 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
510 MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF));
511 auto MIB = MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD);
514 auto &TLI = *MF->getSubtarget().getTargetLowering();
515 Value *Global = TLI.getSDagStackGuard(*MF->getFunction()->getParent());
519 MachinePointerInfo MPInfo(Global);
520 MachineInstr::mmo_iterator MemRefs = MF->allocateMemRefsArray(1);
521 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
522 MachineMemOperand::MODereferenceable;
524 MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8,
525 DL->getPointerABIAlignment());
526 MIB.setMemRefs(MemRefs, MemRefs + 1);
529 bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op,
530 MachineIRBuilder &MIRBuilder) {
531 LLT Ty{*CI.getOperand(0)->getType(), *DL};
532 LLT s1 = LLT::scalar(1);
533 unsigned Width = Ty.getSizeInBits();
534 unsigned Res = MRI->createGenericVirtualRegister(Ty);
535 unsigned Overflow = MRI->createGenericVirtualRegister(s1);
536 auto MIB = MIRBuilder.buildInstr(Op)
539 .addUse(getOrCreateVReg(*CI.getOperand(0)))
540 .addUse(getOrCreateVReg(*CI.getOperand(1)));
542 if (Op == TargetOpcode::G_UADDE || Op == TargetOpcode::G_USUBE) {
543 unsigned Zero = MRI->createGenericVirtualRegister(s1);
544 EntryBuilder.buildConstant(Zero, 0);
548 MIRBuilder.buildSequence(getOrCreateVReg(CI), Res, 0, Overflow, Width);
552 bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID,
553 MachineIRBuilder &MIRBuilder) {
557 case Intrinsic::dbg_declare: {
558 const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI);
559 assert(DI.getVariable() && "Missing variable");
561 const Value *Address = DI.getAddress();
562 if (!Address || isa<UndefValue>(Address)) {
563 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
567 unsigned Reg = getOrCreateVReg(*Address);
568 auto RegDef = MRI->def_instr_begin(Reg);
569 assert(DI.getVariable()->isValidLocationForIntrinsic(
570 MIRBuilder.getDebugLoc()) &&
571 "Expected inlined-at fields to agree");
573 if (RegDef != MRI->def_instr_end() &&
574 RegDef->getOpcode() == TargetOpcode::G_FRAME_INDEX) {
575 MIRBuilder.buildFIDbgValue(RegDef->getOperand(1).getIndex(),
576 DI.getVariable(), DI.getExpression());
578 MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(), DI.getExpression());
581 case Intrinsic::dbg_value: {
582 // This form of DBG_VALUE is target-independent.
583 const DbgValueInst &DI = cast<DbgValueInst>(CI);
584 const Value *V = DI.getValue();
585 assert(DI.getVariable()->isValidLocationForIntrinsic(
586 MIRBuilder.getDebugLoc()) &&
587 "Expected inlined-at fields to agree");
589 // Currently the optimizer can produce this; insert an undef to
590 // help debugging. Probably the optimizer should not do this.
591 MIRBuilder.buildIndirectDbgValue(0, DI.getOffset(), DI.getVariable(),
593 } else if (const auto *CI = dyn_cast<Constant>(V)) {
594 MIRBuilder.buildConstDbgValue(*CI, DI.getOffset(), DI.getVariable(),
597 unsigned Reg = getOrCreateVReg(*V);
598 // FIXME: This does not handle register-indirect values at offset 0. The
599 // direct/indirect thing shouldn't really be handled by something as
600 // implicit as reg+noreg vs reg+imm in the first palce, but it seems
601 // pretty baked in right now.
602 if (DI.getOffset() != 0)
603 MIRBuilder.buildIndirectDbgValue(Reg, DI.getOffset(), DI.getVariable(),
606 MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(),
611 case Intrinsic::uadd_with_overflow:
612 return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDE, MIRBuilder);
613 case Intrinsic::sadd_with_overflow:
614 return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder);
615 case Intrinsic::usub_with_overflow:
616 return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBE, MIRBuilder);
617 case Intrinsic::ssub_with_overflow:
618 return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder);
619 case Intrinsic::umul_with_overflow:
620 return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder);
621 case Intrinsic::smul_with_overflow:
622 return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder);
623 case Intrinsic::memcpy:
624 case Intrinsic::memmove:
625 case Intrinsic::memset:
626 return translateMemfunc(CI, MIRBuilder, ID);
627 case Intrinsic::eh_typeid_for: {
628 GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0));
629 unsigned Reg = getOrCreateVReg(CI);
630 unsigned TypeID = MF->getTypeIDFor(GV);
631 MIRBuilder.buildConstant(Reg, TypeID);
634 case Intrinsic::objectsize: {
635 // If we don't know by now, we're never going to know.
636 const ConstantInt *Min = cast<ConstantInt>(CI.getArgOperand(1));
638 MIRBuilder.buildConstant(getOrCreateVReg(CI), Min->isZero() ? -1ULL : 0);
641 case Intrinsic::stackguard:
642 getStackGuard(getOrCreateVReg(CI), MIRBuilder);
644 case Intrinsic::stackprotector: {
645 LLT PtrTy{*CI.getArgOperand(0)->getType(), *DL};
646 unsigned GuardVal = MRI->createGenericVirtualRegister(PtrTy);
647 getStackGuard(GuardVal, MIRBuilder);
649 AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1));
650 MIRBuilder.buildStore(
651 GuardVal, getOrCreateVReg(*Slot),
652 *MF->getMachineMemOperand(
653 MachinePointerInfo::getFixedStack(*MF,
654 getOrCreateFrameIndex(*Slot)),
655 MachineMemOperand::MOStore | MachineMemOperand::MOVolatile,
656 PtrTy.getSizeInBits() / 8, 8));
663 bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) {
664 const CallInst &CI = cast<CallInst>(U);
665 auto TII = MF->getTarget().getIntrinsicInfo();
666 const Function *F = CI.getCalledFunction();
668 if (CI.isInlineAsm())
671 if (!F || !F->isIntrinsic()) {
672 unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI);
673 SmallVector<unsigned, 8> Args;
674 for (auto &Arg: CI.arg_operands())
675 Args.push_back(getOrCreateVReg(*Arg));
677 return CLI->lowerCall(MIRBuilder, CI, Res, Args, [&]() {
678 return getOrCreateVReg(*CI.getCalledValue());
682 Intrinsic::ID ID = F->getIntrinsicID();
683 if (TII && ID == Intrinsic::not_intrinsic)
684 ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F));
686 assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
688 if (translateKnownIntrinsic(CI, ID, MIRBuilder))
691 unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI);
692 MachineInstrBuilder MIB =
693 MIRBuilder.buildIntrinsic(ID, Res, !CI.doesNotAccessMemory());
695 for (auto &Arg : CI.arg_operands()) {
696 if (ConstantInt *CI = dyn_cast<ConstantInt>(Arg))
697 MIB.addImm(CI->getSExtValue());
699 MIB.addUse(getOrCreateVReg(*Arg));
704 bool IRTranslator::translateInvoke(const User &U,
705 MachineIRBuilder &MIRBuilder) {
706 const InvokeInst &I = cast<InvokeInst>(U);
707 MCContext &Context = MF->getContext();
709 const BasicBlock *ReturnBB = I.getSuccessor(0);
710 const BasicBlock *EHPadBB = I.getSuccessor(1);
712 const Value *Callee(I.getCalledValue());
713 const Function *Fn = dyn_cast<Function>(Callee);
714 if (isa<InlineAsm>(Callee))
717 // FIXME: support invoking patchpoint and statepoint intrinsics.
718 if (Fn && Fn->isIntrinsic())
721 // FIXME: support whatever these are.
722 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
725 // FIXME: support Windows exception handling.
726 if (!isa<LandingPadInst>(EHPadBB->front()))
730 // Emit the actual call, bracketed by EH_LABELs so that the MF knows about
731 // the region covered by the try.
732 MCSymbol *BeginSymbol = Context.createTempSymbol();
733 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol);
735 unsigned Res = I.getType()->isVoidTy() ? 0 : getOrCreateVReg(I);
736 SmallVector<unsigned, 8> Args;
737 for (auto &Arg: I.arg_operands())
738 Args.push_back(getOrCreateVReg(*Arg));
740 CLI->lowerCall(MIRBuilder, I, Res, Args,
741 [&]() { return getOrCreateVReg(*I.getCalledValue()); });
743 MCSymbol *EndSymbol = Context.createTempSymbol();
744 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol);
746 // FIXME: track probabilities.
747 MachineBasicBlock &EHPadMBB = getOrCreateBB(*EHPadBB),
748 &ReturnMBB = getOrCreateBB(*ReturnBB);
749 MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
750 MIRBuilder.getMBB().addSuccessor(&ReturnMBB);
751 MIRBuilder.getMBB().addSuccessor(&EHPadMBB);
756 bool IRTranslator::translateLandingPad(const User &U,
757 MachineIRBuilder &MIRBuilder) {
758 const LandingPadInst &LP = cast<LandingPadInst>(U);
760 MachineBasicBlock &MBB = MIRBuilder.getMBB();
761 addLandingPadInfo(LP, MBB);
765 // If there aren't registers to copy the values into (e.g., during SjLj
766 // exceptions), then don't bother.
767 auto &TLI = *MF->getSubtarget().getTargetLowering();
768 const Constant *PersonalityFn = MF->getFunction()->getPersonalityFn();
769 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
770 TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
773 // If landingpad's return type is token type, we don't create DAG nodes
774 // for its exception pointer and selector value. The extraction of exception
775 // pointer or selector value from token type landingpads is not currently
777 if (LP.getType()->isTokenTy())
780 // Add a label to mark the beginning of the landing pad. Deletion of the
781 // landing pad can thus be detected via the MachineModuleInfo.
782 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL)
783 .addSym(MF->addLandingPad(&MBB));
785 SmallVector<LLT, 2> Tys;
786 for (Type *Ty : cast<StructType>(LP.getType())->elements())
787 Tys.push_back(LLT{*Ty, *DL});
788 assert(Tys.size() == 2 && "Only two-valued landingpads are supported");
790 // Mark exception register as live in.
791 SmallVector<unsigned, 2> Regs;
792 SmallVector<uint64_t, 2> Offsets;
793 if (unsigned Reg = TLI.getExceptionPointerRegister(PersonalityFn)) {
795 unsigned VReg = MRI->createGenericVirtualRegister(Tys[0]);
796 MIRBuilder.buildCopy(VReg, Reg);
797 Regs.push_back(VReg);
798 Offsets.push_back(0);
801 if (unsigned Reg = TLI.getExceptionSelectorRegister(PersonalityFn)) {
804 // N.b. the exception selector register always has pointer type and may not
805 // match the actual IR-level type in the landingpad so an extra cast is
807 unsigned PtrVReg = MRI->createGenericVirtualRegister(Tys[0]);
808 MIRBuilder.buildCopy(PtrVReg, Reg);
810 unsigned VReg = MRI->createGenericVirtualRegister(Tys[1]);
811 MIRBuilder.buildInstr(TargetOpcode::G_PTRTOINT)
814 Regs.push_back(VReg);
815 Offsets.push_back(Tys[0].getSizeInBits());
818 MIRBuilder.buildSequence(getOrCreateVReg(LP), Regs, Offsets);
822 bool IRTranslator::translateStaticAlloca(const AllocaInst &AI,
823 MachineIRBuilder &MIRBuilder) {
824 if (!TPC->isGlobalISelAbortEnabled() && !AI.isStaticAlloca())
827 assert(AI.isStaticAlloca() && "only handle static allocas now");
828 unsigned Res = getOrCreateVReg(AI);
829 int FI = getOrCreateFrameIndex(AI);
830 MIRBuilder.buildFrameIndex(Res, FI);
834 bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) {
835 const PHINode &PI = cast<PHINode>(U);
836 auto MIB = MIRBuilder.buildInstr(TargetOpcode::PHI);
837 MIB.addDef(getOrCreateVReg(PI));
839 PendingPHIs.emplace_back(&PI, MIB.getInstr());
843 void IRTranslator::finishPendingPhis() {
844 for (std::pair<const PHINode *, MachineInstr *> &Phi : PendingPHIs) {
845 const PHINode *PI = Phi.first;
846 MachineInstrBuilder MIB(*MF, Phi.second);
848 // All MachineBasicBlocks exist, add them to the PHI. We assume IRTranslator
849 // won't create extra control flow here, otherwise we need to find the
850 // dominating predecessor here (or perhaps force the weirder IRTranslators
851 // to provide a simple boundary).
852 SmallSet<const BasicBlock *, 4> HandledPreds;
854 for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
855 auto IRPred = PI->getIncomingBlock(i);
856 if (HandledPreds.count(IRPred))
859 HandledPreds.insert(IRPred);
860 unsigned ValReg = getOrCreateVReg(*PI->getIncomingValue(i));
861 for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) {
862 assert(Pred->isSuccessor(MIB->getParent()) &&
863 "incorrect CFG at MachineBasicBlock level");
871 bool IRTranslator::translate(const Instruction &Inst) {
872 CurBuilder.setDebugLoc(Inst.getDebugLoc());
873 switch(Inst.getOpcode()) {
874 #define HANDLE_INST(NUM, OPCODE, CLASS) \
875 case Instruction::OPCODE: return translate##OPCODE(Inst, CurBuilder);
876 #include "llvm/IR/Instruction.def"
878 if (!TPC->isGlobalISelAbortEnabled())
880 llvm_unreachable("unknown opcode");
884 bool IRTranslator::translate(const Constant &C, unsigned Reg) {
885 if (auto CI = dyn_cast<ConstantInt>(&C))
886 EntryBuilder.buildConstant(Reg, *CI);
887 else if (auto CF = dyn_cast<ConstantFP>(&C))
888 EntryBuilder.buildFConstant(Reg, *CF);
889 else if (isa<UndefValue>(C))
890 EntryBuilder.buildInstr(TargetOpcode::IMPLICIT_DEF).addDef(Reg);
891 else if (isa<ConstantPointerNull>(C))
892 EntryBuilder.buildConstant(Reg, 0);
893 else if (auto GV = dyn_cast<GlobalValue>(&C))
894 EntryBuilder.buildGlobalValue(Reg, GV);
895 else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
896 switch(CE->getOpcode()) {
897 #define HANDLE_INST(NUM, OPCODE, CLASS) \
898 case Instruction::OPCODE: return translate##OPCODE(*CE, EntryBuilder);
899 #include "llvm/IR/Instruction.def"
901 if (!TPC->isGlobalISelAbortEnabled())
903 llvm_unreachable("unknown opcode");
905 } else if (!TPC->isGlobalISelAbortEnabled())
908 llvm_unreachable("unhandled constant kind");
913 void IRTranslator::finalizeFunction() {
914 // Release the memory used by the different maps we
915 // needed during the translation.
918 FrameIndices.clear();
920 MachinePreds.clear();
923 bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) {
925 const Function &F = *MF->getFunction();
928 CLI = MF->getSubtarget().getCallLowering();
929 CurBuilder.setMF(*MF);
930 EntryBuilder.setMF(*MF);
931 MRI = &MF->getRegInfo();
932 DL = &F.getParent()->getDataLayout();
933 TPC = &getAnalysis<TargetPassConfig>();
935 assert(PendingPHIs.empty() && "stale PHIs");
937 // Setup a separate basic-block for the arguments and constants, falling
938 // through to the IR-level Function's entry block.
939 MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock();
940 MF->push_back(EntryBB);
941 EntryBB->addSuccessor(&getOrCreateBB(F.front()));
942 EntryBuilder.setMBB(*EntryBB);
944 // Lower the actual args into this basic block.
945 SmallVector<unsigned, 8> VRegArgs;
946 for (const Argument &Arg: F.args())
947 VRegArgs.push_back(getOrCreateVReg(Arg));
948 bool Succeeded = CLI->lowerFormalArguments(EntryBuilder, F, VRegArgs);
950 if (!TPC->isGlobalISelAbortEnabled()) {
951 MF->getProperties().set(
952 MachineFunctionProperties::Property::FailedISel);
956 report_fatal_error("Unable to lower arguments");
959 // And translate the function!
960 for (const BasicBlock &BB: F) {
961 MachineBasicBlock &MBB = getOrCreateBB(BB);
962 // Set the insertion point of all the following translations to
963 // the end of this basic block.
964 CurBuilder.setMBB(MBB);
966 for (const Instruction &Inst: BB) {
967 Succeeded &= translate(Inst);
969 if (TPC->isGlobalISelAbortEnabled())
970 reportTranslationError(Inst, "unable to translate instruction");
971 MF->getProperties().set(
972 MachineFunctionProperties::Property::FailedISel);
981 // Now that the MachineFrameInfo has been configured, no further changes to
982 // the reserved registers are possible.
983 MRI->freezeReservedRegs(*MF);
985 // Merge the argument lowering and constants block with its single
986 // successor, the LLVM-IR entry block. We want the basic block to
988 assert(EntryBB->succ_size() == 1 &&
989 "Custom BB used for lowering should have only one successor");
990 // Get the successor of the current entry block.
991 MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin();
992 assert(NewEntryBB.pred_size() == 1 &&
993 "LLVM-IR entry block has a predecessor!?");
994 // Move all the instruction from the current entry block to the
996 NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(),
999 // Update the live-in information for the new entry block.
1000 for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins())
1001 NewEntryBB.addLiveIn(LiveIn);
1002 NewEntryBB.sortUniqueLiveIns();
1004 // Get rid of the now empty basic block.
1005 EntryBB->removeSuccessor(&NewEntryBB);
1006 MF->remove(EntryBB);
1007 MF->DeleteMachineBasicBlock(EntryBB);
1009 assert(&MF->front() == &NewEntryBB &&
1010 "New entry wasn't next in the list of basic block!");