1 //===- llvm/CodeGen/GlobalISel/IRTranslator.cpp - IRTranslator ---*- C++ -*-==//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 /// \file
9 /// This file implements the IRTranslator class.
10 //===----------------------------------------------------------------------===//
11 
12 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
13 #include "llvm/ADT/PostOrderIterator.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/ADT/ScopeExit.h"
16 #include "llvm/ADT/SmallSet.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
19 #include "llvm/Analysis/ValueTracking.h"
20 #include "llvm/CodeGen/Analysis.h"
21 #include "llvm/CodeGen/GlobalISel/CallLowering.h"
22 #include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h"
23 #include "llvm/CodeGen/LowLevelType.h"
24 #include "llvm/CodeGen/MachineBasicBlock.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineMemOperand.h"
29 #include "llvm/CodeGen/MachineOperand.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/StackProtector.h"
32 #include "llvm/CodeGen/TargetFrameLowering.h"
33 #include "llvm/CodeGen/TargetLowering.h"
34 #include "llvm/CodeGen/TargetPassConfig.h"
35 #include "llvm/CodeGen/TargetRegisterInfo.h"
36 #include "llvm/CodeGen/TargetSubtargetInfo.h"
37 #include "llvm/IR/BasicBlock.h"
38 #include "llvm/IR/CFG.h"
39 #include "llvm/IR/Constant.h"
40 #include "llvm/IR/Constants.h"
41 #include "llvm/IR/DataLayout.h"
42 #include "llvm/IR/DebugInfo.h"
43 #include "llvm/IR/DerivedTypes.h"
44 #include "llvm/IR/Function.h"
45 #include "llvm/IR/GetElementPtrTypeIterator.h"
46 #include "llvm/IR/InlineAsm.h"
47 #include "llvm/IR/InstrTypes.h"
48 #include "llvm/IR/Instructions.h"
49 #include "llvm/IR/IntrinsicInst.h"
50 #include "llvm/IR/Intrinsics.h"
51 #include "llvm/IR/LLVMContext.h"
52 #include "llvm/IR/Metadata.h"
53 #include "llvm/IR/Type.h"
54 #include "llvm/IR/User.h"
55 #include "llvm/IR/Value.h"
56 #include "llvm/MC/MCContext.h"
57 #include "llvm/Pass.h"
58 #include "llvm/Support/Casting.h"
59 #include "llvm/Support/CodeGen.h"
60 #include "llvm/Support/Debug.h"
61 #include "llvm/Support/ErrorHandling.h"
62 #include "llvm/Support/LowLevelTypeImpl.h"
63 #include "llvm/Support/MathExtras.h"
64 #include "llvm/Support/raw_ostream.h"
65 #include "llvm/Target/TargetIntrinsicInfo.h"
66 #include "llvm/Target/TargetMachine.h"
67 #include <algorithm>
68 #include <cassert>
69 #include <cstdint>
70 #include <iterator>
71 #include <string>
72 #include <utility>
73 #include <vector>
74 
75 #define DEBUG_TYPE "irtranslator"
76 
77 using namespace llvm;
78 
79 static cl::opt<bool>
80     EnableCSEInIRTranslator("enable-cse-in-irtranslator",
81                             cl::desc("Should enable CSE in irtranslator"),
82                             cl::Optional, cl::init(false));
83 char IRTranslator::ID = 0;
84 
85 INITIALIZE_PASS_BEGIN(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
86                 false, false)
87 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
88 INITIALIZE_PASS_DEPENDENCY(GISelCSEAnalysisWrapperPass)
89 INITIALIZE_PASS_END(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
90                 false, false)
91 
92 static void reportTranslationError(MachineFunction &MF,
93                                    const TargetPassConfig &TPC,
94                                    OptimizationRemarkEmitter &ORE,
95                                    OptimizationRemarkMissed &R) {
96   MF.getProperties().set(MachineFunctionProperties::Property::FailedISel);
97 
98   // Print the function name explicitly if we don't have a debug location (which
99   // makes the diagnostic less useful) or if we're going to emit a raw error.
100   if (!R.getLocation().isValid() || TPC.isGlobalISelAbortEnabled())
101     R << (" (in function: " + MF.getName() + ")").str();
102 
103   if (TPC.isGlobalISelAbortEnabled())
104     report_fatal_error(R.getMsg());
105   else
106     ORE.emit(R);
107 }
108 
109 IRTranslator::IRTranslator() : MachineFunctionPass(ID) {
110   initializeIRTranslatorPass(*PassRegistry::getPassRegistry());
111 }
112 
113 #ifndef NDEBUG
114 namespace {
115 /// Verify that every instruction created has the same DILocation as the
116 /// instruction being translated.
117 class DILocationVerifier : public GISelChangeObserver {
118   const Instruction *CurrInst = nullptr;
119 
120 public:
121   DILocationVerifier() = default;
122   ~DILocationVerifier() = default;
123 
124   const Instruction *getCurrentInst() const { return CurrInst; }
125   void setCurrentInst(const Instruction *Inst) { CurrInst = Inst; }
126 
127   void erasingInstr(MachineInstr &MI) override {}
128   void changingInstr(MachineInstr &MI) override {}
129   void changedInstr(MachineInstr &MI) override {}
130 
131   void createdInstr(MachineInstr &MI) override {
132     assert(getCurrentInst() && "Inserted instruction without a current MI");
133 
134     // Only print the check message if we're actually checking it.
135 #ifndef NDEBUG
136     LLVM_DEBUG(dbgs() << "Checking DILocation from " << *CurrInst
137                       << " was copied to " << MI);
138 #endif
139     assert(CurrInst->getDebugLoc() == MI.getDebugLoc() &&
140            "Line info was not transferred to all instructions");
141   }
142 };
143 } // namespace
144 #endif // ifndef NDEBUG
145 
146 
147 void IRTranslator::getAnalysisUsage(AnalysisUsage &AU) const {
148   AU.addRequired<StackProtector>();
149   AU.addRequired<TargetPassConfig>();
150   AU.addRequired<GISelCSEAnalysisWrapperPass>();
151   getSelectionDAGFallbackAnalysisUsage(AU);
152   MachineFunctionPass::getAnalysisUsage(AU);
153 }
154 
155 IRTranslator::ValueToVRegInfo::VRegListT &
156 IRTranslator::allocateVRegs(const Value &Val) {
157   assert(!VMap.contains(Val) && "Value already allocated in VMap");
158   auto *Regs = VMap.getVRegs(Val);
159   auto *Offsets = VMap.getOffsets(Val);
160   SmallVector<LLT, 4> SplitTys;
161   computeValueLLTs(*DL, *Val.getType(), SplitTys,
162                    Offsets->empty() ? Offsets : nullptr);
163   for (unsigned i = 0; i < SplitTys.size(); ++i)
164     Regs->push_back(0);
165   return *Regs;
166 }
167 
168 ArrayRef<unsigned> IRTranslator::getOrCreateVRegs(const Value &Val) {
169   auto VRegsIt = VMap.findVRegs(Val);
170   if (VRegsIt != VMap.vregs_end())
171     return *VRegsIt->second;
172 
173   if (Val.getType()->isVoidTy())
174     return *VMap.getVRegs(Val);
175 
176   // Create entry for this type.
177   auto *VRegs = VMap.getVRegs(Val);
178   auto *Offsets = VMap.getOffsets(Val);
179 
180   assert(Val.getType()->isSized() &&
181          "Don't know how to create an empty vreg");
182 
183   SmallVector<LLT, 4> SplitTys;
184   computeValueLLTs(*DL, *Val.getType(), SplitTys,
185                    Offsets->empty() ? Offsets : nullptr);
186 
187   if (!isa<Constant>(Val)) {
188     for (auto Ty : SplitTys)
189       VRegs->push_back(MRI->createGenericVirtualRegister(Ty));
190     return *VRegs;
191   }
192 
193   if (Val.getType()->isAggregateType()) {
194     // UndefValue, ConstantAggregateZero
195     auto &C = cast<Constant>(Val);
196     unsigned Idx = 0;
197     while (auto Elt = C.getAggregateElement(Idx++)) {
198       auto EltRegs = getOrCreateVRegs(*Elt);
199       llvm::copy(EltRegs, std::back_inserter(*VRegs));
200     }
201   } else {
202     assert(SplitTys.size() == 1 && "unexpectedly split LLT");
203     VRegs->push_back(MRI->createGenericVirtualRegister(SplitTys[0]));
204     bool Success = translate(cast<Constant>(Val), VRegs->front());
205     if (!Success) {
206       OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
207                                  MF->getFunction().getSubprogram(),
208                                  &MF->getFunction().getEntryBlock());
209       R << "unable to translate constant: " << ore::NV("Type", Val.getType());
210       reportTranslationError(*MF, *TPC, *ORE, R);
211       return *VRegs;
212     }
213   }
214 
215   return *VRegs;
216 }
217 
218 int IRTranslator::getOrCreateFrameIndex(const AllocaInst &AI) {
219   if (FrameIndices.find(&AI) != FrameIndices.end())
220     return FrameIndices[&AI];
221 
222   unsigned ElementSize = DL->getTypeStoreSize(AI.getAllocatedType());
223   unsigned Size =
224       ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue();
225 
226   // Always allocate at least one byte.
227   Size = std::max(Size, 1u);
228 
229   unsigned Alignment = AI.getAlignment();
230   if (!Alignment)
231     Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
232 
233   int &FI = FrameIndices[&AI];
234   FI = MF->getFrameInfo().CreateStackObject(Size, Alignment, false, &AI);
235   return FI;
236 }
237 
238 unsigned IRTranslator::getMemOpAlignment(const Instruction &I) {
239   unsigned Alignment = 0;
240   Type *ValTy = nullptr;
241   if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
242     Alignment = SI->getAlignment();
243     ValTy = SI->getValueOperand()->getType();
244   } else if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
245     Alignment = LI->getAlignment();
246     ValTy = LI->getType();
247   } else if (const AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(&I)) {
248     // TODO(PR27168): This instruction has no alignment attribute, but unlike
249     // the default alignment for load/store, the default here is to assume
250     // it has NATURAL alignment, not DataLayout-specified alignment.
251     const DataLayout &DL = AI->getModule()->getDataLayout();
252     Alignment = DL.getTypeStoreSize(AI->getCompareOperand()->getType());
253     ValTy = AI->getCompareOperand()->getType();
254   } else if (const AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(&I)) {
255     // TODO(PR27168): This instruction has no alignment attribute, but unlike
256     // the default alignment for load/store, the default here is to assume
257     // it has NATURAL alignment, not DataLayout-specified alignment.
258     const DataLayout &DL = AI->getModule()->getDataLayout();
259     Alignment = DL.getTypeStoreSize(AI->getValOperand()->getType());
260     ValTy = AI->getType();
261   } else {
262     OptimizationRemarkMissed R("gisel-irtranslator", "", &I);
263     R << "unable to translate memop: " << ore::NV("Opcode", &I);
264     reportTranslationError(*MF, *TPC, *ORE, R);
265     return 1;
266   }
267 
268   return Alignment ? Alignment : DL->getABITypeAlignment(ValTy);
269 }
270 
271 MachineBasicBlock &IRTranslator::getMBB(const BasicBlock &BB) {
272   MachineBasicBlock *&MBB = BBToMBB[&BB];
273   assert(MBB && "BasicBlock was not encountered before");
274   return *MBB;
275 }
276 
277 void IRTranslator::addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred) {
278   assert(NewPred && "new predecessor must be a real MachineBasicBlock");
279   MachinePreds[Edge].push_back(NewPred);
280 }
281 
282 bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U,
283                                      MachineIRBuilder &MIRBuilder) {
284   // FIXME: handle signed/unsigned wrapping flags.
285 
286   // Get or create a virtual register for each value.
287   // Unless the value is a Constant => loadimm cst?
288   // or inline constant each time?
289   // Creation of a virtual register needs to have a size.
290   unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
291   unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
292   unsigned Res = getOrCreateVReg(U);
293   uint16_t Flags = 0;
294   if (isa<Instruction>(U)) {
295     const Instruction &I = cast<Instruction>(U);
296     Flags = MachineInstr::copyFlagsFromInstruction(I);
297   }
298 
299   MIRBuilder.buildInstr(Opcode, {Res}, {Op0, Op1}, Flags);
300   return true;
301 }
302 
303 bool IRTranslator::translateFSub(const User &U, MachineIRBuilder &MIRBuilder) {
304   // -0.0 - X --> G_FNEG
305   if (isa<Constant>(U.getOperand(0)) &&
306       U.getOperand(0) == ConstantFP::getZeroValueForNegation(U.getType())) {
307     MIRBuilder.buildInstr(TargetOpcode::G_FNEG)
308         .addDef(getOrCreateVReg(U))
309         .addUse(getOrCreateVReg(*U.getOperand(1)));
310     return true;
311   }
312   return translateBinaryOp(TargetOpcode::G_FSUB, U, MIRBuilder);
313 }
314 
315 bool IRTranslator::translateFNeg(const User &U, MachineIRBuilder &MIRBuilder) {
316   MIRBuilder.buildInstr(TargetOpcode::G_FNEG)
317       .addDef(getOrCreateVReg(U))
318       .addUse(getOrCreateVReg(*U.getOperand(0)));
319   return true;
320 }
321 
322 bool IRTranslator::translateCompare(const User &U,
323                                     MachineIRBuilder &MIRBuilder) {
324   const CmpInst *CI = dyn_cast<CmpInst>(&U);
325   unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
326   unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
327   unsigned Res = getOrCreateVReg(U);
328   CmpInst::Predicate Pred =
329       CI ? CI->getPredicate() : static_cast<CmpInst::Predicate>(
330                                     cast<ConstantExpr>(U).getPredicate());
331   if (CmpInst::isIntPredicate(Pred))
332     MIRBuilder.buildICmp(Pred, Res, Op0, Op1);
333   else if (Pred == CmpInst::FCMP_FALSE)
334     MIRBuilder.buildCopy(
335         Res, getOrCreateVReg(*Constant::getNullValue(CI->getType())));
336   else if (Pred == CmpInst::FCMP_TRUE)
337     MIRBuilder.buildCopy(
338         Res, getOrCreateVReg(*Constant::getAllOnesValue(CI->getType())));
339   else {
340     MIRBuilder.buildInstr(TargetOpcode::G_FCMP, {Res}, {Pred, Op0, Op1},
341                           MachineInstr::copyFlagsFromInstruction(*CI));
342   }
343 
344   return true;
345 }
346 
347 bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) {
348   const ReturnInst &RI = cast<ReturnInst>(U);
349   const Value *Ret = RI.getReturnValue();
350   if (Ret && DL->getTypeStoreSize(Ret->getType()) == 0)
351     Ret = nullptr;
352 
353   ArrayRef<unsigned> VRegs;
354   if (Ret)
355     VRegs = getOrCreateVRegs(*Ret);
356 
357   // The target may mess up with the insertion point, but
358   // this is not important as a return is the last instruction
359   // of the block anyway.
360 
361   return CLI->lowerReturn(MIRBuilder, Ret, VRegs);
362 }
363 
364 bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) {
365   const BranchInst &BrInst = cast<BranchInst>(U);
366   unsigned Succ = 0;
367   if (!BrInst.isUnconditional()) {
368     // We want a G_BRCOND to the true BB followed by an unconditional branch.
369     unsigned Tst = getOrCreateVReg(*BrInst.getCondition());
370     const BasicBlock &TrueTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ++));
371     MachineBasicBlock &TrueBB = getMBB(TrueTgt);
372     MIRBuilder.buildBrCond(Tst, TrueBB);
373   }
374 
375   const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ));
376   MachineBasicBlock &TgtBB = getMBB(BrTgt);
377   MachineBasicBlock &CurBB = MIRBuilder.getMBB();
378 
379   // If the unconditional target is the layout successor, fallthrough.
380   if (!CurBB.isLayoutSuccessor(&TgtBB))
381     MIRBuilder.buildBr(TgtBB);
382 
383   // Link successors.
384   for (const BasicBlock *Succ : successors(&BrInst))
385     CurBB.addSuccessor(&getMBB(*Succ));
386   return true;
387 }
388 
389 bool IRTranslator::translateSwitch(const User &U,
390                                    MachineIRBuilder &MIRBuilder) {
391   // For now, just translate as a chain of conditional branches.
392   // FIXME: could we share most of the logic/code in
393   // SelectionDAGBuilder::visitSwitch between SelectionDAG and GlobalISel?
394   // At first sight, it seems most of the logic in there is independent of
395   // SelectionDAG-specifics and a lot of work went in to optimize switch
396   // lowering in there.
397 
398   const SwitchInst &SwInst = cast<SwitchInst>(U);
399   const unsigned SwCondValue = getOrCreateVReg(*SwInst.getCondition());
400   const BasicBlock *OrigBB = SwInst.getParent();
401 
402   LLT LLTi1 = getLLTForType(*Type::getInt1Ty(U.getContext()), *DL);
403   for (auto &CaseIt : SwInst.cases()) {
404     const unsigned CaseValueReg = getOrCreateVReg(*CaseIt.getCaseValue());
405     const unsigned Tst = MRI->createGenericVirtualRegister(LLTi1);
406     MIRBuilder.buildICmp(CmpInst::ICMP_EQ, Tst, CaseValueReg, SwCondValue);
407     MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
408     const BasicBlock *TrueBB = CaseIt.getCaseSuccessor();
409     MachineBasicBlock &TrueMBB = getMBB(*TrueBB);
410 
411     MIRBuilder.buildBrCond(Tst, TrueMBB);
412     CurMBB.addSuccessor(&TrueMBB);
413     addMachineCFGPred({OrigBB, TrueBB}, &CurMBB);
414 
415     MachineBasicBlock *FalseMBB =
416         MF->CreateMachineBasicBlock(SwInst.getParent());
417     // Insert the comparison blocks one after the other.
418     MF->insert(std::next(CurMBB.getIterator()), FalseMBB);
419     MIRBuilder.buildBr(*FalseMBB);
420     CurMBB.addSuccessor(FalseMBB);
421 
422     MIRBuilder.setMBB(*FalseMBB);
423   }
424   // handle default case
425   const BasicBlock *DefaultBB = SwInst.getDefaultDest();
426   MachineBasicBlock &DefaultMBB = getMBB(*DefaultBB);
427   MIRBuilder.buildBr(DefaultMBB);
428   MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
429   CurMBB.addSuccessor(&DefaultMBB);
430   addMachineCFGPred({OrigBB, DefaultBB}, &CurMBB);
431 
432   return true;
433 }
434 
435 bool IRTranslator::translateIndirectBr(const User &U,
436                                        MachineIRBuilder &MIRBuilder) {
437   const IndirectBrInst &BrInst = cast<IndirectBrInst>(U);
438 
439   const unsigned Tgt = getOrCreateVReg(*BrInst.getAddress());
440   MIRBuilder.buildBrIndirect(Tgt);
441 
442   // Link successors.
443   MachineBasicBlock &CurBB = MIRBuilder.getMBB();
444   for (const BasicBlock *Succ : successors(&BrInst))
445     CurBB.addSuccessor(&getMBB(*Succ));
446 
447   return true;
448 }
449 
450 bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) {
451   const LoadInst &LI = cast<LoadInst>(U);
452 
453   auto Flags = LI.isVolatile() ? MachineMemOperand::MOVolatile
454                                : MachineMemOperand::MONone;
455   Flags |= MachineMemOperand::MOLoad;
456 
457   if (DL->getTypeStoreSize(LI.getType()) == 0)
458     return true;
459 
460   ArrayRef<unsigned> Regs = getOrCreateVRegs(LI);
461   ArrayRef<uint64_t> Offsets = *VMap.getOffsets(LI);
462   unsigned Base = getOrCreateVReg(*LI.getPointerOperand());
463 
464   for (unsigned i = 0; i < Regs.size(); ++i) {
465     unsigned Addr = 0;
466     MIRBuilder.materializeGEP(Addr, Base, LLT::scalar(64), Offsets[i] / 8);
467 
468     MachinePointerInfo Ptr(LI.getPointerOperand(), Offsets[i] / 8);
469     unsigned BaseAlign = getMemOpAlignment(LI);
470     auto MMO = MF->getMachineMemOperand(
471         Ptr, Flags, (MRI->getType(Regs[i]).getSizeInBits() + 7) / 8,
472         MinAlign(BaseAlign, Offsets[i] / 8), AAMDNodes(), nullptr,
473         LI.getSyncScopeID(), LI.getOrdering());
474     MIRBuilder.buildLoad(Regs[i], Addr, *MMO);
475   }
476 
477   return true;
478 }
479 
480 bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) {
481   const StoreInst &SI = cast<StoreInst>(U);
482   auto Flags = SI.isVolatile() ? MachineMemOperand::MOVolatile
483                                : MachineMemOperand::MONone;
484   Flags |= MachineMemOperand::MOStore;
485 
486   if (DL->getTypeStoreSize(SI.getValueOperand()->getType()) == 0)
487     return true;
488 
489   ArrayRef<unsigned> Vals = getOrCreateVRegs(*SI.getValueOperand());
490   ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*SI.getValueOperand());
491   unsigned Base = getOrCreateVReg(*SI.getPointerOperand());
492 
493   for (unsigned i = 0; i < Vals.size(); ++i) {
494     unsigned Addr = 0;
495     MIRBuilder.materializeGEP(Addr, Base, LLT::scalar(64), Offsets[i] / 8);
496 
497     MachinePointerInfo Ptr(SI.getPointerOperand(), Offsets[i] / 8);
498     unsigned BaseAlign = getMemOpAlignment(SI);
499     auto MMO = MF->getMachineMemOperand(
500         Ptr, Flags, (MRI->getType(Vals[i]).getSizeInBits() + 7) / 8,
501         MinAlign(BaseAlign, Offsets[i] / 8), AAMDNodes(), nullptr,
502         SI.getSyncScopeID(), SI.getOrdering());
503     MIRBuilder.buildStore(Vals[i], Addr, *MMO);
504   }
505   return true;
506 }
507 
508 static uint64_t getOffsetFromIndices(const User &U, const DataLayout &DL) {
509   const Value *Src = U.getOperand(0);
510   Type *Int32Ty = Type::getInt32Ty(U.getContext());
511 
512   // getIndexedOffsetInType is designed for GEPs, so the first index is the
513   // usual array element rather than looking into the actual aggregate.
514   SmallVector<Value *, 1> Indices;
515   Indices.push_back(ConstantInt::get(Int32Ty, 0));
516 
517   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) {
518     for (auto Idx : EVI->indices())
519       Indices.push_back(ConstantInt::get(Int32Ty, Idx));
520   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) {
521     for (auto Idx : IVI->indices())
522       Indices.push_back(ConstantInt::get(Int32Ty, Idx));
523   } else {
524     for (unsigned i = 1; i < U.getNumOperands(); ++i)
525       Indices.push_back(U.getOperand(i));
526   }
527 
528   return 8 * static_cast<uint64_t>(
529                  DL.getIndexedOffsetInType(Src->getType(), Indices));
530 }
531 
532 bool IRTranslator::translateExtractValue(const User &U,
533                                          MachineIRBuilder &MIRBuilder) {
534   const Value *Src = U.getOperand(0);
535   uint64_t Offset = getOffsetFromIndices(U, *DL);
536   ArrayRef<unsigned> SrcRegs = getOrCreateVRegs(*Src);
537   ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*Src);
538   unsigned Idx = std::lower_bound(Offsets.begin(), Offsets.end(), Offset) -
539                  Offsets.begin();
540   auto &DstRegs = allocateVRegs(U);
541 
542   for (unsigned i = 0; i < DstRegs.size(); ++i)
543     DstRegs[i] = SrcRegs[Idx++];
544 
545   return true;
546 }
547 
548 bool IRTranslator::translateInsertValue(const User &U,
549                                         MachineIRBuilder &MIRBuilder) {
550   const Value *Src = U.getOperand(0);
551   uint64_t Offset = getOffsetFromIndices(U, *DL);
552   auto &DstRegs = allocateVRegs(U);
553   ArrayRef<uint64_t> DstOffsets = *VMap.getOffsets(U);
554   ArrayRef<unsigned> SrcRegs = getOrCreateVRegs(*Src);
555   ArrayRef<unsigned> InsertedRegs = getOrCreateVRegs(*U.getOperand(1));
556   auto InsertedIt = InsertedRegs.begin();
557 
558   for (unsigned i = 0; i < DstRegs.size(); ++i) {
559     if (DstOffsets[i] >= Offset && InsertedIt != InsertedRegs.end())
560       DstRegs[i] = *InsertedIt++;
561     else
562       DstRegs[i] = SrcRegs[i];
563   }
564 
565   return true;
566 }
567 
568 bool IRTranslator::translateSelect(const User &U,
569                                    MachineIRBuilder &MIRBuilder) {
570   unsigned Tst = getOrCreateVReg(*U.getOperand(0));
571   ArrayRef<unsigned> ResRegs = getOrCreateVRegs(U);
572   ArrayRef<unsigned> Op0Regs = getOrCreateVRegs(*U.getOperand(1));
573   ArrayRef<unsigned> Op1Regs = getOrCreateVRegs(*U.getOperand(2));
574 
575   const SelectInst &SI = cast<SelectInst>(U);
576   uint16_t Flags = 0;
577   if (const CmpInst *Cmp = dyn_cast<CmpInst>(SI.getCondition()))
578     Flags = MachineInstr::copyFlagsFromInstruction(*Cmp);
579 
580   for (unsigned i = 0; i < ResRegs.size(); ++i) {
581     MIRBuilder.buildInstr(TargetOpcode::G_SELECT, {ResRegs[i]},
582                           {Tst, Op0Regs[i], Op1Regs[i]}, Flags);
583   }
584 
585   return true;
586 }
587 
588 bool IRTranslator::translateBitCast(const User &U,
589                                     MachineIRBuilder &MIRBuilder) {
590   // If we're bitcasting to the source type, we can reuse the source vreg.
591   if (getLLTForType(*U.getOperand(0)->getType(), *DL) ==
592       getLLTForType(*U.getType(), *DL)) {
593     unsigned SrcReg = getOrCreateVReg(*U.getOperand(0));
594     auto &Regs = *VMap.getVRegs(U);
595     // If we already assigned a vreg for this bitcast, we can't change that.
596     // Emit a copy to satisfy the users we already emitted.
597     if (!Regs.empty())
598       MIRBuilder.buildCopy(Regs[0], SrcReg);
599     else {
600       Regs.push_back(SrcReg);
601       VMap.getOffsets(U)->push_back(0);
602     }
603     return true;
604   }
605   return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder);
606 }
607 
608 bool IRTranslator::translateCast(unsigned Opcode, const User &U,
609                                  MachineIRBuilder &MIRBuilder) {
610   unsigned Op = getOrCreateVReg(*U.getOperand(0));
611   unsigned Res = getOrCreateVReg(U);
612   MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op);
613   return true;
614 }
615 
616 bool IRTranslator::translateGetElementPtr(const User &U,
617                                           MachineIRBuilder &MIRBuilder) {
618   // FIXME: support vector GEPs.
619   if (U.getType()->isVectorTy())
620     return false;
621 
622   Value &Op0 = *U.getOperand(0);
623   unsigned BaseReg = getOrCreateVReg(Op0);
624   Type *PtrIRTy = Op0.getType();
625   LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
626   Type *OffsetIRTy = DL->getIntPtrType(PtrIRTy);
627   LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
628 
629   int64_t Offset = 0;
630   for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U);
631        GTI != E; ++GTI) {
632     const Value *Idx = GTI.getOperand();
633     if (StructType *StTy = GTI.getStructTypeOrNull()) {
634       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
635       Offset += DL->getStructLayout(StTy)->getElementOffset(Field);
636       continue;
637     } else {
638       uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
639 
640       // If this is a scalar constant or a splat vector of constants,
641       // handle it quickly.
642       if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
643         Offset += ElementSize * CI->getSExtValue();
644         continue;
645       }
646 
647       if (Offset != 0) {
648         unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
649         unsigned OffsetReg =
650             getOrCreateVReg(*ConstantInt::get(OffsetIRTy, Offset));
651         MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg);
652 
653         BaseReg = NewBaseReg;
654         Offset = 0;
655       }
656 
657       unsigned IdxReg = getOrCreateVReg(*Idx);
658       if (MRI->getType(IdxReg) != OffsetTy) {
659         unsigned NewIdxReg = MRI->createGenericVirtualRegister(OffsetTy);
660         MIRBuilder.buildSExtOrTrunc(NewIdxReg, IdxReg);
661         IdxReg = NewIdxReg;
662       }
663 
664       // N = N + Idx * ElementSize;
665       // Avoid doing it for ElementSize of 1.
666       unsigned GepOffsetReg;
667       if (ElementSize != 1) {
668         unsigned ElementSizeReg =
669             getOrCreateVReg(*ConstantInt::get(OffsetIRTy, ElementSize));
670 
671         GepOffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
672         MIRBuilder.buildMul(GepOffsetReg, ElementSizeReg, IdxReg);
673       } else
674         GepOffsetReg = IdxReg;
675 
676       unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
677       MIRBuilder.buildGEP(NewBaseReg, BaseReg, GepOffsetReg);
678       BaseReg = NewBaseReg;
679     }
680   }
681 
682   if (Offset != 0) {
683     unsigned OffsetReg = getOrCreateVReg(*ConstantInt::get(OffsetIRTy, Offset));
684     MIRBuilder.buildGEP(getOrCreateVReg(U), BaseReg, OffsetReg);
685     return true;
686   }
687 
688   MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg);
689   return true;
690 }
691 
692 bool IRTranslator::translateMemfunc(const CallInst &CI,
693                                     MachineIRBuilder &MIRBuilder,
694                                     unsigned ID) {
695   LLT SizeTy = getLLTForType(*CI.getArgOperand(2)->getType(), *DL);
696   Type *DstTy = CI.getArgOperand(0)->getType();
697   if (cast<PointerType>(DstTy)->getAddressSpace() != 0 ||
698       SizeTy.getSizeInBits() != DL->getPointerSizeInBits(0))
699     return false;
700 
701   SmallVector<CallLowering::ArgInfo, 8> Args;
702   for (int i = 0; i < 3; ++i) {
703     const auto &Arg = CI.getArgOperand(i);
704     Args.emplace_back(getOrCreateVReg(*Arg), Arg->getType());
705   }
706 
707   const char *Callee;
708   switch (ID) {
709   case Intrinsic::memmove:
710   case Intrinsic::memcpy: {
711     Type *SrcTy = CI.getArgOperand(1)->getType();
712     if(cast<PointerType>(SrcTy)->getAddressSpace() != 0)
713       return false;
714     Callee = ID == Intrinsic::memcpy ? "memcpy" : "memmove";
715     break;
716   }
717   case Intrinsic::memset:
718     Callee = "memset";
719     break;
720   default:
721     return false;
722   }
723 
724   return CLI->lowerCall(MIRBuilder, CI.getCallingConv(),
725                         MachineOperand::CreateES(Callee),
726                         CallLowering::ArgInfo(0, CI.getType()), Args);
727 }
728 
729 void IRTranslator::getStackGuard(unsigned DstReg,
730                                  MachineIRBuilder &MIRBuilder) {
731   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
732   MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF));
733   auto MIB = MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD);
734   MIB.addDef(DstReg);
735 
736   auto &TLI = *MF->getSubtarget().getTargetLowering();
737   Value *Global = TLI.getSDagStackGuard(*MF->getFunction().getParent());
738   if (!Global)
739     return;
740 
741   MachinePointerInfo MPInfo(Global);
742   auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
743                MachineMemOperand::MODereferenceable;
744   MachineMemOperand *MemRef =
745       MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8,
746                                DL->getPointerABIAlignment(0));
747   MIB.setMemRefs({MemRef});
748 }
749 
750 bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op,
751                                               MachineIRBuilder &MIRBuilder) {
752   ArrayRef<unsigned> ResRegs = getOrCreateVRegs(CI);
753   MIRBuilder.buildInstr(Op)
754       .addDef(ResRegs[0])
755       .addDef(ResRegs[1])
756       .addUse(getOrCreateVReg(*CI.getOperand(0)))
757       .addUse(getOrCreateVReg(*CI.getOperand(1)));
758 
759   return true;
760 }
761 
762 unsigned IRTranslator::getSimpleIntrinsicOpcode(Intrinsic::ID ID) {
763   switch (ID) {
764     default:
765       break;
766     case Intrinsic::bswap:
767       return TargetOpcode::G_BSWAP;
768     case Intrinsic::ceil:
769       return TargetOpcode::G_FCEIL;
770     case Intrinsic::cos:
771       return TargetOpcode::G_FCOS;
772     case Intrinsic::ctpop:
773       return TargetOpcode::G_CTPOP;
774     case Intrinsic::exp:
775       return TargetOpcode::G_FEXP;
776     case Intrinsic::exp2:
777       return TargetOpcode::G_FEXP2;
778     case Intrinsic::fabs:
779       return TargetOpcode::G_FABS;
780     case Intrinsic::canonicalize:
781       return TargetOpcode::G_FCANONICALIZE;
782     case Intrinsic::floor:
783       return TargetOpcode::G_FFLOOR;
784     case Intrinsic::fma:
785       return TargetOpcode::G_FMA;
786     case Intrinsic::log:
787       return TargetOpcode::G_FLOG;
788     case Intrinsic::log2:
789       return TargetOpcode::G_FLOG2;
790     case Intrinsic::log10:
791       return TargetOpcode::G_FLOG10;
792     case Intrinsic::pow:
793       return TargetOpcode::G_FPOW;
794     case Intrinsic::round:
795       return TargetOpcode::G_INTRINSIC_ROUND;
796     case Intrinsic::sin:
797       return TargetOpcode::G_FSIN;
798     case Intrinsic::sqrt:
799       return TargetOpcode::G_FSQRT;
800     case Intrinsic::trunc:
801       return TargetOpcode::G_INTRINSIC_TRUNC;
802   }
803   return Intrinsic::not_intrinsic;
804 }
805 
806 bool IRTranslator::translateSimpleIntrinsic(const CallInst &CI,
807                                             Intrinsic::ID ID,
808                                             MachineIRBuilder &MIRBuilder) {
809 
810   unsigned Op = getSimpleIntrinsicOpcode(ID);
811 
812   // Is this a simple intrinsic?
813   if (Op == Intrinsic::not_intrinsic)
814     return false;
815 
816   // Yes. Let's translate it.
817   SmallVector<llvm::SrcOp, 4> VRegs;
818   for (auto &Arg : CI.arg_operands())
819     VRegs.push_back(getOrCreateVReg(*Arg));
820 
821   MIRBuilder.buildInstr(Op, {getOrCreateVReg(CI)}, VRegs,
822                         MachineInstr::copyFlagsFromInstruction(CI));
823   return true;
824 }
825 
826 bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID,
827                                            MachineIRBuilder &MIRBuilder) {
828 
829   // If this is a simple intrinsic (that is, we just need to add a def of
830   // a vreg, and uses for each arg operand, then translate it.
831   if (translateSimpleIntrinsic(CI, ID, MIRBuilder))
832     return true;
833 
834   switch (ID) {
835   default:
836     break;
837   case Intrinsic::lifetime_start:
838   case Intrinsic::lifetime_end: {
839     // No stack colouring in O0, discard region information.
840     if (MF->getTarget().getOptLevel() == CodeGenOpt::None)
841       return true;
842 
843     unsigned Op = ID == Intrinsic::lifetime_start ? TargetOpcode::LIFETIME_START
844                                                   : TargetOpcode::LIFETIME_END;
845 
846     // Get the underlying objects for the location passed on the lifetime
847     // marker.
848     SmallVector<Value *, 4> Allocas;
849     GetUnderlyingObjects(CI.getArgOperand(1), Allocas, *DL);
850 
851     // Iterate over each underlying object, creating lifetime markers for each
852     // static alloca. Quit if we find a non-static alloca.
853     for (Value *V : Allocas) {
854       AllocaInst *AI = dyn_cast<AllocaInst>(V);
855       if (!AI)
856         continue;
857 
858       if (!AI->isStaticAlloca())
859         return true;
860 
861       MIRBuilder.buildInstr(Op).addFrameIndex(getOrCreateFrameIndex(*AI));
862     }
863     return true;
864   }
865   case Intrinsic::dbg_declare: {
866     const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI);
867     assert(DI.getVariable() && "Missing variable");
868 
869     const Value *Address = DI.getAddress();
870     if (!Address || isa<UndefValue>(Address)) {
871       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
872       return true;
873     }
874 
875     assert(DI.getVariable()->isValidLocationForIntrinsic(
876                MIRBuilder.getDebugLoc()) &&
877            "Expected inlined-at fields to agree");
878     auto AI = dyn_cast<AllocaInst>(Address);
879     if (AI && AI->isStaticAlloca()) {
880       // Static allocas are tracked at the MF level, no need for DBG_VALUE
881       // instructions (in fact, they get ignored if they *do* exist).
882       MF->setVariableDbgInfo(DI.getVariable(), DI.getExpression(),
883                              getOrCreateFrameIndex(*AI), DI.getDebugLoc());
884     } else {
885       // A dbg.declare describes the address of a source variable, so lower it
886       // into an indirect DBG_VALUE.
887       MIRBuilder.buildIndirectDbgValue(getOrCreateVReg(*Address),
888                                        DI.getVariable(), DI.getExpression());
889     }
890     return true;
891   }
892   case Intrinsic::dbg_label: {
893     const DbgLabelInst &DI = cast<DbgLabelInst>(CI);
894     assert(DI.getLabel() && "Missing label");
895 
896     assert(DI.getLabel()->isValidLocationForIntrinsic(
897                MIRBuilder.getDebugLoc()) &&
898            "Expected inlined-at fields to agree");
899 
900     MIRBuilder.buildDbgLabel(DI.getLabel());
901     return true;
902   }
903   case Intrinsic::vaend:
904     // No target I know of cares about va_end. Certainly no in-tree target
905     // does. Simplest intrinsic ever!
906     return true;
907   case Intrinsic::vastart: {
908     auto &TLI = *MF->getSubtarget().getTargetLowering();
909     Value *Ptr = CI.getArgOperand(0);
910     unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8;
911 
912     // FIXME: Get alignment
913     MIRBuilder.buildInstr(TargetOpcode::G_VASTART)
914         .addUse(getOrCreateVReg(*Ptr))
915         .addMemOperand(MF->getMachineMemOperand(
916             MachinePointerInfo(Ptr), MachineMemOperand::MOStore, ListSize, 1));
917     return true;
918   }
919   case Intrinsic::dbg_value: {
920     // This form of DBG_VALUE is target-independent.
921     const DbgValueInst &DI = cast<DbgValueInst>(CI);
922     const Value *V = DI.getValue();
923     assert(DI.getVariable()->isValidLocationForIntrinsic(
924                MIRBuilder.getDebugLoc()) &&
925            "Expected inlined-at fields to agree");
926     if (!V) {
927       // Currently the optimizer can produce this; insert an undef to
928       // help debugging.  Probably the optimizer should not do this.
929       MIRBuilder.buildIndirectDbgValue(0, DI.getVariable(), DI.getExpression());
930     } else if (const auto *CI = dyn_cast<Constant>(V)) {
931       MIRBuilder.buildConstDbgValue(*CI, DI.getVariable(), DI.getExpression());
932     } else {
933       unsigned Reg = getOrCreateVReg(*V);
934       // FIXME: This does not handle register-indirect values at offset 0. The
935       // direct/indirect thing shouldn't really be handled by something as
936       // implicit as reg+noreg vs reg+imm in the first palce, but it seems
937       // pretty baked in right now.
938       MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(), DI.getExpression());
939     }
940     return true;
941   }
942   case Intrinsic::uadd_with_overflow:
943     return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDO, MIRBuilder);
944   case Intrinsic::sadd_with_overflow:
945     return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder);
946   case Intrinsic::usub_with_overflow:
947     return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBO, MIRBuilder);
948   case Intrinsic::ssub_with_overflow:
949     return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder);
950   case Intrinsic::umul_with_overflow:
951     return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder);
952   case Intrinsic::smul_with_overflow:
953     return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder);
954   case Intrinsic::fmuladd: {
955     const TargetMachine &TM = MF->getTarget();
956     const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
957     unsigned Dst = getOrCreateVReg(CI);
958     unsigned Op0 = getOrCreateVReg(*CI.getArgOperand(0));
959     unsigned Op1 = getOrCreateVReg(*CI.getArgOperand(1));
960     unsigned Op2 = getOrCreateVReg(*CI.getArgOperand(2));
961     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
962         TLI.isFMAFasterThanFMulAndFAdd(TLI.getValueType(*DL, CI.getType()))) {
963       // TODO: Revisit this to see if we should move this part of the
964       // lowering to the combiner.
965       MIRBuilder.buildInstr(TargetOpcode::G_FMA, {Dst}, {Op0, Op1, Op2},
966                             MachineInstr::copyFlagsFromInstruction(CI));
967     } else {
968       LLT Ty = getLLTForType(*CI.getType(), *DL);
969       auto FMul = MIRBuilder.buildInstr(TargetOpcode::G_FMUL, {Ty}, {Op0, Op1},
970                                         MachineInstr::copyFlagsFromInstruction(CI));
971       MIRBuilder.buildInstr(TargetOpcode::G_FADD, {Dst}, {FMul, Op2},
972                             MachineInstr::copyFlagsFromInstruction(CI));
973     }
974     return true;
975   }
976   case Intrinsic::memcpy:
977   case Intrinsic::memmove:
978   case Intrinsic::memset:
979     return translateMemfunc(CI, MIRBuilder, ID);
980   case Intrinsic::eh_typeid_for: {
981     GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0));
982     unsigned Reg = getOrCreateVReg(CI);
983     unsigned TypeID = MF->getTypeIDFor(GV);
984     MIRBuilder.buildConstant(Reg, TypeID);
985     return true;
986   }
987   case Intrinsic::objectsize: {
988     // If we don't know by now, we're never going to know.
989     const ConstantInt *Min = cast<ConstantInt>(CI.getArgOperand(1));
990 
991     MIRBuilder.buildConstant(getOrCreateVReg(CI), Min->isZero() ? -1ULL : 0);
992     return true;
993   }
994   case Intrinsic::is_constant:
995     // If this wasn't constant-folded away by now, then it's not a
996     // constant.
997     MIRBuilder.buildConstant(getOrCreateVReg(CI), 0);
998     return true;
999   case Intrinsic::stackguard:
1000     getStackGuard(getOrCreateVReg(CI), MIRBuilder);
1001     return true;
1002   case Intrinsic::stackprotector: {
1003     LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
1004     unsigned GuardVal = MRI->createGenericVirtualRegister(PtrTy);
1005     getStackGuard(GuardVal, MIRBuilder);
1006 
1007     AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1));
1008     int FI = getOrCreateFrameIndex(*Slot);
1009     MF->getFrameInfo().setStackProtectorIndex(FI);
1010 
1011     MIRBuilder.buildStore(
1012         GuardVal, getOrCreateVReg(*Slot),
1013         *MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
1014                                   MachineMemOperand::MOStore |
1015                                       MachineMemOperand::MOVolatile,
1016                                   PtrTy.getSizeInBits() / 8, 8));
1017     return true;
1018   }
1019   case Intrinsic::stacksave: {
1020     // Save the stack pointer to the location provided by the intrinsic.
1021     unsigned Reg = getOrCreateVReg(CI);
1022     unsigned StackPtr = MF->getSubtarget()
1023                             .getTargetLowering()
1024                             ->getStackPointerRegisterToSaveRestore();
1025 
1026     // If the target doesn't specify a stack pointer, then fall back.
1027     if (!StackPtr)
1028       return false;
1029 
1030     MIRBuilder.buildCopy(Reg, StackPtr);
1031     return true;
1032   }
1033   case Intrinsic::stackrestore: {
1034     // Restore the stack pointer from the location provided by the intrinsic.
1035     unsigned Reg = getOrCreateVReg(*CI.getArgOperand(0));
1036     unsigned StackPtr = MF->getSubtarget()
1037                             .getTargetLowering()
1038                             ->getStackPointerRegisterToSaveRestore();
1039 
1040     // If the target doesn't specify a stack pointer, then fall back.
1041     if (!StackPtr)
1042       return false;
1043 
1044     MIRBuilder.buildCopy(StackPtr, Reg);
1045     return true;
1046   }
1047   case Intrinsic::cttz:
1048   case Intrinsic::ctlz: {
1049     ConstantInt *Cst = cast<ConstantInt>(CI.getArgOperand(1));
1050     bool isTrailing = ID == Intrinsic::cttz;
1051     unsigned Opcode = isTrailing
1052                           ? Cst->isZero() ? TargetOpcode::G_CTTZ
1053                                           : TargetOpcode::G_CTTZ_ZERO_UNDEF
1054                           : Cst->isZero() ? TargetOpcode::G_CTLZ
1055                                           : TargetOpcode::G_CTLZ_ZERO_UNDEF;
1056     MIRBuilder.buildInstr(Opcode)
1057         .addDef(getOrCreateVReg(CI))
1058         .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
1059     return true;
1060   }
1061   case Intrinsic::invariant_start: {
1062     LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
1063     unsigned Undef = MRI->createGenericVirtualRegister(PtrTy);
1064     MIRBuilder.buildUndef(Undef);
1065     return true;
1066   }
1067   case Intrinsic::invariant_end:
1068     return true;
1069   }
1070   return false;
1071 }
1072 
1073 bool IRTranslator::translateInlineAsm(const CallInst &CI,
1074                                       MachineIRBuilder &MIRBuilder) {
1075   const InlineAsm &IA = cast<InlineAsm>(*CI.getCalledValue());
1076   if (!IA.getConstraintString().empty())
1077     return false;
1078 
1079   unsigned ExtraInfo = 0;
1080   if (IA.hasSideEffects())
1081     ExtraInfo |= InlineAsm::Extra_HasSideEffects;
1082   if (IA.getDialect() == InlineAsm::AD_Intel)
1083     ExtraInfo |= InlineAsm::Extra_AsmDialect;
1084 
1085   MIRBuilder.buildInstr(TargetOpcode::INLINEASM)
1086     .addExternalSymbol(IA.getAsmString().c_str())
1087     .addImm(ExtraInfo);
1088 
1089   return true;
1090 }
1091 
1092 unsigned IRTranslator::packRegs(const Value &V,
1093                                   MachineIRBuilder &MIRBuilder) {
1094   ArrayRef<unsigned> Regs = getOrCreateVRegs(V);
1095   ArrayRef<uint64_t> Offsets = *VMap.getOffsets(V);
1096   LLT BigTy = getLLTForType(*V.getType(), *DL);
1097 
1098   if (Regs.size() == 1)
1099     return Regs[0];
1100 
1101   unsigned Dst = MRI->createGenericVirtualRegister(BigTy);
1102   MIRBuilder.buildUndef(Dst);
1103   for (unsigned i = 0; i < Regs.size(); ++i) {
1104     unsigned NewDst = MRI->createGenericVirtualRegister(BigTy);
1105     MIRBuilder.buildInsert(NewDst, Dst, Regs[i], Offsets[i]);
1106     Dst = NewDst;
1107   }
1108   return Dst;
1109 }
1110 
1111 void IRTranslator::unpackRegs(const Value &V, unsigned Src,
1112                                 MachineIRBuilder &MIRBuilder) {
1113   ArrayRef<unsigned> Regs = getOrCreateVRegs(V);
1114   ArrayRef<uint64_t> Offsets = *VMap.getOffsets(V);
1115 
1116   for (unsigned i = 0; i < Regs.size(); ++i)
1117     MIRBuilder.buildExtract(Regs[i], Src, Offsets[i]);
1118 }
1119 
1120 bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) {
1121   const CallInst &CI = cast<CallInst>(U);
1122   auto TII = MF->getTarget().getIntrinsicInfo();
1123   const Function *F = CI.getCalledFunction();
1124 
1125   // FIXME: support Windows dllimport function calls.
1126   if (F && F->hasDLLImportStorageClass())
1127     return false;
1128 
1129   if (CI.isInlineAsm())
1130     return translateInlineAsm(CI, MIRBuilder);
1131 
1132   Intrinsic::ID ID = Intrinsic::not_intrinsic;
1133   if (F && F->isIntrinsic()) {
1134     ID = F->getIntrinsicID();
1135     if (TII && ID == Intrinsic::not_intrinsic)
1136       ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F));
1137   }
1138 
1139   if (!F || !F->isIntrinsic() || ID == Intrinsic::not_intrinsic) {
1140     bool IsSplitType = valueIsSplit(CI);
1141     unsigned Res = IsSplitType ? MRI->createGenericVirtualRegister(
1142                                      getLLTForType(*CI.getType(), *DL))
1143                                : getOrCreateVReg(CI);
1144 
1145     SmallVector<unsigned, 8> Args;
1146     for (auto &Arg: CI.arg_operands())
1147       Args.push_back(packRegs(*Arg, MIRBuilder));
1148 
1149     MF->getFrameInfo().setHasCalls(true);
1150     bool Success = CLI->lowerCall(MIRBuilder, &CI, Res, Args, [&]() {
1151       return getOrCreateVReg(*CI.getCalledValue());
1152     });
1153 
1154     if (IsSplitType)
1155       unpackRegs(CI, Res, MIRBuilder);
1156     return Success;
1157   }
1158 
1159   assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
1160 
1161   if (translateKnownIntrinsic(CI, ID, MIRBuilder))
1162     return true;
1163 
1164   ArrayRef<unsigned> ResultRegs;
1165   if (!CI.getType()->isVoidTy())
1166     ResultRegs = getOrCreateVRegs(CI);
1167 
1168   MachineInstrBuilder MIB =
1169       MIRBuilder.buildIntrinsic(ID, ResultRegs, !CI.doesNotAccessMemory());
1170 
1171   for (auto &Arg : CI.arg_operands()) {
1172     // Some intrinsics take metadata parameters. Reject them.
1173     if (isa<MetadataAsValue>(Arg))
1174       return false;
1175     MIB.addUse(packRegs(*Arg, MIRBuilder));
1176   }
1177 
1178   // Add a MachineMemOperand if it is a target mem intrinsic.
1179   const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
1180   TargetLowering::IntrinsicInfo Info;
1181   // TODO: Add a GlobalISel version of getTgtMemIntrinsic.
1182   if (TLI.getTgtMemIntrinsic(Info, CI, *MF, ID)) {
1183     unsigned Align = Info.align;
1184     if (Align == 0)
1185       Align = DL->getABITypeAlignment(Info.memVT.getTypeForEVT(F->getContext()));
1186 
1187     uint64_t Size = Info.memVT.getStoreSize();
1188     MIB.addMemOperand(MF->getMachineMemOperand(MachinePointerInfo(Info.ptrVal),
1189                                                Info.flags, Size, Align));
1190   }
1191 
1192   return true;
1193 }
1194 
1195 bool IRTranslator::translateInvoke(const User &U,
1196                                    MachineIRBuilder &MIRBuilder) {
1197   const InvokeInst &I = cast<InvokeInst>(U);
1198   MCContext &Context = MF->getContext();
1199 
1200   const BasicBlock *ReturnBB = I.getSuccessor(0);
1201   const BasicBlock *EHPadBB = I.getSuccessor(1);
1202 
1203   const Value *Callee = I.getCalledValue();
1204   const Function *Fn = dyn_cast<Function>(Callee);
1205   if (isa<InlineAsm>(Callee))
1206     return false;
1207 
1208   // FIXME: support invoking patchpoint and statepoint intrinsics.
1209   if (Fn && Fn->isIntrinsic())
1210     return false;
1211 
1212   // FIXME: support whatever these are.
1213   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
1214     return false;
1215 
1216   // FIXME: support Windows exception handling.
1217   if (!isa<LandingPadInst>(EHPadBB->front()))
1218     return false;
1219 
1220   // Emit the actual call, bracketed by EH_LABELs so that the MF knows about
1221   // the region covered by the try.
1222   MCSymbol *BeginSymbol = Context.createTempSymbol();
1223   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol);
1224 
1225   unsigned Res = 0;
1226   if (!I.getType()->isVoidTy())
1227     Res = MRI->createGenericVirtualRegister(getLLTForType(*I.getType(), *DL));
1228   SmallVector<unsigned, 8> Args;
1229   for (auto &Arg: I.arg_operands())
1230     Args.push_back(packRegs(*Arg, MIRBuilder));
1231 
1232   if (!CLI->lowerCall(MIRBuilder, &I, Res, Args,
1233                       [&]() { return getOrCreateVReg(*I.getCalledValue()); }))
1234     return false;
1235 
1236   unpackRegs(I, Res, MIRBuilder);
1237 
1238   MCSymbol *EndSymbol = Context.createTempSymbol();
1239   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol);
1240 
1241   // FIXME: track probabilities.
1242   MachineBasicBlock &EHPadMBB = getMBB(*EHPadBB),
1243                     &ReturnMBB = getMBB(*ReturnBB);
1244   MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
1245   MIRBuilder.getMBB().addSuccessor(&ReturnMBB);
1246   MIRBuilder.getMBB().addSuccessor(&EHPadMBB);
1247   MIRBuilder.buildBr(ReturnMBB);
1248 
1249   return true;
1250 }
1251 
1252 bool IRTranslator::translateCallBr(const User &U,
1253                                    MachineIRBuilder &MIRBuilder) {
1254   // FIXME: Implement this.
1255   return false;
1256 }
1257 
1258 bool IRTranslator::translateLandingPad(const User &U,
1259                                        MachineIRBuilder &MIRBuilder) {
1260   const LandingPadInst &LP = cast<LandingPadInst>(U);
1261 
1262   MachineBasicBlock &MBB = MIRBuilder.getMBB();
1263 
1264   MBB.setIsEHPad();
1265 
1266   // If there aren't registers to copy the values into (e.g., during SjLj
1267   // exceptions), then don't bother.
1268   auto &TLI = *MF->getSubtarget().getTargetLowering();
1269   const Constant *PersonalityFn = MF->getFunction().getPersonalityFn();
1270   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
1271       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
1272     return true;
1273 
1274   // If landingpad's return type is token type, we don't create DAG nodes
1275   // for its exception pointer and selector value. The extraction of exception
1276   // pointer or selector value from token type landingpads is not currently
1277   // supported.
1278   if (LP.getType()->isTokenTy())
1279     return true;
1280 
1281   // Add a label to mark the beginning of the landing pad.  Deletion of the
1282   // landing pad can thus be detected via the MachineModuleInfo.
1283   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL)
1284     .addSym(MF->addLandingPad(&MBB));
1285 
1286   LLT Ty = getLLTForType(*LP.getType(), *DL);
1287   unsigned Undef = MRI->createGenericVirtualRegister(Ty);
1288   MIRBuilder.buildUndef(Undef);
1289 
1290   SmallVector<LLT, 2> Tys;
1291   for (Type *Ty : cast<StructType>(LP.getType())->elements())
1292     Tys.push_back(getLLTForType(*Ty, *DL));
1293   assert(Tys.size() == 2 && "Only two-valued landingpads are supported");
1294 
1295   // Mark exception register as live in.
1296   unsigned ExceptionReg = TLI.getExceptionPointerRegister(PersonalityFn);
1297   if (!ExceptionReg)
1298     return false;
1299 
1300   MBB.addLiveIn(ExceptionReg);
1301   ArrayRef<unsigned> ResRegs = getOrCreateVRegs(LP);
1302   MIRBuilder.buildCopy(ResRegs[0], ExceptionReg);
1303 
1304   unsigned SelectorReg = TLI.getExceptionSelectorRegister(PersonalityFn);
1305   if (!SelectorReg)
1306     return false;
1307 
1308   MBB.addLiveIn(SelectorReg);
1309   unsigned PtrVReg = MRI->createGenericVirtualRegister(Tys[0]);
1310   MIRBuilder.buildCopy(PtrVReg, SelectorReg);
1311   MIRBuilder.buildCast(ResRegs[1], PtrVReg);
1312 
1313   return true;
1314 }
1315 
1316 bool IRTranslator::translateAlloca(const User &U,
1317                                    MachineIRBuilder &MIRBuilder) {
1318   auto &AI = cast<AllocaInst>(U);
1319 
1320   if (AI.isSwiftError())
1321     return false;
1322 
1323   if (AI.isStaticAlloca()) {
1324     unsigned Res = getOrCreateVReg(AI);
1325     int FI = getOrCreateFrameIndex(AI);
1326     MIRBuilder.buildFrameIndex(Res, FI);
1327     return true;
1328   }
1329 
1330   // FIXME: support stack probing for Windows.
1331   if (MF->getTarget().getTargetTriple().isOSWindows())
1332     return false;
1333 
1334   // Now we're in the harder dynamic case.
1335   Type *Ty = AI.getAllocatedType();
1336   unsigned Align =
1337       std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI.getAlignment());
1338 
1339   unsigned NumElts = getOrCreateVReg(*AI.getArraySize());
1340 
1341   Type *IntPtrIRTy = DL->getIntPtrType(AI.getType());
1342   LLT IntPtrTy = getLLTForType(*IntPtrIRTy, *DL);
1343   if (MRI->getType(NumElts) != IntPtrTy) {
1344     unsigned ExtElts = MRI->createGenericVirtualRegister(IntPtrTy);
1345     MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts);
1346     NumElts = ExtElts;
1347   }
1348 
1349   unsigned AllocSize = MRI->createGenericVirtualRegister(IntPtrTy);
1350   unsigned TySize =
1351       getOrCreateVReg(*ConstantInt::get(IntPtrIRTy, -DL->getTypeAllocSize(Ty)));
1352   MIRBuilder.buildMul(AllocSize, NumElts, TySize);
1353 
1354   LLT PtrTy = getLLTForType(*AI.getType(), *DL);
1355   auto &TLI = *MF->getSubtarget().getTargetLowering();
1356   unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1357 
1358   unsigned SPTmp = MRI->createGenericVirtualRegister(PtrTy);
1359   MIRBuilder.buildCopy(SPTmp, SPReg);
1360 
1361   unsigned AllocTmp = MRI->createGenericVirtualRegister(PtrTy);
1362   MIRBuilder.buildGEP(AllocTmp, SPTmp, AllocSize);
1363 
1364   // Handle alignment. We have to realign if the allocation granule was smaller
1365   // than stack alignment, or the specific alloca requires more than stack
1366   // alignment.
1367   unsigned StackAlign =
1368       MF->getSubtarget().getFrameLowering()->getStackAlignment();
1369   Align = std::max(Align, StackAlign);
1370   if (Align > StackAlign || DL->getTypeAllocSize(Ty) % StackAlign != 0) {
1371     // Round the size of the allocation up to the stack alignment size
1372     // by add SA-1 to the size. This doesn't overflow because we're computing
1373     // an address inside an alloca.
1374     unsigned AlignedAlloc = MRI->createGenericVirtualRegister(PtrTy);
1375     MIRBuilder.buildPtrMask(AlignedAlloc, AllocTmp, Log2_32(Align));
1376     AllocTmp = AlignedAlloc;
1377   }
1378 
1379   MIRBuilder.buildCopy(SPReg, AllocTmp);
1380   MIRBuilder.buildCopy(getOrCreateVReg(AI), AllocTmp);
1381 
1382   MF->getFrameInfo().CreateVariableSizedObject(Align ? Align : 1, &AI);
1383   assert(MF->getFrameInfo().hasVarSizedObjects());
1384   return true;
1385 }
1386 
1387 bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) {
1388   // FIXME: We may need more info about the type. Because of how LLT works,
1389   // we're completely discarding the i64/double distinction here (amongst
1390   // others). Fortunately the ABIs I know of where that matters don't use va_arg
1391   // anyway but that's not guaranteed.
1392   MIRBuilder.buildInstr(TargetOpcode::G_VAARG)
1393     .addDef(getOrCreateVReg(U))
1394     .addUse(getOrCreateVReg(*U.getOperand(0)))
1395     .addImm(DL->getABITypeAlignment(U.getType()));
1396   return true;
1397 }
1398 
1399 bool IRTranslator::translateInsertElement(const User &U,
1400                                           MachineIRBuilder &MIRBuilder) {
1401   // If it is a <1 x Ty> vector, use the scalar as it is
1402   // not a legal vector type in LLT.
1403   if (U.getType()->getVectorNumElements() == 1) {
1404     unsigned Elt = getOrCreateVReg(*U.getOperand(1));
1405     auto &Regs = *VMap.getVRegs(U);
1406     if (Regs.empty()) {
1407       Regs.push_back(Elt);
1408       VMap.getOffsets(U)->push_back(0);
1409     } else {
1410       MIRBuilder.buildCopy(Regs[0], Elt);
1411     }
1412     return true;
1413   }
1414 
1415   unsigned Res = getOrCreateVReg(U);
1416   unsigned Val = getOrCreateVReg(*U.getOperand(0));
1417   unsigned Elt = getOrCreateVReg(*U.getOperand(1));
1418   unsigned Idx = getOrCreateVReg(*U.getOperand(2));
1419   MIRBuilder.buildInsertVectorElement(Res, Val, Elt, Idx);
1420   return true;
1421 }
1422 
1423 bool IRTranslator::translateExtractElement(const User &U,
1424                                            MachineIRBuilder &MIRBuilder) {
1425   // If it is a <1 x Ty> vector, use the scalar as it is
1426   // not a legal vector type in LLT.
1427   if (U.getOperand(0)->getType()->getVectorNumElements() == 1) {
1428     unsigned Elt = getOrCreateVReg(*U.getOperand(0));
1429     auto &Regs = *VMap.getVRegs(U);
1430     if (Regs.empty()) {
1431       Regs.push_back(Elt);
1432       VMap.getOffsets(U)->push_back(0);
1433     } else {
1434       MIRBuilder.buildCopy(Regs[0], Elt);
1435     }
1436     return true;
1437   }
1438   unsigned Res = getOrCreateVReg(U);
1439   unsigned Val = getOrCreateVReg(*U.getOperand(0));
1440   const auto &TLI = *MF->getSubtarget().getTargetLowering();
1441   unsigned PreferredVecIdxWidth = TLI.getVectorIdxTy(*DL).getSizeInBits();
1442   unsigned Idx = 0;
1443   if (auto *CI = dyn_cast<ConstantInt>(U.getOperand(1))) {
1444     if (CI->getBitWidth() != PreferredVecIdxWidth) {
1445       APInt NewIdx = CI->getValue().sextOrTrunc(PreferredVecIdxWidth);
1446       auto *NewIdxCI = ConstantInt::get(CI->getContext(), NewIdx);
1447       Idx = getOrCreateVReg(*NewIdxCI);
1448     }
1449   }
1450   if (!Idx)
1451     Idx = getOrCreateVReg(*U.getOperand(1));
1452   if (MRI->getType(Idx).getSizeInBits() != PreferredVecIdxWidth) {
1453     const LLT &VecIdxTy = LLT::scalar(PreferredVecIdxWidth);
1454     Idx = MIRBuilder.buildSExtOrTrunc(VecIdxTy, Idx)->getOperand(0).getReg();
1455   }
1456   MIRBuilder.buildExtractVectorElement(Res, Val, Idx);
1457   return true;
1458 }
1459 
1460 bool IRTranslator::translateShuffleVector(const User &U,
1461                                           MachineIRBuilder &MIRBuilder) {
1462   MIRBuilder.buildInstr(TargetOpcode::G_SHUFFLE_VECTOR)
1463       .addDef(getOrCreateVReg(U))
1464       .addUse(getOrCreateVReg(*U.getOperand(0)))
1465       .addUse(getOrCreateVReg(*U.getOperand(1)))
1466       .addUse(getOrCreateVReg(*U.getOperand(2)));
1467   return true;
1468 }
1469 
1470 bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) {
1471   const PHINode &PI = cast<PHINode>(U);
1472 
1473   SmallVector<MachineInstr *, 4> Insts;
1474   for (auto Reg : getOrCreateVRegs(PI)) {
1475     auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_PHI, {Reg}, {});
1476     Insts.push_back(MIB.getInstr());
1477   }
1478 
1479   PendingPHIs.emplace_back(&PI, std::move(Insts));
1480   return true;
1481 }
1482 
1483 bool IRTranslator::translateAtomicCmpXchg(const User &U,
1484                                           MachineIRBuilder &MIRBuilder) {
1485   const AtomicCmpXchgInst &I = cast<AtomicCmpXchgInst>(U);
1486 
1487   if (I.isWeak())
1488     return false;
1489 
1490   auto Flags = I.isVolatile() ? MachineMemOperand::MOVolatile
1491                               : MachineMemOperand::MONone;
1492   Flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1493 
1494   Type *ResType = I.getType();
1495   Type *ValType = ResType->Type::getStructElementType(0);
1496 
1497   auto Res = getOrCreateVRegs(I);
1498   unsigned OldValRes = Res[0];
1499   unsigned SuccessRes = Res[1];
1500   unsigned Addr = getOrCreateVReg(*I.getPointerOperand());
1501   unsigned Cmp = getOrCreateVReg(*I.getCompareOperand());
1502   unsigned NewVal = getOrCreateVReg(*I.getNewValOperand());
1503 
1504   MIRBuilder.buildAtomicCmpXchgWithSuccess(
1505       OldValRes, SuccessRes, Addr, Cmp, NewVal,
1506       *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
1507                                 Flags, DL->getTypeStoreSize(ValType),
1508                                 getMemOpAlignment(I), AAMDNodes(), nullptr,
1509                                 I.getSyncScopeID(), I.getSuccessOrdering(),
1510                                 I.getFailureOrdering()));
1511   return true;
1512 }
1513 
1514 bool IRTranslator::translateAtomicRMW(const User &U,
1515                                       MachineIRBuilder &MIRBuilder) {
1516   const AtomicRMWInst &I = cast<AtomicRMWInst>(U);
1517 
1518   auto Flags = I.isVolatile() ? MachineMemOperand::MOVolatile
1519                               : MachineMemOperand::MONone;
1520   Flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1521 
1522   Type *ResType = I.getType();
1523 
1524   unsigned Res = getOrCreateVReg(I);
1525   unsigned Addr = getOrCreateVReg(*I.getPointerOperand());
1526   unsigned Val = getOrCreateVReg(*I.getValOperand());
1527 
1528   unsigned Opcode = 0;
1529   switch (I.getOperation()) {
1530   default:
1531     llvm_unreachable("Unknown atomicrmw op");
1532     return false;
1533   case AtomicRMWInst::Xchg:
1534     Opcode = TargetOpcode::G_ATOMICRMW_XCHG;
1535     break;
1536   case AtomicRMWInst::Add:
1537     Opcode = TargetOpcode::G_ATOMICRMW_ADD;
1538     break;
1539   case AtomicRMWInst::Sub:
1540     Opcode = TargetOpcode::G_ATOMICRMW_SUB;
1541     break;
1542   case AtomicRMWInst::And:
1543     Opcode = TargetOpcode::G_ATOMICRMW_AND;
1544     break;
1545   case AtomicRMWInst::Nand:
1546     Opcode = TargetOpcode::G_ATOMICRMW_NAND;
1547     break;
1548   case AtomicRMWInst::Or:
1549     Opcode = TargetOpcode::G_ATOMICRMW_OR;
1550     break;
1551   case AtomicRMWInst::Xor:
1552     Opcode = TargetOpcode::G_ATOMICRMW_XOR;
1553     break;
1554   case AtomicRMWInst::Max:
1555     Opcode = TargetOpcode::G_ATOMICRMW_MAX;
1556     break;
1557   case AtomicRMWInst::Min:
1558     Opcode = TargetOpcode::G_ATOMICRMW_MIN;
1559     break;
1560   case AtomicRMWInst::UMax:
1561     Opcode = TargetOpcode::G_ATOMICRMW_UMAX;
1562     break;
1563   case AtomicRMWInst::UMin:
1564     Opcode = TargetOpcode::G_ATOMICRMW_UMIN;
1565     break;
1566   }
1567 
1568   MIRBuilder.buildAtomicRMW(
1569       Opcode, Res, Addr, Val,
1570       *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
1571                                 Flags, DL->getTypeStoreSize(ResType),
1572                                 getMemOpAlignment(I), AAMDNodes(), nullptr,
1573                                 I.getSyncScopeID(), I.getOrdering()));
1574   return true;
1575 }
1576 
1577 void IRTranslator::finishPendingPhis() {
1578 #ifndef NDEBUG
1579   DILocationVerifier Verifier;
1580   GISelObserverWrapper WrapperObserver(&Verifier);
1581   RAIIDelegateInstaller DelInstall(*MF, &WrapperObserver);
1582 #endif // ifndef NDEBUG
1583   for (auto &Phi : PendingPHIs) {
1584     const PHINode *PI = Phi.first;
1585     ArrayRef<MachineInstr *> ComponentPHIs = Phi.second;
1586     EntryBuilder->setDebugLoc(PI->getDebugLoc());
1587 #ifndef NDEBUG
1588     Verifier.setCurrentInst(PI);
1589 #endif // ifndef NDEBUG
1590 
1591     // All MachineBasicBlocks exist, add them to the PHI. We assume IRTranslator
1592     // won't create extra control flow here, otherwise we need to find the
1593     // dominating predecessor here (or perhaps force the weirder IRTranslators
1594     // to provide a simple boundary).
1595     SmallSet<const BasicBlock *, 4> HandledPreds;
1596 
1597     for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
1598       auto IRPred = PI->getIncomingBlock(i);
1599       if (HandledPreds.count(IRPred))
1600         continue;
1601 
1602       HandledPreds.insert(IRPred);
1603       ArrayRef<unsigned> ValRegs = getOrCreateVRegs(*PI->getIncomingValue(i));
1604       for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) {
1605         assert(Pred->isSuccessor(ComponentPHIs[0]->getParent()) &&
1606                "incorrect CFG at MachineBasicBlock level");
1607         for (unsigned j = 0; j < ValRegs.size(); ++j) {
1608           MachineInstrBuilder MIB(*MF, ComponentPHIs[j]);
1609           MIB.addUse(ValRegs[j]);
1610           MIB.addMBB(Pred);
1611         }
1612       }
1613     }
1614   }
1615 }
1616 
1617 bool IRTranslator::valueIsSplit(const Value &V,
1618                                 SmallVectorImpl<uint64_t> *Offsets) {
1619   SmallVector<LLT, 4> SplitTys;
1620   if (Offsets && !Offsets->empty())
1621     Offsets->clear();
1622   computeValueLLTs(*DL, *V.getType(), SplitTys, Offsets);
1623   return SplitTys.size() > 1;
1624 }
1625 
1626 bool IRTranslator::translate(const Instruction &Inst) {
1627   CurBuilder->setDebugLoc(Inst.getDebugLoc());
1628   EntryBuilder->setDebugLoc(Inst.getDebugLoc());
1629   switch(Inst.getOpcode()) {
1630 #define HANDLE_INST(NUM, OPCODE, CLASS)                                        \
1631   case Instruction::OPCODE:                                                    \
1632     return translate##OPCODE(Inst, *CurBuilder.get());
1633 #include "llvm/IR/Instruction.def"
1634   default:
1635     return false;
1636   }
1637 }
1638 
1639 bool IRTranslator::translate(const Constant &C, unsigned Reg) {
1640   if (auto CI = dyn_cast<ConstantInt>(&C))
1641     EntryBuilder->buildConstant(Reg, *CI);
1642   else if (auto CF = dyn_cast<ConstantFP>(&C))
1643     EntryBuilder->buildFConstant(Reg, *CF);
1644   else if (isa<UndefValue>(C))
1645     EntryBuilder->buildUndef(Reg);
1646   else if (isa<ConstantPointerNull>(C)) {
1647     // As we are trying to build a constant val of 0 into a pointer,
1648     // insert a cast to make them correct with respect to types.
1649     unsigned NullSize = DL->getTypeSizeInBits(C.getType());
1650     auto *ZeroTy = Type::getIntNTy(C.getContext(), NullSize);
1651     auto *ZeroVal = ConstantInt::get(ZeroTy, 0);
1652     unsigned ZeroReg = getOrCreateVReg(*ZeroVal);
1653     EntryBuilder->buildCast(Reg, ZeroReg);
1654   } else if (auto GV = dyn_cast<GlobalValue>(&C))
1655     EntryBuilder->buildGlobalValue(Reg, GV);
1656   else if (auto CAZ = dyn_cast<ConstantAggregateZero>(&C)) {
1657     if (!CAZ->getType()->isVectorTy())
1658       return false;
1659     // Return the scalar if it is a <1 x Ty> vector.
1660     if (CAZ->getNumElements() == 1)
1661       return translate(*CAZ->getElementValue(0u), Reg);
1662     SmallVector<unsigned, 4> Ops;
1663     for (unsigned i = 0; i < CAZ->getNumElements(); ++i) {
1664       Constant &Elt = *CAZ->getElementValue(i);
1665       Ops.push_back(getOrCreateVReg(Elt));
1666     }
1667     EntryBuilder->buildBuildVector(Reg, Ops);
1668   } else if (auto CV = dyn_cast<ConstantDataVector>(&C)) {
1669     // Return the scalar if it is a <1 x Ty> vector.
1670     if (CV->getNumElements() == 1)
1671       return translate(*CV->getElementAsConstant(0), Reg);
1672     SmallVector<unsigned, 4> Ops;
1673     for (unsigned i = 0; i < CV->getNumElements(); ++i) {
1674       Constant &Elt = *CV->getElementAsConstant(i);
1675       Ops.push_back(getOrCreateVReg(Elt));
1676     }
1677     EntryBuilder->buildBuildVector(Reg, Ops);
1678   } else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
1679     switch(CE->getOpcode()) {
1680 #define HANDLE_INST(NUM, OPCODE, CLASS)                                        \
1681   case Instruction::OPCODE:                                                    \
1682     return translate##OPCODE(*CE, *EntryBuilder.get());
1683 #include "llvm/IR/Instruction.def"
1684     default:
1685       return false;
1686     }
1687   } else if (auto CV = dyn_cast<ConstantVector>(&C)) {
1688     if (CV->getNumOperands() == 1)
1689       return translate(*CV->getOperand(0), Reg);
1690     SmallVector<unsigned, 4> Ops;
1691     for (unsigned i = 0; i < CV->getNumOperands(); ++i) {
1692       Ops.push_back(getOrCreateVReg(*CV->getOperand(i)));
1693     }
1694     EntryBuilder->buildBuildVector(Reg, Ops);
1695   } else if (auto *BA = dyn_cast<BlockAddress>(&C)) {
1696     EntryBuilder->buildBlockAddress(Reg, BA);
1697   } else
1698     return false;
1699 
1700   return true;
1701 }
1702 
1703 void IRTranslator::finalizeFunction() {
1704   // Release the memory used by the different maps we
1705   // needed during the translation.
1706   PendingPHIs.clear();
1707   VMap.reset();
1708   FrameIndices.clear();
1709   MachinePreds.clear();
1710   // MachineIRBuilder::DebugLoc can outlive the DILocation it holds. Clear it
1711   // to avoid accessing free’d memory (in runOnMachineFunction) and to avoid
1712   // destroying it twice (in ~IRTranslator() and ~LLVMContext())
1713   EntryBuilder.reset();
1714   CurBuilder.reset();
1715 }
1716 
1717 bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) {
1718   MF = &CurMF;
1719   const Function &F = MF->getFunction();
1720   if (F.empty())
1721     return false;
1722   GISelCSEAnalysisWrapper &Wrapper =
1723       getAnalysis<GISelCSEAnalysisWrapperPass>().getCSEWrapper();
1724   // Set the CSEConfig and run the analysis.
1725   GISelCSEInfo *CSEInfo = nullptr;
1726   TPC = &getAnalysis<TargetPassConfig>();
1727   bool EnableCSE = EnableCSEInIRTranslator.getNumOccurrences()
1728                        ? EnableCSEInIRTranslator
1729                        : TPC->isGISelCSEEnabled();
1730 
1731   if (EnableCSE) {
1732     EntryBuilder = make_unique<CSEMIRBuilder>(CurMF);
1733     std::unique_ptr<CSEConfig> Config = make_unique<CSEConfig>();
1734     CSEInfo = &Wrapper.get(std::move(Config));
1735     EntryBuilder->setCSEInfo(CSEInfo);
1736     CurBuilder = make_unique<CSEMIRBuilder>(CurMF);
1737     CurBuilder->setCSEInfo(CSEInfo);
1738   } else {
1739     EntryBuilder = make_unique<MachineIRBuilder>();
1740     CurBuilder = make_unique<MachineIRBuilder>();
1741   }
1742   CLI = MF->getSubtarget().getCallLowering();
1743   CurBuilder->setMF(*MF);
1744   EntryBuilder->setMF(*MF);
1745   MRI = &MF->getRegInfo();
1746   DL = &F.getParent()->getDataLayout();
1747   ORE = llvm::make_unique<OptimizationRemarkEmitter>(&F);
1748 
1749   assert(PendingPHIs.empty() && "stale PHIs");
1750 
1751   if (!DL->isLittleEndian()) {
1752     // Currently we don't properly handle big endian code.
1753     OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1754                                F.getSubprogram(), &F.getEntryBlock());
1755     R << "unable to translate in big endian mode";
1756     reportTranslationError(*MF, *TPC, *ORE, R);
1757   }
1758 
1759   // Release the per-function state when we return, whether we succeeded or not.
1760   auto FinalizeOnReturn = make_scope_exit([this]() { finalizeFunction(); });
1761 
1762   // Setup a separate basic-block for the arguments and constants
1763   MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock();
1764   MF->push_back(EntryBB);
1765   EntryBuilder->setMBB(*EntryBB);
1766 
1767   // Create all blocks, in IR order, to preserve the layout.
1768   for (const BasicBlock &BB: F) {
1769     auto *&MBB = BBToMBB[&BB];
1770 
1771     MBB = MF->CreateMachineBasicBlock(&BB);
1772     MF->push_back(MBB);
1773 
1774     if (BB.hasAddressTaken())
1775       MBB->setHasAddressTaken();
1776   }
1777 
1778   // Make our arguments/constants entry block fallthrough to the IR entry block.
1779   EntryBB->addSuccessor(&getMBB(F.front()));
1780 
1781   // Lower the actual args into this basic block.
1782   SmallVector<unsigned, 8> VRegArgs;
1783   for (const Argument &Arg: F.args()) {
1784     if (DL->getTypeStoreSize(Arg.getType()) == 0)
1785       continue; // Don't handle zero sized types.
1786     VRegArgs.push_back(
1787         MRI->createGenericVirtualRegister(getLLTForType(*Arg.getType(), *DL)));
1788   }
1789 
1790   // We don't currently support translating swifterror or swiftself functions.
1791   for (auto &Arg : F.args()) {
1792     if (Arg.hasSwiftErrorAttr() || Arg.hasSwiftSelfAttr()) {
1793       OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1794                                  F.getSubprogram(), &F.getEntryBlock());
1795       R << "unable to lower arguments due to swifterror/swiftself: "
1796         << ore::NV("Prototype", F.getType());
1797       reportTranslationError(*MF, *TPC, *ORE, R);
1798       return false;
1799     }
1800   }
1801 
1802   if (!CLI->lowerFormalArguments(*EntryBuilder.get(), F, VRegArgs)) {
1803     OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1804                                F.getSubprogram(), &F.getEntryBlock());
1805     R << "unable to lower arguments: " << ore::NV("Prototype", F.getType());
1806     reportTranslationError(*MF, *TPC, *ORE, R);
1807     return false;
1808   }
1809 
1810   auto ArgIt = F.arg_begin();
1811   for (auto &VArg : VRegArgs) {
1812     // If the argument is an unsplit scalar then don't use unpackRegs to avoid
1813     // creating redundant copies.
1814     if (!valueIsSplit(*ArgIt, VMap.getOffsets(*ArgIt))) {
1815       auto &VRegs = *VMap.getVRegs(cast<Value>(*ArgIt));
1816       assert(VRegs.empty() && "VRegs already populated?");
1817       VRegs.push_back(VArg);
1818     } else {
1819       unpackRegs(*ArgIt, VArg, *EntryBuilder.get());
1820     }
1821     ArgIt++;
1822   }
1823 
1824   // Need to visit defs before uses when translating instructions.
1825   GISelObserverWrapper WrapperObserver;
1826   if (EnableCSE && CSEInfo)
1827     WrapperObserver.addObserver(CSEInfo);
1828   {
1829     ReversePostOrderTraversal<const Function *> RPOT(&F);
1830 #ifndef NDEBUG
1831     DILocationVerifier Verifier;
1832     WrapperObserver.addObserver(&Verifier);
1833 #endif // ifndef NDEBUG
1834     RAIIDelegateInstaller DelInstall(*MF, &WrapperObserver);
1835     for (const BasicBlock *BB : RPOT) {
1836       MachineBasicBlock &MBB = getMBB(*BB);
1837       // Set the insertion point of all the following translations to
1838       // the end of this basic block.
1839       CurBuilder->setMBB(MBB);
1840 
1841       for (const Instruction &Inst : *BB) {
1842 #ifndef NDEBUG
1843         Verifier.setCurrentInst(&Inst);
1844 #endif // ifndef NDEBUG
1845         if (translate(Inst))
1846           continue;
1847 
1848         OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1849                                    Inst.getDebugLoc(), BB);
1850         R << "unable to translate instruction: " << ore::NV("Opcode", &Inst);
1851 
1852         if (ORE->allowExtraAnalysis("gisel-irtranslator")) {
1853           std::string InstStrStorage;
1854           raw_string_ostream InstStr(InstStrStorage);
1855           InstStr << Inst;
1856 
1857           R << ": '" << InstStr.str() << "'";
1858         }
1859 
1860         reportTranslationError(*MF, *TPC, *ORE, R);
1861         return false;
1862       }
1863     }
1864 #ifndef NDEBUG
1865     WrapperObserver.removeObserver(&Verifier);
1866 #endif
1867   }
1868 
1869   finishPendingPhis();
1870 
1871   // Merge the argument lowering and constants block with its single
1872   // successor, the LLVM-IR entry block.  We want the basic block to
1873   // be maximal.
1874   assert(EntryBB->succ_size() == 1 &&
1875          "Custom BB used for lowering should have only one successor");
1876   // Get the successor of the current entry block.
1877   MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin();
1878   assert(NewEntryBB.pred_size() == 1 &&
1879          "LLVM-IR entry block has a predecessor!?");
1880   // Move all the instruction from the current entry block to the
1881   // new entry block.
1882   NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(),
1883                     EntryBB->end());
1884 
1885   // Update the live-in information for the new entry block.
1886   for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins())
1887     NewEntryBB.addLiveIn(LiveIn);
1888   NewEntryBB.sortUniqueLiveIns();
1889 
1890   // Get rid of the now empty basic block.
1891   EntryBB->removeSuccessor(&NewEntryBB);
1892   MF->remove(EntryBB);
1893   MF->DeleteMachineBasicBlock(EntryBB);
1894 
1895   assert(&MF->front() == &NewEntryBB &&
1896          "New entry wasn't next in the list of basic block!");
1897 
1898   // Initialize stack protector information.
1899   StackProtector &SP = getAnalysis<StackProtector>();
1900   SP.copyToMachineFrameInfo(MF->getFrameInfo());
1901 
1902   return false;
1903 }
1904