1 //===- llvm/CodeGen/GlobalISel/IRTranslator.cpp - IRTranslator ---*- C++ -*-==//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 /// \file
9 /// This file implements the IRTranslator class.
10 //===----------------------------------------------------------------------===//
11 
12 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
13 #include "llvm/ADT/PostOrderIterator.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/ADT/ScopeExit.h"
16 #include "llvm/ADT/SmallSet.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/Analysis/BranchProbabilityInfo.h"
19 #include "llvm/Analysis/Loads.h"
20 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/CodeGen/Analysis.h"
23 #include "llvm/CodeGen/GlobalISel/CallLowering.h"
24 #include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h"
25 #include "llvm/CodeGen/GlobalISel/InlineAsmLowering.h"
26 #include "llvm/CodeGen/LowLevelType.h"
27 #include "llvm/CodeGen/MachineBasicBlock.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineMemOperand.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineOperand.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/StackProtector.h"
36 #include "llvm/CodeGen/SwitchLoweringUtils.h"
37 #include "llvm/CodeGen/TargetFrameLowering.h"
38 #include "llvm/CodeGen/TargetInstrInfo.h"
39 #include "llvm/CodeGen/TargetLowering.h"
40 #include "llvm/CodeGen/TargetPassConfig.h"
41 #include "llvm/CodeGen/TargetRegisterInfo.h"
42 #include "llvm/CodeGen/TargetSubtargetInfo.h"
43 #include "llvm/IR/BasicBlock.h"
44 #include "llvm/IR/CFG.h"
45 #include "llvm/IR/Constant.h"
46 #include "llvm/IR/Constants.h"
47 #include "llvm/IR/DataLayout.h"
48 #include "llvm/IR/DebugInfo.h"
49 #include "llvm/IR/DerivedTypes.h"
50 #include "llvm/IR/DiagnosticInfo.h"
51 #include "llvm/IR/Function.h"
52 #include "llvm/IR/GetElementPtrTypeIterator.h"
53 #include "llvm/IR/InlineAsm.h"
54 #include "llvm/IR/InstrTypes.h"
55 #include "llvm/IR/Instructions.h"
56 #include "llvm/IR/IntrinsicInst.h"
57 #include "llvm/IR/Intrinsics.h"
58 #include "llvm/IR/LLVMContext.h"
59 #include "llvm/IR/Metadata.h"
60 #include "llvm/IR/PatternMatch.h"
61 #include "llvm/IR/Type.h"
62 #include "llvm/IR/User.h"
63 #include "llvm/IR/Value.h"
64 #include "llvm/InitializePasses.h"
65 #include "llvm/MC/MCContext.h"
66 #include "llvm/Pass.h"
67 #include "llvm/Support/Casting.h"
68 #include "llvm/Support/CodeGen.h"
69 #include "llvm/Support/Debug.h"
70 #include "llvm/Support/ErrorHandling.h"
71 #include "llvm/Support/LowLevelTypeImpl.h"
72 #include "llvm/Support/MathExtras.h"
73 #include "llvm/Support/raw_ostream.h"
74 #include "llvm/Target/TargetIntrinsicInfo.h"
75 #include "llvm/Target/TargetMachine.h"
76 #include "llvm/Transforms/Utils/MemoryOpRemark.h"
77 #include <algorithm>
78 #include <cassert>
79 #include <cstddef>
80 #include <cstdint>
81 #include <iterator>
82 #include <string>
83 #include <utility>
84 #include <vector>
85 
86 #define DEBUG_TYPE "irtranslator"
87 
88 using namespace llvm;
89 
90 static cl::opt<bool>
91     EnableCSEInIRTranslator("enable-cse-in-irtranslator",
92                             cl::desc("Should enable CSE in irtranslator"),
93                             cl::Optional, cl::init(false));
94 char IRTranslator::ID = 0;
95 
96 INITIALIZE_PASS_BEGIN(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
97                 false, false)
98 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
99 INITIALIZE_PASS_DEPENDENCY(GISelCSEAnalysisWrapperPass)
100 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
101 INITIALIZE_PASS_DEPENDENCY(StackProtector)
102 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
103 INITIALIZE_PASS_END(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
104                 false, false)
105 
106 static void reportTranslationError(MachineFunction &MF,
107                                    const TargetPassConfig &TPC,
108                                    OptimizationRemarkEmitter &ORE,
109                                    OptimizationRemarkMissed &R) {
110   MF.getProperties().set(MachineFunctionProperties::Property::FailedISel);
111 
112   // Print the function name explicitly if we don't have a debug location (which
113   // makes the diagnostic less useful) or if we're going to emit a raw error.
114   if (!R.getLocation().isValid() || TPC.isGlobalISelAbortEnabled())
115     R << (" (in function: " + MF.getName() + ")").str();
116 
117   if (TPC.isGlobalISelAbortEnabled())
118     report_fatal_error(R.getMsg());
119   else
120     ORE.emit(R);
121 }
122 
123 IRTranslator::IRTranslator(CodeGenOpt::Level optlevel)
124     : MachineFunctionPass(ID), OptLevel(optlevel) {}
125 
126 #ifndef NDEBUG
127 namespace {
128 /// Verify that every instruction created has the same DILocation as the
129 /// instruction being translated.
130 class DILocationVerifier : public GISelChangeObserver {
131   const Instruction *CurrInst = nullptr;
132 
133 public:
134   DILocationVerifier() = default;
135   ~DILocationVerifier() = default;
136 
137   const Instruction *getCurrentInst() const { return CurrInst; }
138   void setCurrentInst(const Instruction *Inst) { CurrInst = Inst; }
139 
140   void erasingInstr(MachineInstr &MI) override {}
141   void changingInstr(MachineInstr &MI) override {}
142   void changedInstr(MachineInstr &MI) override {}
143 
144   void createdInstr(MachineInstr &MI) override {
145     assert(getCurrentInst() && "Inserted instruction without a current MI");
146 
147     // Only print the check message if we're actually checking it.
148 #ifndef NDEBUG
149     LLVM_DEBUG(dbgs() << "Checking DILocation from " << *CurrInst
150                       << " was copied to " << MI);
151 #endif
152     // We allow insts in the entry block to have a debug loc line of 0 because
153     // they could have originated from constants, and we don't want a jumpy
154     // debug experience.
155     assert((CurrInst->getDebugLoc() == MI.getDebugLoc() ||
156             MI.getDebugLoc().getLine() == 0) &&
157            "Line info was not transferred to all instructions");
158   }
159 };
160 } // namespace
161 #endif // ifndef NDEBUG
162 
163 
164 void IRTranslator::getAnalysisUsage(AnalysisUsage &AU) const {
165   AU.addRequired<StackProtector>();
166   AU.addRequired<TargetPassConfig>();
167   AU.addRequired<GISelCSEAnalysisWrapperPass>();
168   if (OptLevel != CodeGenOpt::None)
169     AU.addRequired<BranchProbabilityInfoWrapperPass>();
170   AU.addRequired<TargetLibraryInfoWrapperPass>();
171   AU.addPreserved<TargetLibraryInfoWrapperPass>();
172   getSelectionDAGFallbackAnalysisUsage(AU);
173   MachineFunctionPass::getAnalysisUsage(AU);
174 }
175 
176 IRTranslator::ValueToVRegInfo::VRegListT &
177 IRTranslator::allocateVRegs(const Value &Val) {
178   auto VRegsIt = VMap.findVRegs(Val);
179   if (VRegsIt != VMap.vregs_end())
180     return *VRegsIt->second;
181   auto *Regs = VMap.getVRegs(Val);
182   auto *Offsets = VMap.getOffsets(Val);
183   SmallVector<LLT, 4> SplitTys;
184   computeValueLLTs(*DL, *Val.getType(), SplitTys,
185                    Offsets->empty() ? Offsets : nullptr);
186   for (unsigned i = 0; i < SplitTys.size(); ++i)
187     Regs->push_back(0);
188   return *Regs;
189 }
190 
191 ArrayRef<Register> IRTranslator::getOrCreateVRegs(const Value &Val) {
192   auto VRegsIt = VMap.findVRegs(Val);
193   if (VRegsIt != VMap.vregs_end())
194     return *VRegsIt->second;
195 
196   if (Val.getType()->isVoidTy())
197     return *VMap.getVRegs(Val);
198 
199   // Create entry for this type.
200   auto *VRegs = VMap.getVRegs(Val);
201   auto *Offsets = VMap.getOffsets(Val);
202 
203   assert(Val.getType()->isSized() &&
204          "Don't know how to create an empty vreg");
205 
206   SmallVector<LLT, 4> SplitTys;
207   computeValueLLTs(*DL, *Val.getType(), SplitTys,
208                    Offsets->empty() ? Offsets : nullptr);
209 
210   if (!isa<Constant>(Val)) {
211     for (auto Ty : SplitTys)
212       VRegs->push_back(MRI->createGenericVirtualRegister(Ty));
213     return *VRegs;
214   }
215 
216   if (Val.getType()->isAggregateType()) {
217     // UndefValue, ConstantAggregateZero
218     auto &C = cast<Constant>(Val);
219     unsigned Idx = 0;
220     while (auto Elt = C.getAggregateElement(Idx++)) {
221       auto EltRegs = getOrCreateVRegs(*Elt);
222       llvm::copy(EltRegs, std::back_inserter(*VRegs));
223     }
224   } else {
225     assert(SplitTys.size() == 1 && "unexpectedly split LLT");
226     VRegs->push_back(MRI->createGenericVirtualRegister(SplitTys[0]));
227     bool Success = translate(cast<Constant>(Val), VRegs->front());
228     if (!Success) {
229       OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
230                                  MF->getFunction().getSubprogram(),
231                                  &MF->getFunction().getEntryBlock());
232       R << "unable to translate constant: " << ore::NV("Type", Val.getType());
233       reportTranslationError(*MF, *TPC, *ORE, R);
234       return *VRegs;
235     }
236   }
237 
238   return *VRegs;
239 }
240 
241 int IRTranslator::getOrCreateFrameIndex(const AllocaInst &AI) {
242   auto MapEntry = FrameIndices.find(&AI);
243   if (MapEntry != FrameIndices.end())
244     return MapEntry->second;
245 
246   uint64_t ElementSize = DL->getTypeAllocSize(AI.getAllocatedType());
247   uint64_t Size =
248       ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue();
249 
250   // Always allocate at least one byte.
251   Size = std::max<uint64_t>(Size, 1u);
252 
253   int &FI = FrameIndices[&AI];
254   FI = MF->getFrameInfo().CreateStackObject(Size, AI.getAlign(), false, &AI);
255   return FI;
256 }
257 
258 Align IRTranslator::getMemOpAlign(const Instruction &I) {
259   if (const StoreInst *SI = dyn_cast<StoreInst>(&I))
260     return SI->getAlign();
261   if (const LoadInst *LI = dyn_cast<LoadInst>(&I))
262     return LI->getAlign();
263   if (const AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(&I))
264     return AI->getAlign();
265   if (const AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(&I))
266     return AI->getAlign();
267 
268   OptimizationRemarkMissed R("gisel-irtranslator", "", &I);
269   R << "unable to translate memop: " << ore::NV("Opcode", &I);
270   reportTranslationError(*MF, *TPC, *ORE, R);
271   return Align(1);
272 }
273 
274 MachineBasicBlock &IRTranslator::getMBB(const BasicBlock &BB) {
275   MachineBasicBlock *&MBB = BBToMBB[&BB];
276   assert(MBB && "BasicBlock was not encountered before");
277   return *MBB;
278 }
279 
280 void IRTranslator::addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred) {
281   assert(NewPred && "new predecessor must be a real MachineBasicBlock");
282   MachinePreds[Edge].push_back(NewPred);
283 }
284 
285 bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U,
286                                      MachineIRBuilder &MIRBuilder) {
287   // Get or create a virtual register for each value.
288   // Unless the value is a Constant => loadimm cst?
289   // or inline constant each time?
290   // Creation of a virtual register needs to have a size.
291   Register Op0 = getOrCreateVReg(*U.getOperand(0));
292   Register Op1 = getOrCreateVReg(*U.getOperand(1));
293   Register Res = getOrCreateVReg(U);
294   uint16_t Flags = 0;
295   if (isa<Instruction>(U)) {
296     const Instruction &I = cast<Instruction>(U);
297     Flags = MachineInstr::copyFlagsFromInstruction(I);
298   }
299 
300   MIRBuilder.buildInstr(Opcode, {Res}, {Op0, Op1}, Flags);
301   return true;
302 }
303 
304 bool IRTranslator::translateUnaryOp(unsigned Opcode, const User &U,
305                                     MachineIRBuilder &MIRBuilder) {
306   Register Op0 = getOrCreateVReg(*U.getOperand(0));
307   Register Res = getOrCreateVReg(U);
308   uint16_t Flags = 0;
309   if (isa<Instruction>(U)) {
310     const Instruction &I = cast<Instruction>(U);
311     Flags = MachineInstr::copyFlagsFromInstruction(I);
312   }
313   MIRBuilder.buildInstr(Opcode, {Res}, {Op0}, Flags);
314   return true;
315 }
316 
317 bool IRTranslator::translateFNeg(const User &U, MachineIRBuilder &MIRBuilder) {
318   return translateUnaryOp(TargetOpcode::G_FNEG, U, MIRBuilder);
319 }
320 
321 bool IRTranslator::translateCompare(const User &U,
322                                     MachineIRBuilder &MIRBuilder) {
323   auto *CI = dyn_cast<CmpInst>(&U);
324   Register Op0 = getOrCreateVReg(*U.getOperand(0));
325   Register Op1 = getOrCreateVReg(*U.getOperand(1));
326   Register Res = getOrCreateVReg(U);
327   CmpInst::Predicate Pred =
328       CI ? CI->getPredicate() : static_cast<CmpInst::Predicate>(
329                                     cast<ConstantExpr>(U).getPredicate());
330   if (CmpInst::isIntPredicate(Pred))
331     MIRBuilder.buildICmp(Pred, Res, Op0, Op1);
332   else if (Pred == CmpInst::FCMP_FALSE)
333     MIRBuilder.buildCopy(
334         Res, getOrCreateVReg(*Constant::getNullValue(U.getType())));
335   else if (Pred == CmpInst::FCMP_TRUE)
336     MIRBuilder.buildCopy(
337         Res, getOrCreateVReg(*Constant::getAllOnesValue(U.getType())));
338   else {
339     assert(CI && "Instruction should be CmpInst");
340     MIRBuilder.buildFCmp(Pred, Res, Op0, Op1,
341                          MachineInstr::copyFlagsFromInstruction(*CI));
342   }
343 
344   return true;
345 }
346 
347 bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) {
348   const ReturnInst &RI = cast<ReturnInst>(U);
349   const Value *Ret = RI.getReturnValue();
350   if (Ret && DL->getTypeStoreSize(Ret->getType()) == 0)
351     Ret = nullptr;
352 
353   ArrayRef<Register> VRegs;
354   if (Ret)
355     VRegs = getOrCreateVRegs(*Ret);
356 
357   Register SwiftErrorVReg = 0;
358   if (CLI->supportSwiftError() && SwiftError.getFunctionArg()) {
359     SwiftErrorVReg = SwiftError.getOrCreateVRegUseAt(
360         &RI, &MIRBuilder.getMBB(), SwiftError.getFunctionArg());
361   }
362 
363   // The target may mess up with the insertion point, but
364   // this is not important as a return is the last instruction
365   // of the block anyway.
366   return CLI->lowerReturn(MIRBuilder, Ret, VRegs, FuncInfo, SwiftErrorVReg);
367 }
368 
369 void IRTranslator::emitBranchForMergedCondition(
370     const Value *Cond, MachineBasicBlock *TBB, MachineBasicBlock *FBB,
371     MachineBasicBlock *CurBB, MachineBasicBlock *SwitchBB,
372     BranchProbability TProb, BranchProbability FProb, bool InvertCond) {
373   // If the leaf of the tree is a comparison, merge the condition into
374   // the caseblock.
375   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
376     CmpInst::Predicate Condition;
377     if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
378       Condition = InvertCond ? IC->getInversePredicate() : IC->getPredicate();
379     } else {
380       const FCmpInst *FC = cast<FCmpInst>(Cond);
381       Condition = InvertCond ? FC->getInversePredicate() : FC->getPredicate();
382     }
383 
384     SwitchCG::CaseBlock CB(Condition, false, BOp->getOperand(0),
385                            BOp->getOperand(1), nullptr, TBB, FBB, CurBB,
386                            CurBuilder->getDebugLoc(), TProb, FProb);
387     SL->SwitchCases.push_back(CB);
388     return;
389   }
390 
391   // Create a CaseBlock record representing this branch.
392   CmpInst::Predicate Pred = InvertCond ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ;
393   SwitchCG::CaseBlock CB(
394       Pred, false, Cond, ConstantInt::getTrue(MF->getFunction().getContext()),
395       nullptr, TBB, FBB, CurBB, CurBuilder->getDebugLoc(), TProb, FProb);
396   SL->SwitchCases.push_back(CB);
397 }
398 
399 static bool isValInBlock(const Value *V, const BasicBlock *BB) {
400   if (const Instruction *I = dyn_cast<Instruction>(V))
401     return I->getParent() == BB;
402   return true;
403 }
404 
405 void IRTranslator::findMergedConditions(
406     const Value *Cond, MachineBasicBlock *TBB, MachineBasicBlock *FBB,
407     MachineBasicBlock *CurBB, MachineBasicBlock *SwitchBB,
408     Instruction::BinaryOps Opc, BranchProbability TProb,
409     BranchProbability FProb, bool InvertCond) {
410   using namespace PatternMatch;
411   assert((Opc == Instruction::And || Opc == Instruction::Or) &&
412          "Expected Opc to be AND/OR");
413   // Skip over not part of the tree and remember to invert op and operands at
414   // next level.
415   Value *NotCond;
416   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
417       isValInBlock(NotCond, CurBB->getBasicBlock())) {
418     findMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
419                          !InvertCond);
420     return;
421   }
422 
423   const Instruction *BOp = dyn_cast<Instruction>(Cond);
424   const Value *BOpOp0, *BOpOp1;
425   // Compute the effective opcode for Cond, taking into account whether it needs
426   // to be inverted, e.g.
427   //   and (not (or A, B)), C
428   // gets lowered as
429   //   and (and (not A, not B), C)
430   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
431   if (BOp) {
432     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
433                ? Instruction::And
434                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
435                       ? Instruction::Or
436                       : (Instruction::BinaryOps)0);
437     if (InvertCond) {
438       if (BOpc == Instruction::And)
439         BOpc = Instruction::Or;
440       else if (BOpc == Instruction::Or)
441         BOpc = Instruction::And;
442     }
443   }
444 
445   // If this node is not part of the or/and tree, emit it as a branch.
446   // Note that all nodes in the tree should have same opcode.
447   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
448   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
449       !isValInBlock(BOpOp0, CurBB->getBasicBlock()) ||
450       !isValInBlock(BOpOp1, CurBB->getBasicBlock())) {
451     emitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, TProb, FProb,
452                                  InvertCond);
453     return;
454   }
455 
456   //  Create TmpBB after CurBB.
457   MachineFunction::iterator BBI(CurBB);
458   MachineBasicBlock *TmpBB =
459       MF->CreateMachineBasicBlock(CurBB->getBasicBlock());
460   CurBB->getParent()->insert(++BBI, TmpBB);
461 
462   if (Opc == Instruction::Or) {
463     // Codegen X | Y as:
464     // BB1:
465     //   jmp_if_X TBB
466     //   jmp TmpBB
467     // TmpBB:
468     //   jmp_if_Y TBB
469     //   jmp FBB
470     //
471 
472     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
473     // The requirement is that
474     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
475     //     = TrueProb for original BB.
476     // Assuming the original probabilities are A and B, one choice is to set
477     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
478     // A/(1+B) and 2B/(1+B). This choice assumes that
479     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
480     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
481     // TmpBB, but the math is more complicated.
482 
483     auto NewTrueProb = TProb / 2;
484     auto NewFalseProb = TProb / 2 + FProb;
485     // Emit the LHS condition.
486     findMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
487                          NewFalseProb, InvertCond);
488 
489     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
490     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
491     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
492     // Emit the RHS condition into TmpBB.
493     findMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
494                          Probs[1], InvertCond);
495   } else {
496     assert(Opc == Instruction::And && "Unknown merge op!");
497     // Codegen X & Y as:
498     // BB1:
499     //   jmp_if_X TmpBB
500     //   jmp FBB
501     // TmpBB:
502     //   jmp_if_Y TBB
503     //   jmp FBB
504     //
505     //  This requires creation of TmpBB after CurBB.
506 
507     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
508     // The requirement is that
509     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
510     //     = FalseProb for original BB.
511     // Assuming the original probabilities are A and B, one choice is to set
512     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
513     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
514     // TrueProb for BB1 * FalseProb for TmpBB.
515 
516     auto NewTrueProb = TProb + FProb / 2;
517     auto NewFalseProb = FProb / 2;
518     // Emit the LHS condition.
519     findMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
520                          NewFalseProb, InvertCond);
521 
522     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
523     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
524     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
525     // Emit the RHS condition into TmpBB.
526     findMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
527                          Probs[1], InvertCond);
528   }
529 }
530 
531 bool IRTranslator::shouldEmitAsBranches(
532     const std::vector<SwitchCG::CaseBlock> &Cases) {
533   // For multiple cases, it's better to emit as branches.
534   if (Cases.size() != 2)
535     return true;
536 
537   // If this is two comparisons of the same values or'd or and'd together, they
538   // will get folded into a single comparison, so don't emit two blocks.
539   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
540        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
541       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
542        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
543     return false;
544   }
545 
546   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
547   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
548   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
549       Cases[0].PredInfo.Pred == Cases[1].PredInfo.Pred &&
550       isa<Constant>(Cases[0].CmpRHS) &&
551       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
552     if (Cases[0].PredInfo.Pred == CmpInst::ICMP_EQ &&
553         Cases[0].TrueBB == Cases[1].ThisBB)
554       return false;
555     if (Cases[0].PredInfo.Pred == CmpInst::ICMP_NE &&
556         Cases[0].FalseBB == Cases[1].ThisBB)
557       return false;
558   }
559 
560   return true;
561 }
562 
563 bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) {
564   const BranchInst &BrInst = cast<BranchInst>(U);
565   auto &CurMBB = MIRBuilder.getMBB();
566   auto *Succ0MBB = &getMBB(*BrInst.getSuccessor(0));
567 
568   if (BrInst.isUnconditional()) {
569     // If the unconditional target is the layout successor, fallthrough.
570     if (OptLevel == CodeGenOpt::None || !CurMBB.isLayoutSuccessor(Succ0MBB))
571       MIRBuilder.buildBr(*Succ0MBB);
572 
573     // Link successors.
574     for (const BasicBlock *Succ : successors(&BrInst))
575       CurMBB.addSuccessor(&getMBB(*Succ));
576     return true;
577   }
578 
579   // If this condition is one of the special cases we handle, do special stuff
580   // now.
581   const Value *CondVal = BrInst.getCondition();
582   MachineBasicBlock *Succ1MBB = &getMBB(*BrInst.getSuccessor(1));
583 
584   const auto &TLI = *MF->getSubtarget().getTargetLowering();
585 
586   // If this is a series of conditions that are or'd or and'd together, emit
587   // this as a sequence of branches instead of setcc's with and/or operations.
588   // As long as jumps are not expensive (exceptions for multi-use logic ops,
589   // unpredictable branches, and vector extracts because those jumps are likely
590   // expensive for any target), this should improve performance.
591   // For example, instead of something like:
592   //     cmp A, B
593   //     C = seteq
594   //     cmp D, E
595   //     F = setle
596   //     or C, F
597   //     jnz foo
598   // Emit:
599   //     cmp A, B
600   //     je foo
601   //     cmp D, E
602   //     jle foo
603   using namespace PatternMatch;
604   const Instruction *CondI = dyn_cast<Instruction>(CondVal);
605   if (!TLI.isJumpExpensive() && CondI && CondI->hasOneUse() &&
606       !BrInst.hasMetadata(LLVMContext::MD_unpredictable)) {
607     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
608     Value *Vec;
609     const Value *BOp0, *BOp1;
610     if (match(CondI, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
611       Opcode = Instruction::And;
612     else if (match(CondI, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
613       Opcode = Instruction::Or;
614 
615     if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
616                     match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
617       findMergedConditions(CondI, Succ0MBB, Succ1MBB, &CurMBB, &CurMBB, Opcode,
618                            getEdgeProbability(&CurMBB, Succ0MBB),
619                            getEdgeProbability(&CurMBB, Succ1MBB),
620                            /*InvertCond=*/false);
621       assert(SL->SwitchCases[0].ThisBB == &CurMBB && "Unexpected lowering!");
622 
623       // Allow some cases to be rejected.
624       if (shouldEmitAsBranches(SL->SwitchCases)) {
625         // Emit the branch for this block.
626         emitSwitchCase(SL->SwitchCases[0], &CurMBB, *CurBuilder);
627         SL->SwitchCases.erase(SL->SwitchCases.begin());
628         return true;
629       }
630 
631       // Okay, we decided not to do this, remove any inserted MBB's and clear
632       // SwitchCases.
633       for (unsigned I = 1, E = SL->SwitchCases.size(); I != E; ++I)
634         MF->erase(SL->SwitchCases[I].ThisBB);
635 
636       SL->SwitchCases.clear();
637     }
638   }
639 
640   // Create a CaseBlock record representing this branch.
641   SwitchCG::CaseBlock CB(CmpInst::ICMP_EQ, false, CondVal,
642                          ConstantInt::getTrue(MF->getFunction().getContext()),
643                          nullptr, Succ0MBB, Succ1MBB, &CurMBB,
644                          CurBuilder->getDebugLoc());
645 
646   // Use emitSwitchCase to actually insert the fast branch sequence for this
647   // cond branch.
648   emitSwitchCase(CB, &CurMBB, *CurBuilder);
649   return true;
650 }
651 
652 void IRTranslator::addSuccessorWithProb(MachineBasicBlock *Src,
653                                         MachineBasicBlock *Dst,
654                                         BranchProbability Prob) {
655   if (!FuncInfo.BPI) {
656     Src->addSuccessorWithoutProb(Dst);
657     return;
658   }
659   if (Prob.isUnknown())
660     Prob = getEdgeProbability(Src, Dst);
661   Src->addSuccessor(Dst, Prob);
662 }
663 
664 BranchProbability
665 IRTranslator::getEdgeProbability(const MachineBasicBlock *Src,
666                                  const MachineBasicBlock *Dst) const {
667   const BasicBlock *SrcBB = Src->getBasicBlock();
668   const BasicBlock *DstBB = Dst->getBasicBlock();
669   if (!FuncInfo.BPI) {
670     // If BPI is not available, set the default probability as 1 / N, where N is
671     // the number of successors.
672     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
673     return BranchProbability(1, SuccSize);
674   }
675   return FuncInfo.BPI->getEdgeProbability(SrcBB, DstBB);
676 }
677 
678 bool IRTranslator::translateSwitch(const User &U, MachineIRBuilder &MIB) {
679   using namespace SwitchCG;
680   // Extract cases from the switch.
681   const SwitchInst &SI = cast<SwitchInst>(U);
682   BranchProbabilityInfo *BPI = FuncInfo.BPI;
683   CaseClusterVector Clusters;
684   Clusters.reserve(SI.getNumCases());
685   for (auto &I : SI.cases()) {
686     MachineBasicBlock *Succ = &getMBB(*I.getCaseSuccessor());
687     assert(Succ && "Could not find successor mbb in mapping");
688     const ConstantInt *CaseVal = I.getCaseValue();
689     BranchProbability Prob =
690         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
691             : BranchProbability(1, SI.getNumCases() + 1);
692     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
693   }
694 
695   MachineBasicBlock *DefaultMBB = &getMBB(*SI.getDefaultDest());
696 
697   // Cluster adjacent cases with the same destination. We do this at all
698   // optimization levels because it's cheap to do and will make codegen faster
699   // if there are many clusters.
700   sortAndRangeify(Clusters);
701 
702   MachineBasicBlock *SwitchMBB = &getMBB(*SI.getParent());
703 
704   // If there is only the default destination, jump there directly.
705   if (Clusters.empty()) {
706     SwitchMBB->addSuccessor(DefaultMBB);
707     if (DefaultMBB != SwitchMBB->getNextNode())
708       MIB.buildBr(*DefaultMBB);
709     return true;
710   }
711 
712   SL->findJumpTables(Clusters, &SI, DefaultMBB, nullptr, nullptr);
713   SL->findBitTestClusters(Clusters, &SI);
714 
715   LLVM_DEBUG({
716     dbgs() << "Case clusters: ";
717     for (const CaseCluster &C : Clusters) {
718       if (C.Kind == CC_JumpTable)
719         dbgs() << "JT:";
720       if (C.Kind == CC_BitTests)
721         dbgs() << "BT:";
722 
723       C.Low->getValue().print(dbgs(), true);
724       if (C.Low != C.High) {
725         dbgs() << '-';
726         C.High->getValue().print(dbgs(), true);
727       }
728       dbgs() << ' ';
729     }
730     dbgs() << '\n';
731   });
732 
733   assert(!Clusters.empty());
734   SwitchWorkList WorkList;
735   CaseClusterIt First = Clusters.begin();
736   CaseClusterIt Last = Clusters.end() - 1;
737   auto DefaultProb = getEdgeProbability(SwitchMBB, DefaultMBB);
738   WorkList.push_back({SwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
739 
740   // FIXME: At the moment we don't do any splitting optimizations here like
741   // SelectionDAG does, so this worklist only has one entry.
742   while (!WorkList.empty()) {
743     SwitchWorkListItem W = WorkList.pop_back_val();
744     if (!lowerSwitchWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB, MIB))
745       return false;
746   }
747   return true;
748 }
749 
750 void IRTranslator::emitJumpTable(SwitchCG::JumpTable &JT,
751                                  MachineBasicBlock *MBB) {
752   // Emit the code for the jump table
753   assert(JT.Reg != -1U && "Should lower JT Header first!");
754   MachineIRBuilder MIB(*MBB->getParent());
755   MIB.setMBB(*MBB);
756   MIB.setDebugLoc(CurBuilder->getDebugLoc());
757 
758   Type *PtrIRTy = Type::getInt8PtrTy(MF->getFunction().getContext());
759   const LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
760 
761   auto Table = MIB.buildJumpTable(PtrTy, JT.JTI);
762   MIB.buildBrJT(Table.getReg(0), JT.JTI, JT.Reg);
763 }
764 
765 bool IRTranslator::emitJumpTableHeader(SwitchCG::JumpTable &JT,
766                                        SwitchCG::JumpTableHeader &JTH,
767                                        MachineBasicBlock *HeaderBB) {
768   MachineIRBuilder MIB(*HeaderBB->getParent());
769   MIB.setMBB(*HeaderBB);
770   MIB.setDebugLoc(CurBuilder->getDebugLoc());
771 
772   const Value &SValue = *JTH.SValue;
773   // Subtract the lowest switch case value from the value being switched on.
774   const LLT SwitchTy = getLLTForType(*SValue.getType(), *DL);
775   Register SwitchOpReg = getOrCreateVReg(SValue);
776   auto FirstCst = MIB.buildConstant(SwitchTy, JTH.First);
777   auto Sub = MIB.buildSub({SwitchTy}, SwitchOpReg, FirstCst);
778 
779   // This value may be smaller or larger than the target's pointer type, and
780   // therefore require extension or truncating.
781   Type *PtrIRTy = SValue.getType()->getPointerTo();
782   const LLT PtrScalarTy = LLT::scalar(DL->getTypeSizeInBits(PtrIRTy));
783   Sub = MIB.buildZExtOrTrunc(PtrScalarTy, Sub);
784 
785   JT.Reg = Sub.getReg(0);
786 
787   if (JTH.FallthroughUnreachable) {
788     if (JT.MBB != HeaderBB->getNextNode())
789       MIB.buildBr(*JT.MBB);
790     return true;
791   }
792 
793   // Emit the range check for the jump table, and branch to the default block
794   // for the switch statement if the value being switched on exceeds the
795   // largest case in the switch.
796   auto Cst = getOrCreateVReg(
797       *ConstantInt::get(SValue.getType(), JTH.Last - JTH.First));
798   Cst = MIB.buildZExtOrTrunc(PtrScalarTy, Cst).getReg(0);
799   auto Cmp = MIB.buildICmp(CmpInst::ICMP_UGT, LLT::scalar(1), Sub, Cst);
800 
801   auto BrCond = MIB.buildBrCond(Cmp.getReg(0), *JT.Default);
802 
803   // Avoid emitting unnecessary branches to the next block.
804   if (JT.MBB != HeaderBB->getNextNode())
805     BrCond = MIB.buildBr(*JT.MBB);
806   return true;
807 }
808 
809 void IRTranslator::emitSwitchCase(SwitchCG::CaseBlock &CB,
810                                   MachineBasicBlock *SwitchBB,
811                                   MachineIRBuilder &MIB) {
812   Register CondLHS = getOrCreateVReg(*CB.CmpLHS);
813   Register Cond;
814   DebugLoc OldDbgLoc = MIB.getDebugLoc();
815   MIB.setDebugLoc(CB.DbgLoc);
816   MIB.setMBB(*CB.ThisBB);
817 
818   if (CB.PredInfo.NoCmp) {
819     // Branch or fall through to TrueBB.
820     addSuccessorWithProb(CB.ThisBB, CB.TrueBB, CB.TrueProb);
821     addMachineCFGPred({SwitchBB->getBasicBlock(), CB.TrueBB->getBasicBlock()},
822                       CB.ThisBB);
823     CB.ThisBB->normalizeSuccProbs();
824     if (CB.TrueBB != CB.ThisBB->getNextNode())
825       MIB.buildBr(*CB.TrueBB);
826     MIB.setDebugLoc(OldDbgLoc);
827     return;
828   }
829 
830   const LLT i1Ty = LLT::scalar(1);
831   // Build the compare.
832   if (!CB.CmpMHS) {
833     const auto *CI = dyn_cast<ConstantInt>(CB.CmpRHS);
834     // For conditional branch lowering, we might try to do something silly like
835     // emit an G_ICMP to compare an existing G_ICMP i1 result with true. If so,
836     // just re-use the existing condition vreg.
837     if (MRI->getType(CondLHS).getSizeInBits() == 1 && CI &&
838         CI->getZExtValue() == 1 && CB.PredInfo.Pred == CmpInst::ICMP_EQ) {
839       Cond = CondLHS;
840     } else {
841       Register CondRHS = getOrCreateVReg(*CB.CmpRHS);
842       if (CmpInst::isFPPredicate(CB.PredInfo.Pred))
843         Cond =
844             MIB.buildFCmp(CB.PredInfo.Pred, i1Ty, CondLHS, CondRHS).getReg(0);
845       else
846         Cond =
847             MIB.buildICmp(CB.PredInfo.Pred, i1Ty, CondLHS, CondRHS).getReg(0);
848     }
849   } else {
850     assert(CB.PredInfo.Pred == CmpInst::ICMP_SLE &&
851            "Can only handle SLE ranges");
852 
853     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
854     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
855 
856     Register CmpOpReg = getOrCreateVReg(*CB.CmpMHS);
857     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
858       Register CondRHS = getOrCreateVReg(*CB.CmpRHS);
859       Cond =
860           MIB.buildICmp(CmpInst::ICMP_SLE, i1Ty, CmpOpReg, CondRHS).getReg(0);
861     } else {
862       const LLT CmpTy = MRI->getType(CmpOpReg);
863       auto Sub = MIB.buildSub({CmpTy}, CmpOpReg, CondLHS);
864       auto Diff = MIB.buildConstant(CmpTy, High - Low);
865       Cond = MIB.buildICmp(CmpInst::ICMP_ULE, i1Ty, Sub, Diff).getReg(0);
866     }
867   }
868 
869   // Update successor info
870   addSuccessorWithProb(CB.ThisBB, CB.TrueBB, CB.TrueProb);
871 
872   addMachineCFGPred({SwitchBB->getBasicBlock(), CB.TrueBB->getBasicBlock()},
873                     CB.ThisBB);
874 
875   // TrueBB and FalseBB are always different unless the incoming IR is
876   // degenerate. This only happens when running llc on weird IR.
877   if (CB.TrueBB != CB.FalseBB)
878     addSuccessorWithProb(CB.ThisBB, CB.FalseBB, CB.FalseProb);
879   CB.ThisBB->normalizeSuccProbs();
880 
881   addMachineCFGPred({SwitchBB->getBasicBlock(), CB.FalseBB->getBasicBlock()},
882                     CB.ThisBB);
883 
884   MIB.buildBrCond(Cond, *CB.TrueBB);
885   MIB.buildBr(*CB.FalseBB);
886   MIB.setDebugLoc(OldDbgLoc);
887 }
888 
889 bool IRTranslator::lowerJumpTableWorkItem(SwitchCG::SwitchWorkListItem W,
890                                           MachineBasicBlock *SwitchMBB,
891                                           MachineBasicBlock *CurMBB,
892                                           MachineBasicBlock *DefaultMBB,
893                                           MachineIRBuilder &MIB,
894                                           MachineFunction::iterator BBI,
895                                           BranchProbability UnhandledProbs,
896                                           SwitchCG::CaseClusterIt I,
897                                           MachineBasicBlock *Fallthrough,
898                                           bool FallthroughUnreachable) {
899   using namespace SwitchCG;
900   MachineFunction *CurMF = SwitchMBB->getParent();
901   // FIXME: Optimize away range check based on pivot comparisons.
902   JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
903   SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
904   BranchProbability DefaultProb = W.DefaultProb;
905 
906   // The jump block hasn't been inserted yet; insert it here.
907   MachineBasicBlock *JumpMBB = JT->MBB;
908   CurMF->insert(BBI, JumpMBB);
909 
910   // Since the jump table block is separate from the switch block, we need
911   // to keep track of it as a machine predecessor to the default block,
912   // otherwise we lose the phi edges.
913   addMachineCFGPred({SwitchMBB->getBasicBlock(), DefaultMBB->getBasicBlock()},
914                     CurMBB);
915   addMachineCFGPred({SwitchMBB->getBasicBlock(), DefaultMBB->getBasicBlock()},
916                     JumpMBB);
917 
918   auto JumpProb = I->Prob;
919   auto FallthroughProb = UnhandledProbs;
920 
921   // If the default statement is a target of the jump table, we evenly
922   // distribute the default probability to successors of CurMBB. Also
923   // update the probability on the edge from JumpMBB to Fallthrough.
924   for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
925                                         SE = JumpMBB->succ_end();
926        SI != SE; ++SI) {
927     if (*SI == DefaultMBB) {
928       JumpProb += DefaultProb / 2;
929       FallthroughProb -= DefaultProb / 2;
930       JumpMBB->setSuccProbability(SI, DefaultProb / 2);
931       JumpMBB->normalizeSuccProbs();
932     } else {
933       // Also record edges from the jump table block to it's successors.
934       addMachineCFGPred({SwitchMBB->getBasicBlock(), (*SI)->getBasicBlock()},
935                         JumpMBB);
936     }
937   }
938 
939   if (FallthroughUnreachable)
940     JTH->FallthroughUnreachable = true;
941 
942   if (!JTH->FallthroughUnreachable)
943     addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
944   addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
945   CurMBB->normalizeSuccProbs();
946 
947   // The jump table header will be inserted in our current block, do the
948   // range check, and fall through to our fallthrough block.
949   JTH->HeaderBB = CurMBB;
950   JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
951 
952   // If we're in the right place, emit the jump table header right now.
953   if (CurMBB == SwitchMBB) {
954     if (!emitJumpTableHeader(*JT, *JTH, CurMBB))
955       return false;
956     JTH->Emitted = true;
957   }
958   return true;
959 }
960 bool IRTranslator::lowerSwitchRangeWorkItem(SwitchCG::CaseClusterIt I,
961                                             Value *Cond,
962                                             MachineBasicBlock *Fallthrough,
963                                             bool FallthroughUnreachable,
964                                             BranchProbability UnhandledProbs,
965                                             MachineBasicBlock *CurMBB,
966                                             MachineIRBuilder &MIB,
967                                             MachineBasicBlock *SwitchMBB) {
968   using namespace SwitchCG;
969   const Value *RHS, *LHS, *MHS;
970   CmpInst::Predicate Pred;
971   if (I->Low == I->High) {
972     // Check Cond == I->Low.
973     Pred = CmpInst::ICMP_EQ;
974     LHS = Cond;
975     RHS = I->Low;
976     MHS = nullptr;
977   } else {
978     // Check I->Low <= Cond <= I->High.
979     Pred = CmpInst::ICMP_SLE;
980     LHS = I->Low;
981     MHS = Cond;
982     RHS = I->High;
983   }
984 
985   // If Fallthrough is unreachable, fold away the comparison.
986   // The false probability is the sum of all unhandled cases.
987   CaseBlock CB(Pred, FallthroughUnreachable, LHS, RHS, MHS, I->MBB, Fallthrough,
988                CurMBB, MIB.getDebugLoc(), I->Prob, UnhandledProbs);
989 
990   emitSwitchCase(CB, SwitchMBB, MIB);
991   return true;
992 }
993 
994 void IRTranslator::emitBitTestHeader(SwitchCG::BitTestBlock &B,
995                                      MachineBasicBlock *SwitchBB) {
996   MachineIRBuilder &MIB = *CurBuilder;
997   MIB.setMBB(*SwitchBB);
998 
999   // Subtract the minimum value.
1000   Register SwitchOpReg = getOrCreateVReg(*B.SValue);
1001 
1002   LLT SwitchOpTy = MRI->getType(SwitchOpReg);
1003   Register MinValReg = MIB.buildConstant(SwitchOpTy, B.First).getReg(0);
1004   auto RangeSub = MIB.buildSub(SwitchOpTy, SwitchOpReg, MinValReg);
1005 
1006   // Ensure that the type will fit the mask value.
1007   LLT MaskTy = SwitchOpTy;
1008   for (unsigned I = 0, E = B.Cases.size(); I != E; ++I) {
1009     if (!isUIntN(SwitchOpTy.getSizeInBits(), B.Cases[I].Mask)) {
1010       // Switch table case range are encoded into series of masks.
1011       // Just use pointer type, it's guaranteed to fit.
1012       MaskTy = LLT::scalar(64);
1013       break;
1014     }
1015   }
1016   Register SubReg = RangeSub.getReg(0);
1017   if (SwitchOpTy != MaskTy)
1018     SubReg = MIB.buildZExtOrTrunc(MaskTy, SubReg).getReg(0);
1019 
1020   B.RegVT = getMVTForLLT(MaskTy);
1021   B.Reg = SubReg;
1022 
1023   MachineBasicBlock *MBB = B.Cases[0].ThisBB;
1024 
1025   if (!B.FallthroughUnreachable)
1026     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
1027   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
1028 
1029   SwitchBB->normalizeSuccProbs();
1030 
1031   if (!B.FallthroughUnreachable) {
1032     // Conditional branch to the default block.
1033     auto RangeCst = MIB.buildConstant(SwitchOpTy, B.Range);
1034     auto RangeCmp = MIB.buildICmp(CmpInst::Predicate::ICMP_UGT, LLT::scalar(1),
1035                                   RangeSub, RangeCst);
1036     MIB.buildBrCond(RangeCmp, *B.Default);
1037   }
1038 
1039   // Avoid emitting unnecessary branches to the next block.
1040   if (MBB != SwitchBB->getNextNode())
1041     MIB.buildBr(*MBB);
1042 }
1043 
1044 void IRTranslator::emitBitTestCase(SwitchCG::BitTestBlock &BB,
1045                                    MachineBasicBlock *NextMBB,
1046                                    BranchProbability BranchProbToNext,
1047                                    Register Reg, SwitchCG::BitTestCase &B,
1048                                    MachineBasicBlock *SwitchBB) {
1049   MachineIRBuilder &MIB = *CurBuilder;
1050   MIB.setMBB(*SwitchBB);
1051 
1052   LLT SwitchTy = getLLTForMVT(BB.RegVT);
1053   Register Cmp;
1054   unsigned PopCount = countPopulation(B.Mask);
1055   if (PopCount == 1) {
1056     // Testing for a single bit; just compare the shift count with what it
1057     // would need to be to shift a 1 bit in that position.
1058     auto MaskTrailingZeros =
1059         MIB.buildConstant(SwitchTy, countTrailingZeros(B.Mask));
1060     Cmp =
1061         MIB.buildICmp(ICmpInst::ICMP_EQ, LLT::scalar(1), Reg, MaskTrailingZeros)
1062             .getReg(0);
1063   } else if (PopCount == BB.Range) {
1064     // There is only one zero bit in the range, test for it directly.
1065     auto MaskTrailingOnes =
1066         MIB.buildConstant(SwitchTy, countTrailingOnes(B.Mask));
1067     Cmp = MIB.buildICmp(CmpInst::ICMP_NE, LLT::scalar(1), Reg, MaskTrailingOnes)
1068               .getReg(0);
1069   } else {
1070     // Make desired shift.
1071     auto CstOne = MIB.buildConstant(SwitchTy, 1);
1072     auto SwitchVal = MIB.buildShl(SwitchTy, CstOne, Reg);
1073 
1074     // Emit bit tests and jumps.
1075     auto CstMask = MIB.buildConstant(SwitchTy, B.Mask);
1076     auto AndOp = MIB.buildAnd(SwitchTy, SwitchVal, CstMask);
1077     auto CstZero = MIB.buildConstant(SwitchTy, 0);
1078     Cmp = MIB.buildICmp(CmpInst::ICMP_NE, LLT::scalar(1), AndOp, CstZero)
1079               .getReg(0);
1080   }
1081 
1082   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
1083   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
1084   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
1085   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
1086   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
1087   // one as they are relative probabilities (and thus work more like weights),
1088   // and hence we need to normalize them to let the sum of them become one.
1089   SwitchBB->normalizeSuccProbs();
1090 
1091   // Record the fact that the IR edge from the header to the bit test target
1092   // will go through our new block. Neeeded for PHIs to have nodes added.
1093   addMachineCFGPred({BB.Parent->getBasicBlock(), B.TargetBB->getBasicBlock()},
1094                     SwitchBB);
1095 
1096   MIB.buildBrCond(Cmp, *B.TargetBB);
1097 
1098   // Avoid emitting unnecessary branches to the next block.
1099   if (NextMBB != SwitchBB->getNextNode())
1100     MIB.buildBr(*NextMBB);
1101 }
1102 
1103 bool IRTranslator::lowerBitTestWorkItem(
1104     SwitchCG::SwitchWorkListItem W, MachineBasicBlock *SwitchMBB,
1105     MachineBasicBlock *CurMBB, MachineBasicBlock *DefaultMBB,
1106     MachineIRBuilder &MIB, MachineFunction::iterator BBI,
1107     BranchProbability DefaultProb, BranchProbability UnhandledProbs,
1108     SwitchCG::CaseClusterIt I, MachineBasicBlock *Fallthrough,
1109     bool FallthroughUnreachable) {
1110   using namespace SwitchCG;
1111   MachineFunction *CurMF = SwitchMBB->getParent();
1112   // FIXME: Optimize away range check based on pivot comparisons.
1113   BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
1114   // The bit test blocks haven't been inserted yet; insert them here.
1115   for (BitTestCase &BTC : BTB->Cases)
1116     CurMF->insert(BBI, BTC.ThisBB);
1117 
1118   // Fill in fields of the BitTestBlock.
1119   BTB->Parent = CurMBB;
1120   BTB->Default = Fallthrough;
1121 
1122   BTB->DefaultProb = UnhandledProbs;
1123   // If the cases in bit test don't form a contiguous range, we evenly
1124   // distribute the probability on the edge to Fallthrough to two
1125   // successors of CurMBB.
1126   if (!BTB->ContiguousRange) {
1127     BTB->Prob += DefaultProb / 2;
1128     BTB->DefaultProb -= DefaultProb / 2;
1129   }
1130 
1131   if (FallthroughUnreachable)
1132     BTB->FallthroughUnreachable = true;
1133 
1134   // If we're in the right place, emit the bit test header right now.
1135   if (CurMBB == SwitchMBB) {
1136     emitBitTestHeader(*BTB, SwitchMBB);
1137     BTB->Emitted = true;
1138   }
1139   return true;
1140 }
1141 
1142 bool IRTranslator::lowerSwitchWorkItem(SwitchCG::SwitchWorkListItem W,
1143                                        Value *Cond,
1144                                        MachineBasicBlock *SwitchMBB,
1145                                        MachineBasicBlock *DefaultMBB,
1146                                        MachineIRBuilder &MIB) {
1147   using namespace SwitchCG;
1148   MachineFunction *CurMF = FuncInfo.MF;
1149   MachineBasicBlock *NextMBB = nullptr;
1150   MachineFunction::iterator BBI(W.MBB);
1151   if (++BBI != FuncInfo.MF->end())
1152     NextMBB = &*BBI;
1153 
1154   if (EnableOpts) {
1155     // Here, we order cases by probability so the most likely case will be
1156     // checked first. However, two clusters can have the same probability in
1157     // which case their relative ordering is non-deterministic. So we use Low
1158     // as a tie-breaker as clusters are guaranteed to never overlap.
1159     llvm::sort(W.FirstCluster, W.LastCluster + 1,
1160                [](const CaseCluster &a, const CaseCluster &b) {
1161                  return a.Prob != b.Prob
1162                             ? a.Prob > b.Prob
1163                             : a.Low->getValue().slt(b.Low->getValue());
1164                });
1165 
1166     // Rearrange the case blocks so that the last one falls through if possible
1167     // without changing the order of probabilities.
1168     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster;) {
1169       --I;
1170       if (I->Prob > W.LastCluster->Prob)
1171         break;
1172       if (I->Kind == CC_Range && I->MBB == NextMBB) {
1173         std::swap(*I, *W.LastCluster);
1174         break;
1175       }
1176     }
1177   }
1178 
1179   // Compute total probability.
1180   BranchProbability DefaultProb = W.DefaultProb;
1181   BranchProbability UnhandledProbs = DefaultProb;
1182   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
1183     UnhandledProbs += I->Prob;
1184 
1185   MachineBasicBlock *CurMBB = W.MBB;
1186   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
1187     bool FallthroughUnreachable = false;
1188     MachineBasicBlock *Fallthrough;
1189     if (I == W.LastCluster) {
1190       // For the last cluster, fall through to the default destination.
1191       Fallthrough = DefaultMBB;
1192       FallthroughUnreachable = isa<UnreachableInst>(
1193           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
1194     } else {
1195       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
1196       CurMF->insert(BBI, Fallthrough);
1197     }
1198     UnhandledProbs -= I->Prob;
1199 
1200     switch (I->Kind) {
1201     case CC_BitTests: {
1202       if (!lowerBitTestWorkItem(W, SwitchMBB, CurMBB, DefaultMBB, MIB, BBI,
1203                                 DefaultProb, UnhandledProbs, I, Fallthrough,
1204                                 FallthroughUnreachable)) {
1205         LLVM_DEBUG(dbgs() << "Failed to lower bit test for switch");
1206         return false;
1207       }
1208       break;
1209     }
1210 
1211     case CC_JumpTable: {
1212       if (!lowerJumpTableWorkItem(W, SwitchMBB, CurMBB, DefaultMBB, MIB, BBI,
1213                                   UnhandledProbs, I, Fallthrough,
1214                                   FallthroughUnreachable)) {
1215         LLVM_DEBUG(dbgs() << "Failed to lower jump table");
1216         return false;
1217       }
1218       break;
1219     }
1220     case CC_Range: {
1221       if (!lowerSwitchRangeWorkItem(I, Cond, Fallthrough,
1222                                     FallthroughUnreachable, UnhandledProbs,
1223                                     CurMBB, MIB, SwitchMBB)) {
1224         LLVM_DEBUG(dbgs() << "Failed to lower switch range");
1225         return false;
1226       }
1227       break;
1228     }
1229     }
1230     CurMBB = Fallthrough;
1231   }
1232 
1233   return true;
1234 }
1235 
1236 bool IRTranslator::translateIndirectBr(const User &U,
1237                                        MachineIRBuilder &MIRBuilder) {
1238   const IndirectBrInst &BrInst = cast<IndirectBrInst>(U);
1239 
1240   const Register Tgt = getOrCreateVReg(*BrInst.getAddress());
1241   MIRBuilder.buildBrIndirect(Tgt);
1242 
1243   // Link successors.
1244   SmallPtrSet<const BasicBlock *, 32> AddedSuccessors;
1245   MachineBasicBlock &CurBB = MIRBuilder.getMBB();
1246   for (const BasicBlock *Succ : successors(&BrInst)) {
1247     // It's legal for indirectbr instructions to have duplicate blocks in the
1248     // destination list. We don't allow this in MIR. Skip anything that's
1249     // already a successor.
1250     if (!AddedSuccessors.insert(Succ).second)
1251       continue;
1252     CurBB.addSuccessor(&getMBB(*Succ));
1253   }
1254 
1255   return true;
1256 }
1257 
1258 static bool isSwiftError(const Value *V) {
1259   if (auto Arg = dyn_cast<Argument>(V))
1260     return Arg->hasSwiftErrorAttr();
1261   if (auto AI = dyn_cast<AllocaInst>(V))
1262     return AI->isSwiftError();
1263   return false;
1264 }
1265 
1266 bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) {
1267   const LoadInst &LI = cast<LoadInst>(U);
1268   if (DL->getTypeStoreSize(LI.getType()) == 0)
1269     return true;
1270 
1271   ArrayRef<Register> Regs = getOrCreateVRegs(LI);
1272   ArrayRef<uint64_t> Offsets = *VMap.getOffsets(LI);
1273   Register Base = getOrCreateVReg(*LI.getPointerOperand());
1274 
1275   Type *OffsetIRTy = DL->getIntPtrType(LI.getPointerOperandType());
1276   LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
1277 
1278   if (CLI->supportSwiftError() && isSwiftError(LI.getPointerOperand())) {
1279     assert(Regs.size() == 1 && "swifterror should be single pointer");
1280     Register VReg = SwiftError.getOrCreateVRegUseAt(&LI, &MIRBuilder.getMBB(),
1281                                                     LI.getPointerOperand());
1282     MIRBuilder.buildCopy(Regs[0], VReg);
1283     return true;
1284   }
1285 
1286   auto &TLI = *MF->getSubtarget().getTargetLowering();
1287   MachineMemOperand::Flags Flags = TLI.getLoadMemOperandFlags(LI, *DL);
1288 
1289   const MDNode *Ranges =
1290       Regs.size() == 1 ? LI.getMetadata(LLVMContext::MD_range) : nullptr;
1291   for (unsigned i = 0; i < Regs.size(); ++i) {
1292     Register Addr;
1293     MIRBuilder.materializePtrAdd(Addr, Base, OffsetTy, Offsets[i] / 8);
1294 
1295     MachinePointerInfo Ptr(LI.getPointerOperand(), Offsets[i] / 8);
1296     Align BaseAlign = getMemOpAlign(LI);
1297     auto MMO = MF->getMachineMemOperand(
1298         Ptr, Flags, MRI->getType(Regs[i]),
1299         commonAlignment(BaseAlign, Offsets[i] / 8), LI.getAAMetadata(), Ranges,
1300         LI.getSyncScopeID(), LI.getOrdering());
1301     MIRBuilder.buildLoad(Regs[i], Addr, *MMO);
1302   }
1303 
1304   return true;
1305 }
1306 
1307 bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) {
1308   const StoreInst &SI = cast<StoreInst>(U);
1309   if (DL->getTypeStoreSize(SI.getValueOperand()->getType()) == 0)
1310     return true;
1311 
1312   ArrayRef<Register> Vals = getOrCreateVRegs(*SI.getValueOperand());
1313   ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*SI.getValueOperand());
1314   Register Base = getOrCreateVReg(*SI.getPointerOperand());
1315 
1316   Type *OffsetIRTy = DL->getIntPtrType(SI.getPointerOperandType());
1317   LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
1318 
1319   if (CLI->supportSwiftError() && isSwiftError(SI.getPointerOperand())) {
1320     assert(Vals.size() == 1 && "swifterror should be single pointer");
1321 
1322     Register VReg = SwiftError.getOrCreateVRegDefAt(&SI, &MIRBuilder.getMBB(),
1323                                                     SI.getPointerOperand());
1324     MIRBuilder.buildCopy(VReg, Vals[0]);
1325     return true;
1326   }
1327 
1328   auto &TLI = *MF->getSubtarget().getTargetLowering();
1329   MachineMemOperand::Flags Flags = TLI.getStoreMemOperandFlags(SI, *DL);
1330 
1331   for (unsigned i = 0; i < Vals.size(); ++i) {
1332     Register Addr;
1333     MIRBuilder.materializePtrAdd(Addr, Base, OffsetTy, Offsets[i] / 8);
1334 
1335     MachinePointerInfo Ptr(SI.getPointerOperand(), Offsets[i] / 8);
1336     Align BaseAlign = getMemOpAlign(SI);
1337     auto MMO = MF->getMachineMemOperand(
1338         Ptr, Flags, MRI->getType(Vals[i]),
1339         commonAlignment(BaseAlign, Offsets[i] / 8), SI.getAAMetadata(), nullptr,
1340         SI.getSyncScopeID(), SI.getOrdering());
1341     MIRBuilder.buildStore(Vals[i], Addr, *MMO);
1342   }
1343   return true;
1344 }
1345 
1346 static uint64_t getOffsetFromIndices(const User &U, const DataLayout &DL) {
1347   const Value *Src = U.getOperand(0);
1348   Type *Int32Ty = Type::getInt32Ty(U.getContext());
1349 
1350   // getIndexedOffsetInType is designed for GEPs, so the first index is the
1351   // usual array element rather than looking into the actual aggregate.
1352   SmallVector<Value *, 1> Indices;
1353   Indices.push_back(ConstantInt::get(Int32Ty, 0));
1354 
1355   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) {
1356     for (auto Idx : EVI->indices())
1357       Indices.push_back(ConstantInt::get(Int32Ty, Idx));
1358   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) {
1359     for (auto Idx : IVI->indices())
1360       Indices.push_back(ConstantInt::get(Int32Ty, Idx));
1361   } else {
1362     for (unsigned i = 1; i < U.getNumOperands(); ++i)
1363       Indices.push_back(U.getOperand(i));
1364   }
1365 
1366   return 8 * static_cast<uint64_t>(
1367                  DL.getIndexedOffsetInType(Src->getType(), Indices));
1368 }
1369 
1370 bool IRTranslator::translateExtractValue(const User &U,
1371                                          MachineIRBuilder &MIRBuilder) {
1372   const Value *Src = U.getOperand(0);
1373   uint64_t Offset = getOffsetFromIndices(U, *DL);
1374   ArrayRef<Register> SrcRegs = getOrCreateVRegs(*Src);
1375   ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*Src);
1376   unsigned Idx = llvm::lower_bound(Offsets, Offset) - Offsets.begin();
1377   auto &DstRegs = allocateVRegs(U);
1378 
1379   for (unsigned i = 0; i < DstRegs.size(); ++i)
1380     DstRegs[i] = SrcRegs[Idx++];
1381 
1382   return true;
1383 }
1384 
1385 bool IRTranslator::translateInsertValue(const User &U,
1386                                         MachineIRBuilder &MIRBuilder) {
1387   const Value *Src = U.getOperand(0);
1388   uint64_t Offset = getOffsetFromIndices(U, *DL);
1389   auto &DstRegs = allocateVRegs(U);
1390   ArrayRef<uint64_t> DstOffsets = *VMap.getOffsets(U);
1391   ArrayRef<Register> SrcRegs = getOrCreateVRegs(*Src);
1392   ArrayRef<Register> InsertedRegs = getOrCreateVRegs(*U.getOperand(1));
1393   auto InsertedIt = InsertedRegs.begin();
1394 
1395   for (unsigned i = 0; i < DstRegs.size(); ++i) {
1396     if (DstOffsets[i] >= Offset && InsertedIt != InsertedRegs.end())
1397       DstRegs[i] = *InsertedIt++;
1398     else
1399       DstRegs[i] = SrcRegs[i];
1400   }
1401 
1402   return true;
1403 }
1404 
1405 bool IRTranslator::translateSelect(const User &U,
1406                                    MachineIRBuilder &MIRBuilder) {
1407   Register Tst = getOrCreateVReg(*U.getOperand(0));
1408   ArrayRef<Register> ResRegs = getOrCreateVRegs(U);
1409   ArrayRef<Register> Op0Regs = getOrCreateVRegs(*U.getOperand(1));
1410   ArrayRef<Register> Op1Regs = getOrCreateVRegs(*U.getOperand(2));
1411 
1412   uint16_t Flags = 0;
1413   if (const SelectInst *SI = dyn_cast<SelectInst>(&U))
1414     Flags = MachineInstr::copyFlagsFromInstruction(*SI);
1415 
1416   for (unsigned i = 0; i < ResRegs.size(); ++i) {
1417     MIRBuilder.buildSelect(ResRegs[i], Tst, Op0Regs[i], Op1Regs[i], Flags);
1418   }
1419 
1420   return true;
1421 }
1422 
1423 bool IRTranslator::translateCopy(const User &U, const Value &V,
1424                                  MachineIRBuilder &MIRBuilder) {
1425   Register Src = getOrCreateVReg(V);
1426   auto &Regs = *VMap.getVRegs(U);
1427   if (Regs.empty()) {
1428     Regs.push_back(Src);
1429     VMap.getOffsets(U)->push_back(0);
1430   } else {
1431     // If we already assigned a vreg for this instruction, we can't change that.
1432     // Emit a copy to satisfy the users we already emitted.
1433     MIRBuilder.buildCopy(Regs[0], Src);
1434   }
1435   return true;
1436 }
1437 
1438 bool IRTranslator::translateBitCast(const User &U,
1439                                     MachineIRBuilder &MIRBuilder) {
1440   // If we're bitcasting to the source type, we can reuse the source vreg.
1441   if (getLLTForType(*U.getOperand(0)->getType(), *DL) ==
1442       getLLTForType(*U.getType(), *DL))
1443     return translateCopy(U, *U.getOperand(0), MIRBuilder);
1444 
1445   return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder);
1446 }
1447 
1448 bool IRTranslator::translateCast(unsigned Opcode, const User &U,
1449                                  MachineIRBuilder &MIRBuilder) {
1450   Register Op = getOrCreateVReg(*U.getOperand(0));
1451   Register Res = getOrCreateVReg(U);
1452   MIRBuilder.buildInstr(Opcode, {Res}, {Op});
1453   return true;
1454 }
1455 
1456 bool IRTranslator::translateGetElementPtr(const User &U,
1457                                           MachineIRBuilder &MIRBuilder) {
1458   Value &Op0 = *U.getOperand(0);
1459   Register BaseReg = getOrCreateVReg(Op0);
1460   Type *PtrIRTy = Op0.getType();
1461   LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
1462   Type *OffsetIRTy = DL->getIntPtrType(PtrIRTy);
1463   LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
1464 
1465   // Normalize Vector GEP - all scalar operands should be converted to the
1466   // splat vector.
1467   unsigned VectorWidth = 0;
1468 
1469   // True if we should use a splat vector; using VectorWidth alone is not
1470   // sufficient.
1471   bool WantSplatVector = false;
1472   if (auto *VT = dyn_cast<VectorType>(U.getType())) {
1473     VectorWidth = cast<FixedVectorType>(VT)->getNumElements();
1474     // We don't produce 1 x N vectors; those are treated as scalars.
1475     WantSplatVector = VectorWidth > 1;
1476   }
1477 
1478   // We might need to splat the base pointer into a vector if the offsets
1479   // are vectors.
1480   if (WantSplatVector && !PtrTy.isVector()) {
1481     BaseReg =
1482         MIRBuilder
1483             .buildSplatVector(LLT::fixed_vector(VectorWidth, PtrTy), BaseReg)
1484             .getReg(0);
1485     PtrIRTy = FixedVectorType::get(PtrIRTy, VectorWidth);
1486     PtrTy = getLLTForType(*PtrIRTy, *DL);
1487     OffsetIRTy = DL->getIntPtrType(PtrIRTy);
1488     OffsetTy = getLLTForType(*OffsetIRTy, *DL);
1489   }
1490 
1491   int64_t Offset = 0;
1492   for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U);
1493        GTI != E; ++GTI) {
1494     const Value *Idx = GTI.getOperand();
1495     if (StructType *StTy = GTI.getStructTypeOrNull()) {
1496       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
1497       Offset += DL->getStructLayout(StTy)->getElementOffset(Field);
1498       continue;
1499     } else {
1500       uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
1501 
1502       // If this is a scalar constant or a splat vector of constants,
1503       // handle it quickly.
1504       if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
1505         Offset += ElementSize * CI->getSExtValue();
1506         continue;
1507       }
1508 
1509       if (Offset != 0) {
1510         auto OffsetMIB = MIRBuilder.buildConstant({OffsetTy}, Offset);
1511         BaseReg = MIRBuilder.buildPtrAdd(PtrTy, BaseReg, OffsetMIB.getReg(0))
1512                       .getReg(0);
1513         Offset = 0;
1514       }
1515 
1516       Register IdxReg = getOrCreateVReg(*Idx);
1517       LLT IdxTy = MRI->getType(IdxReg);
1518       if (IdxTy != OffsetTy) {
1519         if (!IdxTy.isVector() && WantSplatVector) {
1520           IdxReg = MIRBuilder.buildSplatVector(
1521             OffsetTy.changeElementType(IdxTy), IdxReg).getReg(0);
1522         }
1523 
1524         IdxReg = MIRBuilder.buildSExtOrTrunc(OffsetTy, IdxReg).getReg(0);
1525       }
1526 
1527       // N = N + Idx * ElementSize;
1528       // Avoid doing it for ElementSize of 1.
1529       Register GepOffsetReg;
1530       if (ElementSize != 1) {
1531         auto ElementSizeMIB = MIRBuilder.buildConstant(
1532             getLLTForType(*OffsetIRTy, *DL), ElementSize);
1533         GepOffsetReg =
1534             MIRBuilder.buildMul(OffsetTy, IdxReg, ElementSizeMIB).getReg(0);
1535       } else
1536         GepOffsetReg = IdxReg;
1537 
1538       BaseReg = MIRBuilder.buildPtrAdd(PtrTy, BaseReg, GepOffsetReg).getReg(0);
1539     }
1540   }
1541 
1542   if (Offset != 0) {
1543     auto OffsetMIB =
1544         MIRBuilder.buildConstant(OffsetTy, Offset);
1545     MIRBuilder.buildPtrAdd(getOrCreateVReg(U), BaseReg, OffsetMIB.getReg(0));
1546     return true;
1547   }
1548 
1549   MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg);
1550   return true;
1551 }
1552 
1553 bool IRTranslator::translateMemFunc(const CallInst &CI,
1554                                     MachineIRBuilder &MIRBuilder,
1555                                     unsigned Opcode) {
1556 
1557   // If the source is undef, then just emit a nop.
1558   if (isa<UndefValue>(CI.getArgOperand(1)))
1559     return true;
1560 
1561   SmallVector<Register, 3> SrcRegs;
1562 
1563   unsigned MinPtrSize = UINT_MAX;
1564   for (auto AI = CI.arg_begin(), AE = CI.arg_end(); std::next(AI) != AE; ++AI) {
1565     Register SrcReg = getOrCreateVReg(**AI);
1566     LLT SrcTy = MRI->getType(SrcReg);
1567     if (SrcTy.isPointer())
1568       MinPtrSize = std::min<unsigned>(SrcTy.getSizeInBits(), MinPtrSize);
1569     SrcRegs.push_back(SrcReg);
1570   }
1571 
1572   LLT SizeTy = LLT::scalar(MinPtrSize);
1573 
1574   // The size operand should be the minimum of the pointer sizes.
1575   Register &SizeOpReg = SrcRegs[SrcRegs.size() - 1];
1576   if (MRI->getType(SizeOpReg) != SizeTy)
1577     SizeOpReg = MIRBuilder.buildZExtOrTrunc(SizeTy, SizeOpReg).getReg(0);
1578 
1579   auto ICall = MIRBuilder.buildInstr(Opcode);
1580   for (Register SrcReg : SrcRegs)
1581     ICall.addUse(SrcReg);
1582 
1583   Align DstAlign;
1584   Align SrcAlign;
1585   unsigned IsVol =
1586       cast<ConstantInt>(CI.getArgOperand(CI.getNumArgOperands() - 1))
1587           ->getZExtValue();
1588 
1589   if (auto *MCI = dyn_cast<MemCpyInst>(&CI)) {
1590     DstAlign = MCI->getDestAlign().valueOrOne();
1591     SrcAlign = MCI->getSourceAlign().valueOrOne();
1592   } else if (auto *MCI = dyn_cast<MemCpyInlineInst>(&CI)) {
1593     DstAlign = MCI->getDestAlign().valueOrOne();
1594     SrcAlign = MCI->getSourceAlign().valueOrOne();
1595   } else if (auto *MMI = dyn_cast<MemMoveInst>(&CI)) {
1596     DstAlign = MMI->getDestAlign().valueOrOne();
1597     SrcAlign = MMI->getSourceAlign().valueOrOne();
1598   } else {
1599     auto *MSI = cast<MemSetInst>(&CI);
1600     DstAlign = MSI->getDestAlign().valueOrOne();
1601   }
1602 
1603   if (Opcode != TargetOpcode::G_MEMCPY_INLINE) {
1604     // We need to propagate the tail call flag from the IR inst as an argument.
1605     // Otherwise, we have to pessimize and assume later that we cannot tail call
1606     // any memory intrinsics.
1607     ICall.addImm(CI.isTailCall() ? 1 : 0);
1608   }
1609 
1610   // Create mem operands to store the alignment and volatile info.
1611   auto VolFlag = IsVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
1612   ICall.addMemOperand(MF->getMachineMemOperand(
1613       MachinePointerInfo(CI.getArgOperand(0)),
1614       MachineMemOperand::MOStore | VolFlag, 1, DstAlign));
1615   if (Opcode != TargetOpcode::G_MEMSET)
1616     ICall.addMemOperand(MF->getMachineMemOperand(
1617         MachinePointerInfo(CI.getArgOperand(1)),
1618         MachineMemOperand::MOLoad | VolFlag, 1, SrcAlign));
1619 
1620   return true;
1621 }
1622 
1623 void IRTranslator::getStackGuard(Register DstReg,
1624                                  MachineIRBuilder &MIRBuilder) {
1625   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
1626   MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF));
1627   auto MIB =
1628       MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD, {DstReg}, {});
1629 
1630   auto &TLI = *MF->getSubtarget().getTargetLowering();
1631   Value *Global = TLI.getSDagStackGuard(*MF->getFunction().getParent());
1632   if (!Global)
1633     return;
1634 
1635   unsigned AddrSpace = Global->getType()->getPointerAddressSpace();
1636   LLT PtrTy = LLT::pointer(AddrSpace, DL->getPointerSizeInBits(AddrSpace));
1637 
1638   MachinePointerInfo MPInfo(Global);
1639   auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
1640                MachineMemOperand::MODereferenceable;
1641   MachineMemOperand *MemRef = MF->getMachineMemOperand(
1642       MPInfo, Flags, PtrTy, DL->getPointerABIAlignment(AddrSpace));
1643   MIB.setMemRefs({MemRef});
1644 }
1645 
1646 bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op,
1647                                               MachineIRBuilder &MIRBuilder) {
1648   ArrayRef<Register> ResRegs = getOrCreateVRegs(CI);
1649   MIRBuilder.buildInstr(
1650       Op, {ResRegs[0], ResRegs[1]},
1651       {getOrCreateVReg(*CI.getOperand(0)), getOrCreateVReg(*CI.getOperand(1))});
1652 
1653   return true;
1654 }
1655 
1656 bool IRTranslator::translateFixedPointIntrinsic(unsigned Op, const CallInst &CI,
1657                                                 MachineIRBuilder &MIRBuilder) {
1658   Register Dst = getOrCreateVReg(CI);
1659   Register Src0 = getOrCreateVReg(*CI.getOperand(0));
1660   Register Src1 = getOrCreateVReg(*CI.getOperand(1));
1661   uint64_t Scale = cast<ConstantInt>(CI.getOperand(2))->getZExtValue();
1662   MIRBuilder.buildInstr(Op, {Dst}, { Src0, Src1, Scale });
1663   return true;
1664 }
1665 
1666 unsigned IRTranslator::getSimpleIntrinsicOpcode(Intrinsic::ID ID) {
1667   switch (ID) {
1668     default:
1669       break;
1670     case Intrinsic::bswap:
1671       return TargetOpcode::G_BSWAP;
1672     case Intrinsic::bitreverse:
1673       return TargetOpcode::G_BITREVERSE;
1674     case Intrinsic::fshl:
1675       return TargetOpcode::G_FSHL;
1676     case Intrinsic::fshr:
1677       return TargetOpcode::G_FSHR;
1678     case Intrinsic::ceil:
1679       return TargetOpcode::G_FCEIL;
1680     case Intrinsic::cos:
1681       return TargetOpcode::G_FCOS;
1682     case Intrinsic::ctpop:
1683       return TargetOpcode::G_CTPOP;
1684     case Intrinsic::exp:
1685       return TargetOpcode::G_FEXP;
1686     case Intrinsic::exp2:
1687       return TargetOpcode::G_FEXP2;
1688     case Intrinsic::fabs:
1689       return TargetOpcode::G_FABS;
1690     case Intrinsic::copysign:
1691       return TargetOpcode::G_FCOPYSIGN;
1692     case Intrinsic::minnum:
1693       return TargetOpcode::G_FMINNUM;
1694     case Intrinsic::maxnum:
1695       return TargetOpcode::G_FMAXNUM;
1696     case Intrinsic::minimum:
1697       return TargetOpcode::G_FMINIMUM;
1698     case Intrinsic::maximum:
1699       return TargetOpcode::G_FMAXIMUM;
1700     case Intrinsic::canonicalize:
1701       return TargetOpcode::G_FCANONICALIZE;
1702     case Intrinsic::floor:
1703       return TargetOpcode::G_FFLOOR;
1704     case Intrinsic::fma:
1705       return TargetOpcode::G_FMA;
1706     case Intrinsic::log:
1707       return TargetOpcode::G_FLOG;
1708     case Intrinsic::log2:
1709       return TargetOpcode::G_FLOG2;
1710     case Intrinsic::log10:
1711       return TargetOpcode::G_FLOG10;
1712     case Intrinsic::nearbyint:
1713       return TargetOpcode::G_FNEARBYINT;
1714     case Intrinsic::pow:
1715       return TargetOpcode::G_FPOW;
1716     case Intrinsic::powi:
1717       return TargetOpcode::G_FPOWI;
1718     case Intrinsic::rint:
1719       return TargetOpcode::G_FRINT;
1720     case Intrinsic::round:
1721       return TargetOpcode::G_INTRINSIC_ROUND;
1722     case Intrinsic::roundeven:
1723       return TargetOpcode::G_INTRINSIC_ROUNDEVEN;
1724     case Intrinsic::sin:
1725       return TargetOpcode::G_FSIN;
1726     case Intrinsic::sqrt:
1727       return TargetOpcode::G_FSQRT;
1728     case Intrinsic::trunc:
1729       return TargetOpcode::G_INTRINSIC_TRUNC;
1730     case Intrinsic::readcyclecounter:
1731       return TargetOpcode::G_READCYCLECOUNTER;
1732     case Intrinsic::ptrmask:
1733       return TargetOpcode::G_PTRMASK;
1734     case Intrinsic::lrint:
1735       return TargetOpcode::G_INTRINSIC_LRINT;
1736     // FADD/FMUL require checking the FMF, so are handled elsewhere.
1737     case Intrinsic::vector_reduce_fmin:
1738       return TargetOpcode::G_VECREDUCE_FMIN;
1739     case Intrinsic::vector_reduce_fmax:
1740       return TargetOpcode::G_VECREDUCE_FMAX;
1741     case Intrinsic::vector_reduce_add:
1742       return TargetOpcode::G_VECREDUCE_ADD;
1743     case Intrinsic::vector_reduce_mul:
1744       return TargetOpcode::G_VECREDUCE_MUL;
1745     case Intrinsic::vector_reduce_and:
1746       return TargetOpcode::G_VECREDUCE_AND;
1747     case Intrinsic::vector_reduce_or:
1748       return TargetOpcode::G_VECREDUCE_OR;
1749     case Intrinsic::vector_reduce_xor:
1750       return TargetOpcode::G_VECREDUCE_XOR;
1751     case Intrinsic::vector_reduce_smax:
1752       return TargetOpcode::G_VECREDUCE_SMAX;
1753     case Intrinsic::vector_reduce_smin:
1754       return TargetOpcode::G_VECREDUCE_SMIN;
1755     case Intrinsic::vector_reduce_umax:
1756       return TargetOpcode::G_VECREDUCE_UMAX;
1757     case Intrinsic::vector_reduce_umin:
1758       return TargetOpcode::G_VECREDUCE_UMIN;
1759     case Intrinsic::lround:
1760       return TargetOpcode::G_LROUND;
1761     case Intrinsic::llround:
1762       return TargetOpcode::G_LLROUND;
1763   }
1764   return Intrinsic::not_intrinsic;
1765 }
1766 
1767 bool IRTranslator::translateSimpleIntrinsic(const CallInst &CI,
1768                                             Intrinsic::ID ID,
1769                                             MachineIRBuilder &MIRBuilder) {
1770 
1771   unsigned Op = getSimpleIntrinsicOpcode(ID);
1772 
1773   // Is this a simple intrinsic?
1774   if (Op == Intrinsic::not_intrinsic)
1775     return false;
1776 
1777   // Yes. Let's translate it.
1778   SmallVector<llvm::SrcOp, 4> VRegs;
1779   for (auto &Arg : CI.arg_operands())
1780     VRegs.push_back(getOrCreateVReg(*Arg));
1781 
1782   MIRBuilder.buildInstr(Op, {getOrCreateVReg(CI)}, VRegs,
1783                         MachineInstr::copyFlagsFromInstruction(CI));
1784   return true;
1785 }
1786 
1787 // TODO: Include ConstainedOps.def when all strict instructions are defined.
1788 static unsigned getConstrainedOpcode(Intrinsic::ID ID) {
1789   switch (ID) {
1790   case Intrinsic::experimental_constrained_fadd:
1791     return TargetOpcode::G_STRICT_FADD;
1792   case Intrinsic::experimental_constrained_fsub:
1793     return TargetOpcode::G_STRICT_FSUB;
1794   case Intrinsic::experimental_constrained_fmul:
1795     return TargetOpcode::G_STRICT_FMUL;
1796   case Intrinsic::experimental_constrained_fdiv:
1797     return TargetOpcode::G_STRICT_FDIV;
1798   case Intrinsic::experimental_constrained_frem:
1799     return TargetOpcode::G_STRICT_FREM;
1800   case Intrinsic::experimental_constrained_fma:
1801     return TargetOpcode::G_STRICT_FMA;
1802   case Intrinsic::experimental_constrained_sqrt:
1803     return TargetOpcode::G_STRICT_FSQRT;
1804   default:
1805     return 0;
1806   }
1807 }
1808 
1809 bool IRTranslator::translateConstrainedFPIntrinsic(
1810   const ConstrainedFPIntrinsic &FPI, MachineIRBuilder &MIRBuilder) {
1811   fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue();
1812 
1813   unsigned Opcode = getConstrainedOpcode(FPI.getIntrinsicID());
1814   if (!Opcode)
1815     return false;
1816 
1817   unsigned Flags = MachineInstr::copyFlagsFromInstruction(FPI);
1818   if (EB == fp::ExceptionBehavior::ebIgnore)
1819     Flags |= MachineInstr::NoFPExcept;
1820 
1821   SmallVector<llvm::SrcOp, 4> VRegs;
1822   VRegs.push_back(getOrCreateVReg(*FPI.getArgOperand(0)));
1823   if (!FPI.isUnaryOp())
1824     VRegs.push_back(getOrCreateVReg(*FPI.getArgOperand(1)));
1825   if (FPI.isTernaryOp())
1826     VRegs.push_back(getOrCreateVReg(*FPI.getArgOperand(2)));
1827 
1828   MIRBuilder.buildInstr(Opcode, {getOrCreateVReg(FPI)}, VRegs, Flags);
1829   return true;
1830 }
1831 
1832 bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID,
1833                                            MachineIRBuilder &MIRBuilder) {
1834   if (auto *MI = dyn_cast<AnyMemIntrinsic>(&CI)) {
1835     if (ORE->enabled()) {
1836       const Function &F = *MI->getParent()->getParent();
1837       auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
1838       if (MemoryOpRemark::canHandle(MI, TLI)) {
1839         MemoryOpRemark R(*ORE, "gisel-irtranslator-memsize", *DL, TLI);
1840         R.visit(MI);
1841       }
1842     }
1843   }
1844 
1845   // If this is a simple intrinsic (that is, we just need to add a def of
1846   // a vreg, and uses for each arg operand, then translate it.
1847   if (translateSimpleIntrinsic(CI, ID, MIRBuilder))
1848     return true;
1849 
1850   switch (ID) {
1851   default:
1852     break;
1853   case Intrinsic::lifetime_start:
1854   case Intrinsic::lifetime_end: {
1855     // No stack colouring in O0, discard region information.
1856     if (MF->getTarget().getOptLevel() == CodeGenOpt::None)
1857       return true;
1858 
1859     unsigned Op = ID == Intrinsic::lifetime_start ? TargetOpcode::LIFETIME_START
1860                                                   : TargetOpcode::LIFETIME_END;
1861 
1862     // Get the underlying objects for the location passed on the lifetime
1863     // marker.
1864     SmallVector<const Value *, 4> Allocas;
1865     getUnderlyingObjects(CI.getArgOperand(1), Allocas);
1866 
1867     // Iterate over each underlying object, creating lifetime markers for each
1868     // static alloca. Quit if we find a non-static alloca.
1869     for (const Value *V : Allocas) {
1870       const AllocaInst *AI = dyn_cast<AllocaInst>(V);
1871       if (!AI)
1872         continue;
1873 
1874       if (!AI->isStaticAlloca())
1875         return true;
1876 
1877       MIRBuilder.buildInstr(Op).addFrameIndex(getOrCreateFrameIndex(*AI));
1878     }
1879     return true;
1880   }
1881   case Intrinsic::dbg_declare: {
1882     const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI);
1883     assert(DI.getVariable() && "Missing variable");
1884 
1885     const Value *Address = DI.getAddress();
1886     if (!Address || isa<UndefValue>(Address)) {
1887       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
1888       return true;
1889     }
1890 
1891     assert(DI.getVariable()->isValidLocationForIntrinsic(
1892                MIRBuilder.getDebugLoc()) &&
1893            "Expected inlined-at fields to agree");
1894     auto AI = dyn_cast<AllocaInst>(Address);
1895     if (AI && AI->isStaticAlloca()) {
1896       // Static allocas are tracked at the MF level, no need for DBG_VALUE
1897       // instructions (in fact, they get ignored if they *do* exist).
1898       MF->setVariableDbgInfo(DI.getVariable(), DI.getExpression(),
1899                              getOrCreateFrameIndex(*AI), DI.getDebugLoc());
1900     } else {
1901       // A dbg.declare describes the address of a source variable, so lower it
1902       // into an indirect DBG_VALUE.
1903       MIRBuilder.buildIndirectDbgValue(getOrCreateVReg(*Address),
1904                                        DI.getVariable(), DI.getExpression());
1905     }
1906     return true;
1907   }
1908   case Intrinsic::dbg_label: {
1909     const DbgLabelInst &DI = cast<DbgLabelInst>(CI);
1910     assert(DI.getLabel() && "Missing label");
1911 
1912     assert(DI.getLabel()->isValidLocationForIntrinsic(
1913                MIRBuilder.getDebugLoc()) &&
1914            "Expected inlined-at fields to agree");
1915 
1916     MIRBuilder.buildDbgLabel(DI.getLabel());
1917     return true;
1918   }
1919   case Intrinsic::vaend:
1920     // No target I know of cares about va_end. Certainly no in-tree target
1921     // does. Simplest intrinsic ever!
1922     return true;
1923   case Intrinsic::vastart: {
1924     auto &TLI = *MF->getSubtarget().getTargetLowering();
1925     Value *Ptr = CI.getArgOperand(0);
1926     unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8;
1927 
1928     // FIXME: Get alignment
1929     MIRBuilder.buildInstr(TargetOpcode::G_VASTART, {}, {getOrCreateVReg(*Ptr)})
1930         .addMemOperand(MF->getMachineMemOperand(MachinePointerInfo(Ptr),
1931                                                 MachineMemOperand::MOStore,
1932                                                 ListSize, Align(1)));
1933     return true;
1934   }
1935   case Intrinsic::dbg_value: {
1936     // This form of DBG_VALUE is target-independent.
1937     const DbgValueInst &DI = cast<DbgValueInst>(CI);
1938     const Value *V = DI.getValue();
1939     assert(DI.getVariable()->isValidLocationForIntrinsic(
1940                MIRBuilder.getDebugLoc()) &&
1941            "Expected inlined-at fields to agree");
1942     if (!V || DI.hasArgList()) {
1943       // DI cannot produce a valid DBG_VALUE, so produce an undef DBG_VALUE to
1944       // terminate any prior location.
1945       MIRBuilder.buildIndirectDbgValue(0, DI.getVariable(), DI.getExpression());
1946     } else if (const auto *CI = dyn_cast<Constant>(V)) {
1947       MIRBuilder.buildConstDbgValue(*CI, DI.getVariable(), DI.getExpression());
1948     } else {
1949       for (Register Reg : getOrCreateVRegs(*V)) {
1950         // FIXME: This does not handle register-indirect values at offset 0. The
1951         // direct/indirect thing shouldn't really be handled by something as
1952         // implicit as reg+noreg vs reg+imm in the first place, but it seems
1953         // pretty baked in right now.
1954         MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(), DI.getExpression());
1955       }
1956     }
1957     return true;
1958   }
1959   case Intrinsic::uadd_with_overflow:
1960     return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDO, MIRBuilder);
1961   case Intrinsic::sadd_with_overflow:
1962     return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder);
1963   case Intrinsic::usub_with_overflow:
1964     return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBO, MIRBuilder);
1965   case Intrinsic::ssub_with_overflow:
1966     return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder);
1967   case Intrinsic::umul_with_overflow:
1968     return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder);
1969   case Intrinsic::smul_with_overflow:
1970     return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder);
1971   case Intrinsic::uadd_sat:
1972     return translateBinaryOp(TargetOpcode::G_UADDSAT, CI, MIRBuilder);
1973   case Intrinsic::sadd_sat:
1974     return translateBinaryOp(TargetOpcode::G_SADDSAT, CI, MIRBuilder);
1975   case Intrinsic::usub_sat:
1976     return translateBinaryOp(TargetOpcode::G_USUBSAT, CI, MIRBuilder);
1977   case Intrinsic::ssub_sat:
1978     return translateBinaryOp(TargetOpcode::G_SSUBSAT, CI, MIRBuilder);
1979   case Intrinsic::ushl_sat:
1980     return translateBinaryOp(TargetOpcode::G_USHLSAT, CI, MIRBuilder);
1981   case Intrinsic::sshl_sat:
1982     return translateBinaryOp(TargetOpcode::G_SSHLSAT, CI, MIRBuilder);
1983   case Intrinsic::umin:
1984     return translateBinaryOp(TargetOpcode::G_UMIN, CI, MIRBuilder);
1985   case Intrinsic::umax:
1986     return translateBinaryOp(TargetOpcode::G_UMAX, CI, MIRBuilder);
1987   case Intrinsic::smin:
1988     return translateBinaryOp(TargetOpcode::G_SMIN, CI, MIRBuilder);
1989   case Intrinsic::smax:
1990     return translateBinaryOp(TargetOpcode::G_SMAX, CI, MIRBuilder);
1991   case Intrinsic::abs:
1992     // TODO: Preserve "int min is poison" arg in GMIR?
1993     return translateUnaryOp(TargetOpcode::G_ABS, CI, MIRBuilder);
1994   case Intrinsic::smul_fix:
1995     return translateFixedPointIntrinsic(TargetOpcode::G_SMULFIX, CI, MIRBuilder);
1996   case Intrinsic::umul_fix:
1997     return translateFixedPointIntrinsic(TargetOpcode::G_UMULFIX, CI, MIRBuilder);
1998   case Intrinsic::smul_fix_sat:
1999     return translateFixedPointIntrinsic(TargetOpcode::G_SMULFIXSAT, CI, MIRBuilder);
2000   case Intrinsic::umul_fix_sat:
2001     return translateFixedPointIntrinsic(TargetOpcode::G_UMULFIXSAT, CI, MIRBuilder);
2002   case Intrinsic::sdiv_fix:
2003     return translateFixedPointIntrinsic(TargetOpcode::G_SDIVFIX, CI, MIRBuilder);
2004   case Intrinsic::udiv_fix:
2005     return translateFixedPointIntrinsic(TargetOpcode::G_UDIVFIX, CI, MIRBuilder);
2006   case Intrinsic::sdiv_fix_sat:
2007     return translateFixedPointIntrinsic(TargetOpcode::G_SDIVFIXSAT, CI, MIRBuilder);
2008   case Intrinsic::udiv_fix_sat:
2009     return translateFixedPointIntrinsic(TargetOpcode::G_UDIVFIXSAT, CI, MIRBuilder);
2010   case Intrinsic::fmuladd: {
2011     const TargetMachine &TM = MF->getTarget();
2012     const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
2013     Register Dst = getOrCreateVReg(CI);
2014     Register Op0 = getOrCreateVReg(*CI.getArgOperand(0));
2015     Register Op1 = getOrCreateVReg(*CI.getArgOperand(1));
2016     Register Op2 = getOrCreateVReg(*CI.getArgOperand(2));
2017     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
2018         TLI.isFMAFasterThanFMulAndFAdd(*MF,
2019                                        TLI.getValueType(*DL, CI.getType()))) {
2020       // TODO: Revisit this to see if we should move this part of the
2021       // lowering to the combiner.
2022       MIRBuilder.buildFMA(Dst, Op0, Op1, Op2,
2023                           MachineInstr::copyFlagsFromInstruction(CI));
2024     } else {
2025       LLT Ty = getLLTForType(*CI.getType(), *DL);
2026       auto FMul = MIRBuilder.buildFMul(
2027           Ty, Op0, Op1, MachineInstr::copyFlagsFromInstruction(CI));
2028       MIRBuilder.buildFAdd(Dst, FMul, Op2,
2029                            MachineInstr::copyFlagsFromInstruction(CI));
2030     }
2031     return true;
2032   }
2033   case Intrinsic::convert_from_fp16:
2034     // FIXME: This intrinsic should probably be removed from the IR.
2035     MIRBuilder.buildFPExt(getOrCreateVReg(CI),
2036                           getOrCreateVReg(*CI.getArgOperand(0)),
2037                           MachineInstr::copyFlagsFromInstruction(CI));
2038     return true;
2039   case Intrinsic::convert_to_fp16:
2040     // FIXME: This intrinsic should probably be removed from the IR.
2041     MIRBuilder.buildFPTrunc(getOrCreateVReg(CI),
2042                             getOrCreateVReg(*CI.getArgOperand(0)),
2043                             MachineInstr::copyFlagsFromInstruction(CI));
2044     return true;
2045   case Intrinsic::memcpy_inline:
2046     return translateMemFunc(CI, MIRBuilder, TargetOpcode::G_MEMCPY_INLINE);
2047   case Intrinsic::memcpy:
2048     return translateMemFunc(CI, MIRBuilder, TargetOpcode::G_MEMCPY);
2049   case Intrinsic::memmove:
2050     return translateMemFunc(CI, MIRBuilder, TargetOpcode::G_MEMMOVE);
2051   case Intrinsic::memset:
2052     return translateMemFunc(CI, MIRBuilder, TargetOpcode::G_MEMSET);
2053   case Intrinsic::eh_typeid_for: {
2054     GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0));
2055     Register Reg = getOrCreateVReg(CI);
2056     unsigned TypeID = MF->getTypeIDFor(GV);
2057     MIRBuilder.buildConstant(Reg, TypeID);
2058     return true;
2059   }
2060   case Intrinsic::objectsize:
2061     llvm_unreachable("llvm.objectsize.* should have been lowered already");
2062 
2063   case Intrinsic::is_constant:
2064     llvm_unreachable("llvm.is.constant.* should have been lowered already");
2065 
2066   case Intrinsic::stackguard:
2067     getStackGuard(getOrCreateVReg(CI), MIRBuilder);
2068     return true;
2069   case Intrinsic::stackprotector: {
2070     LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
2071     Register GuardVal = MRI->createGenericVirtualRegister(PtrTy);
2072     getStackGuard(GuardVal, MIRBuilder);
2073 
2074     AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1));
2075     int FI = getOrCreateFrameIndex(*Slot);
2076     MF->getFrameInfo().setStackProtectorIndex(FI);
2077 
2078     MIRBuilder.buildStore(
2079         GuardVal, getOrCreateVReg(*Slot),
2080         *MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
2081                                   MachineMemOperand::MOStore |
2082                                       MachineMemOperand::MOVolatile,
2083                                   PtrTy, Align(8)));
2084     return true;
2085   }
2086   case Intrinsic::stacksave: {
2087     // Save the stack pointer to the location provided by the intrinsic.
2088     Register Reg = getOrCreateVReg(CI);
2089     Register StackPtr = MF->getSubtarget()
2090                             .getTargetLowering()
2091                             ->getStackPointerRegisterToSaveRestore();
2092 
2093     // If the target doesn't specify a stack pointer, then fall back.
2094     if (!StackPtr)
2095       return false;
2096 
2097     MIRBuilder.buildCopy(Reg, StackPtr);
2098     return true;
2099   }
2100   case Intrinsic::stackrestore: {
2101     // Restore the stack pointer from the location provided by the intrinsic.
2102     Register Reg = getOrCreateVReg(*CI.getArgOperand(0));
2103     Register StackPtr = MF->getSubtarget()
2104                             .getTargetLowering()
2105                             ->getStackPointerRegisterToSaveRestore();
2106 
2107     // If the target doesn't specify a stack pointer, then fall back.
2108     if (!StackPtr)
2109       return false;
2110 
2111     MIRBuilder.buildCopy(StackPtr, Reg);
2112     return true;
2113   }
2114   case Intrinsic::cttz:
2115   case Intrinsic::ctlz: {
2116     ConstantInt *Cst = cast<ConstantInt>(CI.getArgOperand(1));
2117     bool isTrailing = ID == Intrinsic::cttz;
2118     unsigned Opcode = isTrailing
2119                           ? Cst->isZero() ? TargetOpcode::G_CTTZ
2120                                           : TargetOpcode::G_CTTZ_ZERO_UNDEF
2121                           : Cst->isZero() ? TargetOpcode::G_CTLZ
2122                                           : TargetOpcode::G_CTLZ_ZERO_UNDEF;
2123     MIRBuilder.buildInstr(Opcode, {getOrCreateVReg(CI)},
2124                           {getOrCreateVReg(*CI.getArgOperand(0))});
2125     return true;
2126   }
2127   case Intrinsic::invariant_start: {
2128     LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
2129     Register Undef = MRI->createGenericVirtualRegister(PtrTy);
2130     MIRBuilder.buildUndef(Undef);
2131     return true;
2132   }
2133   case Intrinsic::invariant_end:
2134     return true;
2135   case Intrinsic::expect:
2136   case Intrinsic::annotation:
2137   case Intrinsic::ptr_annotation:
2138   case Intrinsic::launder_invariant_group:
2139   case Intrinsic::strip_invariant_group: {
2140     // Drop the intrinsic, but forward the value.
2141     MIRBuilder.buildCopy(getOrCreateVReg(CI),
2142                          getOrCreateVReg(*CI.getArgOperand(0)));
2143     return true;
2144   }
2145   case Intrinsic::assume:
2146   case Intrinsic::experimental_noalias_scope_decl:
2147   case Intrinsic::var_annotation:
2148   case Intrinsic::sideeffect:
2149     // Discard annotate attributes, assumptions, and artificial side-effects.
2150     return true;
2151   case Intrinsic::read_volatile_register:
2152   case Intrinsic::read_register: {
2153     Value *Arg = CI.getArgOperand(0);
2154     MIRBuilder
2155         .buildInstr(TargetOpcode::G_READ_REGISTER, {getOrCreateVReg(CI)}, {})
2156         .addMetadata(cast<MDNode>(cast<MetadataAsValue>(Arg)->getMetadata()));
2157     return true;
2158   }
2159   case Intrinsic::write_register: {
2160     Value *Arg = CI.getArgOperand(0);
2161     MIRBuilder.buildInstr(TargetOpcode::G_WRITE_REGISTER)
2162       .addMetadata(cast<MDNode>(cast<MetadataAsValue>(Arg)->getMetadata()))
2163       .addUse(getOrCreateVReg(*CI.getArgOperand(1)));
2164     return true;
2165   }
2166   case Intrinsic::localescape: {
2167     MachineBasicBlock &EntryMBB = MF->front();
2168     StringRef EscapedName = GlobalValue::dropLLVMManglingEscape(MF->getName());
2169 
2170     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
2171     // is the same on all targets.
2172     for (unsigned Idx = 0, E = CI.getNumArgOperands(); Idx < E; ++Idx) {
2173       Value *Arg = CI.getArgOperand(Idx)->stripPointerCasts();
2174       if (isa<ConstantPointerNull>(Arg))
2175         continue; // Skip null pointers. They represent a hole in index space.
2176 
2177       int FI = getOrCreateFrameIndex(*cast<AllocaInst>(Arg));
2178       MCSymbol *FrameAllocSym =
2179           MF->getMMI().getContext().getOrCreateFrameAllocSymbol(EscapedName,
2180                                                                 Idx);
2181 
2182       // This should be inserted at the start of the entry block.
2183       auto LocalEscape =
2184           MIRBuilder.buildInstrNoInsert(TargetOpcode::LOCAL_ESCAPE)
2185               .addSym(FrameAllocSym)
2186               .addFrameIndex(FI);
2187 
2188       EntryMBB.insert(EntryMBB.begin(), LocalEscape);
2189     }
2190 
2191     return true;
2192   }
2193   case Intrinsic::vector_reduce_fadd:
2194   case Intrinsic::vector_reduce_fmul: {
2195     // Need to check for the reassoc flag to decide whether we want a
2196     // sequential reduction opcode or not.
2197     Register Dst = getOrCreateVReg(CI);
2198     Register ScalarSrc = getOrCreateVReg(*CI.getArgOperand(0));
2199     Register VecSrc = getOrCreateVReg(*CI.getArgOperand(1));
2200     unsigned Opc = 0;
2201     if (!CI.hasAllowReassoc()) {
2202       // The sequential ordering case.
2203       Opc = ID == Intrinsic::vector_reduce_fadd
2204                 ? TargetOpcode::G_VECREDUCE_SEQ_FADD
2205                 : TargetOpcode::G_VECREDUCE_SEQ_FMUL;
2206       MIRBuilder.buildInstr(Opc, {Dst}, {ScalarSrc, VecSrc},
2207                             MachineInstr::copyFlagsFromInstruction(CI));
2208       return true;
2209     }
2210     // We split the operation into a separate G_FADD/G_FMUL + the reduce,
2211     // since the associativity doesn't matter.
2212     unsigned ScalarOpc;
2213     if (ID == Intrinsic::vector_reduce_fadd) {
2214       Opc = TargetOpcode::G_VECREDUCE_FADD;
2215       ScalarOpc = TargetOpcode::G_FADD;
2216     } else {
2217       Opc = TargetOpcode::G_VECREDUCE_FMUL;
2218       ScalarOpc = TargetOpcode::G_FMUL;
2219     }
2220     LLT DstTy = MRI->getType(Dst);
2221     auto Rdx = MIRBuilder.buildInstr(
2222         Opc, {DstTy}, {VecSrc}, MachineInstr::copyFlagsFromInstruction(CI));
2223     MIRBuilder.buildInstr(ScalarOpc, {Dst}, {ScalarSrc, Rdx},
2224                           MachineInstr::copyFlagsFromInstruction(CI));
2225 
2226     return true;
2227   }
2228   case Intrinsic::trap:
2229   case Intrinsic::debugtrap:
2230   case Intrinsic::ubsantrap: {
2231     StringRef TrapFuncName =
2232         CI.getAttributes().getFnAttr("trap-func-name").getValueAsString();
2233     if (TrapFuncName.empty())
2234       break; // Use the default handling.
2235     CallLowering::CallLoweringInfo Info;
2236     if (ID == Intrinsic::ubsantrap) {
2237       Info.OrigArgs.push_back({getOrCreateVRegs(*CI.getArgOperand(0)),
2238                                CI.getArgOperand(0)->getType(), 0});
2239     }
2240     Info.Callee =
2241         MachineOperand::CreateES(MF->createExternalSymbolName(TrapFuncName));
2242     Info.CB = &CI;
2243     Info.OrigRet = {Register(), Type::getVoidTy(CI.getContext()), 0};
2244     return CLI->lowerCall(MIRBuilder, Info);
2245   }
2246 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)  \
2247   case Intrinsic::INTRINSIC:
2248 #include "llvm/IR/ConstrainedOps.def"
2249     return translateConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(CI),
2250                                            MIRBuilder);
2251 
2252   }
2253   return false;
2254 }
2255 
2256 bool IRTranslator::translateInlineAsm(const CallBase &CB,
2257                                       MachineIRBuilder &MIRBuilder) {
2258 
2259   const InlineAsmLowering *ALI = MF->getSubtarget().getInlineAsmLowering();
2260 
2261   if (!ALI) {
2262     LLVM_DEBUG(
2263         dbgs() << "Inline asm lowering is not supported for this target yet\n");
2264     return false;
2265   }
2266 
2267   return ALI->lowerInlineAsm(
2268       MIRBuilder, CB, [&](const Value &Val) { return getOrCreateVRegs(Val); });
2269 }
2270 
2271 bool IRTranslator::translateCallBase(const CallBase &CB,
2272                                      MachineIRBuilder &MIRBuilder) {
2273   ArrayRef<Register> Res = getOrCreateVRegs(CB);
2274 
2275   SmallVector<ArrayRef<Register>, 8> Args;
2276   Register SwiftInVReg = 0;
2277   Register SwiftErrorVReg = 0;
2278   for (auto &Arg : CB.args()) {
2279     if (CLI->supportSwiftError() && isSwiftError(Arg)) {
2280       assert(SwiftInVReg == 0 && "Expected only one swift error argument");
2281       LLT Ty = getLLTForType(*Arg->getType(), *DL);
2282       SwiftInVReg = MRI->createGenericVirtualRegister(Ty);
2283       MIRBuilder.buildCopy(SwiftInVReg, SwiftError.getOrCreateVRegUseAt(
2284                                             &CB, &MIRBuilder.getMBB(), Arg));
2285       Args.emplace_back(makeArrayRef(SwiftInVReg));
2286       SwiftErrorVReg =
2287           SwiftError.getOrCreateVRegDefAt(&CB, &MIRBuilder.getMBB(), Arg);
2288       continue;
2289     }
2290     Args.push_back(getOrCreateVRegs(*Arg));
2291   }
2292 
2293   if (auto *CI = dyn_cast<CallInst>(&CB)) {
2294     if (ORE->enabled()) {
2295       const Function &F = *CI->getParent()->getParent();
2296       auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
2297       if (MemoryOpRemark::canHandle(CI, TLI)) {
2298         MemoryOpRemark R(*ORE, "gisel-irtranslator-memsize", *DL, TLI);
2299         R.visit(CI);
2300       }
2301     }
2302   }
2303 
2304   // We don't set HasCalls on MFI here yet because call lowering may decide to
2305   // optimize into tail calls. Instead, we defer that to selection where a final
2306   // scan is done to check if any instructions are calls.
2307   bool Success =
2308       CLI->lowerCall(MIRBuilder, CB, Res, Args, SwiftErrorVReg,
2309                      [&]() { return getOrCreateVReg(*CB.getCalledOperand()); });
2310 
2311   // Check if we just inserted a tail call.
2312   if (Success) {
2313     assert(!HasTailCall && "Can't tail call return twice from block?");
2314     const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
2315     HasTailCall = TII->isTailCall(*std::prev(MIRBuilder.getInsertPt()));
2316   }
2317 
2318   return Success;
2319 }
2320 
2321 bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) {
2322   const CallInst &CI = cast<CallInst>(U);
2323   auto TII = MF->getTarget().getIntrinsicInfo();
2324   const Function *F = CI.getCalledFunction();
2325 
2326   // FIXME: support Windows dllimport function calls.
2327   if (F && (F->hasDLLImportStorageClass() ||
2328             (MF->getTarget().getTargetTriple().isOSWindows() &&
2329              F->hasExternalWeakLinkage())))
2330     return false;
2331 
2332   // FIXME: support control flow guard targets.
2333   if (CI.countOperandBundlesOfType(LLVMContext::OB_cfguardtarget))
2334     return false;
2335 
2336   if (CI.isInlineAsm())
2337     return translateInlineAsm(CI, MIRBuilder);
2338 
2339   if (F && F->hasFnAttribute("dontcall")) {
2340     unsigned LocCookie = 0;
2341     if (MDNode *MD = CI.getMetadata("srcloc"))
2342       LocCookie =
2343           mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue();
2344     DiagnosticInfoDontCall D(F->getName(), LocCookie);
2345     F->getContext().diagnose(D);
2346   }
2347 
2348   Intrinsic::ID ID = Intrinsic::not_intrinsic;
2349   if (F && F->isIntrinsic()) {
2350     ID = F->getIntrinsicID();
2351     if (TII && ID == Intrinsic::not_intrinsic)
2352       ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F));
2353   }
2354 
2355   if (!F || !F->isIntrinsic() || ID == Intrinsic::not_intrinsic)
2356     return translateCallBase(CI, MIRBuilder);
2357 
2358   assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
2359 
2360   if (translateKnownIntrinsic(CI, ID, MIRBuilder))
2361     return true;
2362 
2363   ArrayRef<Register> ResultRegs;
2364   if (!CI.getType()->isVoidTy())
2365     ResultRegs = getOrCreateVRegs(CI);
2366 
2367   // Ignore the callsite attributes. Backend code is most likely not expecting
2368   // an intrinsic to sometimes have side effects and sometimes not.
2369   MachineInstrBuilder MIB =
2370       MIRBuilder.buildIntrinsic(ID, ResultRegs, !F->doesNotAccessMemory());
2371   if (isa<FPMathOperator>(CI))
2372     MIB->copyIRFlags(CI);
2373 
2374   for (auto &Arg : enumerate(CI.arg_operands())) {
2375     // If this is required to be an immediate, don't materialize it in a
2376     // register.
2377     if (CI.paramHasAttr(Arg.index(), Attribute::ImmArg)) {
2378       if (ConstantInt *CI = dyn_cast<ConstantInt>(Arg.value())) {
2379         // imm arguments are more convenient than cimm (and realistically
2380         // probably sufficient), so use them.
2381         assert(CI->getBitWidth() <= 64 &&
2382                "large intrinsic immediates not handled");
2383         MIB.addImm(CI->getSExtValue());
2384       } else {
2385         MIB.addFPImm(cast<ConstantFP>(Arg.value()));
2386       }
2387     } else if (auto *MDVal = dyn_cast<MetadataAsValue>(Arg.value())) {
2388       auto *MD = MDVal->getMetadata();
2389       auto *MDN = dyn_cast<MDNode>(MD);
2390       if (!MDN) {
2391         if (auto *ConstMD = dyn_cast<ConstantAsMetadata>(MD))
2392           MDN = MDNode::get(MF->getFunction().getContext(), ConstMD);
2393         else // This was probably an MDString.
2394           return false;
2395       }
2396       MIB.addMetadata(MDN);
2397     } else {
2398       ArrayRef<Register> VRegs = getOrCreateVRegs(*Arg.value());
2399       if (VRegs.size() > 1)
2400         return false;
2401       MIB.addUse(VRegs[0]);
2402     }
2403   }
2404 
2405   // Add a MachineMemOperand if it is a target mem intrinsic.
2406   const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
2407   TargetLowering::IntrinsicInfo Info;
2408   // TODO: Add a GlobalISel version of getTgtMemIntrinsic.
2409   if (TLI.getTgtMemIntrinsic(Info, CI, *MF, ID)) {
2410     Align Alignment = Info.align.getValueOr(
2411         DL->getABITypeAlign(Info.memVT.getTypeForEVT(F->getContext())));
2412     LLT MemTy = Info.memVT.isSimple()
2413                     ? getLLTForMVT(Info.memVT.getSimpleVT())
2414                     : LLT::scalar(Info.memVT.getStoreSizeInBits());
2415     MIB.addMemOperand(MF->getMachineMemOperand(MachinePointerInfo(Info.ptrVal),
2416                                                Info.flags, MemTy, Alignment));
2417   }
2418 
2419   return true;
2420 }
2421 
2422 bool IRTranslator::findUnwindDestinations(
2423     const BasicBlock *EHPadBB,
2424     BranchProbability Prob,
2425     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2426         &UnwindDests) {
2427   EHPersonality Personality = classifyEHPersonality(
2428       EHPadBB->getParent()->getFunction().getPersonalityFn());
2429   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
2430   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
2431   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
2432   bool IsSEH = isAsynchronousEHPersonality(Personality);
2433 
2434   if (IsWasmCXX) {
2435     // Ignore this for now.
2436     return false;
2437   }
2438 
2439   while (EHPadBB) {
2440     const Instruction *Pad = EHPadBB->getFirstNonPHI();
2441     BasicBlock *NewEHPadBB = nullptr;
2442     if (isa<LandingPadInst>(Pad)) {
2443       // Stop on landingpads. They are not funclets.
2444       UnwindDests.emplace_back(&getMBB(*EHPadBB), Prob);
2445       break;
2446     }
2447     if (isa<CleanupPadInst>(Pad)) {
2448       // Stop on cleanup pads. Cleanups are always funclet entries for all known
2449       // personalities.
2450       UnwindDests.emplace_back(&getMBB(*EHPadBB), Prob);
2451       UnwindDests.back().first->setIsEHScopeEntry();
2452       UnwindDests.back().first->setIsEHFuncletEntry();
2453       break;
2454     }
2455     if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
2456       // Add the catchpad handlers to the possible destinations.
2457       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2458         UnwindDests.emplace_back(&getMBB(*CatchPadBB), Prob);
2459         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
2460         if (IsMSVCCXX || IsCoreCLR)
2461           UnwindDests.back().first->setIsEHFuncletEntry();
2462         if (!IsSEH)
2463           UnwindDests.back().first->setIsEHScopeEntry();
2464       }
2465       NewEHPadBB = CatchSwitch->getUnwindDest();
2466     } else {
2467       continue;
2468     }
2469 
2470     BranchProbabilityInfo *BPI = FuncInfo.BPI;
2471     if (BPI && NewEHPadBB)
2472       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
2473     EHPadBB = NewEHPadBB;
2474   }
2475   return true;
2476 }
2477 
2478 bool IRTranslator::translateInvoke(const User &U,
2479                                    MachineIRBuilder &MIRBuilder) {
2480   const InvokeInst &I = cast<InvokeInst>(U);
2481   MCContext &Context = MF->getContext();
2482 
2483   const BasicBlock *ReturnBB = I.getSuccessor(0);
2484   const BasicBlock *EHPadBB = I.getSuccessor(1);
2485 
2486   const Function *Fn = I.getCalledFunction();
2487 
2488   // FIXME: support invoking patchpoint and statepoint intrinsics.
2489   if (Fn && Fn->isIntrinsic())
2490     return false;
2491 
2492   // FIXME: support whatever these are.
2493   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
2494     return false;
2495 
2496   // FIXME: support control flow guard targets.
2497   if (I.countOperandBundlesOfType(LLVMContext::OB_cfguardtarget))
2498     return false;
2499 
2500   // FIXME: support Windows exception handling.
2501   if (!isa<LandingPadInst>(EHPadBB->getFirstNonPHI()))
2502     return false;
2503 
2504   bool LowerInlineAsm = false;
2505   if (I.isInlineAsm()) {
2506     const InlineAsm *IA = cast<InlineAsm>(I.getCalledOperand());
2507     if (!IA->canThrow()) {
2508       // Fast path without emitting EH_LABELs.
2509 
2510       if (!translateInlineAsm(I, MIRBuilder))
2511         return false;
2512 
2513       MachineBasicBlock *InvokeMBB = &MIRBuilder.getMBB(),
2514                         *ReturnMBB = &getMBB(*ReturnBB);
2515 
2516       // Update successor info.
2517       addSuccessorWithProb(InvokeMBB, ReturnMBB, BranchProbability::getOne());
2518 
2519       MIRBuilder.buildBr(*ReturnMBB);
2520       return true;
2521     } else {
2522       LowerInlineAsm = true;
2523     }
2524   }
2525 
2526   // Emit the actual call, bracketed by EH_LABELs so that the MF knows about
2527   // the region covered by the try.
2528   MCSymbol *BeginSymbol = Context.createTempSymbol();
2529   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol);
2530 
2531   if (LowerInlineAsm) {
2532     if (!translateInlineAsm(I, MIRBuilder))
2533       return false;
2534   } else if (!translateCallBase(I, MIRBuilder))
2535     return false;
2536 
2537   MCSymbol *EndSymbol = Context.createTempSymbol();
2538   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol);
2539 
2540   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2541   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2542   MachineBasicBlock *InvokeMBB = &MIRBuilder.getMBB();
2543   BranchProbability EHPadBBProb =
2544       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2545           : BranchProbability::getZero();
2546 
2547   if (!findUnwindDestinations(EHPadBB, EHPadBBProb, UnwindDests))
2548     return false;
2549 
2550   MachineBasicBlock &EHPadMBB = getMBB(*EHPadBB),
2551                     &ReturnMBB = getMBB(*ReturnBB);
2552   // Update successor info.
2553   addSuccessorWithProb(InvokeMBB, &ReturnMBB);
2554   for (auto &UnwindDest : UnwindDests) {
2555     UnwindDest.first->setIsEHPad();
2556     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2557   }
2558   InvokeMBB->normalizeSuccProbs();
2559 
2560   MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
2561   MIRBuilder.buildBr(ReturnMBB);
2562   return true;
2563 }
2564 
2565 bool IRTranslator::translateCallBr(const User &U,
2566                                    MachineIRBuilder &MIRBuilder) {
2567   // FIXME: Implement this.
2568   return false;
2569 }
2570 
2571 bool IRTranslator::translateLandingPad(const User &U,
2572                                        MachineIRBuilder &MIRBuilder) {
2573   const LandingPadInst &LP = cast<LandingPadInst>(U);
2574 
2575   MachineBasicBlock &MBB = MIRBuilder.getMBB();
2576 
2577   MBB.setIsEHPad();
2578 
2579   // If there aren't registers to copy the values into (e.g., during SjLj
2580   // exceptions), then don't bother.
2581   auto &TLI = *MF->getSubtarget().getTargetLowering();
2582   const Constant *PersonalityFn = MF->getFunction().getPersonalityFn();
2583   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2584       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2585     return true;
2586 
2587   // If landingpad's return type is token type, we don't create DAG nodes
2588   // for its exception pointer and selector value. The extraction of exception
2589   // pointer or selector value from token type landingpads is not currently
2590   // supported.
2591   if (LP.getType()->isTokenTy())
2592     return true;
2593 
2594   // Add a label to mark the beginning of the landing pad.  Deletion of the
2595   // landing pad can thus be detected via the MachineModuleInfo.
2596   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL)
2597     .addSym(MF->addLandingPad(&MBB));
2598 
2599   // If the unwinder does not preserve all registers, ensure that the
2600   // function marks the clobbered registers as used.
2601   const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
2602   if (auto *RegMask = TRI.getCustomEHPadPreservedMask(*MF))
2603     MF->getRegInfo().addPhysRegsUsedFromRegMask(RegMask);
2604 
2605   LLT Ty = getLLTForType(*LP.getType(), *DL);
2606   Register Undef = MRI->createGenericVirtualRegister(Ty);
2607   MIRBuilder.buildUndef(Undef);
2608 
2609   SmallVector<LLT, 2> Tys;
2610   for (Type *Ty : cast<StructType>(LP.getType())->elements())
2611     Tys.push_back(getLLTForType(*Ty, *DL));
2612   assert(Tys.size() == 2 && "Only two-valued landingpads are supported");
2613 
2614   // Mark exception register as live in.
2615   Register ExceptionReg = TLI.getExceptionPointerRegister(PersonalityFn);
2616   if (!ExceptionReg)
2617     return false;
2618 
2619   MBB.addLiveIn(ExceptionReg);
2620   ArrayRef<Register> ResRegs = getOrCreateVRegs(LP);
2621   MIRBuilder.buildCopy(ResRegs[0], ExceptionReg);
2622 
2623   Register SelectorReg = TLI.getExceptionSelectorRegister(PersonalityFn);
2624   if (!SelectorReg)
2625     return false;
2626 
2627   MBB.addLiveIn(SelectorReg);
2628   Register PtrVReg = MRI->createGenericVirtualRegister(Tys[0]);
2629   MIRBuilder.buildCopy(PtrVReg, SelectorReg);
2630   MIRBuilder.buildCast(ResRegs[1], PtrVReg);
2631 
2632   return true;
2633 }
2634 
2635 bool IRTranslator::translateAlloca(const User &U,
2636                                    MachineIRBuilder &MIRBuilder) {
2637   auto &AI = cast<AllocaInst>(U);
2638 
2639   if (AI.isSwiftError())
2640     return true;
2641 
2642   if (AI.isStaticAlloca()) {
2643     Register Res = getOrCreateVReg(AI);
2644     int FI = getOrCreateFrameIndex(AI);
2645     MIRBuilder.buildFrameIndex(Res, FI);
2646     return true;
2647   }
2648 
2649   // FIXME: support stack probing for Windows.
2650   if (MF->getTarget().getTargetTriple().isOSWindows())
2651     return false;
2652 
2653   // Now we're in the harder dynamic case.
2654   Register NumElts = getOrCreateVReg(*AI.getArraySize());
2655   Type *IntPtrIRTy = DL->getIntPtrType(AI.getType());
2656   LLT IntPtrTy = getLLTForType(*IntPtrIRTy, *DL);
2657   if (MRI->getType(NumElts) != IntPtrTy) {
2658     Register ExtElts = MRI->createGenericVirtualRegister(IntPtrTy);
2659     MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts);
2660     NumElts = ExtElts;
2661   }
2662 
2663   Type *Ty = AI.getAllocatedType();
2664 
2665   Register AllocSize = MRI->createGenericVirtualRegister(IntPtrTy);
2666   Register TySize =
2667       getOrCreateVReg(*ConstantInt::get(IntPtrIRTy, DL->getTypeAllocSize(Ty)));
2668   MIRBuilder.buildMul(AllocSize, NumElts, TySize);
2669 
2670   // Round the size of the allocation up to the stack alignment size
2671   // by add SA-1 to the size. This doesn't overflow because we're computing
2672   // an address inside an alloca.
2673   Align StackAlign = MF->getSubtarget().getFrameLowering()->getStackAlign();
2674   auto SAMinusOne = MIRBuilder.buildConstant(IntPtrTy, StackAlign.value() - 1);
2675   auto AllocAdd = MIRBuilder.buildAdd(IntPtrTy, AllocSize, SAMinusOne,
2676                                       MachineInstr::NoUWrap);
2677   auto AlignCst =
2678       MIRBuilder.buildConstant(IntPtrTy, ~(uint64_t)(StackAlign.value() - 1));
2679   auto AlignedAlloc = MIRBuilder.buildAnd(IntPtrTy, AllocAdd, AlignCst);
2680 
2681   Align Alignment = std::max(AI.getAlign(), DL->getPrefTypeAlign(Ty));
2682   if (Alignment <= StackAlign)
2683     Alignment = Align(1);
2684   MIRBuilder.buildDynStackAlloc(getOrCreateVReg(AI), AlignedAlloc, Alignment);
2685 
2686   MF->getFrameInfo().CreateVariableSizedObject(Alignment, &AI);
2687   assert(MF->getFrameInfo().hasVarSizedObjects());
2688   return true;
2689 }
2690 
2691 bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) {
2692   // FIXME: We may need more info about the type. Because of how LLT works,
2693   // we're completely discarding the i64/double distinction here (amongst
2694   // others). Fortunately the ABIs I know of where that matters don't use va_arg
2695   // anyway but that's not guaranteed.
2696   MIRBuilder.buildInstr(TargetOpcode::G_VAARG, {getOrCreateVReg(U)},
2697                         {getOrCreateVReg(*U.getOperand(0)),
2698                          DL->getABITypeAlign(U.getType()).value()});
2699   return true;
2700 }
2701 
2702 bool IRTranslator::translateInsertElement(const User &U,
2703                                           MachineIRBuilder &MIRBuilder) {
2704   // If it is a <1 x Ty> vector, use the scalar as it is
2705   // not a legal vector type in LLT.
2706   if (cast<FixedVectorType>(U.getType())->getNumElements() == 1)
2707     return translateCopy(U, *U.getOperand(1), MIRBuilder);
2708 
2709   Register Res = getOrCreateVReg(U);
2710   Register Val = getOrCreateVReg(*U.getOperand(0));
2711   Register Elt = getOrCreateVReg(*U.getOperand(1));
2712   Register Idx = getOrCreateVReg(*U.getOperand(2));
2713   MIRBuilder.buildInsertVectorElement(Res, Val, Elt, Idx);
2714   return true;
2715 }
2716 
2717 bool IRTranslator::translateExtractElement(const User &U,
2718                                            MachineIRBuilder &MIRBuilder) {
2719   // If it is a <1 x Ty> vector, use the scalar as it is
2720   // not a legal vector type in LLT.
2721   if (cast<FixedVectorType>(U.getOperand(0)->getType())->getNumElements() == 1)
2722     return translateCopy(U, *U.getOperand(0), MIRBuilder);
2723 
2724   Register Res = getOrCreateVReg(U);
2725   Register Val = getOrCreateVReg(*U.getOperand(0));
2726   const auto &TLI = *MF->getSubtarget().getTargetLowering();
2727   unsigned PreferredVecIdxWidth = TLI.getVectorIdxTy(*DL).getSizeInBits();
2728   Register Idx;
2729   if (auto *CI = dyn_cast<ConstantInt>(U.getOperand(1))) {
2730     if (CI->getBitWidth() != PreferredVecIdxWidth) {
2731       APInt NewIdx = CI->getValue().sextOrTrunc(PreferredVecIdxWidth);
2732       auto *NewIdxCI = ConstantInt::get(CI->getContext(), NewIdx);
2733       Idx = getOrCreateVReg(*NewIdxCI);
2734     }
2735   }
2736   if (!Idx)
2737     Idx = getOrCreateVReg(*U.getOperand(1));
2738   if (MRI->getType(Idx).getSizeInBits() != PreferredVecIdxWidth) {
2739     const LLT VecIdxTy = LLT::scalar(PreferredVecIdxWidth);
2740     Idx = MIRBuilder.buildSExtOrTrunc(VecIdxTy, Idx).getReg(0);
2741   }
2742   MIRBuilder.buildExtractVectorElement(Res, Val, Idx);
2743   return true;
2744 }
2745 
2746 bool IRTranslator::translateShuffleVector(const User &U,
2747                                           MachineIRBuilder &MIRBuilder) {
2748   ArrayRef<int> Mask;
2749   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&U))
2750     Mask = SVI->getShuffleMask();
2751   else
2752     Mask = cast<ConstantExpr>(U).getShuffleMask();
2753   ArrayRef<int> MaskAlloc = MF->allocateShuffleMask(Mask);
2754   MIRBuilder
2755       .buildInstr(TargetOpcode::G_SHUFFLE_VECTOR, {getOrCreateVReg(U)},
2756                   {getOrCreateVReg(*U.getOperand(0)),
2757                    getOrCreateVReg(*U.getOperand(1))})
2758       .addShuffleMask(MaskAlloc);
2759   return true;
2760 }
2761 
2762 bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) {
2763   const PHINode &PI = cast<PHINode>(U);
2764 
2765   SmallVector<MachineInstr *, 4> Insts;
2766   for (auto Reg : getOrCreateVRegs(PI)) {
2767     auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_PHI, {Reg}, {});
2768     Insts.push_back(MIB.getInstr());
2769   }
2770 
2771   PendingPHIs.emplace_back(&PI, std::move(Insts));
2772   return true;
2773 }
2774 
2775 bool IRTranslator::translateAtomicCmpXchg(const User &U,
2776                                           MachineIRBuilder &MIRBuilder) {
2777   const AtomicCmpXchgInst &I = cast<AtomicCmpXchgInst>(U);
2778 
2779   auto &TLI = *MF->getSubtarget().getTargetLowering();
2780   auto Flags = TLI.getAtomicMemOperandFlags(I, *DL);
2781 
2782   auto Res = getOrCreateVRegs(I);
2783   Register OldValRes = Res[0];
2784   Register SuccessRes = Res[1];
2785   Register Addr = getOrCreateVReg(*I.getPointerOperand());
2786   Register Cmp = getOrCreateVReg(*I.getCompareOperand());
2787   Register NewVal = getOrCreateVReg(*I.getNewValOperand());
2788 
2789   MIRBuilder.buildAtomicCmpXchgWithSuccess(
2790       OldValRes, SuccessRes, Addr, Cmp, NewVal,
2791       *MF->getMachineMemOperand(
2792           MachinePointerInfo(I.getPointerOperand()), Flags, MRI->getType(Cmp),
2793           getMemOpAlign(I), I.getAAMetadata(), nullptr, I.getSyncScopeID(),
2794           I.getSuccessOrdering(), I.getFailureOrdering()));
2795   return true;
2796 }
2797 
2798 bool IRTranslator::translateAtomicRMW(const User &U,
2799                                       MachineIRBuilder &MIRBuilder) {
2800   const AtomicRMWInst &I = cast<AtomicRMWInst>(U);
2801   auto &TLI = *MF->getSubtarget().getTargetLowering();
2802   auto Flags = TLI.getAtomicMemOperandFlags(I, *DL);
2803 
2804   Register Res = getOrCreateVReg(I);
2805   Register Addr = getOrCreateVReg(*I.getPointerOperand());
2806   Register Val = getOrCreateVReg(*I.getValOperand());
2807 
2808   unsigned Opcode = 0;
2809   switch (I.getOperation()) {
2810   default:
2811     return false;
2812   case AtomicRMWInst::Xchg:
2813     Opcode = TargetOpcode::G_ATOMICRMW_XCHG;
2814     break;
2815   case AtomicRMWInst::Add:
2816     Opcode = TargetOpcode::G_ATOMICRMW_ADD;
2817     break;
2818   case AtomicRMWInst::Sub:
2819     Opcode = TargetOpcode::G_ATOMICRMW_SUB;
2820     break;
2821   case AtomicRMWInst::And:
2822     Opcode = TargetOpcode::G_ATOMICRMW_AND;
2823     break;
2824   case AtomicRMWInst::Nand:
2825     Opcode = TargetOpcode::G_ATOMICRMW_NAND;
2826     break;
2827   case AtomicRMWInst::Or:
2828     Opcode = TargetOpcode::G_ATOMICRMW_OR;
2829     break;
2830   case AtomicRMWInst::Xor:
2831     Opcode = TargetOpcode::G_ATOMICRMW_XOR;
2832     break;
2833   case AtomicRMWInst::Max:
2834     Opcode = TargetOpcode::G_ATOMICRMW_MAX;
2835     break;
2836   case AtomicRMWInst::Min:
2837     Opcode = TargetOpcode::G_ATOMICRMW_MIN;
2838     break;
2839   case AtomicRMWInst::UMax:
2840     Opcode = TargetOpcode::G_ATOMICRMW_UMAX;
2841     break;
2842   case AtomicRMWInst::UMin:
2843     Opcode = TargetOpcode::G_ATOMICRMW_UMIN;
2844     break;
2845   case AtomicRMWInst::FAdd:
2846     Opcode = TargetOpcode::G_ATOMICRMW_FADD;
2847     break;
2848   case AtomicRMWInst::FSub:
2849     Opcode = TargetOpcode::G_ATOMICRMW_FSUB;
2850     break;
2851   }
2852 
2853   MIRBuilder.buildAtomicRMW(
2854       Opcode, Res, Addr, Val,
2855       *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
2856                                 Flags, MRI->getType(Val), getMemOpAlign(I),
2857                                 I.getAAMetadata(), nullptr, I.getSyncScopeID(),
2858                                 I.getOrdering()));
2859   return true;
2860 }
2861 
2862 bool IRTranslator::translateFence(const User &U,
2863                                   MachineIRBuilder &MIRBuilder) {
2864   const FenceInst &Fence = cast<FenceInst>(U);
2865   MIRBuilder.buildFence(static_cast<unsigned>(Fence.getOrdering()),
2866                         Fence.getSyncScopeID());
2867   return true;
2868 }
2869 
2870 bool IRTranslator::translateFreeze(const User &U,
2871                                    MachineIRBuilder &MIRBuilder) {
2872   const ArrayRef<Register> DstRegs = getOrCreateVRegs(U);
2873   const ArrayRef<Register> SrcRegs = getOrCreateVRegs(*U.getOperand(0));
2874 
2875   assert(DstRegs.size() == SrcRegs.size() &&
2876          "Freeze with different source and destination type?");
2877 
2878   for (unsigned I = 0; I < DstRegs.size(); ++I) {
2879     MIRBuilder.buildFreeze(DstRegs[I], SrcRegs[I]);
2880   }
2881 
2882   return true;
2883 }
2884 
2885 void IRTranslator::finishPendingPhis() {
2886 #ifndef NDEBUG
2887   DILocationVerifier Verifier;
2888   GISelObserverWrapper WrapperObserver(&Verifier);
2889   RAIIDelegateInstaller DelInstall(*MF, &WrapperObserver);
2890 #endif // ifndef NDEBUG
2891   for (auto &Phi : PendingPHIs) {
2892     const PHINode *PI = Phi.first;
2893     ArrayRef<MachineInstr *> ComponentPHIs = Phi.second;
2894     MachineBasicBlock *PhiMBB = ComponentPHIs[0]->getParent();
2895     EntryBuilder->setDebugLoc(PI->getDebugLoc());
2896 #ifndef NDEBUG
2897     Verifier.setCurrentInst(PI);
2898 #endif // ifndef NDEBUG
2899 
2900     SmallSet<const MachineBasicBlock *, 16> SeenPreds;
2901     for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
2902       auto IRPred = PI->getIncomingBlock(i);
2903       ArrayRef<Register> ValRegs = getOrCreateVRegs(*PI->getIncomingValue(i));
2904       for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) {
2905         if (SeenPreds.count(Pred) || !PhiMBB->isPredecessor(Pred))
2906           continue;
2907         SeenPreds.insert(Pred);
2908         for (unsigned j = 0; j < ValRegs.size(); ++j) {
2909           MachineInstrBuilder MIB(*MF, ComponentPHIs[j]);
2910           MIB.addUse(ValRegs[j]);
2911           MIB.addMBB(Pred);
2912         }
2913       }
2914     }
2915   }
2916 }
2917 
2918 bool IRTranslator::valueIsSplit(const Value &V,
2919                                 SmallVectorImpl<uint64_t> *Offsets) {
2920   SmallVector<LLT, 4> SplitTys;
2921   if (Offsets && !Offsets->empty())
2922     Offsets->clear();
2923   computeValueLLTs(*DL, *V.getType(), SplitTys, Offsets);
2924   return SplitTys.size() > 1;
2925 }
2926 
2927 bool IRTranslator::translate(const Instruction &Inst) {
2928   CurBuilder->setDebugLoc(Inst.getDebugLoc());
2929 
2930   auto &TLI = *MF->getSubtarget().getTargetLowering();
2931   if (TLI.fallBackToDAGISel(Inst))
2932     return false;
2933 
2934   switch (Inst.getOpcode()) {
2935 #define HANDLE_INST(NUM, OPCODE, CLASS)                                        \
2936   case Instruction::OPCODE:                                                    \
2937     return translate##OPCODE(Inst, *CurBuilder.get());
2938 #include "llvm/IR/Instruction.def"
2939   default:
2940     return false;
2941   }
2942 }
2943 
2944 bool IRTranslator::translate(const Constant &C, Register Reg) {
2945   // We only emit constants into the entry block from here. To prevent jumpy
2946   // debug behaviour set the line to 0.
2947   if (auto CurrInstDL = CurBuilder->getDL())
2948     EntryBuilder->setDebugLoc(DILocation::get(C.getContext(), 0, 0,
2949                                               CurrInstDL.getScope(),
2950                                               CurrInstDL.getInlinedAt()));
2951 
2952   if (auto CI = dyn_cast<ConstantInt>(&C))
2953     EntryBuilder->buildConstant(Reg, *CI);
2954   else if (auto CF = dyn_cast<ConstantFP>(&C))
2955     EntryBuilder->buildFConstant(Reg, *CF);
2956   else if (isa<UndefValue>(C))
2957     EntryBuilder->buildUndef(Reg);
2958   else if (isa<ConstantPointerNull>(C))
2959     EntryBuilder->buildConstant(Reg, 0);
2960   else if (auto GV = dyn_cast<GlobalValue>(&C))
2961     EntryBuilder->buildGlobalValue(Reg, GV);
2962   else if (auto CAZ = dyn_cast<ConstantAggregateZero>(&C)) {
2963     if (!isa<FixedVectorType>(CAZ->getType()))
2964       return false;
2965     // Return the scalar if it is a <1 x Ty> vector.
2966     unsigned NumElts = CAZ->getElementCount().getFixedValue();
2967     if (NumElts == 1)
2968       return translateCopy(C, *CAZ->getElementValue(0u), *EntryBuilder.get());
2969     SmallVector<Register, 4> Ops;
2970     for (unsigned I = 0; I < NumElts; ++I) {
2971       Constant &Elt = *CAZ->getElementValue(I);
2972       Ops.push_back(getOrCreateVReg(Elt));
2973     }
2974     EntryBuilder->buildBuildVector(Reg, Ops);
2975   } else if (auto CV = dyn_cast<ConstantDataVector>(&C)) {
2976     // Return the scalar if it is a <1 x Ty> vector.
2977     if (CV->getNumElements() == 1)
2978       return translateCopy(C, *CV->getElementAsConstant(0),
2979                            *EntryBuilder.get());
2980     SmallVector<Register, 4> Ops;
2981     for (unsigned i = 0; i < CV->getNumElements(); ++i) {
2982       Constant &Elt = *CV->getElementAsConstant(i);
2983       Ops.push_back(getOrCreateVReg(Elt));
2984     }
2985     EntryBuilder->buildBuildVector(Reg, Ops);
2986   } else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
2987     switch(CE->getOpcode()) {
2988 #define HANDLE_INST(NUM, OPCODE, CLASS)                                        \
2989   case Instruction::OPCODE:                                                    \
2990     return translate##OPCODE(*CE, *EntryBuilder.get());
2991 #include "llvm/IR/Instruction.def"
2992     default:
2993       return false;
2994     }
2995   } else if (auto CV = dyn_cast<ConstantVector>(&C)) {
2996     if (CV->getNumOperands() == 1)
2997       return translateCopy(C, *CV->getOperand(0), *EntryBuilder.get());
2998     SmallVector<Register, 4> Ops;
2999     for (unsigned i = 0; i < CV->getNumOperands(); ++i) {
3000       Ops.push_back(getOrCreateVReg(*CV->getOperand(i)));
3001     }
3002     EntryBuilder->buildBuildVector(Reg, Ops);
3003   } else if (auto *BA = dyn_cast<BlockAddress>(&C)) {
3004     EntryBuilder->buildBlockAddress(Reg, BA);
3005   } else
3006     return false;
3007 
3008   return true;
3009 }
3010 
3011 void IRTranslator::finalizeBasicBlock() {
3012   for (auto &BTB : SL->BitTestCases) {
3013     // Emit header first, if it wasn't already emitted.
3014     if (!BTB.Emitted)
3015       emitBitTestHeader(BTB, BTB.Parent);
3016 
3017     BranchProbability UnhandledProb = BTB.Prob;
3018     for (unsigned j = 0, ej = BTB.Cases.size(); j != ej; ++j) {
3019       UnhandledProb -= BTB.Cases[j].ExtraProb;
3020       // Set the current basic block to the mbb we wish to insert the code into
3021       MachineBasicBlock *MBB = BTB.Cases[j].ThisBB;
3022       // If all cases cover a contiguous range, it is not necessary to jump to
3023       // the default block after the last bit test fails. This is because the
3024       // range check during bit test header creation has guaranteed that every
3025       // case here doesn't go outside the range. In this case, there is no need
3026       // to perform the last bit test, as it will always be true. Instead, make
3027       // the second-to-last bit-test fall through to the target of the last bit
3028       // test, and delete the last bit test.
3029 
3030       MachineBasicBlock *NextMBB;
3031       if ((BTB.ContiguousRange || BTB.FallthroughUnreachable) && j + 2 == ej) {
3032         // Second-to-last bit-test with contiguous range: fall through to the
3033         // target of the final bit test.
3034         NextMBB = BTB.Cases[j + 1].TargetBB;
3035       } else if (j + 1 == ej) {
3036         // For the last bit test, fall through to Default.
3037         NextMBB = BTB.Default;
3038       } else {
3039         // Otherwise, fall through to the next bit test.
3040         NextMBB = BTB.Cases[j + 1].ThisBB;
3041       }
3042 
3043       emitBitTestCase(BTB, NextMBB, UnhandledProb, BTB.Reg, BTB.Cases[j], MBB);
3044 
3045       if ((BTB.ContiguousRange || BTB.FallthroughUnreachable) && j + 2 == ej) {
3046         // We need to record the replacement phi edge here that normally
3047         // happens in emitBitTestCase before we delete the case, otherwise the
3048         // phi edge will be lost.
3049         addMachineCFGPred({BTB.Parent->getBasicBlock(),
3050                            BTB.Cases[ej - 1].TargetBB->getBasicBlock()},
3051                           MBB);
3052         // Since we're not going to use the final bit test, remove it.
3053         BTB.Cases.pop_back();
3054         break;
3055       }
3056     }
3057     // This is "default" BB. We have two jumps to it. From "header" BB and from
3058     // last "case" BB, unless the latter was skipped.
3059     CFGEdge HeaderToDefaultEdge = {BTB.Parent->getBasicBlock(),
3060                                    BTB.Default->getBasicBlock()};
3061     addMachineCFGPred(HeaderToDefaultEdge, BTB.Parent);
3062     if (!BTB.ContiguousRange) {
3063       addMachineCFGPred(HeaderToDefaultEdge, BTB.Cases.back().ThisBB);
3064     }
3065   }
3066   SL->BitTestCases.clear();
3067 
3068   for (auto &JTCase : SL->JTCases) {
3069     // Emit header first, if it wasn't already emitted.
3070     if (!JTCase.first.Emitted)
3071       emitJumpTableHeader(JTCase.second, JTCase.first, JTCase.first.HeaderBB);
3072 
3073     emitJumpTable(JTCase.second, JTCase.second.MBB);
3074   }
3075   SL->JTCases.clear();
3076 
3077   for (auto &SwCase : SL->SwitchCases)
3078     emitSwitchCase(SwCase, &CurBuilder->getMBB(), *CurBuilder);
3079   SL->SwitchCases.clear();
3080 }
3081 
3082 void IRTranslator::finalizeFunction() {
3083   // Release the memory used by the different maps we
3084   // needed during the translation.
3085   PendingPHIs.clear();
3086   VMap.reset();
3087   FrameIndices.clear();
3088   MachinePreds.clear();
3089   // MachineIRBuilder::DebugLoc can outlive the DILocation it holds. Clear it
3090   // to avoid accessing free’d memory (in runOnMachineFunction) and to avoid
3091   // destroying it twice (in ~IRTranslator() and ~LLVMContext())
3092   EntryBuilder.reset();
3093   CurBuilder.reset();
3094   FuncInfo.clear();
3095 }
3096 
3097 /// Returns true if a BasicBlock \p BB within a variadic function contains a
3098 /// variadic musttail call.
3099 static bool checkForMustTailInVarArgFn(bool IsVarArg, const BasicBlock &BB) {
3100   if (!IsVarArg)
3101     return false;
3102 
3103   // Walk the block backwards, because tail calls usually only appear at the end
3104   // of a block.
3105   return std::any_of(BB.rbegin(), BB.rend(), [](const Instruction &I) {
3106     const auto *CI = dyn_cast<CallInst>(&I);
3107     return CI && CI->isMustTailCall();
3108   });
3109 }
3110 
3111 bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) {
3112   MF = &CurMF;
3113   const Function &F = MF->getFunction();
3114   GISelCSEAnalysisWrapper &Wrapper =
3115       getAnalysis<GISelCSEAnalysisWrapperPass>().getCSEWrapper();
3116   // Set the CSEConfig and run the analysis.
3117   GISelCSEInfo *CSEInfo = nullptr;
3118   TPC = &getAnalysis<TargetPassConfig>();
3119   bool EnableCSE = EnableCSEInIRTranslator.getNumOccurrences()
3120                        ? EnableCSEInIRTranslator
3121                        : TPC->isGISelCSEEnabled();
3122 
3123   if (EnableCSE) {
3124     EntryBuilder = std::make_unique<CSEMIRBuilder>(CurMF);
3125     CSEInfo = &Wrapper.get(TPC->getCSEConfig());
3126     EntryBuilder->setCSEInfo(CSEInfo);
3127     CurBuilder = std::make_unique<CSEMIRBuilder>(CurMF);
3128     CurBuilder->setCSEInfo(CSEInfo);
3129   } else {
3130     EntryBuilder = std::make_unique<MachineIRBuilder>();
3131     CurBuilder = std::make_unique<MachineIRBuilder>();
3132   }
3133   CLI = MF->getSubtarget().getCallLowering();
3134   CurBuilder->setMF(*MF);
3135   EntryBuilder->setMF(*MF);
3136   MRI = &MF->getRegInfo();
3137   DL = &F.getParent()->getDataLayout();
3138   ORE = std::make_unique<OptimizationRemarkEmitter>(&F);
3139   const TargetMachine &TM = MF->getTarget();
3140   TM.resetTargetOptions(F);
3141   EnableOpts = OptLevel != CodeGenOpt::None && !skipFunction(F);
3142   FuncInfo.MF = MF;
3143   if (EnableOpts)
3144     FuncInfo.BPI = &getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
3145   else
3146     FuncInfo.BPI = nullptr;
3147 
3148   FuncInfo.CanLowerReturn = CLI->checkReturnTypeForCallConv(*MF);
3149 
3150   const auto &TLI = *MF->getSubtarget().getTargetLowering();
3151 
3152   SL = std::make_unique<GISelSwitchLowering>(this, FuncInfo);
3153   SL->init(TLI, TM, *DL);
3154 
3155 
3156 
3157   assert(PendingPHIs.empty() && "stale PHIs");
3158 
3159   // Targets which want to use big endian can enable it using
3160   // enableBigEndian()
3161   if (!DL->isLittleEndian() && !CLI->enableBigEndian()) {
3162     // Currently we don't properly handle big endian code.
3163     OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
3164                                F.getSubprogram(), &F.getEntryBlock());
3165     R << "unable to translate in big endian mode";
3166     reportTranslationError(*MF, *TPC, *ORE, R);
3167   }
3168 
3169   // Release the per-function state when we return, whether we succeeded or not.
3170   auto FinalizeOnReturn = make_scope_exit([this]() { finalizeFunction(); });
3171 
3172   // Setup a separate basic-block for the arguments and constants
3173   MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock();
3174   MF->push_back(EntryBB);
3175   EntryBuilder->setMBB(*EntryBB);
3176 
3177   DebugLoc DbgLoc = F.getEntryBlock().getFirstNonPHI()->getDebugLoc();
3178   SwiftError.setFunction(CurMF);
3179   SwiftError.createEntriesInEntryBlock(DbgLoc);
3180 
3181   bool IsVarArg = F.isVarArg();
3182   bool HasMustTailInVarArgFn = false;
3183 
3184   // Create all blocks, in IR order, to preserve the layout.
3185   for (const BasicBlock &BB: F) {
3186     auto *&MBB = BBToMBB[&BB];
3187 
3188     MBB = MF->CreateMachineBasicBlock(&BB);
3189     MF->push_back(MBB);
3190 
3191     if (BB.hasAddressTaken())
3192       MBB->setHasAddressTaken();
3193 
3194     if (!HasMustTailInVarArgFn)
3195       HasMustTailInVarArgFn = checkForMustTailInVarArgFn(IsVarArg, BB);
3196   }
3197 
3198   MF->getFrameInfo().setHasMustTailInVarArgFunc(HasMustTailInVarArgFn);
3199 
3200   // Make our arguments/constants entry block fallthrough to the IR entry block.
3201   EntryBB->addSuccessor(&getMBB(F.front()));
3202 
3203   if (CLI->fallBackToDAGISel(*MF)) {
3204     OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
3205                                F.getSubprogram(), &F.getEntryBlock());
3206     R << "unable to lower function: " << ore::NV("Prototype", F.getType());
3207     reportTranslationError(*MF, *TPC, *ORE, R);
3208     return false;
3209   }
3210 
3211   // Lower the actual args into this basic block.
3212   SmallVector<ArrayRef<Register>, 8> VRegArgs;
3213   for (const Argument &Arg: F.args()) {
3214     if (DL->getTypeStoreSize(Arg.getType()).isZero())
3215       continue; // Don't handle zero sized types.
3216     ArrayRef<Register> VRegs = getOrCreateVRegs(Arg);
3217     VRegArgs.push_back(VRegs);
3218 
3219     if (Arg.hasSwiftErrorAttr()) {
3220       assert(VRegs.size() == 1 && "Too many vregs for Swift error");
3221       SwiftError.setCurrentVReg(EntryBB, SwiftError.getFunctionArg(), VRegs[0]);
3222     }
3223   }
3224 
3225   if (!CLI->lowerFormalArguments(*EntryBuilder.get(), F, VRegArgs, FuncInfo)) {
3226     OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
3227                                F.getSubprogram(), &F.getEntryBlock());
3228     R << "unable to lower arguments: " << ore::NV("Prototype", F.getType());
3229     reportTranslationError(*MF, *TPC, *ORE, R);
3230     return false;
3231   }
3232 
3233   // Need to visit defs before uses when translating instructions.
3234   GISelObserverWrapper WrapperObserver;
3235   if (EnableCSE && CSEInfo)
3236     WrapperObserver.addObserver(CSEInfo);
3237   {
3238     ReversePostOrderTraversal<const Function *> RPOT(&F);
3239 #ifndef NDEBUG
3240     DILocationVerifier Verifier;
3241     WrapperObserver.addObserver(&Verifier);
3242 #endif // ifndef NDEBUG
3243     RAIIDelegateInstaller DelInstall(*MF, &WrapperObserver);
3244     RAIIMFObserverInstaller ObsInstall(*MF, WrapperObserver);
3245     for (const BasicBlock *BB : RPOT) {
3246       MachineBasicBlock &MBB = getMBB(*BB);
3247       // Set the insertion point of all the following translations to
3248       // the end of this basic block.
3249       CurBuilder->setMBB(MBB);
3250       HasTailCall = false;
3251       for (const Instruction &Inst : *BB) {
3252         // If we translated a tail call in the last step, then we know
3253         // everything after the call is either a return, or something that is
3254         // handled by the call itself. (E.g. a lifetime marker or assume
3255         // intrinsic.) In this case, we should stop translating the block and
3256         // move on.
3257         if (HasTailCall)
3258           break;
3259 #ifndef NDEBUG
3260         Verifier.setCurrentInst(&Inst);
3261 #endif // ifndef NDEBUG
3262         if (translate(Inst))
3263           continue;
3264 
3265         OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
3266                                    Inst.getDebugLoc(), BB);
3267         R << "unable to translate instruction: " << ore::NV("Opcode", &Inst);
3268 
3269         if (ORE->allowExtraAnalysis("gisel-irtranslator")) {
3270           std::string InstStrStorage;
3271           raw_string_ostream InstStr(InstStrStorage);
3272           InstStr << Inst;
3273 
3274           R << ": '" << InstStr.str() << "'";
3275         }
3276 
3277         reportTranslationError(*MF, *TPC, *ORE, R);
3278         return false;
3279       }
3280 
3281       finalizeBasicBlock();
3282     }
3283 #ifndef NDEBUG
3284     WrapperObserver.removeObserver(&Verifier);
3285 #endif
3286   }
3287 
3288   finishPendingPhis();
3289 
3290   SwiftError.propagateVRegs();
3291 
3292   // Merge the argument lowering and constants block with its single
3293   // successor, the LLVM-IR entry block.  We want the basic block to
3294   // be maximal.
3295   assert(EntryBB->succ_size() == 1 &&
3296          "Custom BB used for lowering should have only one successor");
3297   // Get the successor of the current entry block.
3298   MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin();
3299   assert(NewEntryBB.pred_size() == 1 &&
3300          "LLVM-IR entry block has a predecessor!?");
3301   // Move all the instruction from the current entry block to the
3302   // new entry block.
3303   NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(),
3304                     EntryBB->end());
3305 
3306   // Update the live-in information for the new entry block.
3307   for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins())
3308     NewEntryBB.addLiveIn(LiveIn);
3309   NewEntryBB.sortUniqueLiveIns();
3310 
3311   // Get rid of the now empty basic block.
3312   EntryBB->removeSuccessor(&NewEntryBB);
3313   MF->remove(EntryBB);
3314   MF->DeleteMachineBasicBlock(EntryBB);
3315 
3316   assert(&MF->front() == &NewEntryBB &&
3317          "New entry wasn't next in the list of basic block!");
3318 
3319   // Initialize stack protector information.
3320   StackProtector &SP = getAnalysis<StackProtector>();
3321   SP.copyToMachineFrameInfo(MF->getFrameInfo());
3322 
3323   return false;
3324 }
3325