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/BranchProbabilityInfo.h"
19 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
20 #include "llvm/Analysis/ValueTracking.h"
21 #include "llvm/CodeGen/Analysis.h"
22 #include "llvm/CodeGen/FunctionLoweringInfo.h"
23 #include "llvm/CodeGen/GlobalISel/CallLowering.h"
24 #include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h"
25 #include "llvm/CodeGen/LowLevelType.h"
26 #include "llvm/CodeGen/MachineBasicBlock.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineMemOperand.h"
31 #include "llvm/CodeGen/MachineOperand.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/StackProtector.h"
34 #include "llvm/CodeGen/TargetFrameLowering.h"
35 #include "llvm/CodeGen/TargetInstrInfo.h"
36 #include "llvm/CodeGen/TargetLowering.h"
37 #include "llvm/CodeGen/TargetPassConfig.h"
38 #include "llvm/CodeGen/TargetRegisterInfo.h"
39 #include "llvm/CodeGen/TargetSubtargetInfo.h"
40 #include "llvm/IR/BasicBlock.h"
41 #include "llvm/IR/CFG.h"
42 #include "llvm/IR/Constant.h"
43 #include "llvm/IR/Constants.h"
44 #include "llvm/IR/DataLayout.h"
45 #include "llvm/IR/DebugInfo.h"
46 #include "llvm/IR/DerivedTypes.h"
47 #include "llvm/IR/Function.h"
48 #include "llvm/IR/GetElementPtrTypeIterator.h"
49 #include "llvm/IR/InlineAsm.h"
50 #include "llvm/IR/InstrTypes.h"
51 #include "llvm/IR/Instructions.h"
52 #include "llvm/IR/IntrinsicInst.h"
53 #include "llvm/IR/Intrinsics.h"
54 #include "llvm/IR/LLVMContext.h"
55 #include "llvm/IR/Metadata.h"
56 #include "llvm/IR/Type.h"
57 #include "llvm/IR/User.h"
58 #include "llvm/IR/Value.h"
59 #include "llvm/MC/MCContext.h"
60 #include "llvm/Pass.h"
61 #include "llvm/Support/Casting.h"
62 #include "llvm/Support/CodeGen.h"
63 #include "llvm/Support/Debug.h"
64 #include "llvm/Support/ErrorHandling.h"
65 #include "llvm/Support/LowLevelTypeImpl.h"
66 #include "llvm/Support/MathExtras.h"
67 #include "llvm/Support/raw_ostream.h"
68 #include "llvm/Target/TargetIntrinsicInfo.h"
69 #include "llvm/Target/TargetMachine.h"
70 #include <algorithm>
71 #include <cassert>
72 #include <cstdint>
73 #include <iterator>
74 #include <string>
75 #include <utility>
76 #include <vector>
77 
78 #define DEBUG_TYPE "irtranslator"
79 
80 using namespace llvm;
81 
82 static cl::opt<bool>
83     EnableCSEInIRTranslator("enable-cse-in-irtranslator",
84                             cl::desc("Should enable CSE in irtranslator"),
85                             cl::Optional, cl::init(false));
86 char IRTranslator::ID = 0;
87 
88 INITIALIZE_PASS_BEGIN(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
89                 false, false)
90 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
91 INITIALIZE_PASS_DEPENDENCY(GISelCSEAnalysisWrapperPass)
92 INITIALIZE_PASS_END(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
93                 false, false)
94 
95 static void reportTranslationError(MachineFunction &MF,
96                                    const TargetPassConfig &TPC,
97                                    OptimizationRemarkEmitter &ORE,
98                                    OptimizationRemarkMissed &R) {
99   MF.getProperties().set(MachineFunctionProperties::Property::FailedISel);
100 
101   // Print the function name explicitly if we don't have a debug location (which
102   // makes the diagnostic less useful) or if we're going to emit a raw error.
103   if (!R.getLocation().isValid() || TPC.isGlobalISelAbortEnabled())
104     R << (" (in function: " + MF.getName() + ")").str();
105 
106   if (TPC.isGlobalISelAbortEnabled())
107     report_fatal_error(R.getMsg());
108   else
109     ORE.emit(R);
110 }
111 
112 IRTranslator::IRTranslator() : MachineFunctionPass(ID) { }
113 
114 #ifndef NDEBUG
115 namespace {
116 /// Verify that every instruction created has the same DILocation as the
117 /// instruction being translated.
118 class DILocationVerifier : public GISelChangeObserver {
119   const Instruction *CurrInst = nullptr;
120 
121 public:
122   DILocationVerifier() = default;
123   ~DILocationVerifier() = default;
124 
125   const Instruction *getCurrentInst() const { return CurrInst; }
126   void setCurrentInst(const Instruction *Inst) { CurrInst = Inst; }
127 
128   void erasingInstr(MachineInstr &MI) override {}
129   void changingInstr(MachineInstr &MI) override {}
130   void changedInstr(MachineInstr &MI) override {}
131 
132   void createdInstr(MachineInstr &MI) override {
133     assert(getCurrentInst() && "Inserted instruction without a current MI");
134 
135     // Only print the check message if we're actually checking it.
136 #ifndef NDEBUG
137     LLVM_DEBUG(dbgs() << "Checking DILocation from " << *CurrInst
138                       << " was copied to " << MI);
139 #endif
140     // We allow insts in the entry block to have a debug loc line of 0 because
141     // they could have originated from constants, and we don't want a jumpy
142     // debug experience.
143     assert((CurrInst->getDebugLoc() == MI.getDebugLoc() ||
144             MI.getDebugLoc().getLine() == 0) &&
145            "Line info was not transferred to all instructions");
146   }
147 };
148 } // namespace
149 #endif // ifndef NDEBUG
150 
151 
152 void IRTranslator::getAnalysisUsage(AnalysisUsage &AU) const {
153   AU.addRequired<StackProtector>();
154   AU.addRequired<TargetPassConfig>();
155   AU.addRequired<GISelCSEAnalysisWrapperPass>();
156   getSelectionDAGFallbackAnalysisUsage(AU);
157   MachineFunctionPass::getAnalysisUsage(AU);
158 }
159 
160 IRTranslator::ValueToVRegInfo::VRegListT &
161 IRTranslator::allocateVRegs(const Value &Val) {
162   assert(!VMap.contains(Val) && "Value already allocated in VMap");
163   auto *Regs = VMap.getVRegs(Val);
164   auto *Offsets = VMap.getOffsets(Val);
165   SmallVector<LLT, 4> SplitTys;
166   computeValueLLTs(*DL, *Val.getType(), SplitTys,
167                    Offsets->empty() ? Offsets : nullptr);
168   for (unsigned i = 0; i < SplitTys.size(); ++i)
169     Regs->push_back(0);
170   return *Regs;
171 }
172 
173 ArrayRef<Register> IRTranslator::getOrCreateVRegs(const Value &Val) {
174   auto VRegsIt = VMap.findVRegs(Val);
175   if (VRegsIt != VMap.vregs_end())
176     return *VRegsIt->second;
177 
178   if (Val.getType()->isVoidTy())
179     return *VMap.getVRegs(Val);
180 
181   // Create entry for this type.
182   auto *VRegs = VMap.getVRegs(Val);
183   auto *Offsets = VMap.getOffsets(Val);
184 
185   assert(Val.getType()->isSized() &&
186          "Don't know how to create an empty vreg");
187 
188   SmallVector<LLT, 4> SplitTys;
189   computeValueLLTs(*DL, *Val.getType(), SplitTys,
190                    Offsets->empty() ? Offsets : nullptr);
191 
192   if (!isa<Constant>(Val)) {
193     for (auto Ty : SplitTys)
194       VRegs->push_back(MRI->createGenericVirtualRegister(Ty));
195     return *VRegs;
196   }
197 
198   if (Val.getType()->isAggregateType()) {
199     // UndefValue, ConstantAggregateZero
200     auto &C = cast<Constant>(Val);
201     unsigned Idx = 0;
202     while (auto Elt = C.getAggregateElement(Idx++)) {
203       auto EltRegs = getOrCreateVRegs(*Elt);
204       llvm::copy(EltRegs, std::back_inserter(*VRegs));
205     }
206   } else {
207     assert(SplitTys.size() == 1 && "unexpectedly split LLT");
208     VRegs->push_back(MRI->createGenericVirtualRegister(SplitTys[0]));
209     bool Success = translate(cast<Constant>(Val), VRegs->front());
210     if (!Success) {
211       OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
212                                  MF->getFunction().getSubprogram(),
213                                  &MF->getFunction().getEntryBlock());
214       R << "unable to translate constant: " << ore::NV("Type", Val.getType());
215       reportTranslationError(*MF, *TPC, *ORE, R);
216       return *VRegs;
217     }
218   }
219 
220   return *VRegs;
221 }
222 
223 int IRTranslator::getOrCreateFrameIndex(const AllocaInst &AI) {
224   if (FrameIndices.find(&AI) != FrameIndices.end())
225     return FrameIndices[&AI];
226 
227   unsigned ElementSize = DL->getTypeAllocSize(AI.getAllocatedType());
228   unsigned Size =
229       ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue();
230 
231   // Always allocate at least one byte.
232   Size = std::max(Size, 1u);
233 
234   unsigned Alignment = AI.getAlignment();
235   if (!Alignment)
236     Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
237 
238   int &FI = FrameIndices[&AI];
239   FI = MF->getFrameInfo().CreateStackObject(Size, Alignment, false, &AI);
240   return FI;
241 }
242 
243 unsigned IRTranslator::getMemOpAlignment(const Instruction &I) {
244   unsigned Alignment = 0;
245   Type *ValTy = nullptr;
246   if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
247     Alignment = SI->getAlignment();
248     ValTy = SI->getValueOperand()->getType();
249   } else if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
250     Alignment = LI->getAlignment();
251     ValTy = LI->getType();
252   } else if (const AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(&I)) {
253     // TODO(PR27168): This instruction has no alignment attribute, but unlike
254     // the default alignment for load/store, the default here is to assume
255     // it has NATURAL alignment, not DataLayout-specified alignment.
256     const DataLayout &DL = AI->getModule()->getDataLayout();
257     Alignment = DL.getTypeStoreSize(AI->getCompareOperand()->getType());
258     ValTy = AI->getCompareOperand()->getType();
259   } else if (const AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(&I)) {
260     // TODO(PR27168): This instruction has no alignment attribute, but unlike
261     // the default alignment for load/store, the default here is to assume
262     // it has NATURAL alignment, not DataLayout-specified alignment.
263     const DataLayout &DL = AI->getModule()->getDataLayout();
264     Alignment = DL.getTypeStoreSize(AI->getValOperand()->getType());
265     ValTy = AI->getType();
266   } else {
267     OptimizationRemarkMissed R("gisel-irtranslator", "", &I);
268     R << "unable to translate memop: " << ore::NV("Opcode", &I);
269     reportTranslationError(*MF, *TPC, *ORE, R);
270     return 1;
271   }
272 
273   return Alignment ? Alignment : DL->getABITypeAlignment(ValTy);
274 }
275 
276 MachineBasicBlock &IRTranslator::getMBB(const BasicBlock &BB) {
277   MachineBasicBlock *&MBB = BBToMBB[&BB];
278   assert(MBB && "BasicBlock was not encountered before");
279   return *MBB;
280 }
281 
282 void IRTranslator::addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred) {
283   assert(NewPred && "new predecessor must be a real MachineBasicBlock");
284   MachinePreds[Edge].push_back(NewPred);
285 }
286 
287 bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U,
288                                      MachineIRBuilder &MIRBuilder) {
289   // Get or create a virtual register for each value.
290   // Unless the value is a Constant => loadimm cst?
291   // or inline constant each time?
292   // Creation of a virtual register needs to have a size.
293   Register Op0 = getOrCreateVReg(*U.getOperand(0));
294   Register Op1 = getOrCreateVReg(*U.getOperand(1));
295   Register Res = getOrCreateVReg(U);
296   uint16_t Flags = 0;
297   if (isa<Instruction>(U)) {
298     const Instruction &I = cast<Instruction>(U);
299     Flags = MachineInstr::copyFlagsFromInstruction(I);
300   }
301 
302   MIRBuilder.buildInstr(Opcode, {Res}, {Op0, Op1}, Flags);
303   return true;
304 }
305 
306 bool IRTranslator::translateFSub(const User &U, MachineIRBuilder &MIRBuilder) {
307   // -0.0 - X --> G_FNEG
308   if (isa<Constant>(U.getOperand(0)) &&
309       U.getOperand(0) == ConstantFP::getZeroValueForNegation(U.getType())) {
310     Register Op1 = getOrCreateVReg(*U.getOperand(1));
311     Register Res = getOrCreateVReg(U);
312     uint16_t Flags = 0;
313     if (isa<Instruction>(U)) {
314       const Instruction &I = cast<Instruction>(U);
315       Flags = MachineInstr::copyFlagsFromInstruction(I);
316     }
317     // Negate the last operand of the FSUB
318     MIRBuilder.buildInstr(TargetOpcode::G_FNEG, {Res}, {Op1}, Flags);
319     return true;
320   }
321   return translateBinaryOp(TargetOpcode::G_FSUB, U, MIRBuilder);
322 }
323 
324 bool IRTranslator::translateFNeg(const User &U, MachineIRBuilder &MIRBuilder) {
325   Register Op0 = getOrCreateVReg(*U.getOperand(0));
326   Register Res = getOrCreateVReg(U);
327   uint16_t Flags = 0;
328   if (isa<Instruction>(U)) {
329     const Instruction &I = cast<Instruction>(U);
330     Flags = MachineInstr::copyFlagsFromInstruction(I);
331   }
332   MIRBuilder.buildInstr(TargetOpcode::G_FNEG, {Res}, {Op0}, Flags);
333   return true;
334 }
335 
336 bool IRTranslator::translateCompare(const User &U,
337                                     MachineIRBuilder &MIRBuilder) {
338   const CmpInst *CI = dyn_cast<CmpInst>(&U);
339   Register Op0 = getOrCreateVReg(*U.getOperand(0));
340   Register Op1 = getOrCreateVReg(*U.getOperand(1));
341   Register Res = getOrCreateVReg(U);
342   CmpInst::Predicate Pred =
343       CI ? CI->getPredicate() : static_cast<CmpInst::Predicate>(
344                                     cast<ConstantExpr>(U).getPredicate());
345   if (CmpInst::isIntPredicate(Pred))
346     MIRBuilder.buildICmp(Pred, Res, Op0, Op1);
347   else if (Pred == CmpInst::FCMP_FALSE)
348     MIRBuilder.buildCopy(
349         Res, getOrCreateVReg(*Constant::getNullValue(CI->getType())));
350   else if (Pred == CmpInst::FCMP_TRUE)
351     MIRBuilder.buildCopy(
352         Res, getOrCreateVReg(*Constant::getAllOnesValue(CI->getType())));
353   else {
354     MIRBuilder.buildInstr(TargetOpcode::G_FCMP, {Res}, {Pred, Op0, Op1},
355                           MachineInstr::copyFlagsFromInstruction(*CI));
356   }
357 
358   return true;
359 }
360 
361 bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) {
362   const ReturnInst &RI = cast<ReturnInst>(U);
363   const Value *Ret = RI.getReturnValue();
364   if (Ret && DL->getTypeStoreSize(Ret->getType()) == 0)
365     Ret = nullptr;
366 
367   ArrayRef<Register> VRegs;
368   if (Ret)
369     VRegs = getOrCreateVRegs(*Ret);
370 
371   Register SwiftErrorVReg = 0;
372   if (CLI->supportSwiftError() && SwiftError.getFunctionArg()) {
373     SwiftErrorVReg = SwiftError.getOrCreateVRegUseAt(
374         &RI, &MIRBuilder.getMBB(), SwiftError.getFunctionArg());
375   }
376 
377   // The target may mess up with the insertion point, but
378   // this is not important as a return is the last instruction
379   // of the block anyway.
380   return CLI->lowerReturn(MIRBuilder, Ret, VRegs, SwiftErrorVReg);
381 }
382 
383 bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) {
384   const BranchInst &BrInst = cast<BranchInst>(U);
385   unsigned Succ = 0;
386   if (!BrInst.isUnconditional()) {
387     // We want a G_BRCOND to the true BB followed by an unconditional branch.
388     Register Tst = getOrCreateVReg(*BrInst.getCondition());
389     const BasicBlock &TrueTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ++));
390     MachineBasicBlock &TrueBB = getMBB(TrueTgt);
391     MIRBuilder.buildBrCond(Tst, TrueBB);
392   }
393 
394   const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ));
395   MachineBasicBlock &TgtBB = getMBB(BrTgt);
396   MachineBasicBlock &CurBB = MIRBuilder.getMBB();
397 
398   // If the unconditional target is the layout successor, fallthrough.
399   if (!CurBB.isLayoutSuccessor(&TgtBB))
400     MIRBuilder.buildBr(TgtBB);
401 
402   // Link successors.
403   for (const BasicBlock *Succ : successors(&BrInst))
404     CurBB.addSuccessor(&getMBB(*Succ));
405   return true;
406 }
407 
408 void IRTranslator::addSuccessorWithProb(MachineBasicBlock *Src,
409                                         MachineBasicBlock *Dst,
410                                         BranchProbability Prob) {
411   if (!FuncInfo.BPI) {
412     Src->addSuccessorWithoutProb(Dst);
413     return;
414   }
415   if (Prob.isUnknown())
416     Prob = getEdgeProbability(Src, Dst);
417   Src->addSuccessor(Dst, Prob);
418 }
419 
420 BranchProbability
421 IRTranslator::getEdgeProbability(const MachineBasicBlock *Src,
422                                  const MachineBasicBlock *Dst) const {
423   const BasicBlock *SrcBB = Src->getBasicBlock();
424   const BasicBlock *DstBB = Dst->getBasicBlock();
425   if (!FuncInfo.BPI) {
426     // If BPI is not available, set the default probability as 1 / N, where N is
427     // the number of successors.
428     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
429     return BranchProbability(1, SuccSize);
430   }
431   return FuncInfo.BPI->getEdgeProbability(SrcBB, DstBB);
432 }
433 
434 bool IRTranslator::translateSwitch(const User &U, MachineIRBuilder &MIB) {
435   using namespace SwitchCG;
436   // Extract cases from the switch.
437   const SwitchInst &SI = cast<SwitchInst>(U);
438   BranchProbabilityInfo *BPI = FuncInfo.BPI;
439   CaseClusterVector Clusters;
440   Clusters.reserve(SI.getNumCases());
441   for (auto &I : SI.cases()) {
442     MachineBasicBlock *Succ = &getMBB(*I.getCaseSuccessor());
443     assert(Succ && "Could not find successor mbb in mapping");
444     const ConstantInt *CaseVal = I.getCaseValue();
445     BranchProbability Prob =
446         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
447             : BranchProbability(1, SI.getNumCases() + 1);
448     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
449   }
450 
451   MachineBasicBlock *DefaultMBB = &getMBB(*SI.getDefaultDest());
452 
453   // Cluster adjacent cases with the same destination. We do this at all
454   // optimization levels because it's cheap to do and will make codegen faster
455   // if there are many clusters.
456   sortAndRangeify(Clusters);
457 
458   MachineBasicBlock *SwitchMBB = &getMBB(*SI.getParent());
459 
460   // If there is only the default destination, jump there directly.
461   if (Clusters.empty()) {
462     SwitchMBB->addSuccessor(DefaultMBB);
463     if (DefaultMBB != SwitchMBB->getNextNode())
464       MIB.buildBr(*DefaultMBB);
465     return true;
466   }
467 
468   SL->findJumpTables(Clusters, &SI, DefaultMBB);
469 
470   LLVM_DEBUG({
471     dbgs() << "Case clusters: ";
472     for (const CaseCluster &C : Clusters) {
473       if (C.Kind == CC_JumpTable)
474         dbgs() << "JT:";
475       if (C.Kind == CC_BitTests)
476         dbgs() << "BT:";
477 
478       C.Low->getValue().print(dbgs(), true);
479       if (C.Low != C.High) {
480         dbgs() << '-';
481         C.High->getValue().print(dbgs(), true);
482       }
483       dbgs() << ' ';
484     }
485     dbgs() << '\n';
486   });
487 
488   assert(!Clusters.empty());
489   SwitchWorkList WorkList;
490   CaseClusterIt First = Clusters.begin();
491   CaseClusterIt Last = Clusters.end() - 1;
492   auto DefaultProb = getEdgeProbability(SwitchMBB, DefaultMBB);
493   WorkList.push_back({SwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
494 
495   // FIXME: At the moment we don't do any splitting optimizations here like
496   // SelectionDAG does, so this worklist only has one entry.
497   while (!WorkList.empty()) {
498     SwitchWorkListItem W = WorkList.back();
499     WorkList.pop_back();
500     if (!lowerSwitchWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB, MIB))
501       return false;
502   }
503   return true;
504 }
505 
506 void IRTranslator::emitJumpTable(SwitchCG::JumpTable &JT,
507                                  MachineBasicBlock *MBB) {
508   // Emit the code for the jump table
509   assert(JT.Reg != -1U && "Should lower JT Header first!");
510   MachineIRBuilder MIB(*MBB->getParent());
511   MIB.setMBB(*MBB);
512   MIB.setDebugLoc(CurBuilder->getDebugLoc());
513 
514   Type *PtrIRTy = Type::getInt8PtrTy(MF->getFunction().getContext());
515   const LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
516 
517   auto Table = MIB.buildJumpTable(PtrTy, JT.JTI);
518   MIB.buildBrJT(Table.getReg(0), JT.JTI, JT.Reg);
519 }
520 
521 bool IRTranslator::emitJumpTableHeader(SwitchCG::JumpTable &JT,
522                                        SwitchCG::JumpTableHeader &JTH,
523                                        MachineBasicBlock *HeaderBB) {
524   MachineIRBuilder MIB(*HeaderBB->getParent());
525   MIB.setMBB(*HeaderBB);
526   MIB.setDebugLoc(CurBuilder->getDebugLoc());
527 
528   const Value &SValue = *JTH.SValue;
529   // Subtract the lowest switch case value from the value being switched on.
530   const LLT SwitchTy = getLLTForType(*SValue.getType(), *DL);
531   Register SwitchOpReg = getOrCreateVReg(SValue);
532   auto FirstCst = MIB.buildConstant(SwitchTy, JTH.First);
533   auto Sub = MIB.buildSub({SwitchTy}, SwitchOpReg, FirstCst);
534 
535   // This value may be smaller or larger than the target's pointer type, and
536   // therefore require extension or truncating.
537   Type *PtrIRTy = SValue.getType()->getPointerTo();
538   const LLT PtrScalarTy = LLT::scalar(DL->getTypeSizeInBits(PtrIRTy));
539   Sub = MIB.buildZExtOrTrunc(PtrScalarTy, Sub);
540 
541   JT.Reg = Sub.getReg(0);
542 
543   if (JTH.OmitRangeCheck) {
544     if (JT.MBB != HeaderBB->getNextNode())
545       MIB.buildBr(*JT.MBB);
546     return true;
547   }
548 
549   // Emit the range check for the jump table, and branch to the default block
550   // for the switch statement if the value being switched on exceeds the
551   // largest case in the switch.
552   auto Cst = getOrCreateVReg(
553       *ConstantInt::get(SValue.getType(), JTH.Last - JTH.First));
554   Cst = MIB.buildZExtOrTrunc(PtrScalarTy, Cst).getReg(0);
555   auto Cmp = MIB.buildICmp(CmpInst::ICMP_UGT, LLT::scalar(1), Sub, Cst);
556 
557   auto BrCond = MIB.buildBrCond(Cmp.getReg(0), *JT.Default);
558 
559   // Avoid emitting unnecessary branches to the next block.
560   if (JT.MBB != HeaderBB->getNextNode())
561     BrCond = MIB.buildBr(*JT.MBB);
562   return true;
563 }
564 
565 void IRTranslator::emitSwitchCase(SwitchCG::CaseBlock &CB,
566                                   MachineBasicBlock *SwitchBB,
567                                   MachineIRBuilder &MIB) {
568   Register CondLHS = getOrCreateVReg(*CB.CmpLHS);
569   Register Cond;
570   DebugLoc OldDbgLoc = MIB.getDebugLoc();
571   MIB.setDebugLoc(CB.DbgLoc);
572   MIB.setMBB(*CB.ThisBB);
573 
574   if (CB.PredInfo.NoCmp) {
575     // Branch or fall through to TrueBB.
576     addSuccessorWithProb(CB.ThisBB, CB.TrueBB, CB.TrueProb);
577     addMachineCFGPred({SwitchBB->getBasicBlock(), CB.TrueBB->getBasicBlock()},
578                       CB.ThisBB);
579     CB.ThisBB->normalizeSuccProbs();
580     if (CB.TrueBB != CB.ThisBB->getNextNode())
581       MIB.buildBr(*CB.TrueBB);
582     MIB.setDebugLoc(OldDbgLoc);
583     return;
584   }
585 
586   const LLT i1Ty = LLT::scalar(1);
587   // Build the compare.
588   if (!CB.CmpMHS) {
589     Register CondRHS = getOrCreateVReg(*CB.CmpRHS);
590     Cond = MIB.buildICmp(CB.PredInfo.Pred, i1Ty, CondLHS, CondRHS).getReg(0);
591   } else {
592     assert(CB.PredInfo.Pred == CmpInst::ICMP_SLE &&
593            "Can only handle SLE ranges");
594 
595     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
596     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
597 
598     Register CmpOpReg = getOrCreateVReg(*CB.CmpMHS);
599     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
600       Register CondRHS = getOrCreateVReg(*CB.CmpRHS);
601       Cond =
602           MIB.buildICmp(CmpInst::ICMP_SLE, i1Ty, CmpOpReg, CondRHS).getReg(0);
603     } else {
604       const LLT &CmpTy = MRI->getType(CmpOpReg);
605       auto Sub = MIB.buildSub({CmpTy}, CmpOpReg, CondLHS);
606       auto Diff = MIB.buildConstant(CmpTy, High - Low);
607       Cond = MIB.buildICmp(CmpInst::ICMP_ULE, i1Ty, Sub, Diff).getReg(0);
608     }
609   }
610 
611   // Update successor info
612   addSuccessorWithProb(CB.ThisBB, CB.TrueBB, CB.TrueProb);
613 
614   addMachineCFGPred({SwitchBB->getBasicBlock(), CB.TrueBB->getBasicBlock()},
615                     CB.ThisBB);
616 
617   // TrueBB and FalseBB are always different unless the incoming IR is
618   // degenerate. This only happens when running llc on weird IR.
619   if (CB.TrueBB != CB.FalseBB)
620     addSuccessorWithProb(CB.ThisBB, CB.FalseBB, CB.FalseProb);
621   CB.ThisBB->normalizeSuccProbs();
622 
623   //  if (SwitchBB->getBasicBlock() != CB.FalseBB->getBasicBlock())
624     addMachineCFGPred({SwitchBB->getBasicBlock(), CB.FalseBB->getBasicBlock()},
625                       CB.ThisBB);
626 
627   // If the lhs block is the next block, invert the condition so that we can
628   // fall through to the lhs instead of the rhs block.
629   if (CB.TrueBB == CB.ThisBB->getNextNode()) {
630     std::swap(CB.TrueBB, CB.FalseBB);
631     auto True = MIB.buildConstant(i1Ty, 1);
632     Cond = MIB.buildInstr(TargetOpcode::G_XOR, {i1Ty}, {Cond, True}, None)
633                .getReg(0);
634   }
635 
636   MIB.buildBrCond(Cond, *CB.TrueBB);
637   MIB.buildBr(*CB.FalseBB);
638   MIB.setDebugLoc(OldDbgLoc);
639 }
640 
641 bool IRTranslator::lowerJumpTableWorkItem(SwitchCG::SwitchWorkListItem W,
642                                           MachineBasicBlock *SwitchMBB,
643                                           MachineBasicBlock *CurMBB,
644                                           MachineBasicBlock *DefaultMBB,
645                                           MachineIRBuilder &MIB,
646                                           MachineFunction::iterator BBI,
647                                           BranchProbability UnhandledProbs,
648                                           SwitchCG::CaseClusterIt I,
649                                           MachineBasicBlock *Fallthrough,
650                                           bool FallthroughUnreachable) {
651   using namespace SwitchCG;
652   MachineFunction *CurMF = SwitchMBB->getParent();
653   // FIXME: Optimize away range check based on pivot comparisons.
654   JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
655   SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
656   BranchProbability DefaultProb = W.DefaultProb;
657 
658   // The jump block hasn't been inserted yet; insert it here.
659   MachineBasicBlock *JumpMBB = JT->MBB;
660   CurMF->insert(BBI, JumpMBB);
661 
662   // Since the jump table block is separate from the switch block, we need
663   // to keep track of it as a machine predecessor to the default block,
664   // otherwise we lose the phi edges.
665   addMachineCFGPred({SwitchMBB->getBasicBlock(), DefaultMBB->getBasicBlock()},
666                     CurMBB);
667   addMachineCFGPred({SwitchMBB->getBasicBlock(), DefaultMBB->getBasicBlock()},
668                     JumpMBB);
669 
670   auto JumpProb = I->Prob;
671   auto FallthroughProb = UnhandledProbs;
672 
673   // If the default statement is a target of the jump table, we evenly
674   // distribute the default probability to successors of CurMBB. Also
675   // update the probability on the edge from JumpMBB to Fallthrough.
676   for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
677                                         SE = JumpMBB->succ_end();
678        SI != SE; ++SI) {
679     if (*SI == DefaultMBB) {
680       JumpProb += DefaultProb / 2;
681       FallthroughProb -= DefaultProb / 2;
682       JumpMBB->setSuccProbability(SI, DefaultProb / 2);
683       JumpMBB->normalizeSuccProbs();
684     } else {
685       // Also record edges from the jump table block to it's successors.
686       addMachineCFGPred({SwitchMBB->getBasicBlock(), (*SI)->getBasicBlock()},
687                         JumpMBB);
688     }
689   }
690 
691   // Skip the range check if the fallthrough block is unreachable.
692   if (FallthroughUnreachable)
693     JTH->OmitRangeCheck = true;
694 
695   if (!JTH->OmitRangeCheck)
696     addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
697   addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
698   CurMBB->normalizeSuccProbs();
699 
700   // The jump table header will be inserted in our current block, do the
701   // range check, and fall through to our fallthrough block.
702   JTH->HeaderBB = CurMBB;
703   JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
704 
705   // If we're in the right place, emit the jump table header right now.
706   if (CurMBB == SwitchMBB) {
707     if (!emitJumpTableHeader(*JT, *JTH, CurMBB))
708       return false;
709     JTH->Emitted = true;
710   }
711   return true;
712 }
713 bool IRTranslator::lowerSwitchRangeWorkItem(SwitchCG::CaseClusterIt I,
714                                             Value *Cond,
715                                             MachineBasicBlock *Fallthrough,
716                                             bool FallthroughUnreachable,
717                                             BranchProbability UnhandledProbs,
718                                             MachineBasicBlock *CurMBB,
719                                             MachineIRBuilder &MIB,
720                                             MachineBasicBlock *SwitchMBB) {
721   using namespace SwitchCG;
722   const Value *RHS, *LHS, *MHS;
723   CmpInst::Predicate Pred;
724   if (I->Low == I->High) {
725     // Check Cond == I->Low.
726     Pred = CmpInst::ICMP_EQ;
727     LHS = Cond;
728     RHS = I->Low;
729     MHS = nullptr;
730   } else {
731     // Check I->Low <= Cond <= I->High.
732     Pred = CmpInst::ICMP_SLE;
733     LHS = I->Low;
734     MHS = Cond;
735     RHS = I->High;
736   }
737 
738   // If Fallthrough is unreachable, fold away the comparison.
739   // The false probability is the sum of all unhandled cases.
740   CaseBlock CB(Pred, FallthroughUnreachable, LHS, RHS, MHS, I->MBB, Fallthrough,
741                CurMBB, MIB.getDebugLoc(), I->Prob, UnhandledProbs);
742 
743   emitSwitchCase(CB, SwitchMBB, MIB);
744   return true;
745 }
746 
747 bool IRTranslator::lowerSwitchWorkItem(SwitchCG::SwitchWorkListItem W,
748                                        Value *Cond,
749                                        MachineBasicBlock *SwitchMBB,
750                                        MachineBasicBlock *DefaultMBB,
751                                        MachineIRBuilder &MIB) {
752   using namespace SwitchCG;
753   MachineFunction *CurMF = FuncInfo.MF;
754   MachineBasicBlock *NextMBB = nullptr;
755   MachineFunction::iterator BBI(W.MBB);
756   if (++BBI != FuncInfo.MF->end())
757     NextMBB = &*BBI;
758 
759   if (EnableOpts) {
760     // Here, we order cases by probability so the most likely case will be
761     // checked first. However, two clusters can have the same probability in
762     // which case their relative ordering is non-deterministic. So we use Low
763     // as a tie-breaker as clusters are guaranteed to never overlap.
764     llvm::sort(W.FirstCluster, W.LastCluster + 1,
765                [](const CaseCluster &a, const CaseCluster &b) {
766                  return a.Prob != b.Prob
767                             ? a.Prob > b.Prob
768                             : a.Low->getValue().slt(b.Low->getValue());
769                });
770 
771     // Rearrange the case blocks so that the last one falls through if possible
772     // without changing the order of probabilities.
773     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster;) {
774       --I;
775       if (I->Prob > W.LastCluster->Prob)
776         break;
777       if (I->Kind == CC_Range && I->MBB == NextMBB) {
778         std::swap(*I, *W.LastCluster);
779         break;
780       }
781     }
782   }
783 
784   // Compute total probability.
785   BranchProbability DefaultProb = W.DefaultProb;
786   BranchProbability UnhandledProbs = DefaultProb;
787   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
788     UnhandledProbs += I->Prob;
789 
790   MachineBasicBlock *CurMBB = W.MBB;
791   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
792     bool FallthroughUnreachable = false;
793     MachineBasicBlock *Fallthrough;
794     if (I == W.LastCluster) {
795       // For the last cluster, fall through to the default destination.
796       Fallthrough = DefaultMBB;
797       FallthroughUnreachable = isa<UnreachableInst>(
798           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
799     } else {
800       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
801       CurMF->insert(BBI, Fallthrough);
802     }
803     UnhandledProbs -= I->Prob;
804 
805     switch (I->Kind) {
806     case CC_BitTests: {
807       LLVM_DEBUG(dbgs() << "Switch to bit test optimization unimplemented");
808       return false; // Bit tests currently unimplemented.
809     }
810     case CC_JumpTable: {
811       if (!lowerJumpTableWorkItem(W, SwitchMBB, CurMBB, DefaultMBB, MIB, BBI,
812                                   UnhandledProbs, I, Fallthrough,
813                                   FallthroughUnreachable)) {
814         LLVM_DEBUG(dbgs() << "Failed to lower jump table");
815         return false;
816       }
817       break;
818     }
819     case CC_Range: {
820       if (!lowerSwitchRangeWorkItem(I, Cond, Fallthrough,
821                                     FallthroughUnreachable, UnhandledProbs,
822                                     CurMBB, MIB, SwitchMBB)) {
823         LLVM_DEBUG(dbgs() << "Failed to lower switch range");
824         return false;
825       }
826       break;
827     }
828     }
829     CurMBB = Fallthrough;
830   }
831 
832   return true;
833 }
834 
835 bool IRTranslator::translateIndirectBr(const User &U,
836                                        MachineIRBuilder &MIRBuilder) {
837   const IndirectBrInst &BrInst = cast<IndirectBrInst>(U);
838 
839   const Register Tgt = getOrCreateVReg(*BrInst.getAddress());
840   MIRBuilder.buildBrIndirect(Tgt);
841 
842   // Link successors.
843   MachineBasicBlock &CurBB = MIRBuilder.getMBB();
844   for (const BasicBlock *Succ : successors(&BrInst))
845     CurBB.addSuccessor(&getMBB(*Succ));
846 
847   return true;
848 }
849 
850 static bool isSwiftError(const Value *V) {
851   if (auto Arg = dyn_cast<Argument>(V))
852     return Arg->hasSwiftErrorAttr();
853   if (auto AI = dyn_cast<AllocaInst>(V))
854     return AI->isSwiftError();
855   return false;
856 }
857 
858 bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) {
859   const LoadInst &LI = cast<LoadInst>(U);
860 
861   auto Flags = LI.isVolatile() ? MachineMemOperand::MOVolatile
862                                : MachineMemOperand::MONone;
863   Flags |= MachineMemOperand::MOLoad;
864 
865   if (DL->getTypeStoreSize(LI.getType()) == 0)
866     return true;
867 
868   ArrayRef<Register> Regs = getOrCreateVRegs(LI);
869   ArrayRef<uint64_t> Offsets = *VMap.getOffsets(LI);
870   Register Base = getOrCreateVReg(*LI.getPointerOperand());
871 
872   Type *OffsetIRTy = DL->getIntPtrType(LI.getPointerOperandType());
873   LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
874 
875   if (CLI->supportSwiftError() && isSwiftError(LI.getPointerOperand())) {
876     assert(Regs.size() == 1 && "swifterror should be single pointer");
877     Register VReg = SwiftError.getOrCreateVRegUseAt(&LI, &MIRBuilder.getMBB(),
878                                                     LI.getPointerOperand());
879     MIRBuilder.buildCopy(Regs[0], VReg);
880     return true;
881   }
882 
883   const MDNode *Ranges =
884       Regs.size() == 1 ? LI.getMetadata(LLVMContext::MD_range) : nullptr;
885   for (unsigned i = 0; i < Regs.size(); ++i) {
886     Register Addr;
887     MIRBuilder.materializeGEP(Addr, Base, OffsetTy, Offsets[i] / 8);
888 
889     MachinePointerInfo Ptr(LI.getPointerOperand(), Offsets[i] / 8);
890     unsigned BaseAlign = getMemOpAlignment(LI);
891     auto MMO = MF->getMachineMemOperand(
892         Ptr, Flags, (MRI->getType(Regs[i]).getSizeInBits() + 7) / 8,
893         MinAlign(BaseAlign, Offsets[i] / 8), AAMDNodes(), Ranges,
894         LI.getSyncScopeID(), LI.getOrdering());
895     MIRBuilder.buildLoad(Regs[i], Addr, *MMO);
896   }
897 
898   return true;
899 }
900 
901 bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) {
902   const StoreInst &SI = cast<StoreInst>(U);
903   auto Flags = SI.isVolatile() ? MachineMemOperand::MOVolatile
904                                : MachineMemOperand::MONone;
905   Flags |= MachineMemOperand::MOStore;
906 
907   if (DL->getTypeStoreSize(SI.getValueOperand()->getType()) == 0)
908     return true;
909 
910   ArrayRef<Register> Vals = getOrCreateVRegs(*SI.getValueOperand());
911   ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*SI.getValueOperand());
912   Register Base = getOrCreateVReg(*SI.getPointerOperand());
913 
914   Type *OffsetIRTy = DL->getIntPtrType(SI.getPointerOperandType());
915   LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
916 
917   if (CLI->supportSwiftError() && isSwiftError(SI.getPointerOperand())) {
918     assert(Vals.size() == 1 && "swifterror should be single pointer");
919 
920     Register VReg = SwiftError.getOrCreateVRegDefAt(&SI, &MIRBuilder.getMBB(),
921                                                     SI.getPointerOperand());
922     MIRBuilder.buildCopy(VReg, Vals[0]);
923     return true;
924   }
925 
926   for (unsigned i = 0; i < Vals.size(); ++i) {
927     Register Addr;
928     MIRBuilder.materializeGEP(Addr, Base, OffsetTy, Offsets[i] / 8);
929 
930     MachinePointerInfo Ptr(SI.getPointerOperand(), Offsets[i] / 8);
931     unsigned BaseAlign = getMemOpAlignment(SI);
932     auto MMO = MF->getMachineMemOperand(
933         Ptr, Flags, (MRI->getType(Vals[i]).getSizeInBits() + 7) / 8,
934         MinAlign(BaseAlign, Offsets[i] / 8), AAMDNodes(), nullptr,
935         SI.getSyncScopeID(), SI.getOrdering());
936     MIRBuilder.buildStore(Vals[i], Addr, *MMO);
937   }
938   return true;
939 }
940 
941 static uint64_t getOffsetFromIndices(const User &U, const DataLayout &DL) {
942   const Value *Src = U.getOperand(0);
943   Type *Int32Ty = Type::getInt32Ty(U.getContext());
944 
945   // getIndexedOffsetInType is designed for GEPs, so the first index is the
946   // usual array element rather than looking into the actual aggregate.
947   SmallVector<Value *, 1> Indices;
948   Indices.push_back(ConstantInt::get(Int32Ty, 0));
949 
950   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) {
951     for (auto Idx : EVI->indices())
952       Indices.push_back(ConstantInt::get(Int32Ty, Idx));
953   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) {
954     for (auto Idx : IVI->indices())
955       Indices.push_back(ConstantInt::get(Int32Ty, Idx));
956   } else {
957     for (unsigned i = 1; i < U.getNumOperands(); ++i)
958       Indices.push_back(U.getOperand(i));
959   }
960 
961   return 8 * static_cast<uint64_t>(
962                  DL.getIndexedOffsetInType(Src->getType(), Indices));
963 }
964 
965 bool IRTranslator::translateExtractValue(const User &U,
966                                          MachineIRBuilder &MIRBuilder) {
967   const Value *Src = U.getOperand(0);
968   uint64_t Offset = getOffsetFromIndices(U, *DL);
969   ArrayRef<Register> SrcRegs = getOrCreateVRegs(*Src);
970   ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*Src);
971   unsigned Idx = llvm::lower_bound(Offsets, Offset) - Offsets.begin();
972   auto &DstRegs = allocateVRegs(U);
973 
974   for (unsigned i = 0; i < DstRegs.size(); ++i)
975     DstRegs[i] = SrcRegs[Idx++];
976 
977   return true;
978 }
979 
980 bool IRTranslator::translateInsertValue(const User &U,
981                                         MachineIRBuilder &MIRBuilder) {
982   const Value *Src = U.getOperand(0);
983   uint64_t Offset = getOffsetFromIndices(U, *DL);
984   auto &DstRegs = allocateVRegs(U);
985   ArrayRef<uint64_t> DstOffsets = *VMap.getOffsets(U);
986   ArrayRef<Register> SrcRegs = getOrCreateVRegs(*Src);
987   ArrayRef<Register> InsertedRegs = getOrCreateVRegs(*U.getOperand(1));
988   auto InsertedIt = InsertedRegs.begin();
989 
990   for (unsigned i = 0; i < DstRegs.size(); ++i) {
991     if (DstOffsets[i] >= Offset && InsertedIt != InsertedRegs.end())
992       DstRegs[i] = *InsertedIt++;
993     else
994       DstRegs[i] = SrcRegs[i];
995   }
996 
997   return true;
998 }
999 
1000 bool IRTranslator::translateSelect(const User &U,
1001                                    MachineIRBuilder &MIRBuilder) {
1002   Register Tst = getOrCreateVReg(*U.getOperand(0));
1003   ArrayRef<Register> ResRegs = getOrCreateVRegs(U);
1004   ArrayRef<Register> Op0Regs = getOrCreateVRegs(*U.getOperand(1));
1005   ArrayRef<Register> Op1Regs = getOrCreateVRegs(*U.getOperand(2));
1006 
1007   const SelectInst &SI = cast<SelectInst>(U);
1008   uint16_t Flags = 0;
1009   if (const CmpInst *Cmp = dyn_cast<CmpInst>(SI.getCondition()))
1010     Flags = MachineInstr::copyFlagsFromInstruction(*Cmp);
1011 
1012   for (unsigned i = 0; i < ResRegs.size(); ++i) {
1013     MIRBuilder.buildInstr(TargetOpcode::G_SELECT, {ResRegs[i]},
1014                           {Tst, Op0Regs[i], Op1Regs[i]}, Flags);
1015   }
1016 
1017   return true;
1018 }
1019 
1020 bool IRTranslator::translateBitCast(const User &U,
1021                                     MachineIRBuilder &MIRBuilder) {
1022   // If we're bitcasting to the source type, we can reuse the source vreg.
1023   if (getLLTForType(*U.getOperand(0)->getType(), *DL) ==
1024       getLLTForType(*U.getType(), *DL)) {
1025     Register SrcReg = getOrCreateVReg(*U.getOperand(0));
1026     auto &Regs = *VMap.getVRegs(U);
1027     // If we already assigned a vreg for this bitcast, we can't change that.
1028     // Emit a copy to satisfy the users we already emitted.
1029     if (!Regs.empty())
1030       MIRBuilder.buildCopy(Regs[0], SrcReg);
1031     else {
1032       Regs.push_back(SrcReg);
1033       VMap.getOffsets(U)->push_back(0);
1034     }
1035     return true;
1036   }
1037   return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder);
1038 }
1039 
1040 bool IRTranslator::translateCast(unsigned Opcode, const User &U,
1041                                  MachineIRBuilder &MIRBuilder) {
1042   Register Op = getOrCreateVReg(*U.getOperand(0));
1043   Register Res = getOrCreateVReg(U);
1044   MIRBuilder.buildInstr(Opcode, {Res}, {Op});
1045   return true;
1046 }
1047 
1048 bool IRTranslator::translateGetElementPtr(const User &U,
1049                                           MachineIRBuilder &MIRBuilder) {
1050   // FIXME: support vector GEPs.
1051   if (U.getType()->isVectorTy())
1052     return false;
1053 
1054   Value &Op0 = *U.getOperand(0);
1055   Register BaseReg = getOrCreateVReg(Op0);
1056   Type *PtrIRTy = Op0.getType();
1057   LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
1058   Type *OffsetIRTy = DL->getIntPtrType(PtrIRTy);
1059   LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
1060 
1061   int64_t Offset = 0;
1062   for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U);
1063        GTI != E; ++GTI) {
1064     const Value *Idx = GTI.getOperand();
1065     if (StructType *StTy = GTI.getStructTypeOrNull()) {
1066       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
1067       Offset += DL->getStructLayout(StTy)->getElementOffset(Field);
1068       continue;
1069     } else {
1070       uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
1071 
1072       // If this is a scalar constant or a splat vector of constants,
1073       // handle it quickly.
1074       if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
1075         Offset += ElementSize * CI->getSExtValue();
1076         continue;
1077       }
1078 
1079       if (Offset != 0) {
1080         LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
1081         auto OffsetMIB = MIRBuilder.buildConstant({OffsetTy}, Offset);
1082         BaseReg =
1083             MIRBuilder.buildGEP(PtrTy, BaseReg, OffsetMIB.getReg(0)).getReg(0);
1084         Offset = 0;
1085       }
1086 
1087       Register IdxReg = getOrCreateVReg(*Idx);
1088       if (MRI->getType(IdxReg) != OffsetTy)
1089         IdxReg = MIRBuilder.buildSExtOrTrunc(OffsetTy, IdxReg).getReg(0);
1090 
1091       // N = N + Idx * ElementSize;
1092       // Avoid doing it for ElementSize of 1.
1093       Register GepOffsetReg;
1094       if (ElementSize != 1) {
1095         auto ElementSizeMIB = MIRBuilder.buildConstant(
1096             getLLTForType(*OffsetIRTy, *DL), ElementSize);
1097         GepOffsetReg =
1098             MIRBuilder.buildMul(OffsetTy, ElementSizeMIB, IdxReg).getReg(0);
1099       } else
1100         GepOffsetReg = IdxReg;
1101 
1102       BaseReg = MIRBuilder.buildGEP(PtrTy, BaseReg, GepOffsetReg).getReg(0);
1103     }
1104   }
1105 
1106   if (Offset != 0) {
1107     auto OffsetMIB =
1108         MIRBuilder.buildConstant(getLLTForType(*OffsetIRTy, *DL), Offset);
1109     MIRBuilder.buildGEP(getOrCreateVReg(U), BaseReg, OffsetMIB.getReg(0));
1110     return true;
1111   }
1112 
1113   MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg);
1114   return true;
1115 }
1116 
1117 bool IRTranslator::translateMemFunc(const CallInst &CI,
1118                                     MachineIRBuilder &MIRBuilder,
1119                                     Intrinsic::ID ID) {
1120 
1121   // If the source is undef, then just emit a nop.
1122   if (isa<UndefValue>(CI.getArgOperand(1)))
1123     return true;
1124 
1125   ArrayRef<Register> Res;
1126   auto ICall = MIRBuilder.buildIntrinsic(ID, Res, true);
1127   for (auto AI = CI.arg_begin(), AE = CI.arg_end(); std::next(AI) != AE; ++AI)
1128     ICall.addUse(getOrCreateVReg(**AI));
1129 
1130   unsigned DstAlign = 0, SrcAlign = 0;
1131   unsigned IsVol =
1132       cast<ConstantInt>(CI.getArgOperand(CI.getNumArgOperands() - 1))
1133           ->getZExtValue();
1134 
1135   if (auto *MCI = dyn_cast<MemCpyInst>(&CI)) {
1136     DstAlign = std::max<unsigned>(MCI->getDestAlignment(), 1);
1137     SrcAlign = std::max<unsigned>(MCI->getSourceAlignment(), 1);
1138   } else if (auto *MMI = dyn_cast<MemMoveInst>(&CI)) {
1139     DstAlign = std::max<unsigned>(MMI->getDestAlignment(), 1);
1140     SrcAlign = std::max<unsigned>(MMI->getSourceAlignment(), 1);
1141   } else {
1142     auto *MSI = cast<MemSetInst>(&CI);
1143     DstAlign = std::max<unsigned>(MSI->getDestAlignment(), 1);
1144   }
1145 
1146   // We need to propagate the tail call flag from the IR inst as an argument.
1147   // Otherwise, we have to pessimize and assume later that we cannot tail call
1148   // any memory intrinsics.
1149   ICall.addImm(CI.isTailCall() ? 1 : 0);
1150 
1151   // Create mem operands to store the alignment and volatile info.
1152   auto VolFlag = IsVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
1153   ICall.addMemOperand(MF->getMachineMemOperand(
1154       MachinePointerInfo(CI.getArgOperand(0)),
1155       MachineMemOperand::MOStore | VolFlag, 1, DstAlign));
1156   if (ID != Intrinsic::memset)
1157     ICall.addMemOperand(MF->getMachineMemOperand(
1158         MachinePointerInfo(CI.getArgOperand(1)),
1159         MachineMemOperand::MOLoad | VolFlag, 1, SrcAlign));
1160 
1161   return true;
1162 }
1163 
1164 void IRTranslator::getStackGuard(Register DstReg,
1165                                  MachineIRBuilder &MIRBuilder) {
1166   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
1167   MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF));
1168   auto MIB = MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD);
1169   MIB.addDef(DstReg);
1170 
1171   auto &TLI = *MF->getSubtarget().getTargetLowering();
1172   Value *Global = TLI.getSDagStackGuard(*MF->getFunction().getParent());
1173   if (!Global)
1174     return;
1175 
1176   MachinePointerInfo MPInfo(Global);
1177   auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
1178                MachineMemOperand::MODereferenceable;
1179   MachineMemOperand *MemRef =
1180       MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8,
1181                                DL->getPointerABIAlignment(0).value());
1182   MIB.setMemRefs({MemRef});
1183 }
1184 
1185 bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op,
1186                                               MachineIRBuilder &MIRBuilder) {
1187   ArrayRef<Register> ResRegs = getOrCreateVRegs(CI);
1188   MIRBuilder.buildInstr(Op)
1189       .addDef(ResRegs[0])
1190       .addDef(ResRegs[1])
1191       .addUse(getOrCreateVReg(*CI.getOperand(0)))
1192       .addUse(getOrCreateVReg(*CI.getOperand(1)));
1193 
1194   return true;
1195 }
1196 
1197 unsigned IRTranslator::getSimpleIntrinsicOpcode(Intrinsic::ID ID) {
1198   switch (ID) {
1199     default:
1200       break;
1201     case Intrinsic::bswap:
1202       return TargetOpcode::G_BSWAP;
1203   case Intrinsic::bitreverse:
1204       return TargetOpcode::G_BITREVERSE;
1205     case Intrinsic::ceil:
1206       return TargetOpcode::G_FCEIL;
1207     case Intrinsic::cos:
1208       return TargetOpcode::G_FCOS;
1209     case Intrinsic::ctpop:
1210       return TargetOpcode::G_CTPOP;
1211     case Intrinsic::exp:
1212       return TargetOpcode::G_FEXP;
1213     case Intrinsic::exp2:
1214       return TargetOpcode::G_FEXP2;
1215     case Intrinsic::fabs:
1216       return TargetOpcode::G_FABS;
1217     case Intrinsic::copysign:
1218       return TargetOpcode::G_FCOPYSIGN;
1219     case Intrinsic::minnum:
1220       return TargetOpcode::G_FMINNUM;
1221     case Intrinsic::maxnum:
1222       return TargetOpcode::G_FMAXNUM;
1223     case Intrinsic::minimum:
1224       return TargetOpcode::G_FMINIMUM;
1225     case Intrinsic::maximum:
1226       return TargetOpcode::G_FMAXIMUM;
1227     case Intrinsic::canonicalize:
1228       return TargetOpcode::G_FCANONICALIZE;
1229     case Intrinsic::floor:
1230       return TargetOpcode::G_FFLOOR;
1231     case Intrinsic::fma:
1232       return TargetOpcode::G_FMA;
1233     case Intrinsic::log:
1234       return TargetOpcode::G_FLOG;
1235     case Intrinsic::log2:
1236       return TargetOpcode::G_FLOG2;
1237     case Intrinsic::log10:
1238       return TargetOpcode::G_FLOG10;
1239     case Intrinsic::nearbyint:
1240       return TargetOpcode::G_FNEARBYINT;
1241     case Intrinsic::pow:
1242       return TargetOpcode::G_FPOW;
1243     case Intrinsic::rint:
1244       return TargetOpcode::G_FRINT;
1245     case Intrinsic::round:
1246       return TargetOpcode::G_INTRINSIC_ROUND;
1247     case Intrinsic::sin:
1248       return TargetOpcode::G_FSIN;
1249     case Intrinsic::sqrt:
1250       return TargetOpcode::G_FSQRT;
1251     case Intrinsic::trunc:
1252       return TargetOpcode::G_INTRINSIC_TRUNC;
1253   }
1254   return Intrinsic::not_intrinsic;
1255 }
1256 
1257 bool IRTranslator::translateSimpleIntrinsic(const CallInst &CI,
1258                                             Intrinsic::ID ID,
1259                                             MachineIRBuilder &MIRBuilder) {
1260 
1261   unsigned Op = getSimpleIntrinsicOpcode(ID);
1262 
1263   // Is this a simple intrinsic?
1264   if (Op == Intrinsic::not_intrinsic)
1265     return false;
1266 
1267   // Yes. Let's translate it.
1268   SmallVector<llvm::SrcOp, 4> VRegs;
1269   for (auto &Arg : CI.arg_operands())
1270     VRegs.push_back(getOrCreateVReg(*Arg));
1271 
1272   MIRBuilder.buildInstr(Op, {getOrCreateVReg(CI)}, VRegs,
1273                         MachineInstr::copyFlagsFromInstruction(CI));
1274   return true;
1275 }
1276 
1277 bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID,
1278                                            MachineIRBuilder &MIRBuilder) {
1279 
1280   // If this is a simple intrinsic (that is, we just need to add a def of
1281   // a vreg, and uses for each arg operand, then translate it.
1282   if (translateSimpleIntrinsic(CI, ID, MIRBuilder))
1283     return true;
1284 
1285   switch (ID) {
1286   default:
1287     break;
1288   case Intrinsic::lifetime_start:
1289   case Intrinsic::lifetime_end: {
1290     // No stack colouring in O0, discard region information.
1291     if (MF->getTarget().getOptLevel() == CodeGenOpt::None)
1292       return true;
1293 
1294     unsigned Op = ID == Intrinsic::lifetime_start ? TargetOpcode::LIFETIME_START
1295                                                   : TargetOpcode::LIFETIME_END;
1296 
1297     // Get the underlying objects for the location passed on the lifetime
1298     // marker.
1299     SmallVector<const Value *, 4> Allocas;
1300     GetUnderlyingObjects(CI.getArgOperand(1), Allocas, *DL);
1301 
1302     // Iterate over each underlying object, creating lifetime markers for each
1303     // static alloca. Quit if we find a non-static alloca.
1304     for (const Value *V : Allocas) {
1305       const AllocaInst *AI = dyn_cast<AllocaInst>(V);
1306       if (!AI)
1307         continue;
1308 
1309       if (!AI->isStaticAlloca())
1310         return true;
1311 
1312       MIRBuilder.buildInstr(Op).addFrameIndex(getOrCreateFrameIndex(*AI));
1313     }
1314     return true;
1315   }
1316   case Intrinsic::dbg_declare: {
1317     const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI);
1318     assert(DI.getVariable() && "Missing variable");
1319 
1320     const Value *Address = DI.getAddress();
1321     if (!Address || isa<UndefValue>(Address)) {
1322       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
1323       return true;
1324     }
1325 
1326     assert(DI.getVariable()->isValidLocationForIntrinsic(
1327                MIRBuilder.getDebugLoc()) &&
1328            "Expected inlined-at fields to agree");
1329     auto AI = dyn_cast<AllocaInst>(Address);
1330     if (AI && AI->isStaticAlloca()) {
1331       // Static allocas are tracked at the MF level, no need for DBG_VALUE
1332       // instructions (in fact, they get ignored if they *do* exist).
1333       MF->setVariableDbgInfo(DI.getVariable(), DI.getExpression(),
1334                              getOrCreateFrameIndex(*AI), DI.getDebugLoc());
1335     } else {
1336       // A dbg.declare describes the address of a source variable, so lower it
1337       // into an indirect DBG_VALUE.
1338       MIRBuilder.buildIndirectDbgValue(getOrCreateVReg(*Address),
1339                                        DI.getVariable(), DI.getExpression());
1340     }
1341     return true;
1342   }
1343   case Intrinsic::dbg_label: {
1344     const DbgLabelInst &DI = cast<DbgLabelInst>(CI);
1345     assert(DI.getLabel() && "Missing label");
1346 
1347     assert(DI.getLabel()->isValidLocationForIntrinsic(
1348                MIRBuilder.getDebugLoc()) &&
1349            "Expected inlined-at fields to agree");
1350 
1351     MIRBuilder.buildDbgLabel(DI.getLabel());
1352     return true;
1353   }
1354   case Intrinsic::vaend:
1355     // No target I know of cares about va_end. Certainly no in-tree target
1356     // does. Simplest intrinsic ever!
1357     return true;
1358   case Intrinsic::vastart: {
1359     auto &TLI = *MF->getSubtarget().getTargetLowering();
1360     Value *Ptr = CI.getArgOperand(0);
1361     unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8;
1362 
1363     // FIXME: Get alignment
1364     MIRBuilder.buildInstr(TargetOpcode::G_VASTART)
1365         .addUse(getOrCreateVReg(*Ptr))
1366         .addMemOperand(MF->getMachineMemOperand(
1367             MachinePointerInfo(Ptr), MachineMemOperand::MOStore, ListSize, 1));
1368     return true;
1369   }
1370   case Intrinsic::dbg_value: {
1371     // This form of DBG_VALUE is target-independent.
1372     const DbgValueInst &DI = cast<DbgValueInst>(CI);
1373     const Value *V = DI.getValue();
1374     assert(DI.getVariable()->isValidLocationForIntrinsic(
1375                MIRBuilder.getDebugLoc()) &&
1376            "Expected inlined-at fields to agree");
1377     if (!V) {
1378       // Currently the optimizer can produce this; insert an undef to
1379       // help debugging.  Probably the optimizer should not do this.
1380       MIRBuilder.buildIndirectDbgValue(0, DI.getVariable(), DI.getExpression());
1381     } else if (const auto *CI = dyn_cast<Constant>(V)) {
1382       MIRBuilder.buildConstDbgValue(*CI, DI.getVariable(), DI.getExpression());
1383     } else {
1384       for (Register Reg : getOrCreateVRegs(*V)) {
1385         // FIXME: This does not handle register-indirect values at offset 0. The
1386         // direct/indirect thing shouldn't really be handled by something as
1387         // implicit as reg+noreg vs reg+imm in the first place, but it seems
1388         // pretty baked in right now.
1389         MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(), DI.getExpression());
1390       }
1391     }
1392     return true;
1393   }
1394   case Intrinsic::uadd_with_overflow:
1395     return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDO, MIRBuilder);
1396   case Intrinsic::sadd_with_overflow:
1397     return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder);
1398   case Intrinsic::usub_with_overflow:
1399     return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBO, MIRBuilder);
1400   case Intrinsic::ssub_with_overflow:
1401     return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder);
1402   case Intrinsic::umul_with_overflow:
1403     return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder);
1404   case Intrinsic::smul_with_overflow:
1405     return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder);
1406   case Intrinsic::fmuladd: {
1407     const TargetMachine &TM = MF->getTarget();
1408     const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
1409     Register Dst = getOrCreateVReg(CI);
1410     Register Op0 = getOrCreateVReg(*CI.getArgOperand(0));
1411     Register Op1 = getOrCreateVReg(*CI.getArgOperand(1));
1412     Register Op2 = getOrCreateVReg(*CI.getArgOperand(2));
1413     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
1414         TLI.isFMAFasterThanFMulAndFAdd(TLI.getValueType(*DL, CI.getType()))) {
1415       // TODO: Revisit this to see if we should move this part of the
1416       // lowering to the combiner.
1417       MIRBuilder.buildInstr(TargetOpcode::G_FMA, {Dst}, {Op0, Op1, Op2},
1418                             MachineInstr::copyFlagsFromInstruction(CI));
1419     } else {
1420       LLT Ty = getLLTForType(*CI.getType(), *DL);
1421       auto FMul = MIRBuilder.buildInstr(TargetOpcode::G_FMUL, {Ty}, {Op0, Op1},
1422                                         MachineInstr::copyFlagsFromInstruction(CI));
1423       MIRBuilder.buildInstr(TargetOpcode::G_FADD, {Dst}, {FMul, Op2},
1424                             MachineInstr::copyFlagsFromInstruction(CI));
1425     }
1426     return true;
1427   }
1428   case Intrinsic::memcpy:
1429   case Intrinsic::memmove:
1430   case Intrinsic::memset:
1431     return translateMemFunc(CI, MIRBuilder, ID);
1432   case Intrinsic::eh_typeid_for: {
1433     GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0));
1434     Register Reg = getOrCreateVReg(CI);
1435     unsigned TypeID = MF->getTypeIDFor(GV);
1436     MIRBuilder.buildConstant(Reg, TypeID);
1437     return true;
1438   }
1439   case Intrinsic::objectsize: {
1440     // If we don't know by now, we're never going to know.
1441     const ConstantInt *Min = cast<ConstantInt>(CI.getArgOperand(1));
1442 
1443     MIRBuilder.buildConstant(getOrCreateVReg(CI), Min->isZero() ? -1ULL : 0);
1444     return true;
1445   }
1446   case Intrinsic::is_constant:
1447     // If this wasn't constant-folded away by now, then it's not a
1448     // constant.
1449     MIRBuilder.buildConstant(getOrCreateVReg(CI), 0);
1450     return true;
1451   case Intrinsic::stackguard:
1452     getStackGuard(getOrCreateVReg(CI), MIRBuilder);
1453     return true;
1454   case Intrinsic::stackprotector: {
1455     LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
1456     Register GuardVal = MRI->createGenericVirtualRegister(PtrTy);
1457     getStackGuard(GuardVal, MIRBuilder);
1458 
1459     AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1));
1460     int FI = getOrCreateFrameIndex(*Slot);
1461     MF->getFrameInfo().setStackProtectorIndex(FI);
1462 
1463     MIRBuilder.buildStore(
1464         GuardVal, getOrCreateVReg(*Slot),
1465         *MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
1466                                   MachineMemOperand::MOStore |
1467                                       MachineMemOperand::MOVolatile,
1468                                   PtrTy.getSizeInBits() / 8, 8));
1469     return true;
1470   }
1471   case Intrinsic::stacksave: {
1472     // Save the stack pointer to the location provided by the intrinsic.
1473     Register Reg = getOrCreateVReg(CI);
1474     Register StackPtr = MF->getSubtarget()
1475                             .getTargetLowering()
1476                             ->getStackPointerRegisterToSaveRestore();
1477 
1478     // If the target doesn't specify a stack pointer, then fall back.
1479     if (!StackPtr)
1480       return false;
1481 
1482     MIRBuilder.buildCopy(Reg, StackPtr);
1483     return true;
1484   }
1485   case Intrinsic::stackrestore: {
1486     // Restore the stack pointer from the location provided by the intrinsic.
1487     Register Reg = getOrCreateVReg(*CI.getArgOperand(0));
1488     Register StackPtr = MF->getSubtarget()
1489                             .getTargetLowering()
1490                             ->getStackPointerRegisterToSaveRestore();
1491 
1492     // If the target doesn't specify a stack pointer, then fall back.
1493     if (!StackPtr)
1494       return false;
1495 
1496     MIRBuilder.buildCopy(StackPtr, Reg);
1497     return true;
1498   }
1499   case Intrinsic::cttz:
1500   case Intrinsic::ctlz: {
1501     ConstantInt *Cst = cast<ConstantInt>(CI.getArgOperand(1));
1502     bool isTrailing = ID == Intrinsic::cttz;
1503     unsigned Opcode = isTrailing
1504                           ? Cst->isZero() ? TargetOpcode::G_CTTZ
1505                                           : TargetOpcode::G_CTTZ_ZERO_UNDEF
1506                           : Cst->isZero() ? TargetOpcode::G_CTLZ
1507                                           : TargetOpcode::G_CTLZ_ZERO_UNDEF;
1508     MIRBuilder.buildInstr(Opcode)
1509         .addDef(getOrCreateVReg(CI))
1510         .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
1511     return true;
1512   }
1513   case Intrinsic::invariant_start: {
1514     LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
1515     Register Undef = MRI->createGenericVirtualRegister(PtrTy);
1516     MIRBuilder.buildUndef(Undef);
1517     return true;
1518   }
1519   case Intrinsic::invariant_end:
1520     return true;
1521   case Intrinsic::assume:
1522   case Intrinsic::var_annotation:
1523   case Intrinsic::sideeffect:
1524     // Discard annotate attributes, assumptions, and artificial side-effects.
1525     return true;
1526   }
1527   return false;
1528 }
1529 
1530 bool IRTranslator::translateInlineAsm(const CallInst &CI,
1531                                       MachineIRBuilder &MIRBuilder) {
1532   const InlineAsm &IA = cast<InlineAsm>(*CI.getCalledValue());
1533   if (!IA.getConstraintString().empty())
1534     return false;
1535 
1536   unsigned ExtraInfo = 0;
1537   if (IA.hasSideEffects())
1538     ExtraInfo |= InlineAsm::Extra_HasSideEffects;
1539   if (IA.getDialect() == InlineAsm::AD_Intel)
1540     ExtraInfo |= InlineAsm::Extra_AsmDialect;
1541 
1542   MIRBuilder.buildInstr(TargetOpcode::INLINEASM)
1543     .addExternalSymbol(IA.getAsmString().c_str())
1544     .addImm(ExtraInfo);
1545 
1546   return true;
1547 }
1548 
1549 bool IRTranslator::translateCallSite(const ImmutableCallSite &CS,
1550                                      MachineIRBuilder &MIRBuilder) {
1551   const Instruction &I = *CS.getInstruction();
1552   ArrayRef<Register> Res = getOrCreateVRegs(I);
1553 
1554   SmallVector<ArrayRef<Register>, 8> Args;
1555   Register SwiftInVReg = 0;
1556   Register SwiftErrorVReg = 0;
1557   for (auto &Arg : CS.args()) {
1558     if (CLI->supportSwiftError() && isSwiftError(Arg)) {
1559       assert(SwiftInVReg == 0 && "Expected only one swift error argument");
1560       LLT Ty = getLLTForType(*Arg->getType(), *DL);
1561       SwiftInVReg = MRI->createGenericVirtualRegister(Ty);
1562       MIRBuilder.buildCopy(SwiftInVReg, SwiftError.getOrCreateVRegUseAt(
1563                                             &I, &MIRBuilder.getMBB(), Arg));
1564       Args.emplace_back(makeArrayRef(SwiftInVReg));
1565       SwiftErrorVReg =
1566           SwiftError.getOrCreateVRegDefAt(&I, &MIRBuilder.getMBB(), Arg);
1567       continue;
1568     }
1569     Args.push_back(getOrCreateVRegs(*Arg));
1570   }
1571 
1572   // We don't set HasCalls on MFI here yet because call lowering may decide to
1573   // optimize into tail calls. Instead, we defer that to selection where a final
1574   // scan is done to check if any instructions are calls.
1575   bool Success =
1576       CLI->lowerCall(MIRBuilder, CS, Res, Args, SwiftErrorVReg,
1577                      [&]() { return getOrCreateVReg(*CS.getCalledValue()); });
1578 
1579   // Check if we just inserted a tail call.
1580   if (Success) {
1581     assert(!HasTailCall && "Can't tail call return twice from block?");
1582     const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1583     HasTailCall = TII->isTailCall(*std::prev(MIRBuilder.getInsertPt()));
1584   }
1585 
1586   return Success;
1587 }
1588 
1589 bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) {
1590   const CallInst &CI = cast<CallInst>(U);
1591   auto TII = MF->getTarget().getIntrinsicInfo();
1592   const Function *F = CI.getCalledFunction();
1593 
1594   // FIXME: support Windows dllimport function calls.
1595   if (F && F->hasDLLImportStorageClass())
1596     return false;
1597 
1598   if (CI.isInlineAsm())
1599     return translateInlineAsm(CI, MIRBuilder);
1600 
1601   Intrinsic::ID ID = Intrinsic::not_intrinsic;
1602   if (F && F->isIntrinsic()) {
1603     ID = F->getIntrinsicID();
1604     if (TII && ID == Intrinsic::not_intrinsic)
1605       ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F));
1606   }
1607 
1608   if (!F || !F->isIntrinsic() || ID == Intrinsic::not_intrinsic)
1609     return translateCallSite(&CI, MIRBuilder);
1610 
1611   assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
1612 
1613   if (translateKnownIntrinsic(CI, ID, MIRBuilder))
1614     return true;
1615 
1616   ArrayRef<Register> ResultRegs;
1617   if (!CI.getType()->isVoidTy())
1618     ResultRegs = getOrCreateVRegs(CI);
1619 
1620   // Ignore the callsite attributes. Backend code is most likely not expecting
1621   // an intrinsic to sometimes have side effects and sometimes not.
1622   MachineInstrBuilder MIB =
1623       MIRBuilder.buildIntrinsic(ID, ResultRegs, !F->doesNotAccessMemory());
1624   if (isa<FPMathOperator>(CI))
1625     MIB->copyIRFlags(CI);
1626 
1627   for (auto &Arg : enumerate(CI.arg_operands())) {
1628     // Some intrinsics take metadata parameters. Reject them.
1629     if (isa<MetadataAsValue>(Arg.value()))
1630       return false;
1631 
1632     // If this is required to be an immediate, don't materialize it in a
1633     // register.
1634     if (CI.paramHasAttr(Arg.index(), Attribute::ImmArg)) {
1635       if (ConstantInt *CI = dyn_cast<ConstantInt>(Arg.value())) {
1636         // imm arguments are more convenient than cimm (and realistically
1637         // probably sufficient), so use them.
1638         assert(CI->getBitWidth() <= 64 &&
1639                "large intrinsic immediates not handled");
1640         MIB.addImm(CI->getSExtValue());
1641       } else {
1642         MIB.addFPImm(cast<ConstantFP>(Arg.value()));
1643       }
1644     } else {
1645       ArrayRef<Register> VRegs = getOrCreateVRegs(*Arg.value());
1646       if (VRegs.size() > 1)
1647         return false;
1648       MIB.addUse(VRegs[0]);
1649     }
1650   }
1651 
1652   // Add a MachineMemOperand if it is a target mem intrinsic.
1653   const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
1654   TargetLowering::IntrinsicInfo Info;
1655   // TODO: Add a GlobalISel version of getTgtMemIntrinsic.
1656   if (TLI.getTgtMemIntrinsic(Info, CI, *MF, ID)) {
1657     MaybeAlign Align = Info.align;
1658     if (!Align)
1659       Align = MaybeAlign(
1660           DL->getABITypeAlignment(Info.memVT.getTypeForEVT(F->getContext())));
1661 
1662     uint64_t Size = Info.memVT.getStoreSize();
1663     MIB.addMemOperand(MF->getMachineMemOperand(
1664         MachinePointerInfo(Info.ptrVal), Info.flags, Size, Align->value()));
1665   }
1666 
1667   return true;
1668 }
1669 
1670 bool IRTranslator::translateInvoke(const User &U,
1671                                    MachineIRBuilder &MIRBuilder) {
1672   const InvokeInst &I = cast<InvokeInst>(U);
1673   MCContext &Context = MF->getContext();
1674 
1675   const BasicBlock *ReturnBB = I.getSuccessor(0);
1676   const BasicBlock *EHPadBB = I.getSuccessor(1);
1677 
1678   const Value *Callee = I.getCalledValue();
1679   const Function *Fn = dyn_cast<Function>(Callee);
1680   if (isa<InlineAsm>(Callee))
1681     return false;
1682 
1683   // FIXME: support invoking patchpoint and statepoint intrinsics.
1684   if (Fn && Fn->isIntrinsic())
1685     return false;
1686 
1687   // FIXME: support whatever these are.
1688   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
1689     return false;
1690 
1691   // FIXME: support Windows exception handling.
1692   if (!isa<LandingPadInst>(EHPadBB->front()))
1693     return false;
1694 
1695   // Emit the actual call, bracketed by EH_LABELs so that the MF knows about
1696   // the region covered by the try.
1697   MCSymbol *BeginSymbol = Context.createTempSymbol();
1698   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol);
1699 
1700   if (!translateCallSite(&I, MIRBuilder))
1701     return false;
1702 
1703   MCSymbol *EndSymbol = Context.createTempSymbol();
1704   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol);
1705 
1706   // FIXME: track probabilities.
1707   MachineBasicBlock &EHPadMBB = getMBB(*EHPadBB),
1708                     &ReturnMBB = getMBB(*ReturnBB);
1709   MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
1710   MIRBuilder.getMBB().addSuccessor(&ReturnMBB);
1711   MIRBuilder.getMBB().addSuccessor(&EHPadMBB);
1712   MIRBuilder.buildBr(ReturnMBB);
1713 
1714   return true;
1715 }
1716 
1717 bool IRTranslator::translateCallBr(const User &U,
1718                                    MachineIRBuilder &MIRBuilder) {
1719   // FIXME: Implement this.
1720   return false;
1721 }
1722 
1723 bool IRTranslator::translateLandingPad(const User &U,
1724                                        MachineIRBuilder &MIRBuilder) {
1725   const LandingPadInst &LP = cast<LandingPadInst>(U);
1726 
1727   MachineBasicBlock &MBB = MIRBuilder.getMBB();
1728 
1729   MBB.setIsEHPad();
1730 
1731   // If there aren't registers to copy the values into (e.g., during SjLj
1732   // exceptions), then don't bother.
1733   auto &TLI = *MF->getSubtarget().getTargetLowering();
1734   const Constant *PersonalityFn = MF->getFunction().getPersonalityFn();
1735   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
1736       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
1737     return true;
1738 
1739   // If landingpad's return type is token type, we don't create DAG nodes
1740   // for its exception pointer and selector value. The extraction of exception
1741   // pointer or selector value from token type landingpads is not currently
1742   // supported.
1743   if (LP.getType()->isTokenTy())
1744     return true;
1745 
1746   // Add a label to mark the beginning of the landing pad.  Deletion of the
1747   // landing pad can thus be detected via the MachineModuleInfo.
1748   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL)
1749     .addSym(MF->addLandingPad(&MBB));
1750 
1751   LLT Ty = getLLTForType(*LP.getType(), *DL);
1752   Register Undef = MRI->createGenericVirtualRegister(Ty);
1753   MIRBuilder.buildUndef(Undef);
1754 
1755   SmallVector<LLT, 2> Tys;
1756   for (Type *Ty : cast<StructType>(LP.getType())->elements())
1757     Tys.push_back(getLLTForType(*Ty, *DL));
1758   assert(Tys.size() == 2 && "Only two-valued landingpads are supported");
1759 
1760   // Mark exception register as live in.
1761   Register ExceptionReg = TLI.getExceptionPointerRegister(PersonalityFn);
1762   if (!ExceptionReg)
1763     return false;
1764 
1765   MBB.addLiveIn(ExceptionReg);
1766   ArrayRef<Register> ResRegs = getOrCreateVRegs(LP);
1767   MIRBuilder.buildCopy(ResRegs[0], ExceptionReg);
1768 
1769   Register SelectorReg = TLI.getExceptionSelectorRegister(PersonalityFn);
1770   if (!SelectorReg)
1771     return false;
1772 
1773   MBB.addLiveIn(SelectorReg);
1774   Register PtrVReg = MRI->createGenericVirtualRegister(Tys[0]);
1775   MIRBuilder.buildCopy(PtrVReg, SelectorReg);
1776   MIRBuilder.buildCast(ResRegs[1], PtrVReg);
1777 
1778   return true;
1779 }
1780 
1781 bool IRTranslator::translateAlloca(const User &U,
1782                                    MachineIRBuilder &MIRBuilder) {
1783   auto &AI = cast<AllocaInst>(U);
1784 
1785   if (AI.isSwiftError())
1786     return true;
1787 
1788   if (AI.isStaticAlloca()) {
1789     Register Res = getOrCreateVReg(AI);
1790     int FI = getOrCreateFrameIndex(AI);
1791     MIRBuilder.buildFrameIndex(Res, FI);
1792     return true;
1793   }
1794 
1795   // FIXME: support stack probing for Windows.
1796   if (MF->getTarget().getTargetTriple().isOSWindows())
1797     return false;
1798 
1799   // Now we're in the harder dynamic case.
1800   Type *Ty = AI.getAllocatedType();
1801   unsigned Align =
1802       std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI.getAlignment());
1803 
1804   Register NumElts = getOrCreateVReg(*AI.getArraySize());
1805 
1806   Type *IntPtrIRTy = DL->getIntPtrType(AI.getType());
1807   LLT IntPtrTy = getLLTForType(*IntPtrIRTy, *DL);
1808   if (MRI->getType(NumElts) != IntPtrTy) {
1809     Register ExtElts = MRI->createGenericVirtualRegister(IntPtrTy);
1810     MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts);
1811     NumElts = ExtElts;
1812   }
1813 
1814   Register AllocSize = MRI->createGenericVirtualRegister(IntPtrTy);
1815   Register TySize =
1816       getOrCreateVReg(*ConstantInt::get(IntPtrIRTy, DL->getTypeAllocSize(Ty)));
1817   MIRBuilder.buildMul(AllocSize, NumElts, TySize);
1818 
1819   unsigned StackAlign =
1820       MF->getSubtarget().getFrameLowering()->getStackAlignment();
1821   if (Align <= StackAlign)
1822     Align = 0;
1823 
1824   // Round the size of the allocation up to the stack alignment size
1825   // by add SA-1 to the size. This doesn't overflow because we're computing
1826   // an address inside an alloca.
1827   auto SAMinusOne = MIRBuilder.buildConstant(IntPtrTy, StackAlign - 1);
1828   auto AllocAdd = MIRBuilder.buildAdd(IntPtrTy, AllocSize, SAMinusOne,
1829                                       MachineInstr::NoUWrap);
1830   auto AlignCst =
1831       MIRBuilder.buildConstant(IntPtrTy, ~(uint64_t)(StackAlign - 1));
1832   auto AlignedAlloc = MIRBuilder.buildAnd(IntPtrTy, AllocAdd, AlignCst);
1833 
1834   MIRBuilder.buildDynStackAlloc(getOrCreateVReg(AI), AlignedAlloc, Align);
1835 
1836   MF->getFrameInfo().CreateVariableSizedObject(Align ? Align : 1, &AI);
1837   assert(MF->getFrameInfo().hasVarSizedObjects());
1838   return true;
1839 }
1840 
1841 bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) {
1842   // FIXME: We may need more info about the type. Because of how LLT works,
1843   // we're completely discarding the i64/double distinction here (amongst
1844   // others). Fortunately the ABIs I know of where that matters don't use va_arg
1845   // anyway but that's not guaranteed.
1846   MIRBuilder.buildInstr(TargetOpcode::G_VAARG)
1847     .addDef(getOrCreateVReg(U))
1848     .addUse(getOrCreateVReg(*U.getOperand(0)))
1849     .addImm(DL->getABITypeAlignment(U.getType()));
1850   return true;
1851 }
1852 
1853 bool IRTranslator::translateInsertElement(const User &U,
1854                                           MachineIRBuilder &MIRBuilder) {
1855   // If it is a <1 x Ty> vector, use the scalar as it is
1856   // not a legal vector type in LLT.
1857   if (U.getType()->getVectorNumElements() == 1) {
1858     Register Elt = getOrCreateVReg(*U.getOperand(1));
1859     auto &Regs = *VMap.getVRegs(U);
1860     if (Regs.empty()) {
1861       Regs.push_back(Elt);
1862       VMap.getOffsets(U)->push_back(0);
1863     } else {
1864       MIRBuilder.buildCopy(Regs[0], Elt);
1865     }
1866     return true;
1867   }
1868 
1869   Register Res = getOrCreateVReg(U);
1870   Register Val = getOrCreateVReg(*U.getOperand(0));
1871   Register Elt = getOrCreateVReg(*U.getOperand(1));
1872   Register Idx = getOrCreateVReg(*U.getOperand(2));
1873   MIRBuilder.buildInsertVectorElement(Res, Val, Elt, Idx);
1874   return true;
1875 }
1876 
1877 bool IRTranslator::translateExtractElement(const User &U,
1878                                            MachineIRBuilder &MIRBuilder) {
1879   // If it is a <1 x Ty> vector, use the scalar as it is
1880   // not a legal vector type in LLT.
1881   if (U.getOperand(0)->getType()->getVectorNumElements() == 1) {
1882     Register Elt = getOrCreateVReg(*U.getOperand(0));
1883     auto &Regs = *VMap.getVRegs(U);
1884     if (Regs.empty()) {
1885       Regs.push_back(Elt);
1886       VMap.getOffsets(U)->push_back(0);
1887     } else {
1888       MIRBuilder.buildCopy(Regs[0], Elt);
1889     }
1890     return true;
1891   }
1892   Register Res = getOrCreateVReg(U);
1893   Register Val = getOrCreateVReg(*U.getOperand(0));
1894   const auto &TLI = *MF->getSubtarget().getTargetLowering();
1895   unsigned PreferredVecIdxWidth = TLI.getVectorIdxTy(*DL).getSizeInBits();
1896   Register Idx;
1897   if (auto *CI = dyn_cast<ConstantInt>(U.getOperand(1))) {
1898     if (CI->getBitWidth() != PreferredVecIdxWidth) {
1899       APInt NewIdx = CI->getValue().sextOrTrunc(PreferredVecIdxWidth);
1900       auto *NewIdxCI = ConstantInt::get(CI->getContext(), NewIdx);
1901       Idx = getOrCreateVReg(*NewIdxCI);
1902     }
1903   }
1904   if (!Idx)
1905     Idx = getOrCreateVReg(*U.getOperand(1));
1906   if (MRI->getType(Idx).getSizeInBits() != PreferredVecIdxWidth) {
1907     const LLT &VecIdxTy = LLT::scalar(PreferredVecIdxWidth);
1908     Idx = MIRBuilder.buildSExtOrTrunc(VecIdxTy, Idx)->getOperand(0).getReg();
1909   }
1910   MIRBuilder.buildExtractVectorElement(Res, Val, Idx);
1911   return true;
1912 }
1913 
1914 bool IRTranslator::translateShuffleVector(const User &U,
1915                                           MachineIRBuilder &MIRBuilder) {
1916   MIRBuilder.buildInstr(TargetOpcode::G_SHUFFLE_VECTOR)
1917       .addDef(getOrCreateVReg(U))
1918       .addUse(getOrCreateVReg(*U.getOperand(0)))
1919       .addUse(getOrCreateVReg(*U.getOperand(1)))
1920       .addShuffleMask(cast<Constant>(U.getOperand(2)));
1921   return true;
1922 }
1923 
1924 bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) {
1925   const PHINode &PI = cast<PHINode>(U);
1926 
1927   SmallVector<MachineInstr *, 4> Insts;
1928   for (auto Reg : getOrCreateVRegs(PI)) {
1929     auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_PHI, {Reg}, {});
1930     Insts.push_back(MIB.getInstr());
1931   }
1932 
1933   PendingPHIs.emplace_back(&PI, std::move(Insts));
1934   return true;
1935 }
1936 
1937 bool IRTranslator::translateAtomicCmpXchg(const User &U,
1938                                           MachineIRBuilder &MIRBuilder) {
1939   const AtomicCmpXchgInst &I = cast<AtomicCmpXchgInst>(U);
1940 
1941   if (I.isWeak())
1942     return false;
1943 
1944   auto Flags = I.isVolatile() ? MachineMemOperand::MOVolatile
1945                               : MachineMemOperand::MONone;
1946   Flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1947 
1948   Type *ResType = I.getType();
1949   Type *ValType = ResType->Type::getStructElementType(0);
1950 
1951   auto Res = getOrCreateVRegs(I);
1952   Register OldValRes = Res[0];
1953   Register SuccessRes = Res[1];
1954   Register Addr = getOrCreateVReg(*I.getPointerOperand());
1955   Register Cmp = getOrCreateVReg(*I.getCompareOperand());
1956   Register NewVal = getOrCreateVReg(*I.getNewValOperand());
1957 
1958   MIRBuilder.buildAtomicCmpXchgWithSuccess(
1959       OldValRes, SuccessRes, Addr, Cmp, NewVal,
1960       *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
1961                                 Flags, DL->getTypeStoreSize(ValType),
1962                                 getMemOpAlignment(I), AAMDNodes(), nullptr,
1963                                 I.getSyncScopeID(), I.getSuccessOrdering(),
1964                                 I.getFailureOrdering()));
1965   return true;
1966 }
1967 
1968 bool IRTranslator::translateAtomicRMW(const User &U,
1969                                       MachineIRBuilder &MIRBuilder) {
1970   const AtomicRMWInst &I = cast<AtomicRMWInst>(U);
1971 
1972   auto Flags = I.isVolatile() ? MachineMemOperand::MOVolatile
1973                               : MachineMemOperand::MONone;
1974   Flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1975 
1976   Type *ResType = I.getType();
1977 
1978   Register Res = getOrCreateVReg(I);
1979   Register Addr = getOrCreateVReg(*I.getPointerOperand());
1980   Register Val = getOrCreateVReg(*I.getValOperand());
1981 
1982   unsigned Opcode = 0;
1983   switch (I.getOperation()) {
1984   default:
1985     return false;
1986   case AtomicRMWInst::Xchg:
1987     Opcode = TargetOpcode::G_ATOMICRMW_XCHG;
1988     break;
1989   case AtomicRMWInst::Add:
1990     Opcode = TargetOpcode::G_ATOMICRMW_ADD;
1991     break;
1992   case AtomicRMWInst::Sub:
1993     Opcode = TargetOpcode::G_ATOMICRMW_SUB;
1994     break;
1995   case AtomicRMWInst::And:
1996     Opcode = TargetOpcode::G_ATOMICRMW_AND;
1997     break;
1998   case AtomicRMWInst::Nand:
1999     Opcode = TargetOpcode::G_ATOMICRMW_NAND;
2000     break;
2001   case AtomicRMWInst::Or:
2002     Opcode = TargetOpcode::G_ATOMICRMW_OR;
2003     break;
2004   case AtomicRMWInst::Xor:
2005     Opcode = TargetOpcode::G_ATOMICRMW_XOR;
2006     break;
2007   case AtomicRMWInst::Max:
2008     Opcode = TargetOpcode::G_ATOMICRMW_MAX;
2009     break;
2010   case AtomicRMWInst::Min:
2011     Opcode = TargetOpcode::G_ATOMICRMW_MIN;
2012     break;
2013   case AtomicRMWInst::UMax:
2014     Opcode = TargetOpcode::G_ATOMICRMW_UMAX;
2015     break;
2016   case AtomicRMWInst::UMin:
2017     Opcode = TargetOpcode::G_ATOMICRMW_UMIN;
2018     break;
2019   case AtomicRMWInst::FAdd:
2020     Opcode = TargetOpcode::G_ATOMICRMW_FADD;
2021     break;
2022   case AtomicRMWInst::FSub:
2023     Opcode = TargetOpcode::G_ATOMICRMW_FSUB;
2024     break;
2025   }
2026 
2027   MIRBuilder.buildAtomicRMW(
2028       Opcode, Res, Addr, Val,
2029       *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
2030                                 Flags, DL->getTypeStoreSize(ResType),
2031                                 getMemOpAlignment(I), AAMDNodes(), nullptr,
2032                                 I.getSyncScopeID(), I.getOrdering()));
2033   return true;
2034 }
2035 
2036 bool IRTranslator::translateFence(const User &U,
2037                                   MachineIRBuilder &MIRBuilder) {
2038   const FenceInst &Fence = cast<FenceInst>(U);
2039   MIRBuilder.buildFence(static_cast<unsigned>(Fence.getOrdering()),
2040                         Fence.getSyncScopeID());
2041   return true;
2042 }
2043 
2044 void IRTranslator::finishPendingPhis() {
2045 #ifndef NDEBUG
2046   DILocationVerifier Verifier;
2047   GISelObserverWrapper WrapperObserver(&Verifier);
2048   RAIIDelegateInstaller DelInstall(*MF, &WrapperObserver);
2049 #endif // ifndef NDEBUG
2050   for (auto &Phi : PendingPHIs) {
2051     const PHINode *PI = Phi.first;
2052     ArrayRef<MachineInstr *> ComponentPHIs = Phi.second;
2053     MachineBasicBlock *PhiMBB = ComponentPHIs[0]->getParent();
2054     EntryBuilder->setDebugLoc(PI->getDebugLoc());
2055 #ifndef NDEBUG
2056     Verifier.setCurrentInst(PI);
2057 #endif // ifndef NDEBUG
2058 
2059     SmallSet<const MachineBasicBlock *, 16> SeenPreds;
2060     for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
2061       auto IRPred = PI->getIncomingBlock(i);
2062       ArrayRef<Register> ValRegs = getOrCreateVRegs(*PI->getIncomingValue(i));
2063       for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) {
2064         if (SeenPreds.count(Pred) || !PhiMBB->isPredecessor(Pred))
2065           continue;
2066         SeenPreds.insert(Pred);
2067         for (unsigned j = 0; j < ValRegs.size(); ++j) {
2068           MachineInstrBuilder MIB(*MF, ComponentPHIs[j]);
2069           MIB.addUse(ValRegs[j]);
2070           MIB.addMBB(Pred);
2071         }
2072       }
2073     }
2074   }
2075 }
2076 
2077 bool IRTranslator::valueIsSplit(const Value &V,
2078                                 SmallVectorImpl<uint64_t> *Offsets) {
2079   SmallVector<LLT, 4> SplitTys;
2080   if (Offsets && !Offsets->empty())
2081     Offsets->clear();
2082   computeValueLLTs(*DL, *V.getType(), SplitTys, Offsets);
2083   return SplitTys.size() > 1;
2084 }
2085 
2086 bool IRTranslator::translate(const Instruction &Inst) {
2087   CurBuilder->setDebugLoc(Inst.getDebugLoc());
2088   // We only emit constants into the entry block from here. To prevent jumpy
2089   // debug behaviour set the line to 0.
2090   if (const DebugLoc &DL = Inst.getDebugLoc())
2091     EntryBuilder->setDebugLoc(
2092         DebugLoc::get(0, 0, DL.getScope(), DL.getInlinedAt()));
2093   else
2094     EntryBuilder->setDebugLoc(DebugLoc());
2095 
2096   switch (Inst.getOpcode()) {
2097 #define HANDLE_INST(NUM, OPCODE, CLASS)                                        \
2098   case Instruction::OPCODE:                                                    \
2099     return translate##OPCODE(Inst, *CurBuilder.get());
2100 #include "llvm/IR/Instruction.def"
2101   default:
2102     return false;
2103   }
2104 }
2105 
2106 bool IRTranslator::translate(const Constant &C, Register Reg) {
2107   if (auto CI = dyn_cast<ConstantInt>(&C))
2108     EntryBuilder->buildConstant(Reg, *CI);
2109   else if (auto CF = dyn_cast<ConstantFP>(&C))
2110     EntryBuilder->buildFConstant(Reg, *CF);
2111   else if (isa<UndefValue>(C))
2112     EntryBuilder->buildUndef(Reg);
2113   else if (isa<ConstantPointerNull>(C)) {
2114     // As we are trying to build a constant val of 0 into a pointer,
2115     // insert a cast to make them correct with respect to types.
2116     unsigned NullSize = DL->getTypeSizeInBits(C.getType());
2117     auto *ZeroTy = Type::getIntNTy(C.getContext(), NullSize);
2118     auto *ZeroVal = ConstantInt::get(ZeroTy, 0);
2119     Register ZeroReg = getOrCreateVReg(*ZeroVal);
2120     EntryBuilder->buildCast(Reg, ZeroReg);
2121   } else if (auto GV = dyn_cast<GlobalValue>(&C))
2122     EntryBuilder->buildGlobalValue(Reg, GV);
2123   else if (auto CAZ = dyn_cast<ConstantAggregateZero>(&C)) {
2124     if (!CAZ->getType()->isVectorTy())
2125       return false;
2126     // Return the scalar if it is a <1 x Ty> vector.
2127     if (CAZ->getNumElements() == 1)
2128       return translate(*CAZ->getElementValue(0u), Reg);
2129     SmallVector<Register, 4> Ops;
2130     for (unsigned i = 0; i < CAZ->getNumElements(); ++i) {
2131       Constant &Elt = *CAZ->getElementValue(i);
2132       Ops.push_back(getOrCreateVReg(Elt));
2133     }
2134     EntryBuilder->buildBuildVector(Reg, Ops);
2135   } else if (auto CV = dyn_cast<ConstantDataVector>(&C)) {
2136     // Return the scalar if it is a <1 x Ty> vector.
2137     if (CV->getNumElements() == 1)
2138       return translate(*CV->getElementAsConstant(0), Reg);
2139     SmallVector<Register, 4> Ops;
2140     for (unsigned i = 0; i < CV->getNumElements(); ++i) {
2141       Constant &Elt = *CV->getElementAsConstant(i);
2142       Ops.push_back(getOrCreateVReg(Elt));
2143     }
2144     EntryBuilder->buildBuildVector(Reg, Ops);
2145   } else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
2146     switch(CE->getOpcode()) {
2147 #define HANDLE_INST(NUM, OPCODE, CLASS)                                        \
2148   case Instruction::OPCODE:                                                    \
2149     return translate##OPCODE(*CE, *EntryBuilder.get());
2150 #include "llvm/IR/Instruction.def"
2151     default:
2152       return false;
2153     }
2154   } else if (auto CV = dyn_cast<ConstantVector>(&C)) {
2155     if (CV->getNumOperands() == 1)
2156       return translate(*CV->getOperand(0), Reg);
2157     SmallVector<Register, 4> Ops;
2158     for (unsigned i = 0; i < CV->getNumOperands(); ++i) {
2159       Ops.push_back(getOrCreateVReg(*CV->getOperand(i)));
2160     }
2161     EntryBuilder->buildBuildVector(Reg, Ops);
2162   } else if (auto *BA = dyn_cast<BlockAddress>(&C)) {
2163     EntryBuilder->buildBlockAddress(Reg, BA);
2164   } else
2165     return false;
2166 
2167   return true;
2168 }
2169 
2170 void IRTranslator::finalizeBasicBlock() {
2171   for (auto &JTCase : SL->JTCases) {
2172     // Emit header first, if it wasn't already emitted.
2173     if (!JTCase.first.Emitted)
2174       emitJumpTableHeader(JTCase.second, JTCase.first, JTCase.first.HeaderBB);
2175 
2176     emitJumpTable(JTCase.second, JTCase.second.MBB);
2177   }
2178   SL->JTCases.clear();
2179 }
2180 
2181 void IRTranslator::finalizeFunction() {
2182   // Release the memory used by the different maps we
2183   // needed during the translation.
2184   PendingPHIs.clear();
2185   VMap.reset();
2186   FrameIndices.clear();
2187   MachinePreds.clear();
2188   // MachineIRBuilder::DebugLoc can outlive the DILocation it holds. Clear it
2189   // to avoid accessing free’d memory (in runOnMachineFunction) and to avoid
2190   // destroying it twice (in ~IRTranslator() and ~LLVMContext())
2191   EntryBuilder.reset();
2192   CurBuilder.reset();
2193   FuncInfo.clear();
2194 }
2195 
2196 /// Returns true if a BasicBlock \p BB within a variadic function contains a
2197 /// variadic musttail call.
2198 static bool checkForMustTailInVarArgFn(bool IsVarArg, const BasicBlock &BB) {
2199   if (!IsVarArg)
2200     return false;
2201 
2202   // Walk the block backwards, because tail calls usually only appear at the end
2203   // of a block.
2204   return std::any_of(BB.rbegin(), BB.rend(), [](const Instruction &I) {
2205     const auto *CI = dyn_cast<CallInst>(&I);
2206     return CI && CI->isMustTailCall();
2207   });
2208 }
2209 
2210 bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) {
2211   MF = &CurMF;
2212   const Function &F = MF->getFunction();
2213   if (F.empty())
2214     return false;
2215   GISelCSEAnalysisWrapper &Wrapper =
2216       getAnalysis<GISelCSEAnalysisWrapperPass>().getCSEWrapper();
2217   // Set the CSEConfig and run the analysis.
2218   GISelCSEInfo *CSEInfo = nullptr;
2219   TPC = &getAnalysis<TargetPassConfig>();
2220   bool EnableCSE = EnableCSEInIRTranslator.getNumOccurrences()
2221                        ? EnableCSEInIRTranslator
2222                        : TPC->isGISelCSEEnabled();
2223 
2224   if (EnableCSE) {
2225     EntryBuilder = std::make_unique<CSEMIRBuilder>(CurMF);
2226     CSEInfo = &Wrapper.get(TPC->getCSEConfig());
2227     EntryBuilder->setCSEInfo(CSEInfo);
2228     CurBuilder = std::make_unique<CSEMIRBuilder>(CurMF);
2229     CurBuilder->setCSEInfo(CSEInfo);
2230   } else {
2231     EntryBuilder = std::make_unique<MachineIRBuilder>();
2232     CurBuilder = std::make_unique<MachineIRBuilder>();
2233   }
2234   CLI = MF->getSubtarget().getCallLowering();
2235   CurBuilder->setMF(*MF);
2236   EntryBuilder->setMF(*MF);
2237   MRI = &MF->getRegInfo();
2238   DL = &F.getParent()->getDataLayout();
2239   ORE = std::make_unique<OptimizationRemarkEmitter>(&F);
2240   FuncInfo.MF = MF;
2241   FuncInfo.BPI = nullptr;
2242   const auto &TLI = *MF->getSubtarget().getTargetLowering();
2243   const TargetMachine &TM = MF->getTarget();
2244   SL = std::make_unique<GISelSwitchLowering>(this, FuncInfo);
2245   SL->init(TLI, TM, *DL);
2246 
2247   EnableOpts = TM.getOptLevel() != CodeGenOpt::None && !skipFunction(F);
2248 
2249   assert(PendingPHIs.empty() && "stale PHIs");
2250 
2251   if (!DL->isLittleEndian()) {
2252     // Currently we don't properly handle big endian code.
2253     OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
2254                                F.getSubprogram(), &F.getEntryBlock());
2255     R << "unable to translate in big endian mode";
2256     reportTranslationError(*MF, *TPC, *ORE, R);
2257   }
2258 
2259   // Release the per-function state when we return, whether we succeeded or not.
2260   auto FinalizeOnReturn = make_scope_exit([this]() { finalizeFunction(); });
2261 
2262   // Setup a separate basic-block for the arguments and constants
2263   MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock();
2264   MF->push_back(EntryBB);
2265   EntryBuilder->setMBB(*EntryBB);
2266 
2267   DebugLoc DbgLoc = F.getEntryBlock().getFirstNonPHI()->getDebugLoc();
2268   SwiftError.setFunction(CurMF);
2269   SwiftError.createEntriesInEntryBlock(DbgLoc);
2270 
2271   bool IsVarArg = F.isVarArg();
2272   bool HasMustTailInVarArgFn = false;
2273 
2274   // Create all blocks, in IR order, to preserve the layout.
2275   for (const BasicBlock &BB: F) {
2276     auto *&MBB = BBToMBB[&BB];
2277 
2278     MBB = MF->CreateMachineBasicBlock(&BB);
2279     MF->push_back(MBB);
2280 
2281     if (BB.hasAddressTaken())
2282       MBB->setHasAddressTaken();
2283 
2284     if (!HasMustTailInVarArgFn)
2285       HasMustTailInVarArgFn = checkForMustTailInVarArgFn(IsVarArg, BB);
2286   }
2287 
2288   MF->getFrameInfo().setHasMustTailInVarArgFunc(HasMustTailInVarArgFn);
2289 
2290   // Make our arguments/constants entry block fallthrough to the IR entry block.
2291   EntryBB->addSuccessor(&getMBB(F.front()));
2292 
2293   // Lower the actual args into this basic block.
2294   SmallVector<ArrayRef<Register>, 8> VRegArgs;
2295   for (const Argument &Arg: F.args()) {
2296     if (DL->getTypeStoreSize(Arg.getType()) == 0)
2297       continue; // Don't handle zero sized types.
2298     ArrayRef<Register> VRegs = getOrCreateVRegs(Arg);
2299     VRegArgs.push_back(VRegs);
2300 
2301     if (Arg.hasSwiftErrorAttr()) {
2302       assert(VRegs.size() == 1 && "Too many vregs for Swift error");
2303       SwiftError.setCurrentVReg(EntryBB, SwiftError.getFunctionArg(), VRegs[0]);
2304     }
2305   }
2306 
2307   if (!CLI->lowerFormalArguments(*EntryBuilder.get(), F, VRegArgs)) {
2308     OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
2309                                F.getSubprogram(), &F.getEntryBlock());
2310     R << "unable to lower arguments: " << ore::NV("Prototype", F.getType());
2311     reportTranslationError(*MF, *TPC, *ORE, R);
2312     return false;
2313   }
2314 
2315   // Need to visit defs before uses when translating instructions.
2316   GISelObserverWrapper WrapperObserver;
2317   if (EnableCSE && CSEInfo)
2318     WrapperObserver.addObserver(CSEInfo);
2319   {
2320     ReversePostOrderTraversal<const Function *> RPOT(&F);
2321 #ifndef NDEBUG
2322     DILocationVerifier Verifier;
2323     WrapperObserver.addObserver(&Verifier);
2324 #endif // ifndef NDEBUG
2325     RAIIDelegateInstaller DelInstall(*MF, &WrapperObserver);
2326     for (const BasicBlock *BB : RPOT) {
2327       MachineBasicBlock &MBB = getMBB(*BB);
2328       // Set the insertion point of all the following translations to
2329       // the end of this basic block.
2330       CurBuilder->setMBB(MBB);
2331       HasTailCall = false;
2332       for (const Instruction &Inst : *BB) {
2333         // If we translated a tail call in the last step, then we know
2334         // everything after the call is either a return, or something that is
2335         // handled by the call itself. (E.g. a lifetime marker or assume
2336         // intrinsic.) In this case, we should stop translating the block and
2337         // move on.
2338         if (HasTailCall)
2339           break;
2340 #ifndef NDEBUG
2341         Verifier.setCurrentInst(&Inst);
2342 #endif // ifndef NDEBUG
2343         if (translate(Inst))
2344           continue;
2345 
2346         OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
2347                                    Inst.getDebugLoc(), BB);
2348         R << "unable to translate instruction: " << ore::NV("Opcode", &Inst);
2349 
2350         if (ORE->allowExtraAnalysis("gisel-irtranslator")) {
2351           std::string InstStrStorage;
2352           raw_string_ostream InstStr(InstStrStorage);
2353           InstStr << Inst;
2354 
2355           R << ": '" << InstStr.str() << "'";
2356         }
2357 
2358         reportTranslationError(*MF, *TPC, *ORE, R);
2359         return false;
2360       }
2361 
2362       finalizeBasicBlock();
2363     }
2364 #ifndef NDEBUG
2365     WrapperObserver.removeObserver(&Verifier);
2366 #endif
2367   }
2368 
2369   finishPendingPhis();
2370 
2371   SwiftError.propagateVRegs();
2372 
2373   // Merge the argument lowering and constants block with its single
2374   // successor, the LLVM-IR entry block.  We want the basic block to
2375   // be maximal.
2376   assert(EntryBB->succ_size() == 1 &&
2377          "Custom BB used for lowering should have only one successor");
2378   // Get the successor of the current entry block.
2379   MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin();
2380   assert(NewEntryBB.pred_size() == 1 &&
2381          "LLVM-IR entry block has a predecessor!?");
2382   // Move all the instruction from the current entry block to the
2383   // new entry block.
2384   NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(),
2385                     EntryBB->end());
2386 
2387   // Update the live-in information for the new entry block.
2388   for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins())
2389     NewEntryBB.addLiveIn(LiveIn);
2390   NewEntryBB.sortUniqueLiveIns();
2391 
2392   // Get rid of the now empty basic block.
2393   EntryBB->removeSuccessor(&NewEntryBB);
2394   MF->remove(EntryBB);
2395   MF->DeleteMachineBasicBlock(EntryBB);
2396 
2397   assert(&MF->front() == &NewEntryBB &&
2398          "New entry wasn't next in the list of basic block!");
2399 
2400   // Initialize stack protector information.
2401   StackProtector &SP = getAnalysis<StackProtector>();
2402   SP.copyToMachineFrameInfo(MF->getFrameInfo());
2403 
2404   return false;
2405 }
2406