OSDN Git Service

[GlobalISel] Preserve IR block layout.
[android-x86/external-llvm.git] / lib / CodeGen / GlobalISel / IRTranslator.cpp
1 //===-- llvm/CodeGen/GlobalISel/IRTranslator.cpp - IRTranslator --*- C++ -*-==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 /// This file implements the IRTranslator class.
11 //===----------------------------------------------------------------------===//
12
13 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
14
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"
36
37 #define DEBUG_TYPE "irtranslator"
38
39 using namespace llvm;
40
41 char IRTranslator::ID = 0;
42 INITIALIZE_PASS_BEGIN(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
43                 false, false)
44 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
45 INITIALIZE_PASS_END(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
46                 false, false)
47
48 static void reportTranslationError(MachineFunction &MF,
49                                    const TargetPassConfig &TPC,
50                                    OptimizationRemarkEmitter &ORE,
51                                    OptimizationRemarkMissed &R) {
52   MF.getProperties().set(MachineFunctionProperties::Property::FailedISel);
53
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();
58
59   if (TPC.isGlobalISelAbortEnabled())
60     report_fatal_error(R.getMsg());
61   else
62     ORE.emit(R);
63 }
64
65 IRTranslator::IRTranslator() : MachineFunctionPass(ID), MRI(nullptr) {
66   initializeIRTranslatorPass(*PassRegistry::getPassRegistry());
67 }
68
69 void IRTranslator::getAnalysisUsage(AnalysisUsage &AU) const {
70   AU.addRequired<TargetPassConfig>();
71   MachineFunctionPass::getAnalysisUsage(AU);
72 }
73
74
75 unsigned IRTranslator::getOrCreateVReg(const Value &Val) {
76   unsigned &ValReg = ValToVReg[&Val];
77
78   if (ValReg)
79     return ValReg;
80
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");
85   unsigned VReg =
86       MRI->createGenericVirtualRegister(getLLTForType(*Val.getType(), *DL));
87   ValReg = VReg;
88
89   if (auto CV = dyn_cast<Constant>(&Val)) {
90     bool Success = translate(*CV, VReg);
91     if (!Success) {
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);
97       return VReg;
98     }
99   }
100
101   return VReg;
102 }
103
104 int IRTranslator::getOrCreateFrameIndex(const AllocaInst &AI) {
105   if (FrameIndices.find(&AI) != FrameIndices.end())
106     return FrameIndices[&AI];
107
108   unsigned ElementSize = DL->getTypeStoreSize(AI.getAllocatedType());
109   unsigned Size =
110       ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue();
111
112   // Always allocate at least one byte.
113   Size = std::max(Size, 1u);
114
115   unsigned Alignment = AI.getAlignment();
116   if (!Alignment)
117     Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
118
119   int &FI = FrameIndices[&AI];
120   FI = MF->getFrameInfo().CreateStackObject(Size, Alignment, false, &AI);
121   return FI;
122 }
123
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();
133   } else {
134     OptimizationRemarkMissed R("gisel-irtranslator", "", &I);
135     R << "unable to translate memop: " << ore::NV("Opcode", &I);
136     reportTranslationError(*MF, *TPC, *ORE, R);
137     return 1;
138   }
139
140   return Alignment ? Alignment : DL->getABITypeAlignment(ValTy);
141 }
142
143 MachineBasicBlock &IRTranslator::getMBB(const BasicBlock &BB) {
144   MachineBasicBlock *&MBB = BBToMBB[&BB];
145   assert(MBB && "BasicBlock was not encountered before");
146   return *MBB;
147 }
148
149 void IRTranslator::addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred) {
150   assert(NewPred && "new predecessor must be a real MachineBasicBlock");
151   MachinePreds[Edge].push_back(NewPred);
152 }
153
154 bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U,
155                                      MachineIRBuilder &MIRBuilder) {
156   // FIXME: handle signed/unsigned wrapping flags.
157
158   // Get or create a virtual register for each value.
159   // Unless the value is a Constant => loadimm cst?
160   // or inline constant each time?
161   // Creation of a virtual register needs to have a size.
162   unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
163   unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
164   unsigned Res = getOrCreateVReg(U);
165   MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op0).addUse(Op1);
166   return true;
167 }
168
169 bool IRTranslator::translateFSub(const User &U, MachineIRBuilder &MIRBuilder) {
170   // -0.0 - X --> G_FNEG
171   if (isa<Constant>(U.getOperand(0)) &&
172       U.getOperand(0) == ConstantFP::getZeroValueForNegation(U.getType())) {
173     MIRBuilder.buildInstr(TargetOpcode::G_FNEG)
174         .addDef(getOrCreateVReg(U))
175         .addUse(getOrCreateVReg(*U.getOperand(1)));
176     return true;
177   }
178   return translateBinaryOp(TargetOpcode::G_FSUB, U, MIRBuilder);
179 }
180
181 bool IRTranslator::translateCompare(const User &U,
182                                     MachineIRBuilder &MIRBuilder) {
183   const CmpInst *CI = dyn_cast<CmpInst>(&U);
184   unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
185   unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
186   unsigned Res = getOrCreateVReg(U);
187   CmpInst::Predicate Pred =
188       CI ? CI->getPredicate() : static_cast<CmpInst::Predicate>(
189                                     cast<ConstantExpr>(U).getPredicate());
190   if (CmpInst::isIntPredicate(Pred))
191     MIRBuilder.buildICmp(Pred, Res, Op0, Op1);
192   else if (Pred == CmpInst::FCMP_FALSE)
193     MIRBuilder.buildConstant(Res, 0);
194   else if  (Pred == CmpInst::FCMP_TRUE)
195     MIRBuilder.buildConstant(Res, 1);
196   else
197     MIRBuilder.buildFCmp(Pred, Res, Op0, Op1);
198
199   return true;
200 }
201
202 bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) {
203   const ReturnInst &RI = cast<ReturnInst>(U);
204   const Value *Ret = RI.getReturnValue();
205   // The target may mess up with the insertion point, but
206   // this is not important as a return is the last instruction
207   // of the block anyway.
208   return CLI->lowerReturn(MIRBuilder, Ret, !Ret ? 0 : getOrCreateVReg(*Ret));
209 }
210
211 bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) {
212   const BranchInst &BrInst = cast<BranchInst>(U);
213   unsigned Succ = 0;
214   if (!BrInst.isUnconditional()) {
215     // We want a G_BRCOND to the true BB followed by an unconditional branch.
216     unsigned Tst = getOrCreateVReg(*BrInst.getCondition());
217     const BasicBlock &TrueTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ++));
218     MachineBasicBlock &TrueBB = getMBB(TrueTgt);
219     MIRBuilder.buildBrCond(Tst, TrueBB);
220   }
221
222   const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ));
223   MachineBasicBlock &TgtBB = getMBB(BrTgt);
224   MIRBuilder.buildBr(TgtBB);
225
226   // Link successors.
227   MachineBasicBlock &CurBB = MIRBuilder.getMBB();
228   for (const BasicBlock *Succ : BrInst.successors())
229     CurBB.addSuccessor(&getMBB(*Succ));
230   return true;
231 }
232
233 bool IRTranslator::translateSwitch(const User &U,
234                                    MachineIRBuilder &MIRBuilder) {
235   // For now, just translate as a chain of conditional branches.
236   // FIXME: could we share most of the logic/code in
237   // SelectionDAGBuilder::visitSwitch between SelectionDAG and GlobalISel?
238   // At first sight, it seems most of the logic in there is independent of
239   // SelectionDAG-specifics and a lot of work went in to optimize switch
240   // lowering in there.
241
242   const SwitchInst &SwInst = cast<SwitchInst>(U);
243   const unsigned SwCondValue = getOrCreateVReg(*SwInst.getCondition());
244   const BasicBlock *OrigBB = SwInst.getParent();
245
246   LLT LLTi1 = getLLTForType(*Type::getInt1Ty(U.getContext()), *DL);
247   for (auto &CaseIt : SwInst.cases()) {
248     const unsigned CaseValueReg = getOrCreateVReg(*CaseIt.getCaseValue());
249     const unsigned Tst = MRI->createGenericVirtualRegister(LLTi1);
250     MIRBuilder.buildICmp(CmpInst::ICMP_EQ, Tst, CaseValueReg, SwCondValue);
251     MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
252     const BasicBlock *TrueBB = CaseIt.getCaseSuccessor();
253     MachineBasicBlock &TrueMBB = getMBB(*TrueBB);
254
255     MIRBuilder.buildBrCond(Tst, TrueMBB);
256     CurMBB.addSuccessor(&TrueMBB);
257     addMachineCFGPred({OrigBB, TrueBB}, &CurMBB);
258
259     MachineBasicBlock *FalseMBB =
260         MF->CreateMachineBasicBlock(SwInst.getParent());
261     MF->push_back(FalseMBB);
262     MIRBuilder.buildBr(*FalseMBB);
263     CurMBB.addSuccessor(FalseMBB);
264
265     MIRBuilder.setMBB(*FalseMBB);
266   }
267   // handle default case
268   const BasicBlock *DefaultBB = SwInst.getDefaultDest();
269   MachineBasicBlock &DefaultMBB = getMBB(*DefaultBB);
270   MIRBuilder.buildBr(DefaultMBB);
271   MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
272   CurMBB.addSuccessor(&DefaultMBB);
273   addMachineCFGPred({OrigBB, DefaultBB}, &CurMBB);
274
275   return true;
276 }
277
278 bool IRTranslator::translateIndirectBr(const User &U,
279                                        MachineIRBuilder &MIRBuilder) {
280   const IndirectBrInst &BrInst = cast<IndirectBrInst>(U);
281
282   const unsigned Tgt = getOrCreateVReg(*BrInst.getAddress());
283   MIRBuilder.buildBrIndirect(Tgt);
284
285   // Link successors.
286   MachineBasicBlock &CurBB = MIRBuilder.getMBB();
287   for (const BasicBlock *Succ : BrInst.successors())
288     CurBB.addSuccessor(&getMBB(*Succ));
289
290   return true;
291 }
292
293 bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) {
294   const LoadInst &LI = cast<LoadInst>(U);
295
296   auto Flags = LI.isVolatile() ? MachineMemOperand::MOVolatile
297                                : MachineMemOperand::MONone;
298   Flags |= MachineMemOperand::MOLoad;
299
300   unsigned Res = getOrCreateVReg(LI);
301   unsigned Addr = getOrCreateVReg(*LI.getPointerOperand());
302
303   MIRBuilder.buildLoad(
304       Res, Addr,
305       *MF->getMachineMemOperand(MachinePointerInfo(LI.getPointerOperand()),
306                                 Flags, DL->getTypeStoreSize(LI.getType()),
307                                 getMemOpAlignment(LI), AAMDNodes(), nullptr,
308                                 LI.getSynchScope(), LI.getOrdering()));
309   return true;
310 }
311
312 bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) {
313   const StoreInst &SI = cast<StoreInst>(U);
314   auto Flags = SI.isVolatile() ? MachineMemOperand::MOVolatile
315                                : MachineMemOperand::MONone;
316   Flags |= MachineMemOperand::MOStore;
317
318   unsigned Val = getOrCreateVReg(*SI.getValueOperand());
319   unsigned Addr = getOrCreateVReg(*SI.getPointerOperand());
320
321   MIRBuilder.buildStore(
322       Val, Addr,
323       *MF->getMachineMemOperand(
324           MachinePointerInfo(SI.getPointerOperand()), Flags,
325           DL->getTypeStoreSize(SI.getValueOperand()->getType()),
326           getMemOpAlignment(SI), AAMDNodes(), nullptr, SI.getSynchScope(),
327           SI.getOrdering()));
328   return true;
329 }
330
331 bool IRTranslator::translateExtractValue(const User &U,
332                                          MachineIRBuilder &MIRBuilder) {
333   const Value *Src = U.getOperand(0);
334   Type *Int32Ty = Type::getInt32Ty(U.getContext());
335   SmallVector<Value *, 1> Indices;
336
337   // getIndexedOffsetInType is designed for GEPs, so the first index is the
338   // usual array element rather than looking into the actual aggregate.
339   Indices.push_back(ConstantInt::get(Int32Ty, 0));
340
341   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) {
342     for (auto Idx : EVI->indices())
343       Indices.push_back(ConstantInt::get(Int32Ty, Idx));
344   } else {
345     for (unsigned i = 1; i < U.getNumOperands(); ++i)
346       Indices.push_back(U.getOperand(i));
347   }
348
349   uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices);
350
351   unsigned Res = getOrCreateVReg(U);
352   MIRBuilder.buildExtract(Res, getOrCreateVReg(*Src), Offset);
353
354   return true;
355 }
356
357 bool IRTranslator::translateInsertValue(const User &U,
358                                         MachineIRBuilder &MIRBuilder) {
359   const Value *Src = U.getOperand(0);
360   Type *Int32Ty = Type::getInt32Ty(U.getContext());
361   SmallVector<Value *, 1> Indices;
362
363   // getIndexedOffsetInType is designed for GEPs, so the first index is the
364   // usual array element rather than looking into the actual aggregate.
365   Indices.push_back(ConstantInt::get(Int32Ty, 0));
366
367   if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) {
368     for (auto Idx : IVI->indices())
369       Indices.push_back(ConstantInt::get(Int32Ty, Idx));
370   } else {
371     for (unsigned i = 2; i < U.getNumOperands(); ++i)
372       Indices.push_back(U.getOperand(i));
373   }
374
375   uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices);
376
377   unsigned Res = getOrCreateVReg(U);
378   const Value &Inserted = *U.getOperand(1);
379   MIRBuilder.buildInsert(Res, getOrCreateVReg(*Src), getOrCreateVReg(Inserted),
380                          Offset);
381
382   return true;
383 }
384
385 bool IRTranslator::translateSelect(const User &U,
386                                    MachineIRBuilder &MIRBuilder) {
387   MIRBuilder.buildSelect(getOrCreateVReg(U), getOrCreateVReg(*U.getOperand(0)),
388                          getOrCreateVReg(*U.getOperand(1)),
389                          getOrCreateVReg(*U.getOperand(2)));
390   return true;
391 }
392
393 bool IRTranslator::translateBitCast(const User &U,
394                                     MachineIRBuilder &MIRBuilder) {
395   // If we're bitcasting to the source type, we can reuse the source vreg.
396   if (getLLTForType(*U.getOperand(0)->getType(), *DL) ==
397       getLLTForType(*U.getType(), *DL)) {
398     // Get the source vreg now, to avoid invalidating ValToVReg.
399     unsigned SrcReg = getOrCreateVReg(*U.getOperand(0));
400     unsigned &Reg = ValToVReg[&U];
401     // If we already assigned a vreg for this bitcast, we can't change that.
402     // Emit a copy to satisfy the users we already emitted.
403     if (Reg)
404       MIRBuilder.buildCopy(Reg, SrcReg);
405     else
406       Reg = SrcReg;
407     return true;
408   }
409   return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder);
410 }
411
412 bool IRTranslator::translateCast(unsigned Opcode, const User &U,
413                                  MachineIRBuilder &MIRBuilder) {
414   unsigned Op = getOrCreateVReg(*U.getOperand(0));
415   unsigned Res = getOrCreateVReg(U);
416   MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op);
417   return true;
418 }
419
420 bool IRTranslator::translateGetElementPtr(const User &U,
421                                           MachineIRBuilder &MIRBuilder) {
422   // FIXME: support vector GEPs.
423   if (U.getType()->isVectorTy())
424     return false;
425
426   Value &Op0 = *U.getOperand(0);
427   unsigned BaseReg = getOrCreateVReg(Op0);
428   LLT PtrTy = getLLTForType(*Op0.getType(), *DL);
429   unsigned PtrSize = DL->getPointerSizeInBits(PtrTy.getAddressSpace());
430   LLT OffsetTy = LLT::scalar(PtrSize);
431
432   int64_t Offset = 0;
433   for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U);
434        GTI != E; ++GTI) {
435     const Value *Idx = GTI.getOperand();
436     if (StructType *StTy = GTI.getStructTypeOrNull()) {
437       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
438       Offset += DL->getStructLayout(StTy)->getElementOffset(Field);
439       continue;
440     } else {
441       uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
442
443       // If this is a scalar constant or a splat vector of constants,
444       // handle it quickly.
445       if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
446         Offset += ElementSize * CI->getSExtValue();
447         continue;
448       }
449
450       if (Offset != 0) {
451         unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
452         unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
453         MIRBuilder.buildConstant(OffsetReg, Offset);
454         MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg);
455
456         BaseReg = NewBaseReg;
457         Offset = 0;
458       }
459
460       // N = N + Idx * ElementSize;
461       unsigned ElementSizeReg = MRI->createGenericVirtualRegister(OffsetTy);
462       MIRBuilder.buildConstant(ElementSizeReg, ElementSize);
463
464       unsigned IdxReg = getOrCreateVReg(*Idx);
465       if (MRI->getType(IdxReg) != OffsetTy) {
466         unsigned NewIdxReg = MRI->createGenericVirtualRegister(OffsetTy);
467         MIRBuilder.buildSExtOrTrunc(NewIdxReg, IdxReg);
468         IdxReg = NewIdxReg;
469       }
470
471       unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
472       MIRBuilder.buildMul(OffsetReg, ElementSizeReg, IdxReg);
473
474       unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
475       MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg);
476       BaseReg = NewBaseReg;
477     }
478   }
479
480   if (Offset != 0) {
481     unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
482     MIRBuilder.buildConstant(OffsetReg, Offset);
483     MIRBuilder.buildGEP(getOrCreateVReg(U), BaseReg, OffsetReg);
484     return true;
485   }
486
487   MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg);
488   return true;
489 }
490
491 bool IRTranslator::translateMemfunc(const CallInst &CI,
492                                     MachineIRBuilder &MIRBuilder,
493                                     unsigned ID) {
494   LLT SizeTy = getLLTForType(*CI.getArgOperand(2)->getType(), *DL);
495   Type *DstTy = CI.getArgOperand(0)->getType();
496   if (cast<PointerType>(DstTy)->getAddressSpace() != 0 ||
497       SizeTy.getSizeInBits() != DL->getPointerSizeInBits(0))
498     return false;
499
500   SmallVector<CallLowering::ArgInfo, 8> Args;
501   for (int i = 0; i < 3; ++i) {
502     const auto &Arg = CI.getArgOperand(i);
503     Args.emplace_back(getOrCreateVReg(*Arg), Arg->getType());
504   }
505
506   const char *Callee;
507   switch (ID) {
508   case Intrinsic::memmove:
509   case Intrinsic::memcpy: {
510     Type *SrcTy = CI.getArgOperand(1)->getType();
511     if(cast<PointerType>(SrcTy)->getAddressSpace() != 0)
512       return false;
513     Callee = ID == Intrinsic::memcpy ? "memcpy" : "memmove";
514     break;
515   }
516   case Intrinsic::memset:
517     Callee = "memset";
518     break;
519   default:
520     return false;
521   }
522
523   return CLI->lowerCall(MIRBuilder, MachineOperand::CreateES(Callee),
524                         CallLowering::ArgInfo(0, CI.getType()), Args);
525 }
526
527 void IRTranslator::getStackGuard(unsigned DstReg,
528                                  MachineIRBuilder &MIRBuilder) {
529   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
530   MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF));
531   auto MIB = MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD);
532   MIB.addDef(DstReg);
533
534   auto &TLI = *MF->getSubtarget().getTargetLowering();
535   Value *Global = TLI.getSDagStackGuard(*MF->getFunction()->getParent());
536   if (!Global)
537     return;
538
539   MachinePointerInfo MPInfo(Global);
540   MachineInstr::mmo_iterator MemRefs = MF->allocateMemRefsArray(1);
541   auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
542                MachineMemOperand::MODereferenceable;
543   *MemRefs =
544       MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8,
545                                DL->getPointerABIAlignment());
546   MIB.setMemRefs(MemRefs, MemRefs + 1);
547 }
548
549 bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op,
550                                               MachineIRBuilder &MIRBuilder) {
551   LLT Ty = getLLTForType(*CI.getOperand(0)->getType(), *DL);
552   LLT s1 = LLT::scalar(1);
553   unsigned Width = Ty.getSizeInBits();
554   unsigned Res = MRI->createGenericVirtualRegister(Ty);
555   unsigned Overflow = MRI->createGenericVirtualRegister(s1);
556   auto MIB = MIRBuilder.buildInstr(Op)
557                  .addDef(Res)
558                  .addDef(Overflow)
559                  .addUse(getOrCreateVReg(*CI.getOperand(0)))
560                  .addUse(getOrCreateVReg(*CI.getOperand(1)));
561
562   if (Op == TargetOpcode::G_UADDE || Op == TargetOpcode::G_USUBE) {
563     unsigned Zero = MRI->createGenericVirtualRegister(s1);
564     EntryBuilder.buildConstant(Zero, 0);
565     MIB.addUse(Zero);
566   }
567
568   MIRBuilder.buildSequence(getOrCreateVReg(CI), Res, 0, Overflow, Width);
569   return true;
570 }
571
572 bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID,
573                                            MachineIRBuilder &MIRBuilder) {
574   switch (ID) {
575   default:
576     break;
577   case Intrinsic::lifetime_start:
578   case Intrinsic::lifetime_end:
579     // Stack coloring is not enabled in O0 (which we care about now) so we can
580     // drop these. Make sure someone notices when we start compiling at higher
581     // opts though.
582     if (MF->getTarget().getOptLevel() != CodeGenOpt::None)
583       return false;
584     return true;
585   case Intrinsic::dbg_declare: {
586     const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI);
587     assert(DI.getVariable() && "Missing variable");
588
589     const Value *Address = DI.getAddress();
590     if (!Address || isa<UndefValue>(Address)) {
591       DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
592       return true;
593     }
594
595     assert(DI.getVariable()->isValidLocationForIntrinsic(
596                MIRBuilder.getDebugLoc()) &&
597            "Expected inlined-at fields to agree");
598     auto AI = dyn_cast<AllocaInst>(Address);
599     if (AI && AI->isStaticAlloca()) {
600       // Static allocas are tracked at the MF level, no need for DBG_VALUE
601       // instructions (in fact, they get ignored if they *do* exist).
602       MF->setVariableDbgInfo(DI.getVariable(), DI.getExpression(),
603                              getOrCreateFrameIndex(*AI), DI.getDebugLoc());
604     } else
605       MIRBuilder.buildDirectDbgValue(getOrCreateVReg(*Address),
606                                      DI.getVariable(), DI.getExpression());
607     return true;
608   }
609   case Intrinsic::vaend:
610     // No target I know of cares about va_end. Certainly no in-tree target
611     // does. Simplest intrinsic ever!
612     return true;
613   case Intrinsic::vastart: {
614     auto &TLI = *MF->getSubtarget().getTargetLowering();
615     Value *Ptr = CI.getArgOperand(0);
616     unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8;
617
618     MIRBuilder.buildInstr(TargetOpcode::G_VASTART)
619         .addUse(getOrCreateVReg(*Ptr))
620         .addMemOperand(MF->getMachineMemOperand(
621             MachinePointerInfo(Ptr), MachineMemOperand::MOStore, ListSize, 0));
622     return true;
623   }
624   case Intrinsic::dbg_value: {
625     // This form of DBG_VALUE is target-independent.
626     const DbgValueInst &DI = cast<DbgValueInst>(CI);
627     const Value *V = DI.getValue();
628     assert(DI.getVariable()->isValidLocationForIntrinsic(
629                MIRBuilder.getDebugLoc()) &&
630            "Expected inlined-at fields to agree");
631     if (!V) {
632       // Currently the optimizer can produce this; insert an undef to
633       // help debugging.  Probably the optimizer should not do this.
634       MIRBuilder.buildIndirectDbgValue(0, DI.getOffset(), DI.getVariable(),
635                                        DI.getExpression());
636     } else if (const auto *CI = dyn_cast<Constant>(V)) {
637       MIRBuilder.buildConstDbgValue(*CI, DI.getOffset(), DI.getVariable(),
638                                     DI.getExpression());
639     } else {
640       unsigned Reg = getOrCreateVReg(*V);
641       // FIXME: This does not handle register-indirect values at offset 0. The
642       // direct/indirect thing shouldn't really be handled by something as
643       // implicit as reg+noreg vs reg+imm in the first palce, but it seems
644       // pretty baked in right now.
645       if (DI.getOffset() != 0)
646         MIRBuilder.buildIndirectDbgValue(Reg, DI.getOffset(), DI.getVariable(),
647                                          DI.getExpression());
648       else
649         MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(),
650                                        DI.getExpression());
651     }
652     return true;
653   }
654   case Intrinsic::uadd_with_overflow:
655     return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDE, MIRBuilder);
656   case Intrinsic::sadd_with_overflow:
657     return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder);
658   case Intrinsic::usub_with_overflow:
659     return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBE, MIRBuilder);
660   case Intrinsic::ssub_with_overflow:
661     return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder);
662   case Intrinsic::umul_with_overflow:
663     return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder);
664   case Intrinsic::smul_with_overflow:
665     return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder);
666   case Intrinsic::pow:
667     MIRBuilder.buildInstr(TargetOpcode::G_FPOW)
668         .addDef(getOrCreateVReg(CI))
669         .addUse(getOrCreateVReg(*CI.getArgOperand(0)))
670         .addUse(getOrCreateVReg(*CI.getArgOperand(1)));
671     return true;
672   case Intrinsic::memcpy:
673   case Intrinsic::memmove:
674   case Intrinsic::memset:
675     return translateMemfunc(CI, MIRBuilder, ID);
676   case Intrinsic::eh_typeid_for: {
677     GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0));
678     unsigned Reg = getOrCreateVReg(CI);
679     unsigned TypeID = MF->getTypeIDFor(GV);
680     MIRBuilder.buildConstant(Reg, TypeID);
681     return true;
682   }
683   case Intrinsic::objectsize: {
684     // If we don't know by now, we're never going to know.
685     const ConstantInt *Min = cast<ConstantInt>(CI.getArgOperand(1));
686
687     MIRBuilder.buildConstant(getOrCreateVReg(CI), Min->isZero() ? -1ULL : 0);
688     return true;
689   }
690   case Intrinsic::stackguard:
691     getStackGuard(getOrCreateVReg(CI), MIRBuilder);
692     return true;
693   case Intrinsic::stackprotector: {
694     LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
695     unsigned GuardVal = MRI->createGenericVirtualRegister(PtrTy);
696     getStackGuard(GuardVal, MIRBuilder);
697
698     AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1));
699     MIRBuilder.buildStore(
700         GuardVal, getOrCreateVReg(*Slot),
701         *MF->getMachineMemOperand(
702             MachinePointerInfo::getFixedStack(*MF,
703                                               getOrCreateFrameIndex(*Slot)),
704             MachineMemOperand::MOStore | MachineMemOperand::MOVolatile,
705             PtrTy.getSizeInBits() / 8, 8));
706     return true;
707   }
708   }
709   return false;
710 }
711
712 bool IRTranslator::translateInlineAsm(const CallInst &CI,
713                                       MachineIRBuilder &MIRBuilder) {
714   const InlineAsm &IA = cast<InlineAsm>(*CI.getCalledValue());
715   if (!IA.getConstraintString().empty())
716     return false;
717
718   unsigned ExtraInfo = 0;
719   if (IA.hasSideEffects())
720     ExtraInfo |= InlineAsm::Extra_HasSideEffects;
721   if (IA.getDialect() == InlineAsm::AD_Intel)
722     ExtraInfo |= InlineAsm::Extra_AsmDialect;
723
724   MIRBuilder.buildInstr(TargetOpcode::INLINEASM)
725     .addExternalSymbol(IA.getAsmString().c_str())
726     .addImm(ExtraInfo);
727
728   return true;
729 }
730
731 bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) {
732   const CallInst &CI = cast<CallInst>(U);
733   auto TII = MF->getTarget().getIntrinsicInfo();
734   const Function *F = CI.getCalledFunction();
735
736   if (CI.isInlineAsm())
737     return translateInlineAsm(CI, MIRBuilder);
738
739   if (!F || !F->isIntrinsic()) {
740     unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI);
741     SmallVector<unsigned, 8> Args;
742     for (auto &Arg: CI.arg_operands())
743       Args.push_back(getOrCreateVReg(*Arg));
744
745     MF->getFrameInfo().setHasCalls(true);
746     return CLI->lowerCall(MIRBuilder, &CI, Res, Args, [&]() {
747       return getOrCreateVReg(*CI.getCalledValue());
748     });
749   }
750
751   Intrinsic::ID ID = F->getIntrinsicID();
752   if (TII && ID == Intrinsic::not_intrinsic)
753     ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F));
754
755   assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
756
757   if (translateKnownIntrinsic(CI, ID, MIRBuilder))
758     return true;
759
760   unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI);
761   MachineInstrBuilder MIB =
762       MIRBuilder.buildIntrinsic(ID, Res, !CI.doesNotAccessMemory());
763
764   for (auto &Arg : CI.arg_operands()) {
765     // Some intrinsics take metadata parameters. Reject them.
766     if (isa<MetadataAsValue>(Arg))
767       return false;
768     if (ConstantInt *CI = dyn_cast<ConstantInt>(Arg))
769       MIB.addImm(CI->getSExtValue());
770     else
771       MIB.addUse(getOrCreateVReg(*Arg));
772   }
773   return true;
774 }
775
776 bool IRTranslator::translateInvoke(const User &U,
777                                    MachineIRBuilder &MIRBuilder) {
778   const InvokeInst &I = cast<InvokeInst>(U);
779   MCContext &Context = MF->getContext();
780
781   const BasicBlock *ReturnBB = I.getSuccessor(0);
782   const BasicBlock *EHPadBB = I.getSuccessor(1);
783
784   const Value *Callee = I.getCalledValue();
785   const Function *Fn = dyn_cast<Function>(Callee);
786   if (isa<InlineAsm>(Callee))
787     return false;
788
789   // FIXME: support invoking patchpoint and statepoint intrinsics.
790   if (Fn && Fn->isIntrinsic())
791     return false;
792
793   // FIXME: support whatever these are.
794   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
795     return false;
796
797   // FIXME: support Windows exception handling.
798   if (!isa<LandingPadInst>(EHPadBB->front()))
799     return false;
800
801
802   // Emit the actual call, bracketed by EH_LABELs so that the MF knows about
803   // the region covered by the try.
804   MCSymbol *BeginSymbol = Context.createTempSymbol();
805   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol);
806
807   unsigned Res = I.getType()->isVoidTy() ? 0 : getOrCreateVReg(I);
808   SmallVector<unsigned, 8> Args;
809   for (auto &Arg: I.arg_operands())
810     Args.push_back(getOrCreateVReg(*Arg));
811
812   if (!CLI->lowerCall(MIRBuilder, &I, Res, Args,
813                       [&]() { return getOrCreateVReg(*I.getCalledValue()); }))
814     return false;
815
816   MCSymbol *EndSymbol = Context.createTempSymbol();
817   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol);
818
819   // FIXME: track probabilities.
820   MachineBasicBlock &EHPadMBB = getMBB(*EHPadBB),
821                     &ReturnMBB = getMBB(*ReturnBB);
822   MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
823   MIRBuilder.getMBB().addSuccessor(&ReturnMBB);
824   MIRBuilder.getMBB().addSuccessor(&EHPadMBB);
825   MIRBuilder.buildBr(ReturnMBB);
826
827   return true;
828 }
829
830 bool IRTranslator::translateLandingPad(const User &U,
831                                        MachineIRBuilder &MIRBuilder) {
832   const LandingPadInst &LP = cast<LandingPadInst>(U);
833
834   MachineBasicBlock &MBB = MIRBuilder.getMBB();
835   addLandingPadInfo(LP, MBB);
836
837   MBB.setIsEHPad();
838
839   // If there aren't registers to copy the values into (e.g., during SjLj
840   // exceptions), then don't bother.
841   auto &TLI = *MF->getSubtarget().getTargetLowering();
842   const Constant *PersonalityFn = MF->getFunction()->getPersonalityFn();
843   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
844       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
845     return true;
846
847   // If landingpad's return type is token type, we don't create DAG nodes
848   // for its exception pointer and selector value. The extraction of exception
849   // pointer or selector value from token type landingpads is not currently
850   // supported.
851   if (LP.getType()->isTokenTy())
852     return true;
853
854   // Add a label to mark the beginning of the landing pad.  Deletion of the
855   // landing pad can thus be detected via the MachineModuleInfo.
856   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL)
857     .addSym(MF->addLandingPad(&MBB));
858
859   LLT Ty = getLLTForType(*LP.getType(), *DL);
860   unsigned Undef = MRI->createGenericVirtualRegister(Ty);
861   MIRBuilder.buildUndef(Undef);
862
863   SmallVector<LLT, 2> Tys;
864   for (Type *Ty : cast<StructType>(LP.getType())->elements())
865     Tys.push_back(getLLTForType(*Ty, *DL));
866   assert(Tys.size() == 2 && "Only two-valued landingpads are supported");
867
868   // Mark exception register as live in.
869   unsigned ExceptionReg = TLI.getExceptionPointerRegister(PersonalityFn);
870   if (!ExceptionReg)
871     return false;
872
873   MBB.addLiveIn(ExceptionReg);
874   unsigned VReg = MRI->createGenericVirtualRegister(Tys[0]),
875            Tmp = MRI->createGenericVirtualRegister(Ty);
876   MIRBuilder.buildCopy(VReg, ExceptionReg);
877   MIRBuilder.buildInsert(Tmp, Undef, VReg, 0);
878
879   unsigned SelectorReg = TLI.getExceptionSelectorRegister(PersonalityFn);
880   if (!SelectorReg)
881     return false;
882
883   MBB.addLiveIn(SelectorReg);
884
885   // N.b. the exception selector register always has pointer type and may not
886   // match the actual IR-level type in the landingpad so an extra cast is
887   // needed.
888   unsigned PtrVReg = MRI->createGenericVirtualRegister(Tys[0]);
889   MIRBuilder.buildCopy(PtrVReg, SelectorReg);
890
891   VReg = MRI->createGenericVirtualRegister(Tys[1]);
892   MIRBuilder.buildInstr(TargetOpcode::G_PTRTOINT).addDef(VReg).addUse(PtrVReg);
893   MIRBuilder.buildInsert(getOrCreateVReg(LP), Tmp, VReg,
894                          Tys[0].getSizeInBits());
895   return true;
896 }
897
898 bool IRTranslator::translateAlloca(const User &U,
899                                    MachineIRBuilder &MIRBuilder) {
900   auto &AI = cast<AllocaInst>(U);
901
902   if (AI.isStaticAlloca()) {
903     unsigned Res = getOrCreateVReg(AI);
904     int FI = getOrCreateFrameIndex(AI);
905     MIRBuilder.buildFrameIndex(Res, FI);
906     return true;
907   }
908
909   // Now we're in the harder dynamic case.
910   Type *Ty = AI.getAllocatedType();
911   unsigned Align =
912       std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI.getAlignment());
913
914   unsigned NumElts = getOrCreateVReg(*AI.getArraySize());
915
916   LLT IntPtrTy = LLT::scalar(DL->getPointerSizeInBits());
917   if (MRI->getType(NumElts) != IntPtrTy) {
918     unsigned ExtElts = MRI->createGenericVirtualRegister(IntPtrTy);
919     MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts);
920     NumElts = ExtElts;
921   }
922
923   unsigned AllocSize = MRI->createGenericVirtualRegister(IntPtrTy);
924   unsigned TySize = MRI->createGenericVirtualRegister(IntPtrTy);
925   MIRBuilder.buildConstant(TySize, -DL->getTypeAllocSize(Ty));
926   MIRBuilder.buildMul(AllocSize, NumElts, TySize);
927
928   LLT PtrTy = getLLTForType(*AI.getType(), *DL);
929   auto &TLI = *MF->getSubtarget().getTargetLowering();
930   unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
931
932   unsigned SPTmp = MRI->createGenericVirtualRegister(PtrTy);
933   MIRBuilder.buildCopy(SPTmp, SPReg);
934
935   unsigned AllocTmp = MRI->createGenericVirtualRegister(PtrTy);
936   MIRBuilder.buildGEP(AllocTmp, SPTmp, AllocSize);
937
938   // Handle alignment. We have to realign if the allocation granule was smaller
939   // than stack alignment, or the specific alloca requires more than stack
940   // alignment.
941   unsigned StackAlign =
942       MF->getSubtarget().getFrameLowering()->getStackAlignment();
943   Align = std::max(Align, StackAlign);
944   if (Align > StackAlign || DL->getTypeAllocSize(Ty) % StackAlign != 0) {
945     // Round the size of the allocation up to the stack alignment size
946     // by add SA-1 to the size. This doesn't overflow because we're computing
947     // an address inside an alloca.
948     unsigned AlignedAlloc = MRI->createGenericVirtualRegister(PtrTy);
949     MIRBuilder.buildPtrMask(AlignedAlloc, AllocTmp, Log2_32(Align));
950     AllocTmp = AlignedAlloc;
951   }
952
953   MIRBuilder.buildCopy(SPReg, AllocTmp);
954   MIRBuilder.buildCopy(getOrCreateVReg(AI), AllocTmp);
955
956   MF->getFrameInfo().CreateVariableSizedObject(Align ? Align : 1, &AI);
957   assert(MF->getFrameInfo().hasVarSizedObjects());
958   return true;
959 }
960
961 bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) {
962   // FIXME: We may need more info about the type. Because of how LLT works,
963   // we're completely discarding the i64/double distinction here (amongst
964   // others). Fortunately the ABIs I know of where that matters don't use va_arg
965   // anyway but that's not guaranteed.
966   MIRBuilder.buildInstr(TargetOpcode::G_VAARG)
967     .addDef(getOrCreateVReg(U))
968     .addUse(getOrCreateVReg(*U.getOperand(0)))
969     .addImm(DL->getABITypeAlignment(U.getType()));
970   return true;
971 }
972
973 bool IRTranslator::translateInsertElement(const User &U,
974                                           MachineIRBuilder &MIRBuilder) {
975   // If it is a <1 x Ty> vector, use the scalar as it is
976   // not a legal vector type in LLT.
977   if (U.getType()->getVectorNumElements() == 1) {
978     unsigned Elt = getOrCreateVReg(*U.getOperand(1));
979     ValToVReg[&U] = Elt;
980     return true;
981   }
982   MIRBuilder.buildInsertVectorElement(
983       getOrCreateVReg(U), getOrCreateVReg(*U.getOperand(0)),
984       getOrCreateVReg(*U.getOperand(1)), getOrCreateVReg(*U.getOperand(2)));
985   return true;
986 }
987
988 bool IRTranslator::translateExtractElement(const User &U,
989                                            MachineIRBuilder &MIRBuilder) {
990   // If it is a <1 x Ty> vector, use the scalar as it is
991   // not a legal vector type in LLT.
992   if (U.getOperand(0)->getType()->getVectorNumElements() == 1) {
993     unsigned Elt = getOrCreateVReg(*U.getOperand(0));
994     ValToVReg[&U] = Elt;
995     return true;
996   }
997   MIRBuilder.buildExtractVectorElement(getOrCreateVReg(U),
998                                        getOrCreateVReg(*U.getOperand(0)),
999                                        getOrCreateVReg(*U.getOperand(1)));
1000   return true;
1001 }
1002
1003 bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) {
1004   const PHINode &PI = cast<PHINode>(U);
1005   auto MIB = MIRBuilder.buildInstr(TargetOpcode::PHI);
1006   MIB.addDef(getOrCreateVReg(PI));
1007
1008   PendingPHIs.emplace_back(&PI, MIB.getInstr());
1009   return true;
1010 }
1011
1012 void IRTranslator::finishPendingPhis() {
1013   for (std::pair<const PHINode *, MachineInstr *> &Phi : PendingPHIs) {
1014     const PHINode *PI = Phi.first;
1015     MachineInstrBuilder MIB(*MF, Phi.second);
1016
1017     // All MachineBasicBlocks exist, add them to the PHI. We assume IRTranslator
1018     // won't create extra control flow here, otherwise we need to find the
1019     // dominating predecessor here (or perhaps force the weirder IRTranslators
1020     // to provide a simple boundary).
1021     SmallSet<const BasicBlock *, 4> HandledPreds;
1022
1023     for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
1024       auto IRPred = PI->getIncomingBlock(i);
1025       if (HandledPreds.count(IRPred))
1026         continue;
1027
1028       HandledPreds.insert(IRPred);
1029       unsigned ValReg = getOrCreateVReg(*PI->getIncomingValue(i));
1030       for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) {
1031         assert(Pred->isSuccessor(MIB->getParent()) &&
1032                "incorrect CFG at MachineBasicBlock level");
1033         MIB.addUse(ValReg);
1034         MIB.addMBB(Pred);
1035       }
1036     }
1037   }
1038 }
1039
1040 bool IRTranslator::translate(const Instruction &Inst) {
1041   CurBuilder.setDebugLoc(Inst.getDebugLoc());
1042   switch(Inst.getOpcode()) {
1043 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1044     case Instruction::OPCODE: return translate##OPCODE(Inst, CurBuilder);
1045 #include "llvm/IR/Instruction.def"
1046   default:
1047     return false;
1048   }
1049 }
1050
1051 bool IRTranslator::translate(const Constant &C, unsigned Reg) {
1052   if (auto CI = dyn_cast<ConstantInt>(&C))
1053     EntryBuilder.buildConstant(Reg, *CI);
1054   else if (auto CF = dyn_cast<ConstantFP>(&C))
1055     EntryBuilder.buildFConstant(Reg, *CF);
1056   else if (isa<UndefValue>(C))
1057     EntryBuilder.buildUndef(Reg);
1058   else if (isa<ConstantPointerNull>(C))
1059     EntryBuilder.buildConstant(Reg, 0);
1060   else if (auto GV = dyn_cast<GlobalValue>(&C))
1061     EntryBuilder.buildGlobalValue(Reg, GV);
1062   else if (auto CAZ = dyn_cast<ConstantAggregateZero>(&C)) {
1063     if (!CAZ->getType()->isVectorTy())
1064       return false;
1065     // Return the scalar if it is a <1 x Ty> vector.
1066     if (CAZ->getNumElements() == 1)
1067       return translate(*CAZ->getElementValue(0u), Reg);
1068     std::vector<unsigned> Ops;
1069     for (unsigned i = 0; i < CAZ->getNumElements(); ++i) {
1070       Constant &Elt = *CAZ->getElementValue(i);
1071       Ops.push_back(getOrCreateVReg(Elt));
1072     }
1073     EntryBuilder.buildMerge(Reg, Ops);
1074   } else if (auto CV = dyn_cast<ConstantDataVector>(&C)) {
1075     // Return the scalar if it is a <1 x Ty> vector.
1076     if (CV->getNumElements() == 1)
1077       return translate(*CV->getElementAsConstant(0), Reg);
1078     std::vector<unsigned> Ops;
1079     for (unsigned i = 0; i < CV->getNumElements(); ++i) {
1080       Constant &Elt = *CV->getElementAsConstant(i);
1081       Ops.push_back(getOrCreateVReg(Elt));
1082     }
1083     EntryBuilder.buildMerge(Reg, Ops);
1084   } else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
1085     switch(CE->getOpcode()) {
1086 #define HANDLE_INST(NUM, OPCODE, CLASS)                         \
1087       case Instruction::OPCODE: return translate##OPCODE(*CE, EntryBuilder);
1088 #include "llvm/IR/Instruction.def"
1089     default:
1090       return false;
1091     }
1092   } else
1093     return false;
1094
1095   return true;
1096 }
1097
1098 void IRTranslator::finalizeFunction() {
1099   // Release the memory used by the different maps we
1100   // needed during the translation.
1101   PendingPHIs.clear();
1102   ValToVReg.clear();
1103   FrameIndices.clear();
1104   MachinePreds.clear();
1105 }
1106
1107 bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) {
1108   MF = &CurMF;
1109   const Function &F = *MF->getFunction();
1110   if (F.empty())
1111     return false;
1112   CLI = MF->getSubtarget().getCallLowering();
1113   CurBuilder.setMF(*MF);
1114   EntryBuilder.setMF(*MF);
1115   MRI = &MF->getRegInfo();
1116   DL = &F.getParent()->getDataLayout();
1117   TPC = &getAnalysis<TargetPassConfig>();
1118   ORE = make_unique<OptimizationRemarkEmitter>(&F);
1119
1120   assert(PendingPHIs.empty() && "stale PHIs");
1121
1122   // Release the per-function state when we return, whether we succeeded or not.
1123   auto FinalizeOnReturn = make_scope_exit([this]() { finalizeFunction(); });
1124
1125   // Setup a separate basic-block for the arguments and constants
1126   MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock();
1127   MF->push_back(EntryBB);
1128   EntryBuilder.setMBB(*EntryBB);
1129
1130   // Create all blocks, in IR order, to preserve the layout.
1131   for (const BasicBlock &BB: F) {
1132     auto *&MBB = BBToMBB[&BB];
1133
1134     MBB = MF->CreateMachineBasicBlock(&BB);
1135     MF->push_back(MBB);
1136
1137     if (BB.hasAddressTaken())
1138       MBB->setHasAddressTaken();
1139   }
1140
1141   // Make our arguments/constants entry block fallthrough to the IR entry block.
1142   EntryBB->addSuccessor(&getMBB(F.front()));
1143
1144   // Lower the actual args into this basic block.
1145   SmallVector<unsigned, 8> VRegArgs;
1146   for (const Argument &Arg: F.args())
1147     VRegArgs.push_back(getOrCreateVReg(Arg));
1148   if (!CLI->lowerFormalArguments(EntryBuilder, F, VRegArgs)) {
1149     OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1150                                MF->getFunction()->getSubprogram(),
1151                                &MF->getFunction()->getEntryBlock());
1152     R << "unable to lower arguments: " << ore::NV("Prototype", F.getType());
1153     reportTranslationError(*MF, *TPC, *ORE, R);
1154     return false;
1155   }
1156
1157   // And translate the function!
1158   for (const BasicBlock &BB: F) {
1159     MachineBasicBlock &MBB = getMBB(BB);
1160     // Set the insertion point of all the following translations to
1161     // the end of this basic block.
1162     CurBuilder.setMBB(MBB);
1163
1164     for (const Instruction &Inst: BB) {
1165       if (translate(Inst))
1166         continue;
1167
1168       std::string InstStrStorage;
1169       raw_string_ostream InstStr(InstStrStorage);
1170       InstStr << Inst;
1171
1172       OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1173                                  Inst.getDebugLoc(), &BB);
1174       R << "unable to translate instruction: " << ore::NV("Opcode", &Inst)
1175         << ": '" << InstStr.str() << "'";
1176       reportTranslationError(*MF, *TPC, *ORE, R);
1177       return false;
1178     }
1179   }
1180
1181   finishPendingPhis();
1182
1183   // Now that the MachineFrameInfo has been configured, no further changes to
1184   // the reserved registers are possible.
1185   MRI->freezeReservedRegs(*MF);
1186
1187   // Merge the argument lowering and constants block with its single
1188   // successor, the LLVM-IR entry block.  We want the basic block to
1189   // be maximal.
1190   assert(EntryBB->succ_size() == 1 &&
1191          "Custom BB used for lowering should have only one successor");
1192   // Get the successor of the current entry block.
1193   MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin();
1194   assert(NewEntryBB.pred_size() == 1 &&
1195          "LLVM-IR entry block has a predecessor!?");
1196   // Move all the instruction from the current entry block to the
1197   // new entry block.
1198   NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(),
1199                     EntryBB->end());
1200
1201   // Update the live-in information for the new entry block.
1202   for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins())
1203     NewEntryBB.addLiveIn(LiveIn);
1204   NewEntryBB.sortUniqueLiveIns();
1205
1206   // Get rid of the now empty basic block.
1207   EntryBB->removeSuccessor(&NewEntryBB);
1208   MF->remove(EntryBB);
1209   MF->DeleteMachineBasicBlock(EntryBB);
1210
1211   assert(&MF->front() == &NewEntryBB &&
1212          "New entry wasn't next in the list of basic block!");
1213
1214   return false;
1215 }