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