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