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