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