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/GlobalISel/CallLowering.h"
24 #include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h"
25 #include "llvm/CodeGen/GlobalISel/InlineAsmLowering.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/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineOperand.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/StackProtector.h"
36 #include "llvm/CodeGen/TargetFrameLowering.h"
37 #include "llvm/CodeGen/TargetInstrInfo.h"
38 #include "llvm/CodeGen/TargetLowering.h"
39 #include "llvm/CodeGen/TargetPassConfig.h"
40 #include "llvm/CodeGen/TargetRegisterInfo.h"
41 #include "llvm/CodeGen/TargetSubtargetInfo.h"
42 #include "llvm/IR/BasicBlock.h"
43 #include "llvm/IR/CFG.h"
44 #include "llvm/IR/Constant.h"
45 #include "llvm/IR/Constants.h"
46 #include "llvm/IR/DataLayout.h"
47 #include "llvm/IR/DebugInfo.h"
48 #include "llvm/IR/DerivedTypes.h"
49 #include "llvm/IR/Function.h"
50 #include "llvm/IR/GetElementPtrTypeIterator.h"
51 #include "llvm/IR/InlineAsm.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   auto MapEntry = FrameIndices.find(&AI);
227   if (MapEntry != FrameIndices.end())
228     return MapEntry->second;
229 
230   uint64_t ElementSize = DL->getTypeAllocSize(AI.getAllocatedType());
231   uint64_t Size =
232       ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue();
233 
234   // Always allocate at least one byte.
235   Size = std::max<uint64_t>(Size, 1u);
236 
237   int &FI = FrameIndices[&AI];
238   FI = MF->getFrameInfo().CreateStackObject(Size, AI.getAlign(), false, &AI);
239   return FI;
240 }
241 
242 Align IRTranslator::getMemOpAlign(const Instruction &I) {
243   if (const StoreInst *SI = dyn_cast<StoreInst>(&I))
244     return SI->getAlign();
245   if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
246     return LI->getAlign();
247   }
248   if (const AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(&I)) {
249     // TODO(PR27168): This instruction has no alignment attribute, but unlike
250     // the default alignment for load/store, the default here is to assume
251     // it has NATURAL alignment, not DataLayout-specified alignment.
252     const DataLayout &DL = AI->getModule()->getDataLayout();
253     return Align(DL.getTypeStoreSize(AI->getCompareOperand()->getType()));
254   }
255   if (const AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(&I)) {
256     // TODO(PR27168): This instruction has no alignment attribute, but unlike
257     // the default alignment for load/store, the default here is to assume
258     // it has NATURAL alignment, not DataLayout-specified alignment.
259     const DataLayout &DL = AI->getModule()->getDataLayout();
260     return Align(DL.getTypeStoreSize(AI->getValOperand()->getType()));
261   }
262   OptimizationRemarkMissed R("gisel-irtranslator", "", &I);
263   R << "unable to translate memop: " << ore::NV("Opcode", &I);
264   reportTranslationError(*MF, *TPC, *ORE, R);
265   return Align(1);
266 }
267 
268 MachineBasicBlock &IRTranslator::getMBB(const BasicBlock &BB) {
269   MachineBasicBlock *&MBB = BBToMBB[&BB];
270   assert(MBB && "BasicBlock was not encountered before");
271   return *MBB;
272 }
273 
274 void IRTranslator::addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred) {
275   assert(NewPred && "new predecessor must be a real MachineBasicBlock");
276   MachinePreds[Edge].push_back(NewPred);
277 }
278 
279 bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U,
280                                      MachineIRBuilder &MIRBuilder) {
281   // Get or create a virtual register for each value.
282   // Unless the value is a Constant => loadimm cst?
283   // or inline constant each time?
284   // Creation of a virtual register needs to have a size.
285   Register Op0 = getOrCreateVReg(*U.getOperand(0));
286   Register Op1 = getOrCreateVReg(*U.getOperand(1));
287   Register Res = getOrCreateVReg(U);
288   uint16_t Flags = 0;
289   if (isa<Instruction>(U)) {
290     const Instruction &I = cast<Instruction>(U);
291     Flags = MachineInstr::copyFlagsFromInstruction(I);
292   }
293 
294   MIRBuilder.buildInstr(Opcode, {Res}, {Op0, Op1}, Flags);
295   return true;
296 }
297 
298 bool IRTranslator::translateUnaryOp(unsigned Opcode, const User &U,
299                                     MachineIRBuilder &MIRBuilder) {
300   Register Op0 = getOrCreateVReg(*U.getOperand(0));
301   Register Res = getOrCreateVReg(U);
302   uint16_t Flags = 0;
303   if (isa<Instruction>(U)) {
304     const Instruction &I = cast<Instruction>(U);
305     Flags = MachineInstr::copyFlagsFromInstruction(I);
306   }
307   MIRBuilder.buildInstr(Opcode, {Res}, {Op0}, Flags);
308   return true;
309 }
310 
311 bool IRTranslator::translateFNeg(const User &U, MachineIRBuilder &MIRBuilder) {
312   return translateUnaryOp(TargetOpcode::G_FNEG, U, MIRBuilder);
313 }
314 
315 bool IRTranslator::translateCompare(const User &U,
316                                     MachineIRBuilder &MIRBuilder) {
317   auto *CI = dyn_cast<CmpInst>(&U);
318   Register Op0 = getOrCreateVReg(*U.getOperand(0));
319   Register Op1 = getOrCreateVReg(*U.getOperand(1));
320   Register Res = getOrCreateVReg(U);
321   CmpInst::Predicate Pred =
322       CI ? CI->getPredicate() : static_cast<CmpInst::Predicate>(
323                                     cast<ConstantExpr>(U).getPredicate());
324   if (CmpInst::isIntPredicate(Pred))
325     MIRBuilder.buildICmp(Pred, Res, Op0, Op1);
326   else if (Pred == CmpInst::FCMP_FALSE)
327     MIRBuilder.buildCopy(
328         Res, getOrCreateVReg(*Constant::getNullValue(U.getType())));
329   else if (Pred == CmpInst::FCMP_TRUE)
330     MIRBuilder.buildCopy(
331         Res, getOrCreateVReg(*Constant::getAllOnesValue(U.getType())));
332   else {
333     assert(CI && "Instruction should be CmpInst");
334     MIRBuilder.buildFCmp(Pred, Res, Op0, Op1,
335                          MachineInstr::copyFlagsFromInstruction(*CI));
336   }
337 
338   return true;
339 }
340 
341 bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) {
342   const ReturnInst &RI = cast<ReturnInst>(U);
343   const Value *Ret = RI.getReturnValue();
344   if (Ret && DL->getTypeStoreSize(Ret->getType()) == 0)
345     Ret = nullptr;
346 
347   ArrayRef<Register> VRegs;
348   if (Ret)
349     VRegs = getOrCreateVRegs(*Ret);
350 
351   Register SwiftErrorVReg = 0;
352   if (CLI->supportSwiftError() && SwiftError.getFunctionArg()) {
353     SwiftErrorVReg = SwiftError.getOrCreateVRegUseAt(
354         &RI, &MIRBuilder.getMBB(), SwiftError.getFunctionArg());
355   }
356 
357   // The target may mess up with the insertion point, but
358   // this is not important as a return is the last instruction
359   // of the block anyway.
360   return CLI->lowerReturn(MIRBuilder, Ret, VRegs, SwiftErrorVReg);
361 }
362 
363 bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) {
364   const BranchInst &BrInst = cast<BranchInst>(U);
365   unsigned Succ = 0;
366   if (!BrInst.isUnconditional()) {
367     // We want a G_BRCOND to the true BB followed by an unconditional branch.
368     Register Tst = getOrCreateVReg(*BrInst.getCondition());
369     const BasicBlock &TrueTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ++));
370     MachineBasicBlock &TrueBB = getMBB(TrueTgt);
371     MIRBuilder.buildBrCond(Tst, TrueBB);
372   }
373 
374   const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ));
375   MachineBasicBlock &TgtBB = getMBB(BrTgt);
376   MachineBasicBlock &CurBB = MIRBuilder.getMBB();
377 
378   // If the unconditional target is the layout successor, fallthrough.
379   if (!CurBB.isLayoutSuccessor(&TgtBB))
380     MIRBuilder.buildBr(TgtBB);
381 
382   // Link successors.
383   for (const BasicBlock *Succ : successors(&BrInst))
384     CurBB.addSuccessor(&getMBB(*Succ));
385   return true;
386 }
387 
388 void IRTranslator::addSuccessorWithProb(MachineBasicBlock *Src,
389                                         MachineBasicBlock *Dst,
390                                         BranchProbability Prob) {
391   if (!FuncInfo.BPI) {
392     Src->addSuccessorWithoutProb(Dst);
393     return;
394   }
395   if (Prob.isUnknown())
396     Prob = getEdgeProbability(Src, Dst);
397   Src->addSuccessor(Dst, Prob);
398 }
399 
400 BranchProbability
401 IRTranslator::getEdgeProbability(const MachineBasicBlock *Src,
402                                  const MachineBasicBlock *Dst) const {
403   const BasicBlock *SrcBB = Src->getBasicBlock();
404   const BasicBlock *DstBB = Dst->getBasicBlock();
405   if (!FuncInfo.BPI) {
406     // If BPI is not available, set the default probability as 1 / N, where N is
407     // the number of successors.
408     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
409     return BranchProbability(1, SuccSize);
410   }
411   return FuncInfo.BPI->getEdgeProbability(SrcBB, DstBB);
412 }
413 
414 bool IRTranslator::translateSwitch(const User &U, MachineIRBuilder &MIB) {
415   using namespace SwitchCG;
416   // Extract cases from the switch.
417   const SwitchInst &SI = cast<SwitchInst>(U);
418   BranchProbabilityInfo *BPI = FuncInfo.BPI;
419   CaseClusterVector Clusters;
420   Clusters.reserve(SI.getNumCases());
421   for (auto &I : SI.cases()) {
422     MachineBasicBlock *Succ = &getMBB(*I.getCaseSuccessor());
423     assert(Succ && "Could not find successor mbb in mapping");
424     const ConstantInt *CaseVal = I.getCaseValue();
425     BranchProbability Prob =
426         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
427             : BranchProbability(1, SI.getNumCases() + 1);
428     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
429   }
430 
431   MachineBasicBlock *DefaultMBB = &getMBB(*SI.getDefaultDest());
432 
433   // Cluster adjacent cases with the same destination. We do this at all
434   // optimization levels because it's cheap to do and will make codegen faster
435   // if there are many clusters.
436   sortAndRangeify(Clusters);
437 
438   MachineBasicBlock *SwitchMBB = &getMBB(*SI.getParent());
439 
440   // If there is only the default destination, jump there directly.
441   if (Clusters.empty()) {
442     SwitchMBB->addSuccessor(DefaultMBB);
443     if (DefaultMBB != SwitchMBB->getNextNode())
444       MIB.buildBr(*DefaultMBB);
445     return true;
446   }
447 
448   SL->findJumpTables(Clusters, &SI, DefaultMBB, nullptr, nullptr);
449   SL->findBitTestClusters(Clusters, &SI);
450 
451   LLVM_DEBUG({
452     dbgs() << "Case clusters: ";
453     for (const CaseCluster &C : Clusters) {
454       if (C.Kind == CC_JumpTable)
455         dbgs() << "JT:";
456       if (C.Kind == CC_BitTests)
457         dbgs() << "BT:";
458 
459       C.Low->getValue().print(dbgs(), true);
460       if (C.Low != C.High) {
461         dbgs() << '-';
462         C.High->getValue().print(dbgs(), true);
463       }
464       dbgs() << ' ';
465     }
466     dbgs() << '\n';
467   });
468 
469   assert(!Clusters.empty());
470   SwitchWorkList WorkList;
471   CaseClusterIt First = Clusters.begin();
472   CaseClusterIt Last = Clusters.end() - 1;
473   auto DefaultProb = getEdgeProbability(SwitchMBB, DefaultMBB);
474   WorkList.push_back({SwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
475 
476   // FIXME: At the moment we don't do any splitting optimizations here like
477   // SelectionDAG does, so this worklist only has one entry.
478   while (!WorkList.empty()) {
479     SwitchWorkListItem W = WorkList.back();
480     WorkList.pop_back();
481     if (!lowerSwitchWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB, MIB))
482       return false;
483   }
484   return true;
485 }
486 
487 void IRTranslator::emitJumpTable(SwitchCG::JumpTable &JT,
488                                  MachineBasicBlock *MBB) {
489   // Emit the code for the jump table
490   assert(JT.Reg != -1U && "Should lower JT Header first!");
491   MachineIRBuilder MIB(*MBB->getParent());
492   MIB.setMBB(*MBB);
493   MIB.setDebugLoc(CurBuilder->getDebugLoc());
494 
495   Type *PtrIRTy = Type::getInt8PtrTy(MF->getFunction().getContext());
496   const LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
497 
498   auto Table = MIB.buildJumpTable(PtrTy, JT.JTI);
499   MIB.buildBrJT(Table.getReg(0), JT.JTI, JT.Reg);
500 }
501 
502 bool IRTranslator::emitJumpTableHeader(SwitchCG::JumpTable &JT,
503                                        SwitchCG::JumpTableHeader &JTH,
504                                        MachineBasicBlock *HeaderBB) {
505   MachineIRBuilder MIB(*HeaderBB->getParent());
506   MIB.setMBB(*HeaderBB);
507   MIB.setDebugLoc(CurBuilder->getDebugLoc());
508 
509   const Value &SValue = *JTH.SValue;
510   // Subtract the lowest switch case value from the value being switched on.
511   const LLT SwitchTy = getLLTForType(*SValue.getType(), *DL);
512   Register SwitchOpReg = getOrCreateVReg(SValue);
513   auto FirstCst = MIB.buildConstant(SwitchTy, JTH.First);
514   auto Sub = MIB.buildSub({SwitchTy}, SwitchOpReg, FirstCst);
515 
516   // This value may be smaller or larger than the target's pointer type, and
517   // therefore require extension or truncating.
518   Type *PtrIRTy = SValue.getType()->getPointerTo();
519   const LLT PtrScalarTy = LLT::scalar(DL->getTypeSizeInBits(PtrIRTy));
520   Sub = MIB.buildZExtOrTrunc(PtrScalarTy, Sub);
521 
522   JT.Reg = Sub.getReg(0);
523 
524   if (JTH.OmitRangeCheck) {
525     if (JT.MBB != HeaderBB->getNextNode())
526       MIB.buildBr(*JT.MBB);
527     return true;
528   }
529 
530   // Emit the range check for the jump table, and branch to the default block
531   // for the switch statement if the value being switched on exceeds the
532   // largest case in the switch.
533   auto Cst = getOrCreateVReg(
534       *ConstantInt::get(SValue.getType(), JTH.Last - JTH.First));
535   Cst = MIB.buildZExtOrTrunc(PtrScalarTy, Cst).getReg(0);
536   auto Cmp = MIB.buildICmp(CmpInst::ICMP_UGT, LLT::scalar(1), Sub, Cst);
537 
538   auto BrCond = MIB.buildBrCond(Cmp.getReg(0), *JT.Default);
539 
540   // Avoid emitting unnecessary branches to the next block.
541   if (JT.MBB != HeaderBB->getNextNode())
542     BrCond = MIB.buildBr(*JT.MBB);
543   return true;
544 }
545 
546 void IRTranslator::emitSwitchCase(SwitchCG::CaseBlock &CB,
547                                   MachineBasicBlock *SwitchBB,
548                                   MachineIRBuilder &MIB) {
549   Register CondLHS = getOrCreateVReg(*CB.CmpLHS);
550   Register Cond;
551   DebugLoc OldDbgLoc = MIB.getDebugLoc();
552   MIB.setDebugLoc(CB.DbgLoc);
553   MIB.setMBB(*CB.ThisBB);
554 
555   if (CB.PredInfo.NoCmp) {
556     // Branch or fall through to TrueBB.
557     addSuccessorWithProb(CB.ThisBB, CB.TrueBB, CB.TrueProb);
558     addMachineCFGPred({SwitchBB->getBasicBlock(), CB.TrueBB->getBasicBlock()},
559                       CB.ThisBB);
560     CB.ThisBB->normalizeSuccProbs();
561     if (CB.TrueBB != CB.ThisBB->getNextNode())
562       MIB.buildBr(*CB.TrueBB);
563     MIB.setDebugLoc(OldDbgLoc);
564     return;
565   }
566 
567   const LLT i1Ty = LLT::scalar(1);
568   // Build the compare.
569   if (!CB.CmpMHS) {
570     Register CondRHS = getOrCreateVReg(*CB.CmpRHS);
571     Cond = MIB.buildICmp(CB.PredInfo.Pred, i1Ty, CondLHS, CondRHS).getReg(0);
572   } else {
573     assert(CB.PredInfo.Pred == CmpInst::ICMP_SLE &&
574            "Can only handle SLE ranges");
575 
576     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
577     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
578 
579     Register CmpOpReg = getOrCreateVReg(*CB.CmpMHS);
580     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
581       Register CondRHS = getOrCreateVReg(*CB.CmpRHS);
582       Cond =
583           MIB.buildICmp(CmpInst::ICMP_SLE, i1Ty, CmpOpReg, CondRHS).getReg(0);
584     } else {
585       const LLT CmpTy = MRI->getType(CmpOpReg);
586       auto Sub = MIB.buildSub({CmpTy}, CmpOpReg, CondLHS);
587       auto Diff = MIB.buildConstant(CmpTy, High - Low);
588       Cond = MIB.buildICmp(CmpInst::ICMP_ULE, i1Ty, Sub, Diff).getReg(0);
589     }
590   }
591 
592   // Update successor info
593   addSuccessorWithProb(CB.ThisBB, CB.TrueBB, CB.TrueProb);
594 
595   addMachineCFGPred({SwitchBB->getBasicBlock(), CB.TrueBB->getBasicBlock()},
596                     CB.ThisBB);
597 
598   // TrueBB and FalseBB are always different unless the incoming IR is
599   // degenerate. This only happens when running llc on weird IR.
600   if (CB.TrueBB != CB.FalseBB)
601     addSuccessorWithProb(CB.ThisBB, CB.FalseBB, CB.FalseProb);
602   CB.ThisBB->normalizeSuccProbs();
603 
604   //  if (SwitchBB->getBasicBlock() != CB.FalseBB->getBasicBlock())
605     addMachineCFGPred({SwitchBB->getBasicBlock(), CB.FalseBB->getBasicBlock()},
606                       CB.ThisBB);
607 
608   // If the lhs block is the next block, invert the condition so that we can
609   // fall through to the lhs instead of the rhs block.
610   if (CB.TrueBB == CB.ThisBB->getNextNode()) {
611     std::swap(CB.TrueBB, CB.FalseBB);
612     auto True = MIB.buildConstant(i1Ty, 1);
613     Cond = MIB.buildXor(i1Ty, Cond, True).getReg(0);
614   }
615 
616   MIB.buildBrCond(Cond, *CB.TrueBB);
617   MIB.buildBr(*CB.FalseBB);
618   MIB.setDebugLoc(OldDbgLoc);
619 }
620 
621 bool IRTranslator::lowerJumpTableWorkItem(SwitchCG::SwitchWorkListItem W,
622                                           MachineBasicBlock *SwitchMBB,
623                                           MachineBasicBlock *CurMBB,
624                                           MachineBasicBlock *DefaultMBB,
625                                           MachineIRBuilder &MIB,
626                                           MachineFunction::iterator BBI,
627                                           BranchProbability UnhandledProbs,
628                                           SwitchCG::CaseClusterIt I,
629                                           MachineBasicBlock *Fallthrough,
630                                           bool FallthroughUnreachable) {
631   using namespace SwitchCG;
632   MachineFunction *CurMF = SwitchMBB->getParent();
633   // FIXME: Optimize away range check based on pivot comparisons.
634   JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
635   SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
636   BranchProbability DefaultProb = W.DefaultProb;
637 
638   // The jump block hasn't been inserted yet; insert it here.
639   MachineBasicBlock *JumpMBB = JT->MBB;
640   CurMF->insert(BBI, JumpMBB);
641 
642   // Since the jump table block is separate from the switch block, we need
643   // to keep track of it as a machine predecessor to the default block,
644   // otherwise we lose the phi edges.
645   addMachineCFGPred({SwitchMBB->getBasicBlock(), DefaultMBB->getBasicBlock()},
646                     CurMBB);
647   addMachineCFGPred({SwitchMBB->getBasicBlock(), DefaultMBB->getBasicBlock()},
648                     JumpMBB);
649 
650   auto JumpProb = I->Prob;
651   auto FallthroughProb = UnhandledProbs;
652 
653   // If the default statement is a target of the jump table, we evenly
654   // distribute the default probability to successors of CurMBB. Also
655   // update the probability on the edge from JumpMBB to Fallthrough.
656   for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
657                                         SE = JumpMBB->succ_end();
658        SI != SE; ++SI) {
659     if (*SI == DefaultMBB) {
660       JumpProb += DefaultProb / 2;
661       FallthroughProb -= DefaultProb / 2;
662       JumpMBB->setSuccProbability(SI, DefaultProb / 2);
663       JumpMBB->normalizeSuccProbs();
664     } else {
665       // Also record edges from the jump table block to it's successors.
666       addMachineCFGPred({SwitchMBB->getBasicBlock(), (*SI)->getBasicBlock()},
667                         JumpMBB);
668     }
669   }
670 
671   // Skip the range check if the fallthrough block is unreachable.
672   if (FallthroughUnreachable)
673     JTH->OmitRangeCheck = true;
674 
675   if (!JTH->OmitRangeCheck)
676     addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
677   addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
678   CurMBB->normalizeSuccProbs();
679 
680   // The jump table header will be inserted in our current block, do the
681   // range check, and fall through to our fallthrough block.
682   JTH->HeaderBB = CurMBB;
683   JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
684 
685   // If we're in the right place, emit the jump table header right now.
686   if (CurMBB == SwitchMBB) {
687     if (!emitJumpTableHeader(*JT, *JTH, CurMBB))
688       return false;
689     JTH->Emitted = true;
690   }
691   return true;
692 }
693 bool IRTranslator::lowerSwitchRangeWorkItem(SwitchCG::CaseClusterIt I,
694                                             Value *Cond,
695                                             MachineBasicBlock *Fallthrough,
696                                             bool FallthroughUnreachable,
697                                             BranchProbability UnhandledProbs,
698                                             MachineBasicBlock *CurMBB,
699                                             MachineIRBuilder &MIB,
700                                             MachineBasicBlock *SwitchMBB) {
701   using namespace SwitchCG;
702   const Value *RHS, *LHS, *MHS;
703   CmpInst::Predicate Pred;
704   if (I->Low == I->High) {
705     // Check Cond == I->Low.
706     Pred = CmpInst::ICMP_EQ;
707     LHS = Cond;
708     RHS = I->Low;
709     MHS = nullptr;
710   } else {
711     // Check I->Low <= Cond <= I->High.
712     Pred = CmpInst::ICMP_SLE;
713     LHS = I->Low;
714     MHS = Cond;
715     RHS = I->High;
716   }
717 
718   // If Fallthrough is unreachable, fold away the comparison.
719   // The false probability is the sum of all unhandled cases.
720   CaseBlock CB(Pred, FallthroughUnreachable, LHS, RHS, MHS, I->MBB, Fallthrough,
721                CurMBB, MIB.getDebugLoc(), I->Prob, UnhandledProbs);
722 
723   emitSwitchCase(CB, SwitchMBB, MIB);
724   return true;
725 }
726 
727 void IRTranslator::emitBitTestHeader(SwitchCG::BitTestBlock &B,
728                                      MachineBasicBlock *SwitchBB) {
729   MachineIRBuilder &MIB = *CurBuilder;
730   MIB.setMBB(*SwitchBB);
731 
732   // Subtract the minimum value.
733   Register SwitchOpReg = getOrCreateVReg(*B.SValue);
734 
735   LLT SwitchOpTy = MRI->getType(SwitchOpReg);
736   Register MinValReg = MIB.buildConstant(SwitchOpTy, B.First).getReg(0);
737   auto RangeSub = MIB.buildSub(SwitchOpTy, SwitchOpReg, MinValReg);
738 
739   // Ensure that the type will fit the mask value.
740   LLT MaskTy = SwitchOpTy;
741   for (unsigned I = 0, E = B.Cases.size(); I != E; ++I) {
742     if (!isUIntN(SwitchOpTy.getSizeInBits(), B.Cases[I].Mask)) {
743       // Switch table case range are encoded into series of masks.
744       // Just use pointer type, it's guaranteed to fit.
745       MaskTy = LLT::scalar(64);
746       break;
747     }
748   }
749   Register SubReg = RangeSub.getReg(0);
750   if (SwitchOpTy != MaskTy)
751     SubReg = MIB.buildZExtOrTrunc(MaskTy, SubReg).getReg(0);
752 
753   B.RegVT = getMVTForLLT(MaskTy);
754   B.Reg = SubReg;
755 
756   MachineBasicBlock *MBB = B.Cases[0].ThisBB;
757 
758   if (!B.OmitRangeCheck)
759     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
760   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
761 
762   SwitchBB->normalizeSuccProbs();
763 
764   if (!B.OmitRangeCheck) {
765     // Conditional branch to the default block.
766     auto RangeCst = MIB.buildConstant(SwitchOpTy, B.Range);
767     auto RangeCmp = MIB.buildICmp(CmpInst::Predicate::ICMP_UGT, LLT::scalar(1),
768                                   RangeSub, RangeCst);
769     MIB.buildBrCond(RangeCmp, *B.Default);
770   }
771 
772   // Avoid emitting unnecessary branches to the next block.
773   if (MBB != SwitchBB->getNextNode())
774     MIB.buildBr(*MBB);
775 }
776 
777 void IRTranslator::emitBitTestCase(SwitchCG::BitTestBlock &BB,
778                                    MachineBasicBlock *NextMBB,
779                                    BranchProbability BranchProbToNext,
780                                    Register Reg, SwitchCG::BitTestCase &B,
781                                    MachineBasicBlock *SwitchBB) {
782   MachineIRBuilder &MIB = *CurBuilder;
783   MIB.setMBB(*SwitchBB);
784 
785   LLT SwitchTy = getLLTForMVT(BB.RegVT);
786   Register Cmp;
787   unsigned PopCount = countPopulation(B.Mask);
788   if (PopCount == 1) {
789     // Testing for a single bit; just compare the shift count with what it
790     // would need to be to shift a 1 bit in that position.
791     auto MaskTrailingZeros =
792         MIB.buildConstant(SwitchTy, countTrailingZeros(B.Mask));
793     Cmp =
794         MIB.buildICmp(ICmpInst::ICMP_EQ, LLT::scalar(1), Reg, MaskTrailingZeros)
795             .getReg(0);
796   } else if (PopCount == BB.Range) {
797     // There is only one zero bit in the range, test for it directly.
798     auto MaskTrailingOnes =
799         MIB.buildConstant(SwitchTy, countTrailingOnes(B.Mask));
800     Cmp = MIB.buildICmp(CmpInst::ICMP_NE, LLT::scalar(1), Reg, MaskTrailingOnes)
801               .getReg(0);
802   } else {
803     // Make desired shift.
804     auto CstOne = MIB.buildConstant(SwitchTy, 1);
805     auto SwitchVal = MIB.buildShl(SwitchTy, CstOne, Reg);
806 
807     // Emit bit tests and jumps.
808     auto CstMask = MIB.buildConstant(SwitchTy, B.Mask);
809     auto AndOp = MIB.buildAnd(SwitchTy, SwitchVal, CstMask);
810     auto CstZero = MIB.buildConstant(SwitchTy, 0);
811     Cmp = MIB.buildICmp(CmpInst::ICMP_NE, LLT::scalar(1), AndOp, CstZero)
812               .getReg(0);
813   }
814 
815   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
816   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
817   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
818   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
819   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
820   // one as they are relative probabilities (and thus work more like weights),
821   // and hence we need to normalize them to let the sum of them become one.
822   SwitchBB->normalizeSuccProbs();
823 
824   // Record the fact that the IR edge from the header to the bit test target
825   // will go through our new block. Neeeded for PHIs to have nodes added.
826   addMachineCFGPred({BB.Parent->getBasicBlock(), B.TargetBB->getBasicBlock()},
827                     SwitchBB);
828 
829   MIB.buildBrCond(Cmp, *B.TargetBB);
830 
831   // Avoid emitting unnecessary branches to the next block.
832   if (NextMBB != SwitchBB->getNextNode())
833     MIB.buildBr(*NextMBB);
834 }
835 
836 bool IRTranslator::lowerBitTestWorkItem(
837     SwitchCG::SwitchWorkListItem W, MachineBasicBlock *SwitchMBB,
838     MachineBasicBlock *CurMBB, MachineBasicBlock *DefaultMBB,
839     MachineIRBuilder &MIB, MachineFunction::iterator BBI,
840     BranchProbability DefaultProb, BranchProbability UnhandledProbs,
841     SwitchCG::CaseClusterIt I, MachineBasicBlock *Fallthrough,
842     bool FallthroughUnreachable) {
843   using namespace SwitchCG;
844   MachineFunction *CurMF = SwitchMBB->getParent();
845   // FIXME: Optimize away range check based on pivot comparisons.
846   BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
847   // The bit test blocks haven't been inserted yet; insert them here.
848   for (BitTestCase &BTC : BTB->Cases)
849     CurMF->insert(BBI, BTC.ThisBB);
850 
851   // Fill in fields of the BitTestBlock.
852   BTB->Parent = CurMBB;
853   BTB->Default = Fallthrough;
854 
855   BTB->DefaultProb = UnhandledProbs;
856   // If the cases in bit test don't form a contiguous range, we evenly
857   // distribute the probability on the edge to Fallthrough to two
858   // successors of CurMBB.
859   if (!BTB->ContiguousRange) {
860     BTB->Prob += DefaultProb / 2;
861     BTB->DefaultProb -= DefaultProb / 2;
862   }
863 
864   if (FallthroughUnreachable) {
865     // Skip the range check if the fallthrough block is unreachable.
866     BTB->OmitRangeCheck = true;
867   }
868 
869   // If we're in the right place, emit the bit test header right now.
870   if (CurMBB == SwitchMBB) {
871     emitBitTestHeader(*BTB, SwitchMBB);
872     BTB->Emitted = true;
873   }
874   return true;
875 }
876 
877 bool IRTranslator::lowerSwitchWorkItem(SwitchCG::SwitchWorkListItem W,
878                                        Value *Cond,
879                                        MachineBasicBlock *SwitchMBB,
880                                        MachineBasicBlock *DefaultMBB,
881                                        MachineIRBuilder &MIB) {
882   using namespace SwitchCG;
883   MachineFunction *CurMF = FuncInfo.MF;
884   MachineBasicBlock *NextMBB = nullptr;
885   MachineFunction::iterator BBI(W.MBB);
886   if (++BBI != FuncInfo.MF->end())
887     NextMBB = &*BBI;
888 
889   if (EnableOpts) {
890     // Here, we order cases by probability so the most likely case will be
891     // checked first. However, two clusters can have the same probability in
892     // which case their relative ordering is non-deterministic. So we use Low
893     // as a tie-breaker as clusters are guaranteed to never overlap.
894     llvm::sort(W.FirstCluster, W.LastCluster + 1,
895                [](const CaseCluster &a, const CaseCluster &b) {
896                  return a.Prob != b.Prob
897                             ? a.Prob > b.Prob
898                             : a.Low->getValue().slt(b.Low->getValue());
899                });
900 
901     // Rearrange the case blocks so that the last one falls through if possible
902     // without changing the order of probabilities.
903     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster;) {
904       --I;
905       if (I->Prob > W.LastCluster->Prob)
906         break;
907       if (I->Kind == CC_Range && I->MBB == NextMBB) {
908         std::swap(*I, *W.LastCluster);
909         break;
910       }
911     }
912   }
913 
914   // Compute total probability.
915   BranchProbability DefaultProb = W.DefaultProb;
916   BranchProbability UnhandledProbs = DefaultProb;
917   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
918     UnhandledProbs += I->Prob;
919 
920   MachineBasicBlock *CurMBB = W.MBB;
921   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
922     bool FallthroughUnreachable = false;
923     MachineBasicBlock *Fallthrough;
924     if (I == W.LastCluster) {
925       // For the last cluster, fall through to the default destination.
926       Fallthrough = DefaultMBB;
927       FallthroughUnreachable = isa<UnreachableInst>(
928           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
929     } else {
930       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
931       CurMF->insert(BBI, Fallthrough);
932     }
933     UnhandledProbs -= I->Prob;
934 
935     switch (I->Kind) {
936     case CC_BitTests: {
937       if (!lowerBitTestWorkItem(W, SwitchMBB, CurMBB, DefaultMBB, MIB, BBI,
938                                 DefaultProb, UnhandledProbs, I, Fallthrough,
939                                 FallthroughUnreachable)) {
940         LLVM_DEBUG(dbgs() << "Failed to lower bit test for switch");
941         return false;
942       }
943       break;
944     }
945 
946     case CC_JumpTable: {
947       if (!lowerJumpTableWorkItem(W, SwitchMBB, CurMBB, DefaultMBB, MIB, BBI,
948                                   UnhandledProbs, I, Fallthrough,
949                                   FallthroughUnreachable)) {
950         LLVM_DEBUG(dbgs() << "Failed to lower jump table");
951         return false;
952       }
953       break;
954     }
955     case CC_Range: {
956       if (!lowerSwitchRangeWorkItem(I, Cond, Fallthrough,
957                                     FallthroughUnreachable, UnhandledProbs,
958                                     CurMBB, MIB, SwitchMBB)) {
959         LLVM_DEBUG(dbgs() << "Failed to lower switch range");
960         return false;
961       }
962       break;
963     }
964     }
965     CurMBB = Fallthrough;
966   }
967 
968   return true;
969 }
970 
971 bool IRTranslator::translateIndirectBr(const User &U,
972                                        MachineIRBuilder &MIRBuilder) {
973   const IndirectBrInst &BrInst = cast<IndirectBrInst>(U);
974 
975   const Register Tgt = getOrCreateVReg(*BrInst.getAddress());
976   MIRBuilder.buildBrIndirect(Tgt);
977 
978   // Link successors.
979   SmallPtrSet<const BasicBlock *, 32> AddedSuccessors;
980   MachineBasicBlock &CurBB = MIRBuilder.getMBB();
981   for (const BasicBlock *Succ : successors(&BrInst)) {
982     // It's legal for indirectbr instructions to have duplicate blocks in the
983     // destination list. We don't allow this in MIR. Skip anything that's
984     // already a successor.
985     if (!AddedSuccessors.insert(Succ).second)
986       continue;
987     CurBB.addSuccessor(&getMBB(*Succ));
988   }
989 
990   return true;
991 }
992 
993 static bool isSwiftError(const Value *V) {
994   if (auto Arg = dyn_cast<Argument>(V))
995     return Arg->hasSwiftErrorAttr();
996   if (auto AI = dyn_cast<AllocaInst>(V))
997     return AI->isSwiftError();
998   return false;
999 }
1000 
1001 bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) {
1002   const LoadInst &LI = cast<LoadInst>(U);
1003   if (DL->getTypeStoreSize(LI.getType()) == 0)
1004     return true;
1005 
1006   ArrayRef<Register> Regs = getOrCreateVRegs(LI);
1007   ArrayRef<uint64_t> Offsets = *VMap.getOffsets(LI);
1008   Register Base = getOrCreateVReg(*LI.getPointerOperand());
1009 
1010   Type *OffsetIRTy = DL->getIntPtrType(LI.getPointerOperandType());
1011   LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
1012 
1013   if (CLI->supportSwiftError() && isSwiftError(LI.getPointerOperand())) {
1014     assert(Regs.size() == 1 && "swifterror should be single pointer");
1015     Register VReg = SwiftError.getOrCreateVRegUseAt(&LI, &MIRBuilder.getMBB(),
1016                                                     LI.getPointerOperand());
1017     MIRBuilder.buildCopy(Regs[0], VReg);
1018     return true;
1019   }
1020 
1021   auto &TLI = *MF->getSubtarget().getTargetLowering();
1022   MachineMemOperand::Flags Flags = TLI.getLoadMemOperandFlags(LI, *DL);
1023 
1024   const MDNode *Ranges =
1025       Regs.size() == 1 ? LI.getMetadata(LLVMContext::MD_range) : nullptr;
1026   for (unsigned i = 0; i < Regs.size(); ++i) {
1027     Register Addr;
1028     MIRBuilder.materializePtrAdd(Addr, Base, OffsetTy, Offsets[i] / 8);
1029 
1030     MachinePointerInfo Ptr(LI.getPointerOperand(), Offsets[i] / 8);
1031     Align BaseAlign = getMemOpAlign(LI);
1032     AAMDNodes AAMetadata;
1033     LI.getAAMetadata(AAMetadata);
1034     auto MMO = MF->getMachineMemOperand(
1035         Ptr, Flags, MRI->getType(Regs[i]).getSizeInBytes(),
1036         commonAlignment(BaseAlign, Offsets[i] / 8), AAMetadata, Ranges,
1037         LI.getSyncScopeID(), LI.getOrdering());
1038     MIRBuilder.buildLoad(Regs[i], Addr, *MMO);
1039   }
1040 
1041   return true;
1042 }
1043 
1044 bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) {
1045   const StoreInst &SI = cast<StoreInst>(U);
1046   if (DL->getTypeStoreSize(SI.getValueOperand()->getType()) == 0)
1047     return true;
1048 
1049   ArrayRef<Register> Vals = getOrCreateVRegs(*SI.getValueOperand());
1050   ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*SI.getValueOperand());
1051   Register Base = getOrCreateVReg(*SI.getPointerOperand());
1052 
1053   Type *OffsetIRTy = DL->getIntPtrType(SI.getPointerOperandType());
1054   LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
1055 
1056   if (CLI->supportSwiftError() && isSwiftError(SI.getPointerOperand())) {
1057     assert(Vals.size() == 1 && "swifterror should be single pointer");
1058 
1059     Register VReg = SwiftError.getOrCreateVRegDefAt(&SI, &MIRBuilder.getMBB(),
1060                                                     SI.getPointerOperand());
1061     MIRBuilder.buildCopy(VReg, Vals[0]);
1062     return true;
1063   }
1064 
1065   auto &TLI = *MF->getSubtarget().getTargetLowering();
1066   MachineMemOperand::Flags Flags = TLI.getStoreMemOperandFlags(SI, *DL);
1067 
1068   for (unsigned i = 0; i < Vals.size(); ++i) {
1069     Register Addr;
1070     MIRBuilder.materializePtrAdd(Addr, Base, OffsetTy, Offsets[i] / 8);
1071 
1072     MachinePointerInfo Ptr(SI.getPointerOperand(), Offsets[i] / 8);
1073     Align BaseAlign = getMemOpAlign(SI);
1074     AAMDNodes AAMetadata;
1075     SI.getAAMetadata(AAMetadata);
1076     auto MMO = MF->getMachineMemOperand(
1077         Ptr, Flags, MRI->getType(Vals[i]).getSizeInBytes(),
1078         commonAlignment(BaseAlign, Offsets[i] / 8), AAMetadata, nullptr,
1079         SI.getSyncScopeID(), SI.getOrdering());
1080     MIRBuilder.buildStore(Vals[i], Addr, *MMO);
1081   }
1082   return true;
1083 }
1084 
1085 static uint64_t getOffsetFromIndices(const User &U, const DataLayout &DL) {
1086   const Value *Src = U.getOperand(0);
1087   Type *Int32Ty = Type::getInt32Ty(U.getContext());
1088 
1089   // getIndexedOffsetInType is designed for GEPs, so the first index is the
1090   // usual array element rather than looking into the actual aggregate.
1091   SmallVector<Value *, 1> Indices;
1092   Indices.push_back(ConstantInt::get(Int32Ty, 0));
1093 
1094   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) {
1095     for (auto Idx : EVI->indices())
1096       Indices.push_back(ConstantInt::get(Int32Ty, Idx));
1097   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) {
1098     for (auto Idx : IVI->indices())
1099       Indices.push_back(ConstantInt::get(Int32Ty, Idx));
1100   } else {
1101     for (unsigned i = 1; i < U.getNumOperands(); ++i)
1102       Indices.push_back(U.getOperand(i));
1103   }
1104 
1105   return 8 * static_cast<uint64_t>(
1106                  DL.getIndexedOffsetInType(Src->getType(), Indices));
1107 }
1108 
1109 bool IRTranslator::translateExtractValue(const User &U,
1110                                          MachineIRBuilder &MIRBuilder) {
1111   const Value *Src = U.getOperand(0);
1112   uint64_t Offset = getOffsetFromIndices(U, *DL);
1113   ArrayRef<Register> SrcRegs = getOrCreateVRegs(*Src);
1114   ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*Src);
1115   unsigned Idx = llvm::lower_bound(Offsets, Offset) - Offsets.begin();
1116   auto &DstRegs = allocateVRegs(U);
1117 
1118   for (unsigned i = 0; i < DstRegs.size(); ++i)
1119     DstRegs[i] = SrcRegs[Idx++];
1120 
1121   return true;
1122 }
1123 
1124 bool IRTranslator::translateInsertValue(const User &U,
1125                                         MachineIRBuilder &MIRBuilder) {
1126   const Value *Src = U.getOperand(0);
1127   uint64_t Offset = getOffsetFromIndices(U, *DL);
1128   auto &DstRegs = allocateVRegs(U);
1129   ArrayRef<uint64_t> DstOffsets = *VMap.getOffsets(U);
1130   ArrayRef<Register> SrcRegs = getOrCreateVRegs(*Src);
1131   ArrayRef<Register> InsertedRegs = getOrCreateVRegs(*U.getOperand(1));
1132   auto InsertedIt = InsertedRegs.begin();
1133 
1134   for (unsigned i = 0; i < DstRegs.size(); ++i) {
1135     if (DstOffsets[i] >= Offset && InsertedIt != InsertedRegs.end())
1136       DstRegs[i] = *InsertedIt++;
1137     else
1138       DstRegs[i] = SrcRegs[i];
1139   }
1140 
1141   return true;
1142 }
1143 
1144 bool IRTranslator::translateSelect(const User &U,
1145                                    MachineIRBuilder &MIRBuilder) {
1146   Register Tst = getOrCreateVReg(*U.getOperand(0));
1147   ArrayRef<Register> ResRegs = getOrCreateVRegs(U);
1148   ArrayRef<Register> Op0Regs = getOrCreateVRegs(*U.getOperand(1));
1149   ArrayRef<Register> Op1Regs = getOrCreateVRegs(*U.getOperand(2));
1150 
1151   uint16_t Flags = 0;
1152   if (const SelectInst *SI = dyn_cast<SelectInst>(&U))
1153     Flags = MachineInstr::copyFlagsFromInstruction(*SI);
1154 
1155   for (unsigned i = 0; i < ResRegs.size(); ++i) {
1156     MIRBuilder.buildSelect(ResRegs[i], Tst, Op0Regs[i], Op1Regs[i], Flags);
1157   }
1158 
1159   return true;
1160 }
1161 
1162 bool IRTranslator::translateCopy(const User &U, const Value &V,
1163                                  MachineIRBuilder &MIRBuilder) {
1164   Register Src = getOrCreateVReg(V);
1165   auto &Regs = *VMap.getVRegs(U);
1166   if (Regs.empty()) {
1167     Regs.push_back(Src);
1168     VMap.getOffsets(U)->push_back(0);
1169   } else {
1170     // If we already assigned a vreg for this instruction, we can't change that.
1171     // Emit a copy to satisfy the users we already emitted.
1172     MIRBuilder.buildCopy(Regs[0], Src);
1173   }
1174   return true;
1175 }
1176 
1177 bool IRTranslator::translateBitCast(const User &U,
1178                                     MachineIRBuilder &MIRBuilder) {
1179   // If we're bitcasting to the source type, we can reuse the source vreg.
1180   if (getLLTForType(*U.getOperand(0)->getType(), *DL) ==
1181       getLLTForType(*U.getType(), *DL))
1182     return translateCopy(U, *U.getOperand(0), MIRBuilder);
1183 
1184   return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder);
1185 }
1186 
1187 bool IRTranslator::translateCast(unsigned Opcode, const User &U,
1188                                  MachineIRBuilder &MIRBuilder) {
1189   Register Op = getOrCreateVReg(*U.getOperand(0));
1190   Register Res = getOrCreateVReg(U);
1191   MIRBuilder.buildInstr(Opcode, {Res}, {Op});
1192   return true;
1193 }
1194 
1195 bool IRTranslator::translateGetElementPtr(const User &U,
1196                                           MachineIRBuilder &MIRBuilder) {
1197   Value &Op0 = *U.getOperand(0);
1198   Register BaseReg = getOrCreateVReg(Op0);
1199   Type *PtrIRTy = Op0.getType();
1200   LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
1201   Type *OffsetIRTy = DL->getIntPtrType(PtrIRTy);
1202   LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
1203 
1204   // Normalize Vector GEP - all scalar operands should be converted to the
1205   // splat vector.
1206   unsigned VectorWidth = 0;
1207   if (auto *VT = dyn_cast<VectorType>(U.getType()))
1208     VectorWidth = cast<FixedVectorType>(VT)->getNumElements();
1209 
1210   // We might need to splat the base pointer into a vector if the offsets
1211   // are vectors.
1212   if (VectorWidth && !PtrTy.isVector()) {
1213     BaseReg =
1214         MIRBuilder.buildSplatVector(LLT::vector(VectorWidth, PtrTy), BaseReg)
1215             .getReg(0);
1216     PtrIRTy = FixedVectorType::get(PtrIRTy, VectorWidth);
1217     PtrTy = getLLTForType(*PtrIRTy, *DL);
1218     OffsetIRTy = DL->getIntPtrType(PtrIRTy);
1219     OffsetTy = getLLTForType(*OffsetIRTy, *DL);
1220   }
1221 
1222   int64_t Offset = 0;
1223   for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U);
1224        GTI != E; ++GTI) {
1225     const Value *Idx = GTI.getOperand();
1226     if (StructType *StTy = GTI.getStructTypeOrNull()) {
1227       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
1228       Offset += DL->getStructLayout(StTy)->getElementOffset(Field);
1229       continue;
1230     } else {
1231       uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
1232 
1233       // If this is a scalar constant or a splat vector of constants,
1234       // handle it quickly.
1235       if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
1236         Offset += ElementSize * CI->getSExtValue();
1237         continue;
1238       }
1239 
1240       if (Offset != 0) {
1241         auto OffsetMIB = MIRBuilder.buildConstant({OffsetTy}, Offset);
1242         BaseReg = MIRBuilder.buildPtrAdd(PtrTy, BaseReg, OffsetMIB.getReg(0))
1243                       .getReg(0);
1244         Offset = 0;
1245       }
1246 
1247       Register IdxReg = getOrCreateVReg(*Idx);
1248       LLT IdxTy = MRI->getType(IdxReg);
1249       if (IdxTy != OffsetTy) {
1250         if (!IdxTy.isVector() && VectorWidth) {
1251           IdxReg = MIRBuilder.buildSplatVector(
1252             OffsetTy.changeElementType(IdxTy), IdxReg).getReg(0);
1253         }
1254 
1255         IdxReg = MIRBuilder.buildSExtOrTrunc(OffsetTy, IdxReg).getReg(0);
1256       }
1257 
1258       // N = N + Idx * ElementSize;
1259       // Avoid doing it for ElementSize of 1.
1260       Register GepOffsetReg;
1261       if (ElementSize != 1) {
1262         auto ElementSizeMIB = MIRBuilder.buildConstant(
1263             getLLTForType(*OffsetIRTy, *DL), ElementSize);
1264         GepOffsetReg =
1265             MIRBuilder.buildMul(OffsetTy, IdxReg, ElementSizeMIB).getReg(0);
1266       } else
1267         GepOffsetReg = IdxReg;
1268 
1269       BaseReg = MIRBuilder.buildPtrAdd(PtrTy, BaseReg, GepOffsetReg).getReg(0);
1270     }
1271   }
1272 
1273   if (Offset != 0) {
1274     auto OffsetMIB =
1275         MIRBuilder.buildConstant(OffsetTy, Offset);
1276     MIRBuilder.buildPtrAdd(getOrCreateVReg(U), BaseReg, OffsetMIB.getReg(0));
1277     return true;
1278   }
1279 
1280   MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg);
1281   return true;
1282 }
1283 
1284 bool IRTranslator::translateMemFunc(const CallInst &CI,
1285                                     MachineIRBuilder &MIRBuilder,
1286                                     unsigned Opcode) {
1287 
1288   // If the source is undef, then just emit a nop.
1289   if (isa<UndefValue>(CI.getArgOperand(1)))
1290     return true;
1291 
1292   SmallVector<Register, 3> SrcRegs;
1293 
1294   unsigned MinPtrSize = UINT_MAX;
1295   for (auto AI = CI.arg_begin(), AE = CI.arg_end(); std::next(AI) != AE; ++AI) {
1296     Register SrcReg = getOrCreateVReg(**AI);
1297     LLT SrcTy = MRI->getType(SrcReg);
1298     if (SrcTy.isPointer())
1299       MinPtrSize = std::min(SrcTy.getSizeInBits(), MinPtrSize);
1300     SrcRegs.push_back(SrcReg);
1301   }
1302 
1303   LLT SizeTy = LLT::scalar(MinPtrSize);
1304 
1305   // The size operand should be the minimum of the pointer sizes.
1306   Register &SizeOpReg = SrcRegs[SrcRegs.size() - 1];
1307   if (MRI->getType(SizeOpReg) != SizeTy)
1308     SizeOpReg = MIRBuilder.buildZExtOrTrunc(SizeTy, SizeOpReg).getReg(0);
1309 
1310   auto ICall = MIRBuilder.buildInstr(Opcode);
1311   for (Register SrcReg : SrcRegs)
1312     ICall.addUse(SrcReg);
1313 
1314   Align DstAlign;
1315   Align SrcAlign;
1316   unsigned IsVol =
1317       cast<ConstantInt>(CI.getArgOperand(CI.getNumArgOperands() - 1))
1318           ->getZExtValue();
1319 
1320   if (auto *MCI = dyn_cast<MemCpyInst>(&CI)) {
1321     DstAlign = MCI->getDestAlign().valueOrOne();
1322     SrcAlign = MCI->getSourceAlign().valueOrOne();
1323   } else if (auto *MMI = dyn_cast<MemMoveInst>(&CI)) {
1324     DstAlign = MMI->getDestAlign().valueOrOne();
1325     SrcAlign = MMI->getSourceAlign().valueOrOne();
1326   } else {
1327     auto *MSI = cast<MemSetInst>(&CI);
1328     DstAlign = MSI->getDestAlign().valueOrOne();
1329   }
1330 
1331   // We need to propagate the tail call flag from the IR inst as an argument.
1332   // Otherwise, we have to pessimize and assume later that we cannot tail call
1333   // any memory intrinsics.
1334   ICall.addImm(CI.isTailCall() ? 1 : 0);
1335 
1336   // Create mem operands to store the alignment and volatile info.
1337   auto VolFlag = IsVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
1338   ICall.addMemOperand(MF->getMachineMemOperand(
1339       MachinePointerInfo(CI.getArgOperand(0)),
1340       MachineMemOperand::MOStore | VolFlag, 1, DstAlign));
1341   if (Opcode != TargetOpcode::G_MEMSET)
1342     ICall.addMemOperand(MF->getMachineMemOperand(
1343         MachinePointerInfo(CI.getArgOperand(1)),
1344         MachineMemOperand::MOLoad | VolFlag, 1, SrcAlign));
1345 
1346   return true;
1347 }
1348 
1349 void IRTranslator::getStackGuard(Register DstReg,
1350                                  MachineIRBuilder &MIRBuilder) {
1351   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
1352   MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF));
1353   auto MIB =
1354       MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD, {DstReg}, {});
1355 
1356   auto &TLI = *MF->getSubtarget().getTargetLowering();
1357   Value *Global = TLI.getSDagStackGuard(*MF->getFunction().getParent());
1358   if (!Global)
1359     return;
1360 
1361   MachinePointerInfo MPInfo(Global);
1362   auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
1363                MachineMemOperand::MODereferenceable;
1364   MachineMemOperand *MemRef =
1365       MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8,
1366                                DL->getPointerABIAlignment(0));
1367   MIB.setMemRefs({MemRef});
1368 }
1369 
1370 bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op,
1371                                               MachineIRBuilder &MIRBuilder) {
1372   ArrayRef<Register> ResRegs = getOrCreateVRegs(CI);
1373   MIRBuilder.buildInstr(
1374       Op, {ResRegs[0], ResRegs[1]},
1375       {getOrCreateVReg(*CI.getOperand(0)), getOrCreateVReg(*CI.getOperand(1))});
1376 
1377   return true;
1378 }
1379 
1380 bool IRTranslator::translateFixedPointIntrinsic(unsigned Op, const CallInst &CI,
1381                                                 MachineIRBuilder &MIRBuilder) {
1382   Register Dst = getOrCreateVReg(CI);
1383   Register Src0 = getOrCreateVReg(*CI.getOperand(0));
1384   Register Src1 = getOrCreateVReg(*CI.getOperand(1));
1385   uint64_t Scale = cast<ConstantInt>(CI.getOperand(2))->getZExtValue();
1386   MIRBuilder.buildInstr(Op, {Dst}, { Src0, Src1, Scale });
1387   return true;
1388 }
1389 
1390 unsigned IRTranslator::getSimpleIntrinsicOpcode(Intrinsic::ID ID) {
1391   switch (ID) {
1392     default:
1393       break;
1394     case Intrinsic::bswap:
1395       return TargetOpcode::G_BSWAP;
1396     case Intrinsic::bitreverse:
1397       return TargetOpcode::G_BITREVERSE;
1398     case Intrinsic::fshl:
1399       return TargetOpcode::G_FSHL;
1400     case Intrinsic::fshr:
1401       return TargetOpcode::G_FSHR;
1402     case Intrinsic::ceil:
1403       return TargetOpcode::G_FCEIL;
1404     case Intrinsic::cos:
1405       return TargetOpcode::G_FCOS;
1406     case Intrinsic::ctpop:
1407       return TargetOpcode::G_CTPOP;
1408     case Intrinsic::exp:
1409       return TargetOpcode::G_FEXP;
1410     case Intrinsic::exp2:
1411       return TargetOpcode::G_FEXP2;
1412     case Intrinsic::fabs:
1413       return TargetOpcode::G_FABS;
1414     case Intrinsic::copysign:
1415       return TargetOpcode::G_FCOPYSIGN;
1416     case Intrinsic::minnum:
1417       return TargetOpcode::G_FMINNUM;
1418     case Intrinsic::maxnum:
1419       return TargetOpcode::G_FMAXNUM;
1420     case Intrinsic::minimum:
1421       return TargetOpcode::G_FMINIMUM;
1422     case Intrinsic::maximum:
1423       return TargetOpcode::G_FMAXIMUM;
1424     case Intrinsic::canonicalize:
1425       return TargetOpcode::G_FCANONICALIZE;
1426     case Intrinsic::floor:
1427       return TargetOpcode::G_FFLOOR;
1428     case Intrinsic::fma:
1429       return TargetOpcode::G_FMA;
1430     case Intrinsic::log:
1431       return TargetOpcode::G_FLOG;
1432     case Intrinsic::log2:
1433       return TargetOpcode::G_FLOG2;
1434     case Intrinsic::log10:
1435       return TargetOpcode::G_FLOG10;
1436     case Intrinsic::nearbyint:
1437       return TargetOpcode::G_FNEARBYINT;
1438     case Intrinsic::pow:
1439       return TargetOpcode::G_FPOW;
1440     case Intrinsic::powi:
1441       return TargetOpcode::G_FPOWI;
1442     case Intrinsic::rint:
1443       return TargetOpcode::G_FRINT;
1444     case Intrinsic::round:
1445       return TargetOpcode::G_INTRINSIC_ROUND;
1446     case Intrinsic::roundeven:
1447       return TargetOpcode::G_INTRINSIC_ROUNDEVEN;
1448     case Intrinsic::sin:
1449       return TargetOpcode::G_FSIN;
1450     case Intrinsic::sqrt:
1451       return TargetOpcode::G_FSQRT;
1452     case Intrinsic::trunc:
1453       return TargetOpcode::G_INTRINSIC_TRUNC;
1454     case Intrinsic::readcyclecounter:
1455       return TargetOpcode::G_READCYCLECOUNTER;
1456     case Intrinsic::ptrmask:
1457       return TargetOpcode::G_PTRMASK;
1458     case Intrinsic::lrint:
1459       return TargetOpcode::G_INTRINSIC_LRINT;
1460   }
1461   return Intrinsic::not_intrinsic;
1462 }
1463 
1464 bool IRTranslator::translateSimpleIntrinsic(const CallInst &CI,
1465                                             Intrinsic::ID ID,
1466                                             MachineIRBuilder &MIRBuilder) {
1467 
1468   unsigned Op = getSimpleIntrinsicOpcode(ID);
1469 
1470   // Is this a simple intrinsic?
1471   if (Op == Intrinsic::not_intrinsic)
1472     return false;
1473 
1474   // Yes. Let's translate it.
1475   SmallVector<llvm::SrcOp, 4> VRegs;
1476   for (auto &Arg : CI.arg_operands())
1477     VRegs.push_back(getOrCreateVReg(*Arg));
1478 
1479   MIRBuilder.buildInstr(Op, {getOrCreateVReg(CI)}, VRegs,
1480                         MachineInstr::copyFlagsFromInstruction(CI));
1481   return true;
1482 }
1483 
1484 // TODO: Include ConstainedOps.def when all strict instructions are defined.
1485 static unsigned getConstrainedOpcode(Intrinsic::ID ID) {
1486   switch (ID) {
1487   case Intrinsic::experimental_constrained_fadd:
1488     return TargetOpcode::G_STRICT_FADD;
1489   case Intrinsic::experimental_constrained_fsub:
1490     return TargetOpcode::G_STRICT_FSUB;
1491   case Intrinsic::experimental_constrained_fmul:
1492     return TargetOpcode::G_STRICT_FMUL;
1493   case Intrinsic::experimental_constrained_fdiv:
1494     return TargetOpcode::G_STRICT_FDIV;
1495   case Intrinsic::experimental_constrained_frem:
1496     return TargetOpcode::G_STRICT_FREM;
1497   case Intrinsic::experimental_constrained_fma:
1498     return TargetOpcode::G_STRICT_FMA;
1499   case Intrinsic::experimental_constrained_sqrt:
1500     return TargetOpcode::G_STRICT_FSQRT;
1501   default:
1502     return 0;
1503   }
1504 }
1505 
1506 bool IRTranslator::translateConstrainedFPIntrinsic(
1507   const ConstrainedFPIntrinsic &FPI, MachineIRBuilder &MIRBuilder) {
1508   fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue();
1509 
1510   unsigned Opcode = getConstrainedOpcode(FPI.getIntrinsicID());
1511   if (!Opcode)
1512     return false;
1513 
1514   unsigned Flags = MachineInstr::copyFlagsFromInstruction(FPI);
1515   if (EB == fp::ExceptionBehavior::ebIgnore)
1516     Flags |= MachineInstr::NoFPExcept;
1517 
1518   SmallVector<llvm::SrcOp, 4> VRegs;
1519   VRegs.push_back(getOrCreateVReg(*FPI.getArgOperand(0)));
1520   if (!FPI.isUnaryOp())
1521     VRegs.push_back(getOrCreateVReg(*FPI.getArgOperand(1)));
1522   if (FPI.isTernaryOp())
1523     VRegs.push_back(getOrCreateVReg(*FPI.getArgOperand(2)));
1524 
1525   MIRBuilder.buildInstr(Opcode, {getOrCreateVReg(FPI)}, VRegs, Flags);
1526   return true;
1527 }
1528 
1529 bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID,
1530                                            MachineIRBuilder &MIRBuilder) {
1531 
1532   // If this is a simple intrinsic (that is, we just need to add a def of
1533   // a vreg, and uses for each arg operand, then translate it.
1534   if (translateSimpleIntrinsic(CI, ID, MIRBuilder))
1535     return true;
1536 
1537   switch (ID) {
1538   default:
1539     break;
1540   case Intrinsic::lifetime_start:
1541   case Intrinsic::lifetime_end: {
1542     // No stack colouring in O0, discard region information.
1543     if (MF->getTarget().getOptLevel() == CodeGenOpt::None)
1544       return true;
1545 
1546     unsigned Op = ID == Intrinsic::lifetime_start ? TargetOpcode::LIFETIME_START
1547                                                   : TargetOpcode::LIFETIME_END;
1548 
1549     // Get the underlying objects for the location passed on the lifetime
1550     // marker.
1551     SmallVector<const Value *, 4> Allocas;
1552     getUnderlyingObjects(CI.getArgOperand(1), Allocas);
1553 
1554     // Iterate over each underlying object, creating lifetime markers for each
1555     // static alloca. Quit if we find a non-static alloca.
1556     for (const Value *V : Allocas) {
1557       const AllocaInst *AI = dyn_cast<AllocaInst>(V);
1558       if (!AI)
1559         continue;
1560 
1561       if (!AI->isStaticAlloca())
1562         return true;
1563 
1564       MIRBuilder.buildInstr(Op).addFrameIndex(getOrCreateFrameIndex(*AI));
1565     }
1566     return true;
1567   }
1568   case Intrinsic::dbg_declare: {
1569     const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI);
1570     assert(DI.getVariable() && "Missing variable");
1571 
1572     const Value *Address = DI.getAddress();
1573     if (!Address || isa<UndefValue>(Address)) {
1574       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
1575       return true;
1576     }
1577 
1578     assert(DI.getVariable()->isValidLocationForIntrinsic(
1579                MIRBuilder.getDebugLoc()) &&
1580            "Expected inlined-at fields to agree");
1581     auto AI = dyn_cast<AllocaInst>(Address);
1582     if (AI && AI->isStaticAlloca()) {
1583       // Static allocas are tracked at the MF level, no need for DBG_VALUE
1584       // instructions (in fact, they get ignored if they *do* exist).
1585       MF->setVariableDbgInfo(DI.getVariable(), DI.getExpression(),
1586                              getOrCreateFrameIndex(*AI), DI.getDebugLoc());
1587     } else {
1588       // A dbg.declare describes the address of a source variable, so lower it
1589       // into an indirect DBG_VALUE.
1590       MIRBuilder.buildIndirectDbgValue(getOrCreateVReg(*Address),
1591                                        DI.getVariable(), DI.getExpression());
1592     }
1593     return true;
1594   }
1595   case Intrinsic::dbg_label: {
1596     const DbgLabelInst &DI = cast<DbgLabelInst>(CI);
1597     assert(DI.getLabel() && "Missing label");
1598 
1599     assert(DI.getLabel()->isValidLocationForIntrinsic(
1600                MIRBuilder.getDebugLoc()) &&
1601            "Expected inlined-at fields to agree");
1602 
1603     MIRBuilder.buildDbgLabel(DI.getLabel());
1604     return true;
1605   }
1606   case Intrinsic::vaend:
1607     // No target I know of cares about va_end. Certainly no in-tree target
1608     // does. Simplest intrinsic ever!
1609     return true;
1610   case Intrinsic::vastart: {
1611     auto &TLI = *MF->getSubtarget().getTargetLowering();
1612     Value *Ptr = CI.getArgOperand(0);
1613     unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8;
1614 
1615     // FIXME: Get alignment
1616     MIRBuilder.buildInstr(TargetOpcode::G_VASTART, {}, {getOrCreateVReg(*Ptr)})
1617         .addMemOperand(MF->getMachineMemOperand(MachinePointerInfo(Ptr),
1618                                                 MachineMemOperand::MOStore,
1619                                                 ListSize, Align(1)));
1620     return true;
1621   }
1622   case Intrinsic::dbg_value: {
1623     // This form of DBG_VALUE is target-independent.
1624     const DbgValueInst &DI = cast<DbgValueInst>(CI);
1625     const Value *V = DI.getValue();
1626     assert(DI.getVariable()->isValidLocationForIntrinsic(
1627                MIRBuilder.getDebugLoc()) &&
1628            "Expected inlined-at fields to agree");
1629     if (!V) {
1630       // Currently the optimizer can produce this; insert an undef to
1631       // help debugging.  Probably the optimizer should not do this.
1632       MIRBuilder.buildIndirectDbgValue(0, DI.getVariable(), DI.getExpression());
1633     } else if (const auto *CI = dyn_cast<Constant>(V)) {
1634       MIRBuilder.buildConstDbgValue(*CI, DI.getVariable(), DI.getExpression());
1635     } else {
1636       for (Register Reg : getOrCreateVRegs(*V)) {
1637         // FIXME: This does not handle register-indirect values at offset 0. The
1638         // direct/indirect thing shouldn't really be handled by something as
1639         // implicit as reg+noreg vs reg+imm in the first place, but it seems
1640         // pretty baked in right now.
1641         MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(), DI.getExpression());
1642       }
1643     }
1644     return true;
1645   }
1646   case Intrinsic::uadd_with_overflow:
1647     return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDO, MIRBuilder);
1648   case Intrinsic::sadd_with_overflow:
1649     return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder);
1650   case Intrinsic::usub_with_overflow:
1651     return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBO, MIRBuilder);
1652   case Intrinsic::ssub_with_overflow:
1653     return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder);
1654   case Intrinsic::umul_with_overflow:
1655     return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder);
1656   case Intrinsic::smul_with_overflow:
1657     return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder);
1658   case Intrinsic::uadd_sat:
1659     return translateBinaryOp(TargetOpcode::G_UADDSAT, CI, MIRBuilder);
1660   case Intrinsic::sadd_sat:
1661     return translateBinaryOp(TargetOpcode::G_SADDSAT, CI, MIRBuilder);
1662   case Intrinsic::usub_sat:
1663     return translateBinaryOp(TargetOpcode::G_USUBSAT, CI, MIRBuilder);
1664   case Intrinsic::ssub_sat:
1665     return translateBinaryOp(TargetOpcode::G_SSUBSAT, CI, MIRBuilder);
1666   case Intrinsic::ushl_sat:
1667     return translateBinaryOp(TargetOpcode::G_USHLSAT, CI, MIRBuilder);
1668   case Intrinsic::sshl_sat:
1669     return translateBinaryOp(TargetOpcode::G_SSHLSAT, CI, MIRBuilder);
1670   case Intrinsic::umin:
1671     return translateBinaryOp(TargetOpcode::G_UMIN, CI, MIRBuilder);
1672   case Intrinsic::umax:
1673     return translateBinaryOp(TargetOpcode::G_UMAX, CI, MIRBuilder);
1674   case Intrinsic::smin:
1675     return translateBinaryOp(TargetOpcode::G_SMIN, CI, MIRBuilder);
1676   case Intrinsic::smax:
1677     return translateBinaryOp(TargetOpcode::G_SMAX, CI, MIRBuilder);
1678   case Intrinsic::abs:
1679     // TODO: Preserve "int min is poison" arg in GMIR?
1680     return translateUnaryOp(TargetOpcode::G_ABS, CI, MIRBuilder);
1681   case Intrinsic::smul_fix:
1682     return translateFixedPointIntrinsic(TargetOpcode::G_SMULFIX, CI, MIRBuilder);
1683   case Intrinsic::umul_fix:
1684     return translateFixedPointIntrinsic(TargetOpcode::G_UMULFIX, CI, MIRBuilder);
1685   case Intrinsic::smul_fix_sat:
1686     return translateFixedPointIntrinsic(TargetOpcode::G_SMULFIXSAT, CI, MIRBuilder);
1687   case Intrinsic::umul_fix_sat:
1688     return translateFixedPointIntrinsic(TargetOpcode::G_UMULFIXSAT, CI, MIRBuilder);
1689   case Intrinsic::sdiv_fix:
1690     return translateFixedPointIntrinsic(TargetOpcode::G_SDIVFIX, CI, MIRBuilder);
1691   case Intrinsic::udiv_fix:
1692     return translateFixedPointIntrinsic(TargetOpcode::G_UDIVFIX, CI, MIRBuilder);
1693   case Intrinsic::sdiv_fix_sat:
1694     return translateFixedPointIntrinsic(TargetOpcode::G_SDIVFIXSAT, CI, MIRBuilder);
1695   case Intrinsic::udiv_fix_sat:
1696     return translateFixedPointIntrinsic(TargetOpcode::G_UDIVFIXSAT, CI, MIRBuilder);
1697   case Intrinsic::fmuladd: {
1698     const TargetMachine &TM = MF->getTarget();
1699     const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
1700     Register Dst = getOrCreateVReg(CI);
1701     Register Op0 = getOrCreateVReg(*CI.getArgOperand(0));
1702     Register Op1 = getOrCreateVReg(*CI.getArgOperand(1));
1703     Register Op2 = getOrCreateVReg(*CI.getArgOperand(2));
1704     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
1705         TLI.isFMAFasterThanFMulAndFAdd(*MF,
1706                                        TLI.getValueType(*DL, CI.getType()))) {
1707       // TODO: Revisit this to see if we should move this part of the
1708       // lowering to the combiner.
1709       MIRBuilder.buildFMA(Dst, Op0, Op1, Op2,
1710                           MachineInstr::copyFlagsFromInstruction(CI));
1711     } else {
1712       LLT Ty = getLLTForType(*CI.getType(), *DL);
1713       auto FMul = MIRBuilder.buildFMul(
1714           Ty, Op0, Op1, MachineInstr::copyFlagsFromInstruction(CI));
1715       MIRBuilder.buildFAdd(Dst, FMul, Op2,
1716                            MachineInstr::copyFlagsFromInstruction(CI));
1717     }
1718     return true;
1719   }
1720   case Intrinsic::convert_from_fp16:
1721     // FIXME: This intrinsic should probably be removed from the IR.
1722     MIRBuilder.buildFPExt(getOrCreateVReg(CI),
1723                           getOrCreateVReg(*CI.getArgOperand(0)),
1724                           MachineInstr::copyFlagsFromInstruction(CI));
1725     return true;
1726   case Intrinsic::convert_to_fp16:
1727     // FIXME: This intrinsic should probably be removed from the IR.
1728     MIRBuilder.buildFPTrunc(getOrCreateVReg(CI),
1729                             getOrCreateVReg(*CI.getArgOperand(0)),
1730                             MachineInstr::copyFlagsFromInstruction(CI));
1731     return true;
1732   case Intrinsic::memcpy:
1733     return translateMemFunc(CI, MIRBuilder, TargetOpcode::G_MEMCPY);
1734   case Intrinsic::memmove:
1735     return translateMemFunc(CI, MIRBuilder, TargetOpcode::G_MEMMOVE);
1736   case Intrinsic::memset:
1737     return translateMemFunc(CI, MIRBuilder, TargetOpcode::G_MEMSET);
1738   case Intrinsic::eh_typeid_for: {
1739     GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0));
1740     Register Reg = getOrCreateVReg(CI);
1741     unsigned TypeID = MF->getTypeIDFor(GV);
1742     MIRBuilder.buildConstant(Reg, TypeID);
1743     return true;
1744   }
1745   case Intrinsic::objectsize:
1746     llvm_unreachable("llvm.objectsize.* should have been lowered already");
1747 
1748   case Intrinsic::is_constant:
1749     llvm_unreachable("llvm.is.constant.* should have been lowered already");
1750 
1751   case Intrinsic::stackguard:
1752     getStackGuard(getOrCreateVReg(CI), MIRBuilder);
1753     return true;
1754   case Intrinsic::stackprotector: {
1755     LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
1756     Register GuardVal = MRI->createGenericVirtualRegister(PtrTy);
1757     getStackGuard(GuardVal, MIRBuilder);
1758 
1759     AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1));
1760     int FI = getOrCreateFrameIndex(*Slot);
1761     MF->getFrameInfo().setStackProtectorIndex(FI);
1762 
1763     MIRBuilder.buildStore(
1764         GuardVal, getOrCreateVReg(*Slot),
1765         *MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
1766                                   MachineMemOperand::MOStore |
1767                                       MachineMemOperand::MOVolatile,
1768                                   PtrTy.getSizeInBits() / 8, Align(8)));
1769     return true;
1770   }
1771   case Intrinsic::stacksave: {
1772     // Save the stack pointer to the location provided by the intrinsic.
1773     Register Reg = getOrCreateVReg(CI);
1774     Register StackPtr = MF->getSubtarget()
1775                             .getTargetLowering()
1776                             ->getStackPointerRegisterToSaveRestore();
1777 
1778     // If the target doesn't specify a stack pointer, then fall back.
1779     if (!StackPtr)
1780       return false;
1781 
1782     MIRBuilder.buildCopy(Reg, StackPtr);
1783     return true;
1784   }
1785   case Intrinsic::stackrestore: {
1786     // Restore the stack pointer from the location provided by the intrinsic.
1787     Register Reg = getOrCreateVReg(*CI.getArgOperand(0));
1788     Register StackPtr = MF->getSubtarget()
1789                             .getTargetLowering()
1790                             ->getStackPointerRegisterToSaveRestore();
1791 
1792     // If the target doesn't specify a stack pointer, then fall back.
1793     if (!StackPtr)
1794       return false;
1795 
1796     MIRBuilder.buildCopy(StackPtr, Reg);
1797     return true;
1798   }
1799   case Intrinsic::cttz:
1800   case Intrinsic::ctlz: {
1801     ConstantInt *Cst = cast<ConstantInt>(CI.getArgOperand(1));
1802     bool isTrailing = ID == Intrinsic::cttz;
1803     unsigned Opcode = isTrailing
1804                           ? Cst->isZero() ? TargetOpcode::G_CTTZ
1805                                           : TargetOpcode::G_CTTZ_ZERO_UNDEF
1806                           : Cst->isZero() ? TargetOpcode::G_CTLZ
1807                                           : TargetOpcode::G_CTLZ_ZERO_UNDEF;
1808     MIRBuilder.buildInstr(Opcode, {getOrCreateVReg(CI)},
1809                           {getOrCreateVReg(*CI.getArgOperand(0))});
1810     return true;
1811   }
1812   case Intrinsic::invariant_start: {
1813     LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
1814     Register Undef = MRI->createGenericVirtualRegister(PtrTy);
1815     MIRBuilder.buildUndef(Undef);
1816     return true;
1817   }
1818   case Intrinsic::invariant_end:
1819     return true;
1820   case Intrinsic::expect:
1821   case Intrinsic::annotation:
1822   case Intrinsic::ptr_annotation:
1823   case Intrinsic::launder_invariant_group:
1824   case Intrinsic::strip_invariant_group: {
1825     // Drop the intrinsic, but forward the value.
1826     MIRBuilder.buildCopy(getOrCreateVReg(CI),
1827                          getOrCreateVReg(*CI.getArgOperand(0)));
1828     return true;
1829   }
1830   case Intrinsic::assume:
1831   case Intrinsic::var_annotation:
1832   case Intrinsic::sideeffect:
1833     // Discard annotate attributes, assumptions, and artificial side-effects.
1834     return true;
1835   case Intrinsic::read_volatile_register:
1836   case Intrinsic::read_register: {
1837     Value *Arg = CI.getArgOperand(0);
1838     MIRBuilder
1839         .buildInstr(TargetOpcode::G_READ_REGISTER, {getOrCreateVReg(CI)}, {})
1840         .addMetadata(cast<MDNode>(cast<MetadataAsValue>(Arg)->getMetadata()));
1841     return true;
1842   }
1843   case Intrinsic::write_register: {
1844     Value *Arg = CI.getArgOperand(0);
1845     MIRBuilder.buildInstr(TargetOpcode::G_WRITE_REGISTER)
1846       .addMetadata(cast<MDNode>(cast<MetadataAsValue>(Arg)->getMetadata()))
1847       .addUse(getOrCreateVReg(*CI.getArgOperand(1)));
1848     return true;
1849   }
1850   case Intrinsic::localescape: {
1851     MachineBasicBlock &EntryMBB = MF->front();
1852     StringRef EscapedName = GlobalValue::dropLLVMManglingEscape(MF->getName());
1853 
1854     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
1855     // is the same on all targets.
1856     for (unsigned Idx = 0, E = CI.getNumArgOperands(); Idx < E; ++Idx) {
1857       Value *Arg = CI.getArgOperand(Idx)->stripPointerCasts();
1858       if (isa<ConstantPointerNull>(Arg))
1859         continue; // Skip null pointers. They represent a hole in index space.
1860 
1861       int FI = getOrCreateFrameIndex(*cast<AllocaInst>(Arg));
1862       MCSymbol *FrameAllocSym =
1863           MF->getMMI().getContext().getOrCreateFrameAllocSymbol(EscapedName,
1864                                                                 Idx);
1865 
1866       // This should be inserted at the start of the entry block.
1867       auto LocalEscape =
1868           MIRBuilder.buildInstrNoInsert(TargetOpcode::LOCAL_ESCAPE)
1869               .addSym(FrameAllocSym)
1870               .addFrameIndex(FI);
1871 
1872       EntryMBB.insert(EntryMBB.begin(), LocalEscape);
1873     }
1874 
1875     return true;
1876   }
1877 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)  \
1878   case Intrinsic::INTRINSIC:
1879 #include "llvm/IR/ConstrainedOps.def"
1880     return translateConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(CI),
1881                                            MIRBuilder);
1882 
1883   }
1884   return false;
1885 }
1886 
1887 bool IRTranslator::translateInlineAsm(const CallBase &CB,
1888                                       MachineIRBuilder &MIRBuilder) {
1889 
1890   const InlineAsmLowering *ALI = MF->getSubtarget().getInlineAsmLowering();
1891 
1892   if (!ALI) {
1893     LLVM_DEBUG(
1894         dbgs() << "Inline asm lowering is not supported for this target yet\n");
1895     return false;
1896   }
1897 
1898   return ALI->lowerInlineAsm(
1899       MIRBuilder, CB, [&](const Value &Val) { return getOrCreateVRegs(Val); });
1900 }
1901 
1902 bool IRTranslator::translateCallBase(const CallBase &CB,
1903                                      MachineIRBuilder &MIRBuilder) {
1904   ArrayRef<Register> Res = getOrCreateVRegs(CB);
1905 
1906   SmallVector<ArrayRef<Register>, 8> Args;
1907   Register SwiftInVReg = 0;
1908   Register SwiftErrorVReg = 0;
1909   for (auto &Arg : CB.args()) {
1910     if (CLI->supportSwiftError() && isSwiftError(Arg)) {
1911       assert(SwiftInVReg == 0 && "Expected only one swift error argument");
1912       LLT Ty = getLLTForType(*Arg->getType(), *DL);
1913       SwiftInVReg = MRI->createGenericVirtualRegister(Ty);
1914       MIRBuilder.buildCopy(SwiftInVReg, SwiftError.getOrCreateVRegUseAt(
1915                                             &CB, &MIRBuilder.getMBB(), Arg));
1916       Args.emplace_back(makeArrayRef(SwiftInVReg));
1917       SwiftErrorVReg =
1918           SwiftError.getOrCreateVRegDefAt(&CB, &MIRBuilder.getMBB(), Arg);
1919       continue;
1920     }
1921     Args.push_back(getOrCreateVRegs(*Arg));
1922   }
1923 
1924   // We don't set HasCalls on MFI here yet because call lowering may decide to
1925   // optimize into tail calls. Instead, we defer that to selection where a final
1926   // scan is done to check if any instructions are calls.
1927   bool Success =
1928       CLI->lowerCall(MIRBuilder, CB, Res, Args, SwiftErrorVReg,
1929                      [&]() { return getOrCreateVReg(*CB.getCalledOperand()); });
1930 
1931   // Check if we just inserted a tail call.
1932   if (Success) {
1933     assert(!HasTailCall && "Can't tail call return twice from block?");
1934     const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1935     HasTailCall = TII->isTailCall(*std::prev(MIRBuilder.getInsertPt()));
1936   }
1937 
1938   return Success;
1939 }
1940 
1941 bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) {
1942   const CallInst &CI = cast<CallInst>(U);
1943   auto TII = MF->getTarget().getIntrinsicInfo();
1944   const Function *F = CI.getCalledFunction();
1945 
1946   // FIXME: support Windows dllimport function calls.
1947   if (F && (F->hasDLLImportStorageClass() ||
1948             (MF->getTarget().getTargetTriple().isOSWindows() &&
1949              F->hasExternalWeakLinkage())))
1950     return false;
1951 
1952   // FIXME: support control flow guard targets.
1953   if (CI.countOperandBundlesOfType(LLVMContext::OB_cfguardtarget))
1954     return false;
1955 
1956   if (CI.isInlineAsm())
1957     return translateInlineAsm(CI, MIRBuilder);
1958 
1959   Intrinsic::ID ID = Intrinsic::not_intrinsic;
1960   if (F && F->isIntrinsic()) {
1961     ID = F->getIntrinsicID();
1962     if (TII && ID == Intrinsic::not_intrinsic)
1963       ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F));
1964   }
1965 
1966   if (!F || !F->isIntrinsic() || ID == Intrinsic::not_intrinsic)
1967     return translateCallBase(CI, MIRBuilder);
1968 
1969   assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
1970 
1971   if (translateKnownIntrinsic(CI, ID, MIRBuilder))
1972     return true;
1973 
1974   ArrayRef<Register> ResultRegs;
1975   if (!CI.getType()->isVoidTy())
1976     ResultRegs = getOrCreateVRegs(CI);
1977 
1978   // Ignore the callsite attributes. Backend code is most likely not expecting
1979   // an intrinsic to sometimes have side effects and sometimes not.
1980   MachineInstrBuilder MIB =
1981       MIRBuilder.buildIntrinsic(ID, ResultRegs, !F->doesNotAccessMemory());
1982   if (isa<FPMathOperator>(CI))
1983     MIB->copyIRFlags(CI);
1984 
1985   for (auto &Arg : enumerate(CI.arg_operands())) {
1986     // If this is required to be an immediate, don't materialize it in a
1987     // register.
1988     if (CI.paramHasAttr(Arg.index(), Attribute::ImmArg)) {
1989       if (ConstantInt *CI = dyn_cast<ConstantInt>(Arg.value())) {
1990         // imm arguments are more convenient than cimm (and realistically
1991         // probably sufficient), so use them.
1992         assert(CI->getBitWidth() <= 64 &&
1993                "large intrinsic immediates not handled");
1994         MIB.addImm(CI->getSExtValue());
1995       } else {
1996         MIB.addFPImm(cast<ConstantFP>(Arg.value()));
1997       }
1998     } else if (auto MD = dyn_cast<MetadataAsValue>(Arg.value())) {
1999       auto *MDN = dyn_cast<MDNode>(MD->getMetadata());
2000       if (!MDN) // This was probably an MDString.
2001         return false;
2002       MIB.addMetadata(MDN);
2003     } else {
2004       ArrayRef<Register> VRegs = getOrCreateVRegs(*Arg.value());
2005       if (VRegs.size() > 1)
2006         return false;
2007       MIB.addUse(VRegs[0]);
2008     }
2009   }
2010 
2011   // Add a MachineMemOperand if it is a target mem intrinsic.
2012   const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
2013   TargetLowering::IntrinsicInfo Info;
2014   // TODO: Add a GlobalISel version of getTgtMemIntrinsic.
2015   if (TLI.getTgtMemIntrinsic(Info, CI, *MF, ID)) {
2016     Align Alignment = Info.align.getValueOr(
2017         DL->getABITypeAlign(Info.memVT.getTypeForEVT(F->getContext())));
2018 
2019     uint64_t Size = Info.memVT.getStoreSize();
2020     MIB.addMemOperand(MF->getMachineMemOperand(MachinePointerInfo(Info.ptrVal),
2021                                                Info.flags, Size, Alignment));
2022   }
2023 
2024   return true;
2025 }
2026 
2027 bool IRTranslator::translateInvoke(const User &U,
2028                                    MachineIRBuilder &MIRBuilder) {
2029   const InvokeInst &I = cast<InvokeInst>(U);
2030   MCContext &Context = MF->getContext();
2031 
2032   const BasicBlock *ReturnBB = I.getSuccessor(0);
2033   const BasicBlock *EHPadBB = I.getSuccessor(1);
2034 
2035   const Function *Fn = I.getCalledFunction();
2036   if (I.isInlineAsm())
2037     return false;
2038 
2039   // FIXME: support invoking patchpoint and statepoint intrinsics.
2040   if (Fn && Fn->isIntrinsic())
2041     return false;
2042 
2043   // FIXME: support whatever these are.
2044   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
2045     return false;
2046 
2047   // FIXME: support control flow guard targets.
2048   if (I.countOperandBundlesOfType(LLVMContext::OB_cfguardtarget))
2049     return false;
2050 
2051   // FIXME: support Windows exception handling.
2052   if (!isa<LandingPadInst>(EHPadBB->getFirstNonPHI()))
2053     return false;
2054 
2055   // Emit the actual call, bracketed by EH_LABELs so that the MF knows about
2056   // the region covered by the try.
2057   MCSymbol *BeginSymbol = Context.createTempSymbol();
2058   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol);
2059 
2060   if (!translateCallBase(I, MIRBuilder))
2061     return false;
2062 
2063   MCSymbol *EndSymbol = Context.createTempSymbol();
2064   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol);
2065 
2066   // FIXME: track probabilities.
2067   MachineBasicBlock &EHPadMBB = getMBB(*EHPadBB),
2068                     &ReturnMBB = getMBB(*ReturnBB);
2069   MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
2070   MIRBuilder.getMBB().addSuccessor(&ReturnMBB);
2071   MIRBuilder.getMBB().addSuccessor(&EHPadMBB);
2072   MIRBuilder.buildBr(ReturnMBB);
2073 
2074   return true;
2075 }
2076 
2077 bool IRTranslator::translateCallBr(const User &U,
2078                                    MachineIRBuilder &MIRBuilder) {
2079   // FIXME: Implement this.
2080   return false;
2081 }
2082 
2083 bool IRTranslator::translateLandingPad(const User &U,
2084                                        MachineIRBuilder &MIRBuilder) {
2085   const LandingPadInst &LP = cast<LandingPadInst>(U);
2086 
2087   MachineBasicBlock &MBB = MIRBuilder.getMBB();
2088 
2089   MBB.setIsEHPad();
2090 
2091   // If there aren't registers to copy the values into (e.g., during SjLj
2092   // exceptions), then don't bother.
2093   auto &TLI = *MF->getSubtarget().getTargetLowering();
2094   const Constant *PersonalityFn = MF->getFunction().getPersonalityFn();
2095   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2096       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2097     return true;
2098 
2099   // If landingpad's return type is token type, we don't create DAG nodes
2100   // for its exception pointer and selector value. The extraction of exception
2101   // pointer or selector value from token type landingpads is not currently
2102   // supported.
2103   if (LP.getType()->isTokenTy())
2104     return true;
2105 
2106   // Add a label to mark the beginning of the landing pad.  Deletion of the
2107   // landing pad can thus be detected via the MachineModuleInfo.
2108   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL)
2109     .addSym(MF->addLandingPad(&MBB));
2110 
2111   // If the unwinder does not preserve all registers, ensure that the
2112   // function marks the clobbered registers as used.
2113   const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
2114   if (auto *RegMask = TRI.getCustomEHPadPreservedMask(*MF))
2115     MF->getRegInfo().addPhysRegsUsedFromRegMask(RegMask);
2116 
2117   LLT Ty = getLLTForType(*LP.getType(), *DL);
2118   Register Undef = MRI->createGenericVirtualRegister(Ty);
2119   MIRBuilder.buildUndef(Undef);
2120 
2121   SmallVector<LLT, 2> Tys;
2122   for (Type *Ty : cast<StructType>(LP.getType())->elements())
2123     Tys.push_back(getLLTForType(*Ty, *DL));
2124   assert(Tys.size() == 2 && "Only two-valued landingpads are supported");
2125 
2126   // Mark exception register as live in.
2127   Register ExceptionReg = TLI.getExceptionPointerRegister(PersonalityFn);
2128   if (!ExceptionReg)
2129     return false;
2130 
2131   MBB.addLiveIn(ExceptionReg);
2132   ArrayRef<Register> ResRegs = getOrCreateVRegs(LP);
2133   MIRBuilder.buildCopy(ResRegs[0], ExceptionReg);
2134 
2135   Register SelectorReg = TLI.getExceptionSelectorRegister(PersonalityFn);
2136   if (!SelectorReg)
2137     return false;
2138 
2139   MBB.addLiveIn(SelectorReg);
2140   Register PtrVReg = MRI->createGenericVirtualRegister(Tys[0]);
2141   MIRBuilder.buildCopy(PtrVReg, SelectorReg);
2142   MIRBuilder.buildCast(ResRegs[1], PtrVReg);
2143 
2144   return true;
2145 }
2146 
2147 bool IRTranslator::translateAlloca(const User &U,
2148                                    MachineIRBuilder &MIRBuilder) {
2149   auto &AI = cast<AllocaInst>(U);
2150 
2151   if (AI.isSwiftError())
2152     return true;
2153 
2154   if (AI.isStaticAlloca()) {
2155     Register Res = getOrCreateVReg(AI);
2156     int FI = getOrCreateFrameIndex(AI);
2157     MIRBuilder.buildFrameIndex(Res, FI);
2158     return true;
2159   }
2160 
2161   // FIXME: support stack probing for Windows.
2162   if (MF->getTarget().getTargetTriple().isOSWindows())
2163     return false;
2164 
2165   // Now we're in the harder dynamic case.
2166   Register NumElts = getOrCreateVReg(*AI.getArraySize());
2167   Type *IntPtrIRTy = DL->getIntPtrType(AI.getType());
2168   LLT IntPtrTy = getLLTForType(*IntPtrIRTy, *DL);
2169   if (MRI->getType(NumElts) != IntPtrTy) {
2170     Register ExtElts = MRI->createGenericVirtualRegister(IntPtrTy);
2171     MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts);
2172     NumElts = ExtElts;
2173   }
2174 
2175   Type *Ty = AI.getAllocatedType();
2176 
2177   Register AllocSize = MRI->createGenericVirtualRegister(IntPtrTy);
2178   Register TySize =
2179       getOrCreateVReg(*ConstantInt::get(IntPtrIRTy, DL->getTypeAllocSize(Ty)));
2180   MIRBuilder.buildMul(AllocSize, NumElts, TySize);
2181 
2182   // Round the size of the allocation up to the stack alignment size
2183   // by add SA-1 to the size. This doesn't overflow because we're computing
2184   // an address inside an alloca.
2185   Align StackAlign = MF->getSubtarget().getFrameLowering()->getStackAlign();
2186   auto SAMinusOne = MIRBuilder.buildConstant(IntPtrTy, StackAlign.value() - 1);
2187   auto AllocAdd = MIRBuilder.buildAdd(IntPtrTy, AllocSize, SAMinusOne,
2188                                       MachineInstr::NoUWrap);
2189   auto AlignCst =
2190       MIRBuilder.buildConstant(IntPtrTy, ~(uint64_t)(StackAlign.value() - 1));
2191   auto AlignedAlloc = MIRBuilder.buildAnd(IntPtrTy, AllocAdd, AlignCst);
2192 
2193   Align Alignment = std::max(AI.getAlign(), DL->getPrefTypeAlign(Ty));
2194   if (Alignment <= StackAlign)
2195     Alignment = Align(1);
2196   MIRBuilder.buildDynStackAlloc(getOrCreateVReg(AI), AlignedAlloc, Alignment);
2197 
2198   MF->getFrameInfo().CreateVariableSizedObject(Alignment, &AI);
2199   assert(MF->getFrameInfo().hasVarSizedObjects());
2200   return true;
2201 }
2202 
2203 bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) {
2204   // FIXME: We may need more info about the type. Because of how LLT works,
2205   // we're completely discarding the i64/double distinction here (amongst
2206   // others). Fortunately the ABIs I know of where that matters don't use va_arg
2207   // anyway but that's not guaranteed.
2208   MIRBuilder.buildInstr(TargetOpcode::G_VAARG, {getOrCreateVReg(U)},
2209                         {getOrCreateVReg(*U.getOperand(0)),
2210                          DL->getABITypeAlign(U.getType()).value()});
2211   return true;
2212 }
2213 
2214 bool IRTranslator::translateInsertElement(const User &U,
2215                                           MachineIRBuilder &MIRBuilder) {
2216   // If it is a <1 x Ty> vector, use the scalar as it is
2217   // not a legal vector type in LLT.
2218   if (cast<FixedVectorType>(U.getType())->getNumElements() == 1)
2219     return translateCopy(U, *U.getOperand(1), MIRBuilder);
2220 
2221   Register Res = getOrCreateVReg(U);
2222   Register Val = getOrCreateVReg(*U.getOperand(0));
2223   Register Elt = getOrCreateVReg(*U.getOperand(1));
2224   Register Idx = getOrCreateVReg(*U.getOperand(2));
2225   MIRBuilder.buildInsertVectorElement(Res, Val, Elt, Idx);
2226   return true;
2227 }
2228 
2229 bool IRTranslator::translateExtractElement(const User &U,
2230                                            MachineIRBuilder &MIRBuilder) {
2231   // If it is a <1 x Ty> vector, use the scalar as it is
2232   // not a legal vector type in LLT.
2233   if (cast<FixedVectorType>(U.getOperand(0)->getType())->getNumElements() == 1)
2234     return translateCopy(U, *U.getOperand(0), MIRBuilder);
2235 
2236   Register Res = getOrCreateVReg(U);
2237   Register Val = getOrCreateVReg(*U.getOperand(0));
2238   const auto &TLI = *MF->getSubtarget().getTargetLowering();
2239   unsigned PreferredVecIdxWidth = TLI.getVectorIdxTy(*DL).getSizeInBits();
2240   Register Idx;
2241   if (auto *CI = dyn_cast<ConstantInt>(U.getOperand(1))) {
2242     if (CI->getBitWidth() != PreferredVecIdxWidth) {
2243       APInt NewIdx = CI->getValue().sextOrTrunc(PreferredVecIdxWidth);
2244       auto *NewIdxCI = ConstantInt::get(CI->getContext(), NewIdx);
2245       Idx = getOrCreateVReg(*NewIdxCI);
2246     }
2247   }
2248   if (!Idx)
2249     Idx = getOrCreateVReg(*U.getOperand(1));
2250   if (MRI->getType(Idx).getSizeInBits() != PreferredVecIdxWidth) {
2251     const LLT VecIdxTy = LLT::scalar(PreferredVecIdxWidth);
2252     Idx = MIRBuilder.buildSExtOrTrunc(VecIdxTy, Idx).getReg(0);
2253   }
2254   MIRBuilder.buildExtractVectorElement(Res, Val, Idx);
2255   return true;
2256 }
2257 
2258 bool IRTranslator::translateShuffleVector(const User &U,
2259                                           MachineIRBuilder &MIRBuilder) {
2260   ArrayRef<int> Mask;
2261   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&U))
2262     Mask = SVI->getShuffleMask();
2263   else
2264     Mask = cast<ConstantExpr>(U).getShuffleMask();
2265   ArrayRef<int> MaskAlloc = MF->allocateShuffleMask(Mask);
2266   MIRBuilder
2267       .buildInstr(TargetOpcode::G_SHUFFLE_VECTOR, {getOrCreateVReg(U)},
2268                   {getOrCreateVReg(*U.getOperand(0)),
2269                    getOrCreateVReg(*U.getOperand(1))})
2270       .addShuffleMask(MaskAlloc);
2271   return true;
2272 }
2273 
2274 bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) {
2275   const PHINode &PI = cast<PHINode>(U);
2276 
2277   SmallVector<MachineInstr *, 4> Insts;
2278   for (auto Reg : getOrCreateVRegs(PI)) {
2279     auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_PHI, {Reg}, {});
2280     Insts.push_back(MIB.getInstr());
2281   }
2282 
2283   PendingPHIs.emplace_back(&PI, std::move(Insts));
2284   return true;
2285 }
2286 
2287 bool IRTranslator::translateAtomicCmpXchg(const User &U,
2288                                           MachineIRBuilder &MIRBuilder) {
2289   const AtomicCmpXchgInst &I = cast<AtomicCmpXchgInst>(U);
2290 
2291   auto &TLI = *MF->getSubtarget().getTargetLowering();
2292   auto Flags = TLI.getAtomicMemOperandFlags(I, *DL);
2293 
2294   Type *ResType = I.getType();
2295   Type *ValType = ResType->Type::getStructElementType(0);
2296 
2297   auto Res = getOrCreateVRegs(I);
2298   Register OldValRes = Res[0];
2299   Register SuccessRes = Res[1];
2300   Register Addr = getOrCreateVReg(*I.getPointerOperand());
2301   Register Cmp = getOrCreateVReg(*I.getCompareOperand());
2302   Register NewVal = getOrCreateVReg(*I.getNewValOperand());
2303 
2304   AAMDNodes AAMetadata;
2305   I.getAAMetadata(AAMetadata);
2306 
2307   MIRBuilder.buildAtomicCmpXchgWithSuccess(
2308       OldValRes, SuccessRes, Addr, Cmp, NewVal,
2309       *MF->getMachineMemOperand(
2310           MachinePointerInfo(I.getPointerOperand()), Flags,
2311           DL->getTypeStoreSize(ValType), getMemOpAlign(I), AAMetadata, nullptr,
2312           I.getSyncScopeID(), I.getSuccessOrdering(), I.getFailureOrdering()));
2313   return true;
2314 }
2315 
2316 bool IRTranslator::translateAtomicRMW(const User &U,
2317                                       MachineIRBuilder &MIRBuilder) {
2318   const AtomicRMWInst &I = cast<AtomicRMWInst>(U);
2319   auto &TLI = *MF->getSubtarget().getTargetLowering();
2320   auto Flags = TLI.getAtomicMemOperandFlags(I, *DL);
2321 
2322   Type *ResType = I.getType();
2323 
2324   Register Res = getOrCreateVReg(I);
2325   Register Addr = getOrCreateVReg(*I.getPointerOperand());
2326   Register Val = getOrCreateVReg(*I.getValOperand());
2327 
2328   unsigned Opcode = 0;
2329   switch (I.getOperation()) {
2330   default:
2331     return false;
2332   case AtomicRMWInst::Xchg:
2333     Opcode = TargetOpcode::G_ATOMICRMW_XCHG;
2334     break;
2335   case AtomicRMWInst::Add:
2336     Opcode = TargetOpcode::G_ATOMICRMW_ADD;
2337     break;
2338   case AtomicRMWInst::Sub:
2339     Opcode = TargetOpcode::G_ATOMICRMW_SUB;
2340     break;
2341   case AtomicRMWInst::And:
2342     Opcode = TargetOpcode::G_ATOMICRMW_AND;
2343     break;
2344   case AtomicRMWInst::Nand:
2345     Opcode = TargetOpcode::G_ATOMICRMW_NAND;
2346     break;
2347   case AtomicRMWInst::Or:
2348     Opcode = TargetOpcode::G_ATOMICRMW_OR;
2349     break;
2350   case AtomicRMWInst::Xor:
2351     Opcode = TargetOpcode::G_ATOMICRMW_XOR;
2352     break;
2353   case AtomicRMWInst::Max:
2354     Opcode = TargetOpcode::G_ATOMICRMW_MAX;
2355     break;
2356   case AtomicRMWInst::Min:
2357     Opcode = TargetOpcode::G_ATOMICRMW_MIN;
2358     break;
2359   case AtomicRMWInst::UMax:
2360     Opcode = TargetOpcode::G_ATOMICRMW_UMAX;
2361     break;
2362   case AtomicRMWInst::UMin:
2363     Opcode = TargetOpcode::G_ATOMICRMW_UMIN;
2364     break;
2365   case AtomicRMWInst::FAdd:
2366     Opcode = TargetOpcode::G_ATOMICRMW_FADD;
2367     break;
2368   case AtomicRMWInst::FSub:
2369     Opcode = TargetOpcode::G_ATOMICRMW_FSUB;
2370     break;
2371   }
2372 
2373   AAMDNodes AAMetadata;
2374   I.getAAMetadata(AAMetadata);
2375 
2376   MIRBuilder.buildAtomicRMW(
2377       Opcode, Res, Addr, Val,
2378       *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
2379                                 Flags, DL->getTypeStoreSize(ResType),
2380                                 getMemOpAlign(I), AAMetadata, nullptr,
2381                                 I.getSyncScopeID(), I.getOrdering()));
2382   return true;
2383 }
2384 
2385 bool IRTranslator::translateFence(const User &U,
2386                                   MachineIRBuilder &MIRBuilder) {
2387   const FenceInst &Fence = cast<FenceInst>(U);
2388   MIRBuilder.buildFence(static_cast<unsigned>(Fence.getOrdering()),
2389                         Fence.getSyncScopeID());
2390   return true;
2391 }
2392 
2393 bool IRTranslator::translateFreeze(const User &U,
2394                                    MachineIRBuilder &MIRBuilder) {
2395   const ArrayRef<Register> DstRegs = getOrCreateVRegs(U);
2396   const ArrayRef<Register> SrcRegs = getOrCreateVRegs(*U.getOperand(0));
2397 
2398   assert(DstRegs.size() == SrcRegs.size() &&
2399          "Freeze with different source and destination type?");
2400 
2401   for (unsigned I = 0; I < DstRegs.size(); ++I) {
2402     MIRBuilder.buildFreeze(DstRegs[I], SrcRegs[I]);
2403   }
2404 
2405   return true;
2406 }
2407 
2408 void IRTranslator::finishPendingPhis() {
2409 #ifndef NDEBUG
2410   DILocationVerifier Verifier;
2411   GISelObserverWrapper WrapperObserver(&Verifier);
2412   RAIIDelegateInstaller DelInstall(*MF, &WrapperObserver);
2413 #endif // ifndef NDEBUG
2414   for (auto &Phi : PendingPHIs) {
2415     const PHINode *PI = Phi.first;
2416     ArrayRef<MachineInstr *> ComponentPHIs = Phi.second;
2417     MachineBasicBlock *PhiMBB = ComponentPHIs[0]->getParent();
2418     EntryBuilder->setDebugLoc(PI->getDebugLoc());
2419 #ifndef NDEBUG
2420     Verifier.setCurrentInst(PI);
2421 #endif // ifndef NDEBUG
2422 
2423     SmallSet<const MachineBasicBlock *, 16> SeenPreds;
2424     for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
2425       auto IRPred = PI->getIncomingBlock(i);
2426       ArrayRef<Register> ValRegs = getOrCreateVRegs(*PI->getIncomingValue(i));
2427       for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) {
2428         if (SeenPreds.count(Pred) || !PhiMBB->isPredecessor(Pred))
2429           continue;
2430         SeenPreds.insert(Pred);
2431         for (unsigned j = 0; j < ValRegs.size(); ++j) {
2432           MachineInstrBuilder MIB(*MF, ComponentPHIs[j]);
2433           MIB.addUse(ValRegs[j]);
2434           MIB.addMBB(Pred);
2435         }
2436       }
2437     }
2438   }
2439 }
2440 
2441 bool IRTranslator::valueIsSplit(const Value &V,
2442                                 SmallVectorImpl<uint64_t> *Offsets) {
2443   SmallVector<LLT, 4> SplitTys;
2444   if (Offsets && !Offsets->empty())
2445     Offsets->clear();
2446   computeValueLLTs(*DL, *V.getType(), SplitTys, Offsets);
2447   return SplitTys.size() > 1;
2448 }
2449 
2450 bool IRTranslator::translate(const Instruction &Inst) {
2451   CurBuilder->setDebugLoc(Inst.getDebugLoc());
2452   // We only emit constants into the entry block from here. To prevent jumpy
2453   // debug behaviour set the line to 0.
2454   if (const DebugLoc &DL = Inst.getDebugLoc())
2455     EntryBuilder->setDebugLoc(
2456         DebugLoc::get(0, 0, DL.getScope(), DL.getInlinedAt()));
2457   else
2458     EntryBuilder->setDebugLoc(DebugLoc());
2459 
2460   auto &TLI = *MF->getSubtarget().getTargetLowering();
2461   if (TLI.fallBackToDAGISel(Inst))
2462     return false;
2463 
2464   switch (Inst.getOpcode()) {
2465 #define HANDLE_INST(NUM, OPCODE, CLASS)                                        \
2466   case Instruction::OPCODE:                                                    \
2467     return translate##OPCODE(Inst, *CurBuilder.get());
2468 #include "llvm/IR/Instruction.def"
2469   default:
2470     return false;
2471   }
2472 }
2473 
2474 bool IRTranslator::translate(const Constant &C, Register Reg) {
2475   if (auto CI = dyn_cast<ConstantInt>(&C))
2476     EntryBuilder->buildConstant(Reg, *CI);
2477   else if (auto CF = dyn_cast<ConstantFP>(&C))
2478     EntryBuilder->buildFConstant(Reg, *CF);
2479   else if (isa<UndefValue>(C))
2480     EntryBuilder->buildUndef(Reg);
2481   else if (isa<ConstantPointerNull>(C))
2482     EntryBuilder->buildConstant(Reg, 0);
2483   else if (auto GV = dyn_cast<GlobalValue>(&C))
2484     EntryBuilder->buildGlobalValue(Reg, GV);
2485   else if (auto CAZ = dyn_cast<ConstantAggregateZero>(&C)) {
2486     if (!CAZ->getType()->isVectorTy())
2487       return false;
2488     // Return the scalar if it is a <1 x Ty> vector.
2489     if (CAZ->getNumElements() == 1)
2490       return translateCopy(C, *CAZ->getElementValue(0u), *EntryBuilder.get());
2491     SmallVector<Register, 4> Ops;
2492     for (unsigned i = 0; i < CAZ->getNumElements(); ++i) {
2493       Constant &Elt = *CAZ->getElementValue(i);
2494       Ops.push_back(getOrCreateVReg(Elt));
2495     }
2496     EntryBuilder->buildBuildVector(Reg, Ops);
2497   } else if (auto CV = dyn_cast<ConstantDataVector>(&C)) {
2498     // Return the scalar if it is a <1 x Ty> vector.
2499     if (CV->getNumElements() == 1)
2500       return translateCopy(C, *CV->getElementAsConstant(0),
2501                            *EntryBuilder.get());
2502     SmallVector<Register, 4> Ops;
2503     for (unsigned i = 0; i < CV->getNumElements(); ++i) {
2504       Constant &Elt = *CV->getElementAsConstant(i);
2505       Ops.push_back(getOrCreateVReg(Elt));
2506     }
2507     EntryBuilder->buildBuildVector(Reg, Ops);
2508   } else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
2509     switch(CE->getOpcode()) {
2510 #define HANDLE_INST(NUM, OPCODE, CLASS)                                        \
2511   case Instruction::OPCODE:                                                    \
2512     return translate##OPCODE(*CE, *EntryBuilder.get());
2513 #include "llvm/IR/Instruction.def"
2514     default:
2515       return false;
2516     }
2517   } else if (auto CV = dyn_cast<ConstantVector>(&C)) {
2518     if (CV->getNumOperands() == 1)
2519       return translateCopy(C, *CV->getOperand(0), *EntryBuilder.get());
2520     SmallVector<Register, 4> Ops;
2521     for (unsigned i = 0; i < CV->getNumOperands(); ++i) {
2522       Ops.push_back(getOrCreateVReg(*CV->getOperand(i)));
2523     }
2524     EntryBuilder->buildBuildVector(Reg, Ops);
2525   } else if (auto *BA = dyn_cast<BlockAddress>(&C)) {
2526     EntryBuilder->buildBlockAddress(Reg, BA);
2527   } else
2528     return false;
2529 
2530   return true;
2531 }
2532 
2533 void IRTranslator::finalizeBasicBlock() {
2534   for (auto &BTB : SL->BitTestCases) {
2535     // Emit header first, if it wasn't already emitted.
2536     if (!BTB.Emitted)
2537       emitBitTestHeader(BTB, BTB.Parent);
2538 
2539     BranchProbability UnhandledProb = BTB.Prob;
2540     for (unsigned j = 0, ej = BTB.Cases.size(); j != ej; ++j) {
2541       UnhandledProb -= BTB.Cases[j].ExtraProb;
2542       // Set the current basic block to the mbb we wish to insert the code into
2543       MachineBasicBlock *MBB = BTB.Cases[j].ThisBB;
2544       // If all cases cover a contiguous range, it is not necessary to jump to
2545       // the default block after the last bit test fails. This is because the
2546       // range check during bit test header creation has guaranteed that every
2547       // case here doesn't go outside the range. In this case, there is no need
2548       // to perform the last bit test, as it will always be true. Instead, make
2549       // the second-to-last bit-test fall through to the target of the last bit
2550       // test, and delete the last bit test.
2551 
2552       MachineBasicBlock *NextMBB;
2553       if (BTB.ContiguousRange && j + 2 == ej) {
2554         // Second-to-last bit-test with contiguous range: fall through to the
2555         // target of the final bit test.
2556         NextMBB = BTB.Cases[j + 1].TargetBB;
2557       } else if (j + 1 == ej) {
2558         // For the last bit test, fall through to Default.
2559         NextMBB = BTB.Default;
2560       } else {
2561         // Otherwise, fall through to the next bit test.
2562         NextMBB = BTB.Cases[j + 1].ThisBB;
2563       }
2564 
2565       emitBitTestCase(BTB, NextMBB, UnhandledProb, BTB.Reg, BTB.Cases[j], MBB);
2566 
2567       // FIXME delete this block below?
2568       if (BTB.ContiguousRange && j + 2 == ej) {
2569         // Since we're not going to use the final bit test, remove it.
2570         BTB.Cases.pop_back();
2571         break;
2572       }
2573     }
2574     // This is "default" BB. We have two jumps to it. From "header" BB and from
2575     // last "case" BB, unless the latter was skipped.
2576     CFGEdge HeaderToDefaultEdge = {BTB.Parent->getBasicBlock(),
2577                                    BTB.Default->getBasicBlock()};
2578     addMachineCFGPred(HeaderToDefaultEdge, BTB.Parent);
2579     if (!BTB.ContiguousRange) {
2580       addMachineCFGPred(HeaderToDefaultEdge, BTB.Cases.back().ThisBB);
2581     }
2582   }
2583   SL->BitTestCases.clear();
2584 
2585   for (auto &JTCase : SL->JTCases) {
2586     // Emit header first, if it wasn't already emitted.
2587     if (!JTCase.first.Emitted)
2588       emitJumpTableHeader(JTCase.second, JTCase.first, JTCase.first.HeaderBB);
2589 
2590     emitJumpTable(JTCase.second, JTCase.second.MBB);
2591   }
2592   SL->JTCases.clear();
2593 }
2594 
2595 void IRTranslator::finalizeFunction() {
2596   // Release the memory used by the different maps we
2597   // needed during the translation.
2598   PendingPHIs.clear();
2599   VMap.reset();
2600   FrameIndices.clear();
2601   MachinePreds.clear();
2602   // MachineIRBuilder::DebugLoc can outlive the DILocation it holds. Clear it
2603   // to avoid accessing free’d memory (in runOnMachineFunction) and to avoid
2604   // destroying it twice (in ~IRTranslator() and ~LLVMContext())
2605   EntryBuilder.reset();
2606   CurBuilder.reset();
2607   FuncInfo.clear();
2608 }
2609 
2610 /// Returns true if a BasicBlock \p BB within a variadic function contains a
2611 /// variadic musttail call.
2612 static bool checkForMustTailInVarArgFn(bool IsVarArg, const BasicBlock &BB) {
2613   if (!IsVarArg)
2614     return false;
2615 
2616   // Walk the block backwards, because tail calls usually only appear at the end
2617   // of a block.
2618   return std::any_of(BB.rbegin(), BB.rend(), [](const Instruction &I) {
2619     const auto *CI = dyn_cast<CallInst>(&I);
2620     return CI && CI->isMustTailCall();
2621   });
2622 }
2623 
2624 bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) {
2625   MF = &CurMF;
2626   const Function &F = MF->getFunction();
2627   if (F.empty())
2628     return false;
2629   GISelCSEAnalysisWrapper &Wrapper =
2630       getAnalysis<GISelCSEAnalysisWrapperPass>().getCSEWrapper();
2631   // Set the CSEConfig and run the analysis.
2632   GISelCSEInfo *CSEInfo = nullptr;
2633   TPC = &getAnalysis<TargetPassConfig>();
2634   bool EnableCSE = EnableCSEInIRTranslator.getNumOccurrences()
2635                        ? EnableCSEInIRTranslator
2636                        : TPC->isGISelCSEEnabled();
2637 
2638   if (EnableCSE) {
2639     EntryBuilder = std::make_unique<CSEMIRBuilder>(CurMF);
2640     CSEInfo = &Wrapper.get(TPC->getCSEConfig());
2641     EntryBuilder->setCSEInfo(CSEInfo);
2642     CurBuilder = std::make_unique<CSEMIRBuilder>(CurMF);
2643     CurBuilder->setCSEInfo(CSEInfo);
2644   } else {
2645     EntryBuilder = std::make_unique<MachineIRBuilder>();
2646     CurBuilder = std::make_unique<MachineIRBuilder>();
2647   }
2648   CLI = MF->getSubtarget().getCallLowering();
2649   CurBuilder->setMF(*MF);
2650   EntryBuilder->setMF(*MF);
2651   MRI = &MF->getRegInfo();
2652   DL = &F.getParent()->getDataLayout();
2653   ORE = std::make_unique<OptimizationRemarkEmitter>(&F);
2654   FuncInfo.MF = MF;
2655   FuncInfo.BPI = nullptr;
2656   const auto &TLI = *MF->getSubtarget().getTargetLowering();
2657   const TargetMachine &TM = MF->getTarget();
2658   SL = std::make_unique<GISelSwitchLowering>(this, FuncInfo);
2659   SL->init(TLI, TM, *DL);
2660 
2661   EnableOpts = TM.getOptLevel() != CodeGenOpt::None && !skipFunction(F);
2662 
2663   assert(PendingPHIs.empty() && "stale PHIs");
2664 
2665   if (!DL->isLittleEndian()) {
2666     // Currently we don't properly handle big endian code.
2667     OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
2668                                F.getSubprogram(), &F.getEntryBlock());
2669     R << "unable to translate in big endian mode";
2670     reportTranslationError(*MF, *TPC, *ORE, R);
2671   }
2672 
2673   // Release the per-function state when we return, whether we succeeded or not.
2674   auto FinalizeOnReturn = make_scope_exit([this]() { finalizeFunction(); });
2675 
2676   // Setup a separate basic-block for the arguments and constants
2677   MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock();
2678   MF->push_back(EntryBB);
2679   EntryBuilder->setMBB(*EntryBB);
2680 
2681   DebugLoc DbgLoc = F.getEntryBlock().getFirstNonPHI()->getDebugLoc();
2682   SwiftError.setFunction(CurMF);
2683   SwiftError.createEntriesInEntryBlock(DbgLoc);
2684 
2685   bool IsVarArg = F.isVarArg();
2686   bool HasMustTailInVarArgFn = false;
2687 
2688   // Create all blocks, in IR order, to preserve the layout.
2689   for (const BasicBlock &BB: F) {
2690     auto *&MBB = BBToMBB[&BB];
2691 
2692     MBB = MF->CreateMachineBasicBlock(&BB);
2693     MF->push_back(MBB);
2694 
2695     if (BB.hasAddressTaken())
2696       MBB->setHasAddressTaken();
2697 
2698     if (!HasMustTailInVarArgFn)
2699       HasMustTailInVarArgFn = checkForMustTailInVarArgFn(IsVarArg, BB);
2700   }
2701 
2702   MF->getFrameInfo().setHasMustTailInVarArgFunc(HasMustTailInVarArgFn);
2703 
2704   // Make our arguments/constants entry block fallthrough to the IR entry block.
2705   EntryBB->addSuccessor(&getMBB(F.front()));
2706 
2707   if (CLI->fallBackToDAGISel(F)) {
2708     OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
2709                                F.getSubprogram(), &F.getEntryBlock());
2710     R << "unable to lower function: " << ore::NV("Prototype", F.getType());
2711     reportTranslationError(*MF, *TPC, *ORE, R);
2712     return false;
2713   }
2714 
2715   // Lower the actual args into this basic block.
2716   SmallVector<ArrayRef<Register>, 8> VRegArgs;
2717   for (const Argument &Arg: F.args()) {
2718     if (DL->getTypeStoreSize(Arg.getType()).isZero())
2719       continue; // Don't handle zero sized types.
2720     ArrayRef<Register> VRegs = getOrCreateVRegs(Arg);
2721     VRegArgs.push_back(VRegs);
2722 
2723     if (Arg.hasSwiftErrorAttr()) {
2724       assert(VRegs.size() == 1 && "Too many vregs for Swift error");
2725       SwiftError.setCurrentVReg(EntryBB, SwiftError.getFunctionArg(), VRegs[0]);
2726     }
2727   }
2728 
2729   if (!CLI->lowerFormalArguments(*EntryBuilder.get(), F, VRegArgs)) {
2730     OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
2731                                F.getSubprogram(), &F.getEntryBlock());
2732     R << "unable to lower arguments: " << ore::NV("Prototype", F.getType());
2733     reportTranslationError(*MF, *TPC, *ORE, R);
2734     return false;
2735   }
2736 
2737   // Need to visit defs before uses when translating instructions.
2738   GISelObserverWrapper WrapperObserver;
2739   if (EnableCSE && CSEInfo)
2740     WrapperObserver.addObserver(CSEInfo);
2741   {
2742     ReversePostOrderTraversal<const Function *> RPOT(&F);
2743 #ifndef NDEBUG
2744     DILocationVerifier Verifier;
2745     WrapperObserver.addObserver(&Verifier);
2746 #endif // ifndef NDEBUG
2747     RAIIDelegateInstaller DelInstall(*MF, &WrapperObserver);
2748     RAIIMFObserverInstaller ObsInstall(*MF, WrapperObserver);
2749     for (const BasicBlock *BB : RPOT) {
2750       MachineBasicBlock &MBB = getMBB(*BB);
2751       // Set the insertion point of all the following translations to
2752       // the end of this basic block.
2753       CurBuilder->setMBB(MBB);
2754       HasTailCall = false;
2755       for (const Instruction &Inst : *BB) {
2756         // If we translated a tail call in the last step, then we know
2757         // everything after the call is either a return, or something that is
2758         // handled by the call itself. (E.g. a lifetime marker or assume
2759         // intrinsic.) In this case, we should stop translating the block and
2760         // move on.
2761         if (HasTailCall)
2762           break;
2763 #ifndef NDEBUG
2764         Verifier.setCurrentInst(&Inst);
2765 #endif // ifndef NDEBUG
2766         if (translate(Inst))
2767           continue;
2768 
2769         OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
2770                                    Inst.getDebugLoc(), BB);
2771         R << "unable to translate instruction: " << ore::NV("Opcode", &Inst);
2772 
2773         if (ORE->allowExtraAnalysis("gisel-irtranslator")) {
2774           std::string InstStrStorage;
2775           raw_string_ostream InstStr(InstStrStorage);
2776           InstStr << Inst;
2777 
2778           R << ": '" << InstStr.str() << "'";
2779         }
2780 
2781         reportTranslationError(*MF, *TPC, *ORE, R);
2782         return false;
2783       }
2784 
2785       finalizeBasicBlock();
2786     }
2787 #ifndef NDEBUG
2788     WrapperObserver.removeObserver(&Verifier);
2789 #endif
2790   }
2791 
2792   finishPendingPhis();
2793 
2794   SwiftError.propagateVRegs();
2795 
2796   // Merge the argument lowering and constants block with its single
2797   // successor, the LLVM-IR entry block.  We want the basic block to
2798   // be maximal.
2799   assert(EntryBB->succ_size() == 1 &&
2800          "Custom BB used for lowering should have only one successor");
2801   // Get the successor of the current entry block.
2802   MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin();
2803   assert(NewEntryBB.pred_size() == 1 &&
2804          "LLVM-IR entry block has a predecessor!?");
2805   // Move all the instruction from the current entry block to the
2806   // new entry block.
2807   NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(),
2808                     EntryBB->end());
2809 
2810   // Update the live-in information for the new entry block.
2811   for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins())
2812     NewEntryBB.addLiveIn(LiveIn);
2813   NewEntryBB.sortUniqueLiveIns();
2814 
2815   // Get rid of the now empty basic block.
2816   EntryBB->removeSuccessor(&NewEntryBB);
2817   MF->remove(EntryBB);
2818   MF->DeleteMachineBasicBlock(EntryBB);
2819 
2820   assert(&MF->front() == &NewEntryBB &&
2821          "New entry wasn't next in the list of basic block!");
2822 
2823   // Initialize stack protector information.
2824   StackProtector &SP = getAnalysis<StackProtector>();
2825   SP.copyToMachineFrameInfo(MF->getFrameInfo());
2826 
2827   return false;
2828 }
2829