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