LCOV - code coverage report
Current view: top level - lib/CodeGen/GlobalISel - IRTranslator.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 749 779 96.1 %
Date: 2018-10-20 13:21:21 Functions: 52 52 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===- llvm/CodeGen/GlobalISel/IRTranslator.cpp - IRTranslator ---*- C++ -*-==//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : /// \file
      10             : /// This file implements the IRTranslator class.
      11             : //===----------------------------------------------------------------------===//
      12             : 
      13             : #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
      14             : #include "llvm/ADT/PostOrderIterator.h"
      15             : #include "llvm/ADT/STLExtras.h"
      16             : #include "llvm/ADT/ScopeExit.h"
      17             : #include "llvm/ADT/SmallSet.h"
      18             : #include "llvm/ADT/SmallVector.h"
      19             : #include "llvm/Analysis/OptimizationRemarkEmitter.h"
      20             : #include "llvm/CodeGen/Analysis.h"
      21             : #include "llvm/CodeGen/GlobalISel/CallLowering.h"
      22             : #include "llvm/CodeGen/LowLevelType.h"
      23             : #include "llvm/CodeGen/MachineBasicBlock.h"
      24             : #include "llvm/CodeGen/MachineFrameInfo.h"
      25             : #include "llvm/CodeGen/MachineFunction.h"
      26             : #include "llvm/CodeGen/MachineInstrBuilder.h"
      27             : #include "llvm/CodeGen/MachineMemOperand.h"
      28             : #include "llvm/CodeGen/MachineOperand.h"
      29             : #include "llvm/CodeGen/MachineRegisterInfo.h"
      30             : #include "llvm/CodeGen/StackProtector.h"
      31             : #include "llvm/CodeGen/TargetFrameLowering.h"
      32             : #include "llvm/CodeGen/TargetLowering.h"
      33             : #include "llvm/CodeGen/TargetPassConfig.h"
      34             : #include "llvm/CodeGen/TargetRegisterInfo.h"
      35             : #include "llvm/CodeGen/TargetSubtargetInfo.h"
      36             : #include "llvm/IR/BasicBlock.h"
      37             : #include "llvm/IR/CFG.h"
      38             : #include "llvm/IR/Constant.h"
      39             : #include "llvm/IR/Constants.h"
      40             : #include "llvm/IR/DataLayout.h"
      41             : #include "llvm/IR/DebugInfo.h"
      42             : #include "llvm/IR/DerivedTypes.h"
      43             : #include "llvm/IR/Function.h"
      44             : #include "llvm/IR/GetElementPtrTypeIterator.h"
      45             : #include "llvm/IR/InlineAsm.h"
      46             : #include "llvm/IR/InstrTypes.h"
      47             : #include "llvm/IR/Instructions.h"
      48             : #include "llvm/IR/IntrinsicInst.h"
      49             : #include "llvm/IR/Intrinsics.h"
      50             : #include "llvm/IR/LLVMContext.h"
      51             : #include "llvm/IR/Metadata.h"
      52             : #include "llvm/IR/Type.h"
      53             : #include "llvm/IR/User.h"
      54             : #include "llvm/IR/Value.h"
      55             : #include "llvm/MC/MCContext.h"
      56             : #include "llvm/Pass.h"
      57             : #include "llvm/Support/Casting.h"
      58             : #include "llvm/Support/CodeGen.h"
      59             : #include "llvm/Support/Debug.h"
      60             : #include "llvm/Support/ErrorHandling.h"
      61             : #include "llvm/Support/LowLevelTypeImpl.h"
      62             : #include "llvm/Support/MathExtras.h"
      63             : #include "llvm/Support/raw_ostream.h"
      64             : #include "llvm/Target/TargetIntrinsicInfo.h"
      65             : #include "llvm/Target/TargetMachine.h"
      66             : #include <algorithm>
      67             : #include <cassert>
      68             : #include <cstdint>
      69             : #include <iterator>
      70             : #include <string>
      71             : #include <utility>
      72             : #include <vector>
      73             : 
      74             : #define DEBUG_TYPE "irtranslator"
      75             : 
      76             : using namespace llvm;
      77             : 
      78             : char IRTranslator::ID = 0;
      79             : 
      80       85394 : INITIALIZE_PASS_BEGIN(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
      81             :                 false, false)
      82       85394 : INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
      83      655478 : INITIALIZE_PASS_END(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
      84             :                 false, false)
      85             : 
      86         134 : static void reportTranslationError(MachineFunction &MF,
      87             :                                    const TargetPassConfig &TPC,
      88             :                                    OptimizationRemarkEmitter &ORE,
      89             :                                    OptimizationRemarkMissed &R) {
      90             :   MF.getProperties().set(MachineFunctionProperties::Property::FailedISel);
      91             : 
      92             :   // Print the function name explicitly if we don't have a debug location (which
      93             :   // makes the diagnostic less useful) or if we're going to emit a raw error.
      94         134 :   if (!R.getLocation().isValid() || TPC.isGlobalISelAbortEnabled())
      95         536 :     R << (" (in function: " + MF.getName() + ")").str();
      96             : 
      97         134 :   if (TPC.isGlobalISelAbortEnabled())
      98           2 :     report_fatal_error(R.getMsg());
      99             :   else
     100         132 :     ORE.emit(R);
     101         132 : }
     102             : 
     103         200 : IRTranslator::IRTranslator() : MachineFunctionPass(ID) {
     104         200 :   initializeIRTranslatorPass(*PassRegistry::getPassRegistry());
     105         200 : }
     106             : 
     107         196 : void IRTranslator::getAnalysisUsage(AnalysisUsage &AU) const {
     108             :   AU.addRequired<StackProtector>();
     109             :   AU.addRequired<TargetPassConfig>();
     110         196 :   getSelectionDAGFallbackAnalysisUsage(AU);
     111         196 :   MachineFunctionPass::getAnalysisUsage(AU);
     112         196 : }
     113             : 
     114        5471 : static void computeValueLLTs(const DataLayout &DL, Type &Ty,
     115             :                              SmallVectorImpl<LLT> &ValueTys,
     116             :                              SmallVectorImpl<uint64_t> *Offsets = nullptr,
     117             :                              uint64_t StartingOffset = 0) {
     118             :   // Given a struct type, recursively traverse the elements.
     119             :   if (StructType *STy = dyn_cast<StructType>(&Ty)) {
     120         129 :     const StructLayout *SL = DL.getStructLayout(STy);
     121         413 :     for (unsigned I = 0, E = STy->getNumElements(); I != E; ++I)
     122         568 :       computeValueLLTs(DL, *STy->getElementType(I), ValueTys, Offsets,
     123             :                        StartingOffset + SL->getElementOffset(I));
     124             :     return;
     125             :   }
     126             :   // Given an array type, recursively traverse the elements.
     127             :   if (ArrayType *ATy = dyn_cast<ArrayType>(&Ty)) {
     128         126 :     Type *EltTy = ATy->getElementType();
     129         126 :     uint64_t EltSize = DL.getTypeAllocSize(EltTy);
     130         849 :     for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
     131         723 :       computeValueLLTs(DL, *EltTy, ValueTys, Offsets,
     132         723 :                        StartingOffset + i * EltSize);
     133             :     return;
     134             :   }
     135             :   // Interpret void as zero return values.
     136        5216 :   if (Ty.isVoidTy())
     137             :     return;
     138             :   // Base case: we can get an LLT for this LLVM IR type.
     139        5089 :   ValueTys.push_back(getLLTForType(Ty, DL));
     140        5089 :   if (Offsets != nullptr)
     141        3383 :     Offsets->push_back(StartingOffset * 8);
     142             : }
     143             : 
     144             : IRTranslator::ValueToVRegInfo::VRegListT &
     145          29 : IRTranslator::allocateVRegs(const Value &Val) {
     146             :   assert(!VMap.contains(Val) && "Value already allocated in VMap");
     147          29 :   auto *Regs = VMap.getVRegs(Val);
     148          29 :   auto *Offsets = VMap.getOffsets(Val);
     149             :   SmallVector<LLT, 4> SplitTys;
     150          29 :   computeValueLLTs(*DL, *Val.getType(), SplitTys,
     151          29 :                    Offsets->empty() ? Offsets : nullptr);
     152          75 :   for (unsigned i = 0; i < SplitTys.size(); ++i)
     153          46 :     Regs->push_back(0);
     154          29 :   return *Regs;
     155             : }
     156             : 
     157        5826 : ArrayRef<unsigned> IRTranslator::getOrCreateVRegs(const Value &Val) {
     158             :   auto VRegsIt = VMap.findVRegs(Val);
     159        5826 :   if (VRegsIt != VMap.vregs_end())
     160        7022 :     return *VRegsIt->second;
     161             : 
     162        4630 :   if (Val.getType()->isVoidTy())
     163          83 :     return *VMap.getVRegs(Val);
     164             : 
     165             :   // Create entry for this type.
     166        2232 :   auto *VRegs = VMap.getVRegs(Val);
     167        2232 :   auto *Offsets = VMap.getOffsets(Val);
     168             : 
     169             :   assert(Val.getType()->isSized() &&
     170             :          "Don't know how to create an empty vreg");
     171             : 
     172             :   SmallVector<LLT, 4> SplitTys;
     173        2232 :   computeValueLLTs(*DL, *Val.getType(), SplitTys,
     174        2232 :                    Offsets->empty() ? Offsets : nullptr);
     175             : 
     176        2232 :   if (!isa<Constant>(Val)) {
     177        3274 :     for (auto Ty : SplitTys)
     178        3678 :       VRegs->push_back(MRI->createGenericVirtualRegister(Ty));
     179        1435 :     return *VRegs;
     180             :   }
     181             : 
     182         797 :   if (Val.getType()->isAggregateType()) {
     183             :     // UndefValue, ConstantAggregateZero
     184             :     auto &C = cast<Constant>(Val);
     185             :     unsigned Idx = 0;
     186          79 :     while (auto Elt = C.getAggregateElement(Idx++)) {
     187          59 :       auto EltRegs = getOrCreateVRegs(*Elt);
     188          59 :       std::copy(EltRegs.begin(), EltRegs.end(), std::back_inserter(*VRegs));
     189          59 :     }
     190             :   } else {
     191             :     assert(SplitTys.size() == 1 && "unexpectedly split LLT");
     192        1554 :     VRegs->push_back(MRI->createGenericVirtualRegister(SplitTys[0]));
     193         777 :     bool Success = translate(cast<Constant>(Val), VRegs->front());
     194         777 :     if (!Success) {
     195             :       OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
     196           0 :                                  MF->getFunction().getSubprogram(),
     197           0 :                                  &MF->getFunction().getEntryBlock());
     198           0 :       R << "unable to translate constant: " << ore::NV("Type", Val.getType());
     199           0 :       reportTranslationError(*MF, *TPC, *ORE, R);
     200           0 :       return *VRegs;
     201             :     }
     202             :   }
     203             : 
     204         797 :   return *VRegs;
     205             : }
     206             : 
     207          47 : int IRTranslator::getOrCreateFrameIndex(const AllocaInst &AI) {
     208          47 :   if (FrameIndices.find(&AI) != FrameIndices.end())
     209           2 :     return FrameIndices[&AI];
     210             : 
     211          45 :   unsigned ElementSize = DL->getTypeStoreSize(AI.getAllocatedType());
     212             :   unsigned Size =
     213          45 :       ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue();
     214             : 
     215             :   // Always allocate at least one byte.
     216          46 :   Size = std::max(Size, 1u);
     217             : 
     218             :   unsigned Alignment = AI.getAlignment();
     219          45 :   if (!Alignment)
     220          14 :     Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
     221             : 
     222          45 :   int &FI = FrameIndices[&AI];
     223          45 :   FI = MF->getFrameInfo().CreateStackObject(Size, Alignment, false, &AI);
     224          45 :   return FI;
     225             : }
     226             : 
     227         792 : unsigned IRTranslator::getMemOpAlignment(const Instruction &I) {
     228             :   unsigned Alignment = 0;
     229             :   Type *ValTy = nullptr;
     230             :   if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
     231             :     Alignment = SI->getAlignment();
     232         396 :     ValTy = SI->getValueOperand()->getType();
     233             :   } else if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
     234             :     Alignment = LI->getAlignment();
     235         382 :     ValTy = LI->getType();
     236             :   } else if (const AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(&I)) {
     237             :     // TODO(PR27168): This instruction has no alignment attribute, but unlike
     238             :     // the default alignment for load/store, the default here is to assume
     239             :     // it has NATURAL alignment, not DataLayout-specified alignment.
     240           3 :     const DataLayout &DL = AI->getModule()->getDataLayout();
     241           3 :     Alignment = DL.getTypeStoreSize(AI->getCompareOperand()->getType());
     242           3 :     ValTy = AI->getCompareOperand()->getType();
     243             :   } else if (const AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(&I)) {
     244             :     // TODO(PR27168): This instruction has no alignment attribute, but unlike
     245             :     // the default alignment for load/store, the default here is to assume
     246             :     // it has NATURAL alignment, not DataLayout-specified alignment.
     247          11 :     const DataLayout &DL = AI->getModule()->getDataLayout();
     248          11 :     Alignment = DL.getTypeStoreSize(AI->getValOperand()->getType());
     249          11 :     ValTy = AI->getType();
     250             :   } else {
     251           0 :     OptimizationRemarkMissed R("gisel-irtranslator", "", &I);
     252           0 :     R << "unable to translate memop: " << ore::NV("Opcode", &I);
     253           0 :     reportTranslationError(*MF, *TPC, *ORE, R);
     254             :     return 1;
     255             :   }
     256             : 
     257         792 :   return Alignment ? Alignment : DL->getABITypeAlignment(ValTy);
     258             : }
     259             : 
     260        2890 : MachineBasicBlock &IRTranslator::getMBB(const BasicBlock &BB) {
     261        2890 :   MachineBasicBlock *&MBB = BBToMBB[&BB];
     262             :   assert(MBB && "BasicBlock was not encountered before");
     263        2890 :   return *MBB;
     264             : }
     265             : 
     266          11 : void IRTranslator::addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred) {
     267             :   assert(NewPred && "new predecessor must be a real MachineBasicBlock");
     268          11 :   MachinePreds[Edge].push_back(NewPred);
     269          11 : }
     270             : 
     271         510 : bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U,
     272             :                                      MachineIRBuilder &MIRBuilder) {
     273             :   // FIXME: handle signed/unsigned wrapping flags.
     274             : 
     275             :   // Get or create a virtual register for each value.
     276             :   // Unless the value is a Constant => loadimm cst?
     277             :   // or inline constant each time?
     278             :   // Creation of a virtual register needs to have a size.
     279             :   unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
     280             :   unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
     281         510 :   unsigned Res = getOrCreateVReg(U);
     282        1020 :   auto FBinOp = MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op0).addUse(Op1);
     283         510 :   if (isa<Instruction>(U)) {
     284             :     MachineInstr *FBinOpMI = FBinOp.getInstr();
     285             :     const Instruction &I = cast<Instruction>(U);
     286         510 :     FBinOpMI->copyIRFlags(I);
     287             :   }
     288         510 :   return true;
     289             : }
     290             : 
     291          23 : bool IRTranslator::translateFSub(const User &U, MachineIRBuilder &MIRBuilder) {
     292             :   // -0.0 - X --> G_FNEG
     293          25 :   if (isa<Constant>(U.getOperand(0)) &&
     294           2 :       U.getOperand(0) == ConstantFP::getZeroValueForNegation(U.getType())) {
     295           2 :     MIRBuilder.buildInstr(TargetOpcode::G_FNEG)
     296           2 :         .addDef(getOrCreateVReg(U))
     297             :         .addUse(getOrCreateVReg(*U.getOperand(1)));
     298           2 :     return true;
     299             :   }
     300          21 :   return translateBinaryOp(TargetOpcode::G_FSUB, U, MIRBuilder);
     301             : }
     302             : 
     303          56 : bool IRTranslator::translateCompare(const User &U,
     304             :                                     MachineIRBuilder &MIRBuilder) {
     305             :   const CmpInst *CI = dyn_cast<CmpInst>(&U);
     306             :   unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
     307             :   unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
     308          56 :   unsigned Res = getOrCreateVReg(U);
     309             :   CmpInst::Predicate Pred =
     310          56 :       CI ? CI->getPredicate() : static_cast<CmpInst::Predicate>(
     311           0 :                                     cast<ConstantExpr>(U).getPredicate());
     312          56 :   if (CmpInst::isIntPredicate(Pred))
     313          47 :     MIRBuilder.buildICmp(Pred, Res, Op0, Op1);
     314           9 :   else if (Pred == CmpInst::FCMP_FALSE)
     315             :     MIRBuilder.buildCopy(
     316           2 :         Res, getOrCreateVReg(*Constant::getNullValue(CI->getType())));
     317           8 :   else if (Pred == CmpInst::FCMP_TRUE)
     318             :     MIRBuilder.buildCopy(
     319           2 :         Res, getOrCreateVReg(*Constant::getAllOnesValue(CI->getType())));
     320             :   else
     321           7 :     MIRBuilder.buildFCmp(Pred, Res, Op0, Op1);
     322             : 
     323          56 :   return true;
     324             : }
     325             : 
     326        1200 : bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) {
     327             :   const ReturnInst &RI = cast<ReturnInst>(U);
     328             :   const Value *Ret = RI.getReturnValue();
     329         929 :   if (Ret && DL->getTypeStoreSize(Ret->getType()) == 0)
     330             :     Ret = nullptr;
     331             : 
     332        1200 :   ArrayRef<unsigned> VRegs;
     333        1200 :   if (Ret)
     334         928 :     VRegs = getOrCreateVRegs(*Ret);
     335             : 
     336             :   // The target may mess up with the insertion point, but
     337             :   // this is not important as a return is the last instruction
     338             :   // of the block anyway.
     339             : 
     340        1200 :   return CLI->lowerReturn(MIRBuilder, Ret, VRegs);
     341             : }
     342             : 
     343          86 : bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) {
     344             :   const BranchInst &BrInst = cast<BranchInst>(U);
     345             :   unsigned Succ = 0;
     346          86 :   if (!BrInst.isUnconditional()) {
     347             :     // We want a G_BRCOND to the true BB followed by an unconditional branch.
     348             :     unsigned Tst = getOrCreateVReg(*BrInst.getCondition());
     349             :     const BasicBlock &TrueTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ++));
     350          27 :     MachineBasicBlock &TrueBB = getMBB(TrueTgt);
     351          27 :     MIRBuilder.buildBrCond(Tst, TrueBB);
     352             :   }
     353             : 
     354             :   const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ));
     355          86 :   MachineBasicBlock &TgtBB = getMBB(BrTgt);
     356          86 :   MachineBasicBlock &CurBB = MIRBuilder.getMBB();
     357             : 
     358             :   // If the unconditional target is the layout successor, fallthrough.
     359          86 :   if (!CurBB.isLayoutSuccessor(&TgtBB))
     360          54 :     MIRBuilder.buildBr(TgtBB);
     361             : 
     362             :   // Link successors.
     363         285 :   for (const BasicBlock *Succ : successors(&BrInst))
     364         113 :     CurBB.addSuccessor(&getMBB(*Succ));
     365          86 :   return true;
     366             : }
     367             : 
     368           3 : bool IRTranslator::translateSwitch(const User &U,
     369             :                                    MachineIRBuilder &MIRBuilder) {
     370             :   // For now, just translate as a chain of conditional branches.
     371             :   // FIXME: could we share most of the logic/code in
     372             :   // SelectionDAGBuilder::visitSwitch between SelectionDAG and GlobalISel?
     373             :   // At first sight, it seems most of the logic in there is independent of
     374             :   // SelectionDAG-specifics and a lot of work went in to optimize switch
     375             :   // lowering in there.
     376             : 
     377             :   const SwitchInst &SwInst = cast<SwitchInst>(U);
     378             :   const unsigned SwCondValue = getOrCreateVReg(*SwInst.getCondition());
     379           3 :   const BasicBlock *OrigBB = SwInst.getParent();
     380             : 
     381           3 :   LLT LLTi1 = getLLTForType(*Type::getInt1Ty(U.getContext()), *DL);
     382          11 :   for (auto &CaseIt : SwInst.cases()) {
     383          16 :     const unsigned CaseValueReg = getOrCreateVReg(*CaseIt.getCaseValue());
     384          16 :     const unsigned Tst = MRI->createGenericVirtualRegister(LLTi1);
     385           8 :     MIRBuilder.buildICmp(CmpInst::ICMP_EQ, Tst, CaseValueReg, SwCondValue);
     386           8 :     MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
     387           8 :     const BasicBlock *TrueBB = CaseIt.getCaseSuccessor();
     388           8 :     MachineBasicBlock &TrueMBB = getMBB(*TrueBB);
     389             : 
     390           8 :     MIRBuilder.buildBrCond(Tst, TrueMBB);
     391           8 :     CurMBB.addSuccessor(&TrueMBB);
     392           8 :     addMachineCFGPred({OrigBB, TrueBB}, &CurMBB);
     393             : 
     394             :     MachineBasicBlock *FalseMBB =
     395           8 :         MF->CreateMachineBasicBlock(SwInst.getParent());
     396             :     // Insert the comparison blocks one after the other.
     397           8 :     MF->insert(std::next(CurMBB.getIterator()), FalseMBB);
     398           8 :     MIRBuilder.buildBr(*FalseMBB);
     399           8 :     CurMBB.addSuccessor(FalseMBB);
     400             : 
     401           8 :     MIRBuilder.setMBB(*FalseMBB);
     402             :   }
     403             :   // handle default case
     404             :   const BasicBlock *DefaultBB = SwInst.getDefaultDest();
     405           3 :   MachineBasicBlock &DefaultMBB = getMBB(*DefaultBB);
     406           3 :   MIRBuilder.buildBr(DefaultMBB);
     407           3 :   MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
     408           3 :   CurMBB.addSuccessor(&DefaultMBB);
     409           3 :   addMachineCFGPred({OrigBB, DefaultBB}, &CurMBB);
     410             : 
     411           3 :   return true;
     412             : }
     413             : 
     414           3 : bool IRTranslator::translateIndirectBr(const User &U,
     415             :                                        MachineIRBuilder &MIRBuilder) {
     416             :   const IndirectBrInst &BrInst = cast<IndirectBrInst>(U);
     417             : 
     418             :   const unsigned Tgt = getOrCreateVReg(*BrInst.getAddress());
     419           3 :   MIRBuilder.buildBrIndirect(Tgt);
     420             : 
     421             :   // Link successors.
     422           3 :   MachineBasicBlock &CurBB = MIRBuilder.getMBB();
     423          11 :   for (const BasicBlock *Succ : successors(&BrInst))
     424           5 :     CurBB.addSuccessor(&getMBB(*Succ));
     425             : 
     426           3 :   return true;
     427             : }
     428             : 
     429         266 : bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) {
     430             :   const LoadInst &LI = cast<LoadInst>(U);
     431             : 
     432         266 :   auto Flags = LI.isVolatile() ? MachineMemOperand::MOVolatile
     433             :                                : MachineMemOperand::MONone;
     434             :   Flags |= MachineMemOperand::MOLoad;
     435             : 
     436         266 :   if (DL->getTypeStoreSize(LI.getType()) == 0)
     437             :     return true;
     438             : 
     439         265 :   ArrayRef<unsigned> Regs = getOrCreateVRegs(LI);
     440         265 :   ArrayRef<uint64_t> Offsets = *VMap.getOffsets(LI);
     441             :   unsigned Base = getOrCreateVReg(*LI.getPointerOperand());
     442             : 
     443         647 :   for (unsigned i = 0; i < Regs.size(); ++i) {
     444         382 :     unsigned Addr = 0;
     445         764 :     MIRBuilder.materializeGEP(Addr, Base, LLT::scalar(64), Offsets[i] / 8);
     446             : 
     447         382 :     MachinePointerInfo Ptr(LI.getPointerOperand(), Offsets[i] / 8);
     448         382 :     unsigned BaseAlign = getMemOpAlignment(LI);
     449         382 :     auto MMO = MF->getMachineMemOperand(
     450        1146 :         Ptr, Flags, (MRI->getType(Regs[i]).getSizeInBits() + 7) / 8,
     451         382 :         MinAlign(BaseAlign, Offsets[i] / 8), AAMDNodes(), nullptr,
     452         382 :         LI.getSyncScopeID(), LI.getOrdering());
     453         382 :     MIRBuilder.buildLoad(Regs[i], Addr, *MMO);
     454             :   }
     455             : 
     456             :   return true;
     457             : }
     458             : 
     459         268 : bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) {
     460             :   const StoreInst &SI = cast<StoreInst>(U);
     461         268 :   auto Flags = SI.isVolatile() ? MachineMemOperand::MOVolatile
     462             :                                : MachineMemOperand::MONone;
     463             :   Flags |= MachineMemOperand::MOStore;
     464             : 
     465         268 :   if (DL->getTypeStoreSize(SI.getValueOperand()->getType()) == 0)
     466             :     return true;
     467             : 
     468         267 :   ArrayRef<unsigned> Vals = getOrCreateVRegs(*SI.getValueOperand());
     469         267 :   ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*SI.getValueOperand());
     470             :   unsigned Base = getOrCreateVReg(*SI.getPointerOperand());
     471             : 
     472         663 :   for (unsigned i = 0; i < Vals.size(); ++i) {
     473         396 :     unsigned Addr = 0;
     474         792 :     MIRBuilder.materializeGEP(Addr, Base, LLT::scalar(64), Offsets[i] / 8);
     475             : 
     476         396 :     MachinePointerInfo Ptr(SI.getPointerOperand(), Offsets[i] / 8);
     477         396 :     unsigned BaseAlign = getMemOpAlignment(SI);
     478         396 :     auto MMO = MF->getMachineMemOperand(
     479        1188 :         Ptr, Flags, (MRI->getType(Vals[i]).getSizeInBits() + 7) / 8,
     480         396 :         MinAlign(BaseAlign, Offsets[i] / 8), AAMDNodes(), nullptr,
     481         396 :         SI.getSyncScopeID(), SI.getOrdering());
     482         396 :     MIRBuilder.buildStore(Vals[i], Addr, *MMO);
     483             :   }
     484             :   return true;
     485             : }
     486             : 
     487          29 : static uint64_t getOffsetFromIndices(const User &U, const DataLayout &DL) {
     488             :   const Value *Src = U.getOperand(0);
     489          29 :   Type *Int32Ty = Type::getInt32Ty(U.getContext());
     490             : 
     491             :   // getIndexedOffsetInType is designed for GEPs, so the first index is the
     492             :   // usual array element rather than looking into the actual aggregate.
     493             :   SmallVector<Value *, 1> Indices;
     494          29 :   Indices.push_back(ConstantInt::get(Int32Ty, 0));
     495             : 
     496             :   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) {
     497          43 :     for (auto Idx : EVI->indices())
     498          22 :       Indices.push_back(ConstantInt::get(Int32Ty, Idx));
     499             :   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) {
     500          18 :     for (auto Idx : IVI->indices())
     501          10 :       Indices.push_back(ConstantInt::get(Int32Ty, Idx));
     502             :   } else {
     503           0 :     for (unsigned i = 1; i < U.getNumOperands(); ++i)
     504           0 :       Indices.push_back(U.getOperand(i));
     505             :   }
     506             : 
     507          29 :   return 8 * static_cast<uint64_t>(
     508          29 :                  DL.getIndexedOffsetInType(Src->getType(), Indices));
     509             : }
     510             : 
     511          21 : bool IRTranslator::translateExtractValue(const User &U,
     512             :                                          MachineIRBuilder &MIRBuilder) {
     513             :   const Value *Src = U.getOperand(0);
     514          21 :   uint64_t Offset = getOffsetFromIndices(U, *DL);
     515          21 :   ArrayRef<unsigned> SrcRegs = getOrCreateVRegs(*Src);
     516          21 :   ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*Src);
     517          21 :   unsigned Idx = std::lower_bound(Offsets.begin(), Offsets.end(), Offset) -
     518          21 :                  Offsets.begin();
     519          21 :   auto &DstRegs = allocateVRegs(U);
     520             : 
     521          43 :   for (unsigned i = 0; i < DstRegs.size(); ++i)
     522          44 :     DstRegs[i] = SrcRegs[Idx++];
     523             : 
     524          21 :   return true;
     525             : }
     526             : 
     527           8 : bool IRTranslator::translateInsertValue(const User &U,
     528             :                                         MachineIRBuilder &MIRBuilder) {
     529             :   const Value *Src = U.getOperand(0);
     530           8 :   uint64_t Offset = getOffsetFromIndices(U, *DL);
     531           8 :   auto &DstRegs = allocateVRegs(U);
     532           8 :   ArrayRef<uint64_t> DstOffsets = *VMap.getOffsets(U);
     533           8 :   ArrayRef<unsigned> SrcRegs = getOrCreateVRegs(*Src);
     534           8 :   ArrayRef<unsigned> InsertedRegs = getOrCreateVRegs(*U.getOperand(1));
     535             :   auto InsertedIt = InsertedRegs.begin();
     536             : 
     537          32 :   for (unsigned i = 0; i < DstRegs.size(); ++i) {
     538          24 :     if (DstOffsets[i] >= Offset && InsertedIt != InsertedRegs.end())
     539          22 :       DstRegs[i] = *InsertedIt++;
     540             :     else
     541          26 :       DstRegs[i] = SrcRegs[i];
     542             :   }
     543             : 
     544           8 :   return true;
     545             : }
     546             : 
     547           6 : bool IRTranslator::translateSelect(const User &U,
     548             :                                    MachineIRBuilder &MIRBuilder) {
     549             :   unsigned Tst = getOrCreateVReg(*U.getOperand(0));
     550           6 :   ArrayRef<unsigned> ResRegs = getOrCreateVRegs(U);
     551           6 :   ArrayRef<unsigned> Op0Regs = getOrCreateVRegs(*U.getOperand(1));
     552           6 :   ArrayRef<unsigned> Op1Regs = getOrCreateVRegs(*U.getOperand(2));
     553             : 
     554          12 :   for (unsigned i = 0; i < ResRegs.size(); ++i)
     555          24 :     MIRBuilder.buildSelect(ResRegs[i], Tst, Op0Regs[i], Op1Regs[i]);
     556             : 
     557           6 :   return true;
     558             : }
     559             : 
     560          68 : bool IRTranslator::translateBitCast(const User &U,
     561             :                                     MachineIRBuilder &MIRBuilder) {
     562             :   // If we're bitcasting to the source type, we can reuse the source vreg.
     563         136 :   if (getLLTForType(*U.getOperand(0)->getType(), *DL) ==
     564         134 :       getLLTForType(*U.getType(), *DL)) {
     565          66 :     unsigned SrcReg = getOrCreateVReg(*U.getOperand(0));
     566          66 :     auto &Regs = *VMap.getVRegs(U);
     567             :     // If we already assigned a vreg for this bitcast, we can't change that.
     568             :     // Emit a copy to satisfy the users we already emitted.
     569          66 :     if (!Regs.empty())
     570          12 :       MIRBuilder.buildCopy(Regs[0], SrcReg);
     571             :     else {
     572          60 :       Regs.push_back(SrcReg);
     573          60 :       VMap.getOffsets(U)->push_back(0);
     574             :     }
     575             :     return true;
     576             :   }
     577           2 :   return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder);
     578             : }
     579             : 
     580         237 : bool IRTranslator::translateCast(unsigned Opcode, const User &U,
     581             :                                  MachineIRBuilder &MIRBuilder) {
     582             :   unsigned Op = getOrCreateVReg(*U.getOperand(0));
     583         237 :   unsigned Res = getOrCreateVReg(U);
     584         237 :   MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op);
     585         237 :   return true;
     586             : }
     587             : 
     588          94 : bool IRTranslator::translateGetElementPtr(const User &U,
     589             :                                           MachineIRBuilder &MIRBuilder) {
     590             :   // FIXME: support vector GEPs.
     591         188 :   if (U.getType()->isVectorTy())
     592             :     return false;
     593             : 
     594             :   Value &Op0 = *U.getOperand(0);
     595             :   unsigned BaseReg = getOrCreateVReg(Op0);
     596          94 :   Type *PtrIRTy = Op0.getType();
     597          94 :   LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
     598          94 :   Type *OffsetIRTy = DL->getIntPtrType(PtrIRTy);
     599          94 :   LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
     600             : 
     601             :   int64_t Offset = 0;
     602         230 :   for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U);
     603         366 :        GTI != E; ++GTI) {
     604             :     const Value *Idx = GTI.getOperand();
     605          10 :     if (StructType *StTy = GTI.getStructTypeOrNull()) {
     606          10 :       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
     607          10 :       Offset += DL->getStructLayout(StTy)->getElementOffset(Field);
     608          10 :       continue;
     609             :     } else {
     610         126 :       uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
     611             : 
     612             :       // If this is a scalar constant or a splat vector of constants,
     613             :       // handle it quickly.
     614             :       if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
     615         103 :         Offset += ElementSize * CI->getSExtValue();
     616         103 :         continue;
     617             :       }
     618             : 
     619          23 :       if (Offset != 0) {
     620           2 :         unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
     621             :         unsigned OffsetReg =
     622           1 :             getOrCreateVReg(*ConstantInt::get(OffsetIRTy, Offset));
     623           1 :         MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg);
     624             : 
     625             :         BaseReg = NewBaseReg;
     626             :         Offset = 0;
     627             :       }
     628             : 
     629             :       unsigned IdxReg = getOrCreateVReg(*Idx);
     630          46 :       if (MRI->getType(IdxReg) != OffsetTy) {
     631           5 :         unsigned NewIdxReg = MRI->createGenericVirtualRegister(OffsetTy);
     632           5 :         MIRBuilder.buildSExtOrTrunc(NewIdxReg, IdxReg);
     633             :         IdxReg = NewIdxReg;
     634             :       }
     635             : 
     636             :       // N = N + Idx * ElementSize;
     637             :       // Avoid doing it for ElementSize of 1.
     638             :       unsigned GepOffsetReg;
     639          23 :       if (ElementSize != 1) {
     640             :         unsigned ElementSizeReg =
     641          20 :             getOrCreateVReg(*ConstantInt::get(OffsetIRTy, ElementSize));
     642             : 
     643          40 :         GepOffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
     644          20 :         MIRBuilder.buildMul(GepOffsetReg, ElementSizeReg, IdxReg);
     645             :       } else
     646             :         GepOffsetReg = IdxReg;
     647             : 
     648          46 :       unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
     649          23 :       MIRBuilder.buildGEP(NewBaseReg, BaseReg, GepOffsetReg);
     650             :       BaseReg = NewBaseReg;
     651             :     }
     652             :   }
     653             : 
     654          94 :   if (Offset != 0) {
     655          44 :     unsigned OffsetReg = getOrCreateVReg(*ConstantInt::get(OffsetIRTy, Offset));
     656          88 :     MIRBuilder.buildGEP(getOrCreateVReg(U), BaseReg, OffsetReg);
     657          44 :     return true;
     658             :   }
     659             : 
     660         100 :   MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg);
     661          50 :   return true;
     662             : }
     663             : 
     664          13 : bool IRTranslator::translateMemfunc(const CallInst &CI,
     665             :                                     MachineIRBuilder &MIRBuilder,
     666             :                                     unsigned ID) {
     667          13 :   LLT SizeTy = getLLTForType(*CI.getArgOperand(2)->getType(), *DL);
     668          13 :   Type *DstTy = CI.getArgOperand(0)->getType();
     669          26 :   if (cast<PointerType>(DstTy)->getAddressSpace() != 0 ||
     670          13 :       SizeTy.getSizeInBits() != DL->getPointerSizeInBits(0))
     671           0 :     return false;
     672             : 
     673             :   SmallVector<CallLowering::ArgInfo, 8> Args;
     674          52 :   for (int i = 0; i < 3; ++i) {
     675          39 :     const auto &Arg = CI.getArgOperand(i);
     676          78 :     Args.emplace_back(getOrCreateVReg(*Arg), Arg->getType());
     677             :   }
     678             : 
     679             :   const char *Callee;
     680          13 :   switch (ID) {
     681          12 :   case Intrinsic::memmove:
     682             :   case Intrinsic::memcpy: {
     683          12 :     Type *SrcTy = CI.getArgOperand(1)->getType();
     684          12 :     if(cast<PointerType>(SrcTy)->getAddressSpace() != 0)
     685             :       return false;
     686          12 :     Callee = ID == Intrinsic::memcpy ? "memcpy" : "memmove";
     687             :     break;
     688             :   }
     689             :   case Intrinsic::memset:
     690             :     Callee = "memset";
     691             :     break;
     692             :   default:
     693             :     return false;
     694             :   }
     695             : 
     696          13 :   return CLI->lowerCall(MIRBuilder, CI.getCallingConv(),
     697          13 :                         MachineOperand::CreateES(Callee),
     698          26 :                         CallLowering::ArgInfo(0, CI.getType()), Args);
     699             : }
     700             : 
     701           1 : void IRTranslator::getStackGuard(unsigned DstReg,
     702             :                                  MachineIRBuilder &MIRBuilder) {
     703           1 :   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
     704           1 :   MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF));
     705           1 :   auto MIB = MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD);
     706             :   MIB.addDef(DstReg);
     707             : 
     708           1 :   auto &TLI = *MF->getSubtarget().getTargetLowering();
     709           1 :   Value *Global = TLI.getSDagStackGuard(*MF->getFunction().getParent());
     710           1 :   if (!Global)
     711           0 :     return;
     712             : 
     713             :   MachinePointerInfo MPInfo(Global);
     714             :   auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
     715             :                MachineMemOperand::MODereferenceable;
     716             :   MachineMemOperand *MemRef =
     717           1 :       MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8,
     718           1 :                                DL->getPointerABIAlignment(0));
     719           1 :   MIB.setMemRefs({MemRef});
     720             : }
     721             : 
     722           6 : bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op,
     723             :                                               MachineIRBuilder &MIRBuilder) {
     724           6 :   ArrayRef<unsigned> ResRegs = getOrCreateVRegs(CI);
     725           6 :   MIRBuilder.buildInstr(Op)
     726           6 :       .addDef(ResRegs[0])
     727           6 :       .addDef(ResRegs[1])
     728           6 :       .addUse(getOrCreateVReg(*CI.getOperand(0)))
     729             :       .addUse(getOrCreateVReg(*CI.getOperand(1)));
     730             : 
     731           6 :   return true;
     732             : }
     733             : 
     734          95 : bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID,
     735             :                                            MachineIRBuilder &MIRBuilder) {
     736          95 :   switch (ID) {
     737             :   default:
     738             :     break;
     739           2 :   case Intrinsic::lifetime_start:
     740             :   case Intrinsic::lifetime_end:
     741             :     // Stack coloring is not enabled in O0 (which we care about now) so we can
     742             :     // drop these. Make sure someone notices when we start compiling at higher
     743             :     // opts though.
     744           2 :     if (MF->getTarget().getOptLevel() != CodeGenOpt::None)
     745           0 :       return false;
     746             :     return true;
     747             :   case Intrinsic::dbg_declare: {
     748             :     const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI);
     749             :     assert(DI.getVariable() && "Missing variable");
     750             : 
     751             :     const Value *Address = DI.getAddress();
     752           3 :     if (!Address || isa<UndefValue>(Address)) {
     753             :       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
     754             :       return true;
     755             :     }
     756             : 
     757             :     assert(DI.getVariable()->isValidLocationForIntrinsic(
     758             :                MIRBuilder.getDebugLoc()) &&
     759             :            "Expected inlined-at fields to agree");
     760             :     auto AI = dyn_cast<AllocaInst>(Address);
     761           2 :     if (AI && AI->isStaticAlloca()) {
     762             :       // Static allocas are tracked at the MF level, no need for DBG_VALUE
     763             :       // instructions (in fact, they get ignored if they *do* exist).
     764           2 :       MF->setVariableDbgInfo(DI.getVariable(), DI.getExpression(),
     765             :                              getOrCreateFrameIndex(*AI), DI.getDebugLoc());
     766             :     } else {
     767             :       // A dbg.declare describes the address of a source variable, so lower it
     768             :       // into an indirect DBG_VALUE.
     769             :       MIRBuilder.buildIndirectDbgValue(getOrCreateVReg(*Address),
     770           4 :                                        DI.getVariable(), DI.getExpression());
     771             :     }
     772             :     return true;
     773             :   }
     774             :   case Intrinsic::dbg_label: {
     775             :     const DbgLabelInst &DI = cast<DbgLabelInst>(CI);
     776             :     assert(DI.getLabel() && "Missing label");
     777             : 
     778             :     assert(DI.getLabel()->isValidLocationForIntrinsic(
     779             :                MIRBuilder.getDebugLoc()) &&
     780             :            "Expected inlined-at fields to agree");
     781             : 
     782           0 :     MIRBuilder.buildDbgLabel(DI.getLabel());
     783           0 :     return true;
     784             :   }
     785             :   case Intrinsic::vaend:
     786             :     // No target I know of cares about va_end. Certainly no in-tree target
     787             :     // does. Simplest intrinsic ever!
     788             :     return true;
     789           3 :   case Intrinsic::vastart: {
     790           3 :     auto &TLI = *MF->getSubtarget().getTargetLowering();
     791           3 :     Value *Ptr = CI.getArgOperand(0);
     792           3 :     unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8;
     793             : 
     794           3 :     MIRBuilder.buildInstr(TargetOpcode::G_VASTART)
     795             :         .addUse(getOrCreateVReg(*Ptr))
     796           3 :         .addMemOperand(MF->getMachineMemOperand(
     797           6 :             MachinePointerInfo(Ptr), MachineMemOperand::MOStore, ListSize, 0));
     798           3 :     return true;
     799             :   }
     800             :   case Intrinsic::dbg_value: {
     801             :     // This form of DBG_VALUE is target-independent.
     802             :     const DbgValueInst &DI = cast<DbgValueInst>(CI);
     803             :     const Value *V = DI.getValue();
     804             :     assert(DI.getVariable()->isValidLocationForIntrinsic(
     805             :                MIRBuilder.getDebugLoc()) &&
     806             :            "Expected inlined-at fields to agree");
     807          14 :     if (!V) {
     808             :       // Currently the optimizer can produce this; insert an undef to
     809             :       // help debugging.  Probably the optimizer should not do this.
     810           0 :       MIRBuilder.buildIndirectDbgValue(0, DI.getVariable(), DI.getExpression());
     811             :     } else if (const auto *CI = dyn_cast<Constant>(V)) {
     812          10 :       MIRBuilder.buildConstDbgValue(*CI, DI.getVariable(), DI.getExpression());
     813             :     } else {
     814             :       unsigned Reg = getOrCreateVReg(*V);
     815             :       // FIXME: This does not handle register-indirect values at offset 0. The
     816             :       // direct/indirect thing shouldn't really be handled by something as
     817             :       // implicit as reg+noreg vs reg+imm in the first palce, but it seems
     818             :       // pretty baked in right now.
     819          18 :       MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(), DI.getExpression());
     820             :     }
     821             :     return true;
     822             :   }
     823           1 :   case Intrinsic::uadd_with_overflow:
     824           1 :     return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDO, MIRBuilder);
     825           1 :   case Intrinsic::sadd_with_overflow:
     826           1 :     return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder);
     827           1 :   case Intrinsic::usub_with_overflow:
     828           1 :     return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBO, MIRBuilder);
     829           1 :   case Intrinsic::ssub_with_overflow:
     830           1 :     return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder);
     831           1 :   case Intrinsic::umul_with_overflow:
     832           1 :     return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder);
     833           1 :   case Intrinsic::smul_with_overflow:
     834           1 :     return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder);
     835           7 :   case Intrinsic::pow:
     836           7 :     MIRBuilder.buildInstr(TargetOpcode::G_FPOW)
     837           7 :         .addDef(getOrCreateVReg(CI))
     838           7 :         .addUse(getOrCreateVReg(*CI.getArgOperand(0)))
     839             :         .addUse(getOrCreateVReg(*CI.getArgOperand(1)));
     840           7 :     return true;
     841           1 :   case Intrinsic::exp:
     842           1 :     MIRBuilder.buildInstr(TargetOpcode::G_FEXP)
     843           1 :         .addDef(getOrCreateVReg(CI))
     844           1 :         .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
     845           1 :     return true;
     846           1 :   case Intrinsic::exp2:
     847           1 :     MIRBuilder.buildInstr(TargetOpcode::G_FEXP2)
     848           1 :         .addDef(getOrCreateVReg(CI))
     849           1 :         .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
     850           1 :     return true;
     851           1 :   case Intrinsic::log:
     852           1 :     MIRBuilder.buildInstr(TargetOpcode::G_FLOG)
     853           1 :         .addDef(getOrCreateVReg(CI))
     854           1 :         .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
     855           1 :     return true;
     856           1 :   case Intrinsic::log2:
     857           1 :     MIRBuilder.buildInstr(TargetOpcode::G_FLOG2)
     858           1 :         .addDef(getOrCreateVReg(CI))
     859           1 :         .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
     860           1 :     return true;
     861           1 :   case Intrinsic::fabs:
     862           1 :     MIRBuilder.buildInstr(TargetOpcode::G_FABS)
     863           1 :         .addDef(getOrCreateVReg(CI))
     864           1 :         .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
     865           1 :     return true;
     866           1 :   case Intrinsic::trunc:
     867           1 :     MIRBuilder.buildInstr(TargetOpcode::G_INTRINSIC_TRUNC)
     868           1 :         .addDef(getOrCreateVReg(CI))
     869           1 :         .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
     870           1 :     return true;
     871           1 :   case Intrinsic::round:
     872           1 :     MIRBuilder.buildInstr(TargetOpcode::G_INTRINSIC_ROUND)
     873           1 :         .addDef(getOrCreateVReg(CI))
     874           1 :         .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
     875           1 :     return true;
     876           1 :   case Intrinsic::fma:
     877           1 :     MIRBuilder.buildInstr(TargetOpcode::G_FMA)
     878           1 :         .addDef(getOrCreateVReg(CI))
     879           1 :         .addUse(getOrCreateVReg(*CI.getArgOperand(0)))
     880             :         .addUse(getOrCreateVReg(*CI.getArgOperand(1)))
     881             :         .addUse(getOrCreateVReg(*CI.getArgOperand(2)));
     882           1 :     return true;
     883           2 :   case Intrinsic::fmuladd: {
     884           2 :     const TargetMachine &TM = MF->getTarget();
     885           2 :     const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
     886           2 :     unsigned Dst = getOrCreateVReg(CI);
     887           4 :     unsigned Op0 = getOrCreateVReg(*CI.getArgOperand(0));
     888           2 :     unsigned Op1 = getOrCreateVReg(*CI.getArgOperand(1));
     889           2 :     unsigned Op2 = getOrCreateVReg(*CI.getArgOperand(2));
     890           3 :     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
     891           1 :         TLI.isFMAFasterThanFMulAndFAdd(TLI.getValueType(*DL, CI.getType()))) {
     892             :       // TODO: Revisit this to see if we should move this part of the
     893             :       // lowering to the combiner.
     894           1 :       MIRBuilder.buildInstr(TargetOpcode::G_FMA, Dst, Op0, Op1, Op2);
     895             :     } else {
     896           1 :       LLT Ty = getLLTForType(*CI.getType(), *DL);
     897           1 :       auto FMul = MIRBuilder.buildInstr(TargetOpcode::G_FMUL, Ty, Op0, Op1);
     898           1 :       MIRBuilder.buildInstr(TargetOpcode::G_FADD, Dst, FMul, Op2);
     899             :     }
     900             :     return true;
     901             :   }
     902          13 :   case Intrinsic::memcpy:
     903             :   case Intrinsic::memmove:
     904             :   case Intrinsic::memset:
     905          13 :     return translateMemfunc(CI, MIRBuilder, ID);
     906           1 :   case Intrinsic::eh_typeid_for: {
     907           1 :     GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0));
     908           1 :     unsigned Reg = getOrCreateVReg(CI);
     909           1 :     unsigned TypeID = MF->getTypeIDFor(GV);
     910           1 :     MIRBuilder.buildConstant(Reg, TypeID);
     911           1 :     return true;
     912             :   }
     913           4 :   case Intrinsic::objectsize: {
     914             :     // If we don't know by now, we're never going to know.
     915           4 :     const ConstantInt *Min = cast<ConstantInt>(CI.getArgOperand(1));
     916             : 
     917          14 :     MIRBuilder.buildConstant(getOrCreateVReg(CI), Min->isZero() ? -1ULL : 0);
     918           4 :     return true;
     919             :   }
     920           0 :   case Intrinsic::stackguard:
     921           0 :     getStackGuard(getOrCreateVReg(CI), MIRBuilder);
     922           0 :     return true;
     923           1 :   case Intrinsic::stackprotector: {
     924           1 :     LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
     925           2 :     unsigned GuardVal = MRI->createGenericVirtualRegister(PtrTy);
     926           1 :     getStackGuard(GuardVal, MIRBuilder);
     927             : 
     928             :     AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1));
     929             :     MIRBuilder.buildStore(
     930             :         GuardVal, getOrCreateVReg(*Slot),
     931           2 :         *MF->getMachineMemOperand(
     932           1 :             MachinePointerInfo::getFixedStack(*MF,
     933             :                                               getOrCreateFrameIndex(*Slot)),
     934             :             MachineMemOperand::MOStore | MachineMemOperand::MOVolatile,
     935           4 :             PtrTy.getSizeInBits() / 8, 8));
     936             :     return true;
     937             :   }
     938           2 :   case Intrinsic::cttz:
     939             :   case Intrinsic::ctlz: {
     940           2 :     ConstantInt *Cst = cast<ConstantInt>(CI.getArgOperand(1));
     941             :     bool isTrailing = ID == Intrinsic::cttz;
     942             :     unsigned Opcode = isTrailing
     943           4 :                           ? Cst->isZero() ? TargetOpcode::G_CTTZ
     944             :                                           : TargetOpcode::G_CTTZ_ZERO_UNDEF
     945             :                           : Cst->isZero() ? TargetOpcode::G_CTLZ
     946             :                                           : TargetOpcode::G_CTLZ_ZERO_UNDEF;
     947           2 :     MIRBuilder.buildInstr(Opcode)
     948           2 :         .addDef(getOrCreateVReg(CI))
     949             :         .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
     950           2 :     return true;
     951             :   }
     952           1 :   case Intrinsic::ctpop: {
     953           1 :     MIRBuilder.buildInstr(TargetOpcode::G_CTPOP)
     954           1 :         .addDef(getOrCreateVReg(CI))
     955           1 :         .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
     956           1 :     return true;
     957             :   }
     958           1 :   case Intrinsic::invariant_start: {
     959           1 :     LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
     960           2 :     unsigned Undef = MRI->createGenericVirtualRegister(PtrTy);
     961           1 :     MIRBuilder.buildUndef(Undef);
     962             :     return true;
     963             :   }
     964             :   case Intrinsic::invariant_end:
     965             :     return true;
     966             :   }
     967          25 :   return false;
     968             : }
     969             : 
     970           4 : bool IRTranslator::translateInlineAsm(const CallInst &CI,
     971             :                                       MachineIRBuilder &MIRBuilder) {
     972             :   const InlineAsm &IA = cast<InlineAsm>(*CI.getCalledValue());
     973           4 :   if (!IA.getConstraintString().empty())
     974             :     return false;
     975             : 
     976             :   unsigned ExtraInfo = 0;
     977           2 :   if (IA.hasSideEffects())
     978             :     ExtraInfo |= InlineAsm::Extra_HasSideEffects;
     979           2 :   if (IA.getDialect() == InlineAsm::AD_Intel)
     980           0 :     ExtraInfo |= InlineAsm::Extra_AsmDialect;
     981             : 
     982           2 :   MIRBuilder.buildInstr(TargetOpcode::INLINEASM)
     983             :     .addExternalSymbol(IA.getAsmString().c_str())
     984           2 :     .addImm(ExtraInfo);
     985             : 
     986           2 :   return true;
     987             : }
     988             : 
     989         341 : unsigned IRTranslator::packRegs(const Value &V,
     990             :                                   MachineIRBuilder &MIRBuilder) {
     991         341 :   ArrayRef<unsigned> Regs = getOrCreateVRegs(V);
     992         341 :   ArrayRef<uint64_t> Offsets = *VMap.getOffsets(V);
     993         341 :   LLT BigTy = getLLTForType(*V.getType(), *DL);
     994             : 
     995         341 :   if (Regs.size() == 1)
     996         313 :     return Regs[0];
     997             : 
     998          56 :   unsigned Dst = MRI->createGenericVirtualRegister(BigTy);
     999          28 :   MIRBuilder.buildUndef(Dst);
    1000         194 :   for (unsigned i = 0; i < Regs.size(); ++i) {
    1001         332 :     unsigned NewDst = MRI->createGenericVirtualRegister(BigTy);
    1002         332 :     MIRBuilder.buildInsert(NewDst, Dst, Regs[i], Offsets[i]);
    1003             :     Dst = NewDst;
    1004             :   }
    1005             :   return Dst;
    1006             : }
    1007             : 
    1008          61 : void IRTranslator::unpackRegs(const Value &V, unsigned Src,
    1009             :                                 MachineIRBuilder &MIRBuilder) {
    1010          61 :   ArrayRef<unsigned> Regs = getOrCreateVRegs(V);
    1011          61 :   ArrayRef<uint64_t> Offsets = *VMap.getOffsets(V);
    1012             : 
    1013         391 :   for (unsigned i = 0; i < Regs.size(); ++i)
    1014         990 :     MIRBuilder.buildExtract(Regs[i], Src, Offsets[i]);
    1015          61 : }
    1016             : 
    1017         244 : bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) {
    1018             :   const CallInst &CI = cast<CallInst>(U);
    1019         244 :   auto TII = MF->getTarget().getIntrinsicInfo();
    1020             :   const Function *F = CI.getCalledFunction();
    1021             : 
    1022             :   // FIXME: support Windows dllimport function calls.
    1023         232 :   if (F && F->hasDLLImportStorageClass())
    1024             :     return false;
    1025             : 
    1026         243 :   if (CI.isInlineAsm())
    1027           4 :     return translateInlineAsm(CI, MIRBuilder);
    1028             : 
    1029             :   Intrinsic::ID ID = Intrinsic::not_intrinsic;
    1030         239 :   if (F && F->isIntrinsic()) {
    1031          95 :     ID = F->getIntrinsicID();
    1032          95 :     if (TII && ID == Intrinsic::not_intrinsic)
    1033           0 :       ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F));
    1034             :   }
    1035             : 
    1036         239 :   bool IsSplitType = valueIsSplit(CI);
    1037         239 :   if (!F || !F->isIntrinsic() || ID == Intrinsic::not_intrinsic) {
    1038         267 :     unsigned Res = IsSplitType ? MRI->createGenericVirtualRegister(
    1039          21 :                                      getLLTForType(*CI.getType(), *DL))
    1040             :                                : getOrCreateVReg(CI);
    1041             : 
    1042             :     SmallVector<unsigned, 8> Args;
    1043         430 :     for (auto &Arg: CI.arg_operands())
    1044         286 :       Args.push_back(packRegs(*Arg, MIRBuilder));
    1045             : 
    1046         144 :     MF->getFrameInfo().setHasCalls(true);
    1047         288 :     bool Success = CLI->lowerCall(MIRBuilder, &CI, Res, Args, [&]() {
    1048             :       return getOrCreateVReg(*CI.getCalledValue());
    1049             :     });
    1050             : 
    1051         144 :     if (IsSplitType)
    1052          21 :       unpackRegs(CI, Res, MIRBuilder);
    1053             :     return Success;
    1054             :   }
    1055             : 
    1056             :   assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
    1057             : 
    1058          95 :   if (translateKnownIntrinsic(CI, ID, MIRBuilder))
    1059             :     return true;
    1060             : 
    1061             :   unsigned Res = 0;
    1062          50 :   if (!CI.getType()->isVoidTy()) {
    1063          17 :     if (IsSplitType)
    1064             :       Res =
    1065           0 :           MRI->createGenericVirtualRegister(getLLTForType(*CI.getType(), *DL));
    1066             :     else
    1067             :       Res = getOrCreateVReg(CI);
    1068             :   }
    1069             :   MachineInstrBuilder MIB =
    1070          25 :       MIRBuilder.buildIntrinsic(ID, Res, !CI.doesNotAccessMemory());
    1071             : 
    1072          73 :   for (auto &Arg : CI.arg_operands()) {
    1073             :     // Some intrinsics take metadata parameters. Reject them.
    1074          50 :     if (isa<MetadataAsValue>(Arg))
    1075             :       return false;
    1076          48 :     MIB.addUse(packRegs(*Arg, MIRBuilder));
    1077             :   }
    1078             : 
    1079          23 :   if (IsSplitType)
    1080           0 :     unpackRegs(CI, Res, MIRBuilder);
    1081             : 
    1082             :   // Add a MachineMemOperand if it is a target mem intrinsic.
    1083          23 :   const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
    1084          23 :   TargetLowering::IntrinsicInfo Info;
    1085             :   // TODO: Add a GlobalISel version of getTgtMemIntrinsic.
    1086          23 :   if (TLI.getTgtMemIntrinsic(Info, CI, *MF, ID)) {
    1087           2 :     uint64_t Size = Info.memVT.getStoreSize();
    1088           2 :     MIB.addMemOperand(MF->getMachineMemOperand(MachinePointerInfo(Info.ptrVal),
    1089           4 :                                                Info.flags, Size, Info.align));
    1090             :   }
    1091             : 
    1092             :   return true;
    1093             : }
    1094             : 
    1095           6 : bool IRTranslator::translateInvoke(const User &U,
    1096             :                                    MachineIRBuilder &MIRBuilder) {
    1097             :   const InvokeInst &I = cast<InvokeInst>(U);
    1098           6 :   MCContext &Context = MF->getContext();
    1099             : 
    1100             :   const BasicBlock *ReturnBB = I.getSuccessor(0);
    1101             :   const BasicBlock *EHPadBB = I.getSuccessor(1);
    1102             : 
    1103             :   const Value *Callee = I.getCalledValue();
    1104             :   const Function *Fn = dyn_cast<Function>(Callee);
    1105           6 :   if (isa<InlineAsm>(Callee))
    1106             :     return false;
    1107             : 
    1108             :   // FIXME: support invoking patchpoint and statepoint intrinsics.
    1109           6 :   if (Fn && Fn->isIntrinsic())
    1110             :     return false;
    1111             : 
    1112             :   // FIXME: support whatever these are.
    1113           6 :   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
    1114             :     return false;
    1115             : 
    1116             :   // FIXME: support Windows exception handling.
    1117           6 :   if (!isa<LandingPadInst>(EHPadBB->front()))
    1118             :     return false;
    1119             : 
    1120             :   // Emit the actual call, bracketed by EH_LABELs so that the MF knows about
    1121             :   // the region covered by the try.
    1122           6 :   MCSymbol *BeginSymbol = Context.createTempSymbol();
    1123           6 :   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol);
    1124             : 
    1125             :   unsigned Res =
    1126          12 :         MRI->createGenericVirtualRegister(getLLTForType(*I.getType(), *DL));
    1127             :   SmallVector<unsigned, 8> Args;
    1128          13 :   for (auto &Arg: I.arg_operands())
    1129           7 :     Args.push_back(packRegs(*Arg, MIRBuilder));
    1130             : 
    1131          18 :   if (!CLI->lowerCall(MIRBuilder, &I, Res, Args,
    1132             :                       [&]() { return getOrCreateVReg(*I.getCalledValue()); }))
    1133             :     return false;
    1134             : 
    1135           4 :   unpackRegs(I, Res, MIRBuilder);
    1136             : 
    1137           4 :   MCSymbol *EndSymbol = Context.createTempSymbol();
    1138           4 :   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol);
    1139             : 
    1140             :   // FIXME: track probabilities.
    1141           4 :   MachineBasicBlock &EHPadMBB = getMBB(*EHPadBB),
    1142           4 :                     &ReturnMBB = getMBB(*ReturnBB);
    1143           4 :   MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
    1144           4 :   MIRBuilder.getMBB().addSuccessor(&ReturnMBB);
    1145           4 :   MIRBuilder.getMBB().addSuccessor(&EHPadMBB);
    1146           4 :   MIRBuilder.buildBr(ReturnMBB);
    1147             : 
    1148           4 :   return true;
    1149             : }
    1150             : 
    1151           4 : bool IRTranslator::translateLandingPad(const User &U,
    1152             :                                        MachineIRBuilder &MIRBuilder) {
    1153             :   const LandingPadInst &LP = cast<LandingPadInst>(U);
    1154             : 
    1155           4 :   MachineBasicBlock &MBB = MIRBuilder.getMBB();
    1156             : 
    1157             :   MBB.setIsEHPad();
    1158             : 
    1159             :   // If there aren't registers to copy the values into (e.g., during SjLj
    1160             :   // exceptions), then don't bother.
    1161           4 :   auto &TLI = *MF->getSubtarget().getTargetLowering();
    1162           4 :   const Constant *PersonalityFn = MF->getFunction().getPersonalityFn();
    1163           4 :   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
    1164           0 :       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
    1165             :     return true;
    1166             : 
    1167             :   // If landingpad's return type is token type, we don't create DAG nodes
    1168             :   // for its exception pointer and selector value. The extraction of exception
    1169             :   // pointer or selector value from token type landingpads is not currently
    1170             :   // supported.
    1171           8 :   if (LP.getType()->isTokenTy())
    1172             :     return true;
    1173             : 
    1174             :   // Add a label to mark the beginning of the landing pad.  Deletion of the
    1175             :   // landing pad can thus be detected via the MachineModuleInfo.
    1176           4 :   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL)
    1177           4 :     .addSym(MF->addLandingPad(&MBB));
    1178             : 
    1179           4 :   LLT Ty = getLLTForType(*LP.getType(), *DL);
    1180           8 :   unsigned Undef = MRI->createGenericVirtualRegister(Ty);
    1181           4 :   MIRBuilder.buildUndef(Undef);
    1182             : 
    1183             :   SmallVector<LLT, 2> Tys;
    1184          12 :   for (Type *Ty : cast<StructType>(LP.getType())->elements())
    1185           8 :     Tys.push_back(getLLTForType(*Ty, *DL));
    1186             :   assert(Tys.size() == 2 && "Only two-valued landingpads are supported");
    1187             : 
    1188             :   // Mark exception register as live in.
    1189           4 :   unsigned ExceptionReg = TLI.getExceptionPointerRegister(PersonalityFn);
    1190           4 :   if (!ExceptionReg)
    1191             :     return false;
    1192             : 
    1193           4 :   MBB.addLiveIn(ExceptionReg);
    1194           4 :   ArrayRef<unsigned> ResRegs = getOrCreateVRegs(LP);
    1195           4 :   MIRBuilder.buildCopy(ResRegs[0], ExceptionReg);
    1196             : 
    1197           4 :   unsigned SelectorReg = TLI.getExceptionSelectorRegister(PersonalityFn);
    1198           4 :   if (!SelectorReg)
    1199             :     return false;
    1200             : 
    1201           4 :   MBB.addLiveIn(SelectorReg);
    1202           8 :   unsigned PtrVReg = MRI->createGenericVirtualRegister(Tys[0]);
    1203           4 :   MIRBuilder.buildCopy(PtrVReg, SelectorReg);
    1204           4 :   MIRBuilder.buildCast(ResRegs[1], PtrVReg);
    1205             : 
    1206           4 :   return true;
    1207             : }
    1208             : 
    1209          52 : bool IRTranslator::translateAlloca(const User &U,
    1210             :                                    MachineIRBuilder &MIRBuilder) {
    1211             :   auto &AI = cast<AllocaInst>(U);
    1212             : 
    1213          52 :   if (AI.isSwiftError())
    1214             :     return false;
    1215             : 
    1216          50 :   if (AI.isStaticAlloca()) {
    1217          45 :     unsigned Res = getOrCreateVReg(AI);
    1218          45 :     int FI = getOrCreateFrameIndex(AI);
    1219          45 :     MIRBuilder.buildFrameIndex(Res, FI);
    1220          45 :     return true;
    1221             :   }
    1222             : 
    1223             :   // FIXME: support stack probing for Windows.
    1224          10 :   if (MF->getTarget().getTargetTriple().isOSWindows())
    1225             :     return false;
    1226             : 
    1227             :   // Now we're in the harder dynamic case.
    1228           4 :   Type *Ty = AI.getAllocatedType();
    1229             :   unsigned Align =
    1230           5 :       std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI.getAlignment());
    1231             : 
    1232             :   unsigned NumElts = getOrCreateVReg(*AI.getArraySize());
    1233             : 
    1234           8 :   Type *IntPtrIRTy = DL->getIntPtrType(AI.getType());
    1235           4 :   LLT IntPtrTy = getLLTForType(*IntPtrIRTy, *DL);
    1236           8 :   if (MRI->getType(NumElts) != IntPtrTy) {
    1237           4 :     unsigned ExtElts = MRI->createGenericVirtualRegister(IntPtrTy);
    1238           4 :     MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts);
    1239             :     NumElts = ExtElts;
    1240             :   }
    1241             : 
    1242           8 :   unsigned AllocSize = MRI->createGenericVirtualRegister(IntPtrTy);
    1243             :   unsigned TySize =
    1244           4 :       getOrCreateVReg(*ConstantInt::get(IntPtrIRTy, -DL->getTypeAllocSize(Ty)));
    1245           4 :   MIRBuilder.buildMul(AllocSize, NumElts, TySize);
    1246             : 
    1247           8 :   LLT PtrTy = getLLTForType(*AI.getType(), *DL);
    1248           4 :   auto &TLI = *MF->getSubtarget().getTargetLowering();
    1249           4 :   unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
    1250             : 
    1251           8 :   unsigned SPTmp = MRI->createGenericVirtualRegister(PtrTy);
    1252           4 :   MIRBuilder.buildCopy(SPTmp, SPReg);
    1253             : 
    1254           8 :   unsigned AllocTmp = MRI->createGenericVirtualRegister(PtrTy);
    1255           4 :   MIRBuilder.buildGEP(AllocTmp, SPTmp, AllocSize);
    1256             : 
    1257             :   // Handle alignment. We have to realign if the allocation granule was smaller
    1258             :   // than stack alignment, or the specific alloca requires more than stack
    1259             :   // alignment.
    1260             :   unsigned StackAlign =
    1261           4 :       MF->getSubtarget().getFrameLowering()->getStackAlignment();
    1262           4 :   Align = std::max(Align, StackAlign);
    1263           4 :   if (Align > StackAlign || DL->getTypeAllocSize(Ty) % StackAlign != 0) {
    1264             :     // Round the size of the allocation up to the stack alignment size
    1265             :     // by add SA-1 to the size. This doesn't overflow because we're computing
    1266             :     // an address inside an alloca.
    1267           6 :     unsigned AlignedAlloc = MRI->createGenericVirtualRegister(PtrTy);
    1268           3 :     MIRBuilder.buildPtrMask(AlignedAlloc, AllocTmp, Log2_32(Align));
    1269             :     AllocTmp = AlignedAlloc;
    1270             :   }
    1271             : 
    1272           4 :   MIRBuilder.buildCopy(SPReg, AllocTmp);
    1273           8 :   MIRBuilder.buildCopy(getOrCreateVReg(AI), AllocTmp);
    1274             : 
    1275           8 :   MF->getFrameInfo().CreateVariableSizedObject(Align ? Align : 1, &AI);
    1276             :   assert(MF->getFrameInfo().hasVarSizedObjects());
    1277           4 :   return true;
    1278             : }
    1279             : 
    1280           3 : bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) {
    1281             :   // FIXME: We may need more info about the type. Because of how LLT works,
    1282             :   // we're completely discarding the i64/double distinction here (amongst
    1283             :   // others). Fortunately the ABIs I know of where that matters don't use va_arg
    1284             :   // anyway but that's not guaranteed.
    1285           3 :   MIRBuilder.buildInstr(TargetOpcode::G_VAARG)
    1286           3 :     .addDef(getOrCreateVReg(U))
    1287             :     .addUse(getOrCreateVReg(*U.getOperand(0)))
    1288           3 :     .addImm(DL->getABITypeAlignment(U.getType()));
    1289           3 :   return true;
    1290             : }
    1291             : 
    1292          25 : bool IRTranslator::translateInsertElement(const User &U,
    1293             :                                           MachineIRBuilder &MIRBuilder) {
    1294             :   // If it is a <1 x Ty> vector, use the scalar as it is
    1295             :   // not a legal vector type in LLT.
    1296          50 :   if (U.getType()->getVectorNumElements() == 1) {
    1297           6 :     unsigned Elt = getOrCreateVReg(*U.getOperand(1));
    1298           6 :     auto &Regs = *VMap.getVRegs(U);
    1299           6 :     if (Regs.empty()) {
    1300           6 :       Regs.push_back(Elt);
    1301           6 :       VMap.getOffsets(U)->push_back(0);
    1302             :     } else {
    1303           0 :       MIRBuilder.buildCopy(Regs[0], Elt);
    1304             :     }
    1305             :     return true;
    1306             :   }
    1307             : 
    1308          19 :   unsigned Res = getOrCreateVReg(U);
    1309             :   unsigned Val = getOrCreateVReg(*U.getOperand(0));
    1310             :   unsigned Elt = getOrCreateVReg(*U.getOperand(1));
    1311             :   unsigned Idx = getOrCreateVReg(*U.getOperand(2));
    1312          19 :   MIRBuilder.buildInsertVectorElement(Res, Val, Elt, Idx);
    1313          19 :   return true;
    1314             : }
    1315             : 
    1316          26 : bool IRTranslator::translateExtractElement(const User &U,
    1317             :                                            MachineIRBuilder &MIRBuilder) {
    1318             :   // If it is a <1 x Ty> vector, use the scalar as it is
    1319             :   // not a legal vector type in LLT.
    1320          52 :   if (U.getOperand(0)->getType()->getVectorNumElements() == 1) {
    1321           4 :     unsigned Elt = getOrCreateVReg(*U.getOperand(0));
    1322           4 :     auto &Regs = *VMap.getVRegs(U);
    1323           4 :     if (Regs.empty()) {
    1324           4 :       Regs.push_back(Elt);
    1325           4 :       VMap.getOffsets(U)->push_back(0);
    1326             :     } else {
    1327           0 :       MIRBuilder.buildCopy(Regs[0], Elt);
    1328             :     }
    1329             :     return true;
    1330             :   }
    1331          22 :   unsigned Res = getOrCreateVReg(U);
    1332             :   unsigned Val = getOrCreateVReg(*U.getOperand(0));
    1333             :   unsigned Idx = getOrCreateVReg(*U.getOperand(1));
    1334          22 :   MIRBuilder.buildExtractVectorElement(Res, Val, Idx);
    1335          22 :   return true;
    1336             : }
    1337             : 
    1338          15 : bool IRTranslator::translateShuffleVector(const User &U,
    1339             :                                           MachineIRBuilder &MIRBuilder) {
    1340          15 :   MIRBuilder.buildInstr(TargetOpcode::G_SHUFFLE_VECTOR)
    1341          15 :       .addDef(getOrCreateVReg(U))
    1342             :       .addUse(getOrCreateVReg(*U.getOperand(0)))
    1343             :       .addUse(getOrCreateVReg(*U.getOperand(1)))
    1344             :       .addUse(getOrCreateVReg(*U.getOperand(2)));
    1345          15 :   return true;
    1346             : }
    1347             : 
    1348          18 : bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) {
    1349             :   const PHINode &PI = cast<PHINode>(U);
    1350             : 
    1351             :   SmallVector<MachineInstr *, 4> Insts;
    1352          39 :   for (auto Reg : getOrCreateVRegs(PI)) {
    1353          21 :     auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_PHI, Reg);
    1354          21 :     Insts.push_back(MIB.getInstr());
    1355             :   }
    1356             : 
    1357          18 :   PendingPHIs.emplace_back(&PI, std::move(Insts));
    1358          18 :   return true;
    1359             : }
    1360             : 
    1361           3 : bool IRTranslator::translateAtomicCmpXchg(const User &U,
    1362             :                                           MachineIRBuilder &MIRBuilder) {
    1363             :   const AtomicCmpXchgInst &I = cast<AtomicCmpXchgInst>(U);
    1364             : 
    1365           3 :   if (I.isWeak())
    1366             :     return false;
    1367             : 
    1368           3 :   auto Flags = I.isVolatile() ? MachineMemOperand::MOVolatile
    1369             :                               : MachineMemOperand::MONone;
    1370             :   Flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
    1371             : 
    1372           3 :   Type *ResType = I.getType();
    1373             :   Type *ValType = ResType->Type::getStructElementType(0);
    1374             : 
    1375           3 :   auto Res = getOrCreateVRegs(I);
    1376           3 :   unsigned OldValRes = Res[0];
    1377           3 :   unsigned SuccessRes = Res[1];
    1378             :   unsigned Addr = getOrCreateVReg(*I.getPointerOperand());
    1379             :   unsigned Cmp = getOrCreateVReg(*I.getCompareOperand());
    1380             :   unsigned NewVal = getOrCreateVReg(*I.getNewValOperand());
    1381             : 
    1382             :   MIRBuilder.buildAtomicCmpXchgWithSuccess(
    1383             :       OldValRes, SuccessRes, Addr, Cmp, NewVal,
    1384           9 :       *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
    1385           3 :                                 Flags, DL->getTypeStoreSize(ValType),
    1386           3 :                                 getMemOpAlignment(I), AAMDNodes(), nullptr,
    1387           3 :                                 I.getSyncScopeID(), I.getSuccessOrdering(),
    1388           6 :                                 I.getFailureOrdering()));
    1389           3 :   return true;
    1390             : }
    1391             : 
    1392          11 : bool IRTranslator::translateAtomicRMW(const User &U,
    1393             :                                       MachineIRBuilder &MIRBuilder) {
    1394             :   const AtomicRMWInst &I = cast<AtomicRMWInst>(U);
    1395             : 
    1396          11 :   auto Flags = I.isVolatile() ? MachineMemOperand::MOVolatile
    1397             :                               : MachineMemOperand::MONone;
    1398             :   Flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
    1399             : 
    1400          11 :   Type *ResType = I.getType();
    1401             : 
    1402          11 :   unsigned Res = getOrCreateVReg(I);
    1403             :   unsigned Addr = getOrCreateVReg(*I.getPointerOperand());
    1404             :   unsigned Val = getOrCreateVReg(*I.getValOperand());
    1405             : 
    1406             :   unsigned Opcode = 0;
    1407             :   switch (I.getOperation()) {
    1408           0 :   default:
    1409           0 :     llvm_unreachable("Unknown atomicrmw op");
    1410             :     return false;
    1411             :   case AtomicRMWInst::Xchg:
    1412             :     Opcode = TargetOpcode::G_ATOMICRMW_XCHG;
    1413             :     break;
    1414             :   case AtomicRMWInst::Add:
    1415             :     Opcode = TargetOpcode::G_ATOMICRMW_ADD;
    1416             :     break;
    1417             :   case AtomicRMWInst::Sub:
    1418             :     Opcode = TargetOpcode::G_ATOMICRMW_SUB;
    1419             :     break;
    1420             :   case AtomicRMWInst::And:
    1421             :     Opcode = TargetOpcode::G_ATOMICRMW_AND;
    1422             :     break;
    1423             :   case AtomicRMWInst::Nand:
    1424             :     Opcode = TargetOpcode::G_ATOMICRMW_NAND;
    1425             :     break;
    1426             :   case AtomicRMWInst::Or:
    1427             :     Opcode = TargetOpcode::G_ATOMICRMW_OR;
    1428             :     break;
    1429             :   case AtomicRMWInst::Xor:
    1430             :     Opcode = TargetOpcode::G_ATOMICRMW_XOR;
    1431             :     break;
    1432             :   case AtomicRMWInst::Max:
    1433             :     Opcode = TargetOpcode::G_ATOMICRMW_MAX;
    1434             :     break;
    1435             :   case AtomicRMWInst::Min:
    1436             :     Opcode = TargetOpcode::G_ATOMICRMW_MIN;
    1437             :     break;
    1438             :   case AtomicRMWInst::UMax:
    1439             :     Opcode = TargetOpcode::G_ATOMICRMW_UMAX;
    1440             :     break;
    1441             :   case AtomicRMWInst::UMin:
    1442             :     Opcode = TargetOpcode::G_ATOMICRMW_UMIN;
    1443             :     break;
    1444             :   }
    1445             : 
    1446             :   MIRBuilder.buildAtomicRMW(
    1447             :       Opcode, Res, Addr, Val,
    1448          33 :       *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
    1449          11 :                                 Flags, DL->getTypeStoreSize(ResType),
    1450          11 :                                 getMemOpAlignment(I), AAMDNodes(), nullptr,
    1451          33 :                                 I.getSyncScopeID(), I.getOrdering()));
    1452             :   return true;
    1453             : }
    1454             : 
    1455        1187 : void IRTranslator::finishPendingPhis() {
    1456        1205 :   for (auto &Phi : PendingPHIs) {
    1457          18 :     const PHINode *PI = Phi.first;
    1458             :     ArrayRef<MachineInstr *> ComponentPHIs = Phi.second;
    1459             : 
    1460             :     // All MachineBasicBlocks exist, add them to the PHI. We assume IRTranslator
    1461             :     // won't create extra control flow here, otherwise we need to find the
    1462             :     // dominating predecessor here (or perhaps force the weirder IRTranslators
    1463             :     // to provide a simple boundary).
    1464             :     SmallSet<const BasicBlock *, 4> HandledPreds;
    1465             : 
    1466          55 :     for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
    1467             :       auto IRPred = PI->getIncomingBlock(i);
    1468          37 :       if (HandledPreds.count(IRPred))
    1469           1 :         continue;
    1470             : 
    1471          36 :       HandledPreds.insert(IRPred);
    1472          36 :       ArrayRef<unsigned> ValRegs = getOrCreateVRegs(*PI->getIncomingValue(i));
    1473         109 :       for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) {
    1474             :         assert(Pred->isSuccessor(ComponentPHIs[0]->getParent()) &&
    1475             :                "incorrect CFG at MachineBasicBlock level");
    1476          80 :         for (unsigned j = 0; j < ValRegs.size(); ++j) {
    1477          43 :           MachineInstrBuilder MIB(*MF, ComponentPHIs[j]);
    1478          86 :           MIB.addUse(ValRegs[j]);
    1479             :           MIB.addMBB(Pred);
    1480             :         }
    1481             :       }
    1482             :     }
    1483             :   }
    1484        1187 : }
    1485             : 
    1486        2203 : bool IRTranslator::valueIsSplit(const Value &V,
    1487             :                                 SmallVectorImpl<uint64_t> *Offsets) {
    1488             :   SmallVector<LLT, 4> SplitTys;
    1489        2203 :   if (Offsets && !Offsets->empty())
    1490             :     Offsets->clear();
    1491        2203 :   computeValueLLTs(*DL, *V.getType(), SplitTys, Offsets);
    1492        2203 :   return SplitTys.size() > 1;
    1493             : }
    1494             : 
    1495        3202 : bool IRTranslator::translate(const Instruction &Inst) {
    1496             :   CurBuilder.setDebugLoc(Inst.getDebugLoc());
    1497        3202 :   switch(Inst.getOpcode()) {
    1498             : #define HANDLE_INST(NUM, OPCODE, CLASS) \
    1499             :     case Instruction::OPCODE: return translate##OPCODE(Inst, CurBuilder);
    1500             : #include "llvm/IR/Instruction.def"
    1501             :   default:
    1502             :     return false;
    1503             :   }
    1504             : }
    1505             : 
    1506         780 : bool IRTranslator::translate(const Constant &C, unsigned Reg) {
    1507             :   if (auto CI = dyn_cast<ConstantInt>(&C))
    1508         426 :     EntryBuilder.buildConstant(Reg, *CI);
    1509             :   else if (auto CF = dyn_cast<ConstantFP>(&C))
    1510          46 :     EntryBuilder.buildFConstant(Reg, *CF);
    1511         308 :   else if (isa<UndefValue>(C))
    1512          74 :     EntryBuilder.buildUndef(Reg);
    1513         234 :   else if (isa<ConstantPointerNull>(C)) {
    1514             :     // As we are trying to build a constant val of 0 into a pointer,
    1515             :     // insert a cast to make them correct with respect to types.
    1516          11 :     unsigned NullSize = DL->getTypeSizeInBits(C.getType());
    1517          11 :     auto *ZeroTy = Type::getIntNTy(C.getContext(), NullSize);
    1518          11 :     auto *ZeroVal = ConstantInt::get(ZeroTy, 0);
    1519          11 :     unsigned ZeroReg = getOrCreateVReg(*ZeroVal);
    1520          11 :     EntryBuilder.buildCast(Reg, ZeroReg);
    1521             :   } else if (auto GV = dyn_cast<GlobalValue>(&C))
    1522         159 :     EntryBuilder.buildGlobalValue(Reg, GV);
    1523             :   else if (auto CAZ = dyn_cast<ConstantAggregateZero>(&C)) {
    1524          18 :     if (!CAZ->getType()->isVectorTy())
    1525           1 :       return false;
    1526             :     // Return the scalar if it is a <1 x Ty> vector.
    1527           9 :     if (CAZ->getNumElements() == 1)
    1528           1 :       return translate(*CAZ->getElementValue(0u), Reg);
    1529             :     std::vector<unsigned> Ops;
    1530          29 :     for (unsigned i = 0; i < CAZ->getNumElements(); ++i) {
    1531          21 :       Constant &Elt = *CAZ->getElementValue(i);
    1532          21 :       Ops.push_back(getOrCreateVReg(Elt));
    1533             :     }
    1534          16 :     EntryBuilder.buildMerge(Reg, Ops);
    1535             :   } else if (auto CV = dyn_cast<ConstantDataVector>(&C)) {
    1536             :     // Return the scalar if it is a <1 x Ty> vector.
    1537          19 :     if (CV->getNumElements() == 1)
    1538           2 :       return translate(*CV->getElementAsConstant(0), Reg);
    1539             :     std::vector<unsigned> Ops;
    1540          73 :     for (unsigned i = 0; i < CV->getNumElements(); ++i) {
    1541          56 :       Constant &Elt = *CV->getElementAsConstant(i);
    1542          56 :       Ops.push_back(getOrCreateVReg(Elt));
    1543             :     }
    1544          34 :     EntryBuilder.buildMerge(Reg, Ops);
    1545             :   } else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
    1546          34 :     switch(CE->getOpcode()) {
    1547             : #define HANDLE_INST(NUM, OPCODE, CLASS)                         \
    1548             :       case Instruction::OPCODE: return translate##OPCODE(*CE, EntryBuilder);
    1549             : #include "llvm/IR/Instruction.def"
    1550             :     default:
    1551             :       return false;
    1552             :     }
    1553             :   } else if (auto CV = dyn_cast<ConstantVector>(&C)) {
    1554           1 :     if (CV->getNumOperands() == 1)
    1555           0 :       return translate(*CV->getOperand(0), Reg);
    1556             :     SmallVector<unsigned, 4> Ops;
    1557           5 :     for (unsigned i = 0; i < CV->getNumOperands(); ++i) {
    1558           4 :       Ops.push_back(getOrCreateVReg(*CV->getOperand(i)));
    1559             :     }
    1560           2 :     EntryBuilder.buildMerge(Reg, Ops);
    1561             :   } else if (auto *BA = dyn_cast<BlockAddress>(&C)) {
    1562           1 :     EntryBuilder.buildBlockAddress(Reg, BA);
    1563             :   } else
    1564             :     return false;
    1565             : 
    1566             :   return true;
    1567             : }
    1568             : 
    1569        1275 : void IRTranslator::finalizeFunction() {
    1570             :   // Release the memory used by the different maps we
    1571             :   // needed during the translation.
    1572        1275 :   PendingPHIs.clear();
    1573        1275 :   VMap.reset();
    1574        1275 :   FrameIndices.clear();
    1575        1275 :   MachinePreds.clear();
    1576             :   // MachineIRBuilder::DebugLoc can outlive the DILocation it holds. Clear it
    1577             :   // to avoid accessing free’d memory (in runOnMachineFunction) and to avoid
    1578             :   // destroying it twice (in ~IRTranslator() and ~LLVMContext())
    1579        1275 :   EntryBuilder = MachineIRBuilder();
    1580        1275 :   CurBuilder = MachineIRBuilder();
    1581        1275 : }
    1582             : 
    1583        1277 : bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) {
    1584        1277 :   MF = &CurMF;
    1585        1277 :   const Function &F = MF->getFunction();
    1586        1277 :   if (F.empty())
    1587             :     return false;
    1588        1277 :   CLI = MF->getSubtarget().getCallLowering();
    1589        1277 :   CurBuilder.setMF(*MF);
    1590        1277 :   EntryBuilder.setMF(*MF);
    1591        1277 :   MRI = &MF->getRegInfo();
    1592        1277 :   DL = &F.getParent()->getDataLayout();
    1593        1277 :   TPC = &getAnalysis<TargetPassConfig>();
    1594        1277 :   ORE = llvm::make_unique<OptimizationRemarkEmitter>(&F);
    1595             : 
    1596             :   assert(PendingPHIs.empty() && "stale PHIs");
    1597             : 
    1598        1277 :   if (!DL->isLittleEndian()) {
    1599             :     // Currently we don't properly handle big endian code.
    1600             :     OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
    1601          45 :                                F.getSubprogram(), &F.getEntryBlock());
    1602          45 :     R << "unable to translate in big endian mode";
    1603          45 :     reportTranslationError(*MF, *TPC, *ORE, R);
    1604             :   }
    1605             : 
    1606             :   // Release the per-function state when we return, whether we succeeded or not.
    1607        1275 :   auto FinalizeOnReturn = make_scope_exit([this]() { finalizeFunction(); });
    1608             : 
    1609             :   // Setup a separate basic-block for the arguments and constants
    1610        1276 :   MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock();
    1611        1276 :   MF->push_back(EntryBB);
    1612        1276 :   EntryBuilder.setMBB(*EntryBB);
    1613             : 
    1614             :   // Create all blocks, in IR order, to preserve the layout.
    1615        2665 :   for (const BasicBlock &BB: F) {
    1616        1389 :     auto *&MBB = BBToMBB[&BB];
    1617             : 
    1618        1389 :     MBB = MF->CreateMachineBasicBlock(&BB);
    1619        1389 :     MF->push_back(MBB);
    1620             : 
    1621        1389 :     if (BB.hasAddressTaken())
    1622           5 :       MBB->setHasAddressTaken();
    1623             :   }
    1624             : 
    1625             :   // Make our arguments/constants entry block fallthrough to the IR entry block.
    1626        1276 :   EntryBB->addSuccessor(&getMBB(F.front()));
    1627             : 
    1628             :   // Lower the actual args into this basic block.
    1629             :   SmallVector<unsigned, 8> VRegArgs;
    1630        3327 :   for (const Argument &Arg: F.args()) {
    1631        2051 :     if (DL->getTypeStoreSize(Arg.getType()) == 0)
    1632             :       continue; // Don't handle zero sized types.
    1633        2049 :     VRegArgs.push_back(
    1634        4098 :         MRI->createGenericVirtualRegister(getLLTForType(*Arg.getType(), *DL)));
    1635             :   }
    1636             : 
    1637             :   // We don't currently support translating swifterror or swiftself functions.
    1638        3325 :   for (auto &Arg : F.args()) {
    1639        2051 :     if (Arg.hasSwiftErrorAttr() || Arg.hasSwiftSelfAttr()) {
    1640             :       OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
    1641           2 :                                  F.getSubprogram(), &F.getEntryBlock());
    1642             :       R << "unable to lower arguments due to swifterror/swiftself: "
    1643           4 :         << ore::NV("Prototype", F.getType());
    1644           2 :       reportTranslationError(*MF, *TPC, *ORE, R);
    1645             :       return false;
    1646             :     }
    1647             :   }
    1648             : 
    1649        2548 :   if (!CLI->lowerFormalArguments(EntryBuilder, F, VRegArgs)) {
    1650             :     OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
    1651          53 :                                F.getSubprogram(), &F.getEntryBlock());
    1652         106 :     R << "unable to lower arguments: " << ore::NV("Prototype", F.getType());
    1653          53 :     reportTranslationError(*MF, *TPC, *ORE, R);
    1654             :     return false;
    1655             :   }
    1656             : 
    1657             :   auto ArgIt = F.arg_begin();
    1658        3185 :   for (auto &VArg : VRegArgs) {
    1659             :     // If the argument is an unsplit scalar then don't use unpackRegs to avoid
    1660             :     // creating redundant copies.
    1661        1964 :     if (!valueIsSplit(*ArgIt, VMap.getOffsets(*ArgIt))) {
    1662        1928 :       auto &VRegs = *VMap.getVRegs(cast<Value>(*ArgIt));
    1663             :       assert(VRegs.empty() && "VRegs already populated?");
    1664        1928 :       VRegs.push_back(VArg);
    1665             :     } else {
    1666          36 :       unpackRegs(*ArgIt, VArg, EntryBuilder);
    1667             :     }
    1668        1964 :     ArgIt++;
    1669             :   }
    1670             : 
    1671             :   // Need to visit defs before uses when translating instructions.
    1672             :   ReversePostOrderTraversal<const Function *> RPOT(&F);
    1673        2517 :   for (const BasicBlock *BB : RPOT) {
    1674        1330 :     MachineBasicBlock &MBB = getMBB(*BB);
    1675             :     // Set the insertion point of all the following translations to
    1676             :     // the end of this basic block.
    1677        1330 :     CurBuilder.setMBB(MBB);
    1678             : 
    1679        4498 :     for (const Instruction &Inst : *BB) {
    1680        3202 :       if (translate(Inst))
    1681        3168 :         continue;
    1682             : 
    1683             :       OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
    1684          34 :                                  Inst.getDebugLoc(), BB);
    1685          68 :       R << "unable to translate instruction: " << ore::NV("Opcode", &Inst);
    1686             : 
    1687          34 :       if (ORE->allowExtraAnalysis("gisel-irtranslator")) {
    1688             :         std::string InstStrStorage;
    1689          25 :         raw_string_ostream InstStr(InstStrStorage);
    1690             :         InstStr << Inst;
    1691             : 
    1692          50 :         R << ": '" << InstStr.str() << "'";
    1693             :       }
    1694             : 
    1695          34 :       reportTranslationError(*MF, *TPC, *ORE, R);
    1696             :       return false;
    1697             :     }
    1698             :   }
    1699             : 
    1700        1187 :   finishPendingPhis();
    1701             : 
    1702             :   // Merge the argument lowering and constants block with its single
    1703             :   // successor, the LLVM-IR entry block.  We want the basic block to
    1704             :   // be maximal.
    1705             :   assert(EntryBB->succ_size() == 1 &&
    1706             :          "Custom BB used for lowering should have only one successor");
    1707             :   // Get the successor of the current entry block.
    1708        1187 :   MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin();
    1709             :   assert(NewEntryBB.pred_size() == 1 &&
    1710             :          "LLVM-IR entry block has a predecessor!?");
    1711             :   // Move all the instruction from the current entry block to the
    1712             :   // new entry block.
    1713             :   NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(),
    1714             :                     EntryBB->end());
    1715             : 
    1716             :   // Update the live-in information for the new entry block.
    1717        3015 :   for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins())
    1718             :     NewEntryBB.addLiveIn(LiveIn);
    1719        1187 :   NewEntryBB.sortUniqueLiveIns();
    1720             : 
    1721             :   // Get rid of the now empty basic block.
    1722        1187 :   EntryBB->removeSuccessor(&NewEntryBB);
    1723        1187 :   MF->remove(EntryBB);
    1724        1187 :   MF->DeleteMachineBasicBlock(EntryBB);
    1725             : 
    1726             :   assert(&MF->front() == &NewEntryBB &&
    1727             :          "New entry wasn't next in the list of basic block!");
    1728             : 
    1729             :   // Initialize stack protector information.
    1730        1187 :   StackProtector &SP = getAnalysis<StackProtector>();
    1731        1187 :   SP.copyToMachineFrameInfo(MF->getFrameInfo());
    1732             : 
    1733        1187 :   return false;
    1734             : }

Generated by: LCOV version 1.13