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