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