LCOV - code coverage report
Current view: top level - lib/CodeGen/GlobalISel - IRTranslator.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 719 743 96.8 %
Date: 2017-09-14 15:23:50 Functions: 44 44 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/STLExtras.h"
      15             : #include "llvm/ADT/ScopeExit.h"
      16             : #include "llvm/ADT/SmallSet.h"
      17             : #include "llvm/ADT/SmallVector.h"
      18             : #include "llvm/Analysis/OptimizationDiagnosticInfo.h"
      19             : #include "llvm/CodeGen/Analysis.h"
      20             : #include "llvm/CodeGen/GlobalISel/CallLowering.h"
      21             : #include "llvm/CodeGen/LowLevelType.h"
      22             : #include "llvm/CodeGen/MachineBasicBlock.h"
      23             : #include "llvm/CodeGen/MachineFrameInfo.h"
      24             : #include "llvm/CodeGen/MachineFunction.h"
      25             : #include "llvm/CodeGen/MachineInstrBuilder.h"
      26             : #include "llvm/CodeGen/MachineMemOperand.h"
      27             : #include "llvm/CodeGen/MachineOperand.h"
      28             : #include "llvm/CodeGen/MachineRegisterInfo.h"
      29             : #include "llvm/CodeGen/TargetPassConfig.h"
      30             : #include "llvm/IR/BasicBlock.h"
      31             : #include "llvm/IR/Constant.h"
      32             : #include "llvm/IR/Constants.h"
      33             : #include "llvm/IR/DataLayout.h"
      34             : #include "llvm/IR/DebugInfo.h"
      35             : #include "llvm/IR/DerivedTypes.h"
      36             : #include "llvm/IR/Function.h"
      37             : #include "llvm/IR/GetElementPtrTypeIterator.h"
      38             : #include "llvm/IR/InlineAsm.h"
      39             : #include "llvm/IR/InstrTypes.h"
      40             : #include "llvm/IR/Instructions.h"
      41             : #include "llvm/IR/IntrinsicInst.h"
      42             : #include "llvm/IR/Intrinsics.h"
      43             : #include "llvm/IR/LLVMContext.h"
      44             : #include "llvm/IR/Metadata.h"
      45             : #include "llvm/IR/Type.h"
      46             : #include "llvm/IR/User.h"
      47             : #include "llvm/IR/Value.h"
      48             : #include "llvm/MC/MCContext.h"
      49             : #include "llvm/Pass.h"
      50             : #include "llvm/Support/Casting.h"
      51             : #include "llvm/Support/CodeGen.h"
      52             : #include "llvm/Support/Debug.h"
      53             : #include "llvm/Support/ErrorHandling.h"
      54             : #include "llvm/Support/LowLevelTypeImpl.h"
      55             : #include "llvm/Support/MathExtras.h"
      56             : #include "llvm/Support/raw_ostream.h"
      57             : #include "llvm/Target/TargetFrameLowering.h"
      58             : #include "llvm/Target/TargetIntrinsicInfo.h"
      59             : #include "llvm/Target/TargetLowering.h"
      60             : #include "llvm/Target/TargetMachine.h"
      61             : #include "llvm/Target/TargetRegisterInfo.h"
      62             : #include "llvm/Target/TargetSubtargetInfo.h"
      63             : #include <algorithm>
      64             : #include <cassert>
      65             : #include <cstdint>
      66             : #include <iterator>
      67             : #include <string>
      68             : #include <utility>
      69             : #include <vector>
      70             : 
      71             : #define DEBUG_TYPE "irtranslator"
      72             : 
      73             : using namespace llvm;
      74             : 
      75             : char IRTranslator::ID = 0;
      76             : 
      77       53279 : INITIALIZE_PASS_BEGIN(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
      78             :                 false, false)
      79       53279 : INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
      80      726973 : INITIALIZE_PASS_END(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
      81             :                 false, false)
      82             : 
      83          73 : static void reportTranslationError(MachineFunction &MF,
      84             :                                    const TargetPassConfig &TPC,
      85             :                                    OptimizationRemarkEmitter &ORE,
      86             :                                    OptimizationRemarkMissed &R) {
      87         146 :   MF.getProperties().set(MachineFunctionProperties::Property::FailedISel);
      88             : 
      89             :   // Print the function name explicitly if we don't have a debug location (which
      90             :   // makes the diagnostic less useful) or if we're going to emit a raw error.
      91         219 :   if (!R.getLocation().isValid() || TPC.isGlobalISelAbortEnabled())
      92         438 :     R << (" (in function: " + MF.getName() + ")").str();
      93             : 
      94          73 :   if (TPC.isGlobalISelAbortEnabled())
      95           1 :     report_fatal_error(R.getMsg());
      96             :   else
      97          72 :     ORE.emit(R);
      98          72 : }
      99             : 
     100        1026 : IRTranslator::IRTranslator() : MachineFunctionPass(ID) {
     101         114 :   initializeIRTranslatorPass(*PassRegistry::getPassRegistry());
     102         114 : }
     103             : 
     104         111 : void IRTranslator::getAnalysisUsage(AnalysisUsage &AU) const {
     105         111 :   AU.addRequired<TargetPassConfig>();
     106         111 :   MachineFunctionPass::getAnalysisUsage(AU);
     107         111 : }
     108             : 
     109        5012 : unsigned IRTranslator::getOrCreateVReg(const Value &Val) {
     110       10024 :   unsigned &ValReg = ValToVReg[&Val];
     111             : 
     112        5012 :   if (ValReg)
     113             :     return ValReg;
     114             : 
     115             :   // Fill ValRegsSequence with the sequence of registers
     116             :   // we need to concat together to produce the value.
     117             :   assert(Val.getType()->isSized() &&
     118             :          "Don't know how to create an empty vreg");
     119             :   unsigned VReg =
     120        2805 :       MRI->createGenericVirtualRegister(getLLTForType(*Val.getType(), *DL));
     121        2805 :   ValReg = VReg;
     122             : 
     123         425 :   if (auto CV = dyn_cast<Constant>(&Val)) {
     124         425 :     bool Success = translate(*CV, VReg);
     125         425 :     if (!Success) {
     126             :       OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
     127           2 :                                  MF->getFunction()->getSubprogram(),
     128          10 :                                  &MF->getFunction()->getEntryBlock());
     129           4 :       R << "unable to translate constant: " << ore::NV("Type", Val.getType());
     130           4 :       reportTranslationError(*MF, *TPC, *ORE, R);
     131           2 :       return VReg;
     132             :     }
     133             :   }
     134             : 
     135             :   return VReg;
     136             : }
     137             : 
     138          19 : int IRTranslator::getOrCreateFrameIndex(const AllocaInst &AI) {
     139          57 :   if (FrameIndices.find(&AI) != FrameIndices.end())
     140           4 :     return FrameIndices[&AI];
     141             : 
     142          34 :   unsigned ElementSize = DL->getTypeStoreSize(AI.getAllocatedType());
     143             :   unsigned Size =
     144          51 :       ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue();
     145             : 
     146             :   // Always allocate at least one byte.
     147          34 :   Size = std::max(Size, 1u);
     148             : 
     149          17 :   unsigned Alignment = AI.getAlignment();
     150          17 :   if (!Alignment)
     151          13 :     Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
     152             : 
     153          34 :   int &FI = FrameIndices[&AI];
     154          17 :   FI = MF->getFrameInfo().CreateStackObject(Size, Alignment, false, &AI);
     155          17 :   return FI;
     156             : }
     157             : 
     158         304 : unsigned IRTranslator::getMemOpAlignment(const Instruction &I) {
     159         304 :   unsigned Alignment = 0;
     160         304 :   Type *ValTy = nullptr;
     161         304 :   if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
     162         115 :     Alignment = SI->getAlignment();
     163         115 :     ValTy = SI->getValueOperand()->getType();
     164         189 :   } else if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
     165         189 :     Alignment = LI->getAlignment();
     166         189 :     ValTy = LI->getType();
     167             :   } else {
     168           0 :     OptimizationRemarkMissed R("gisel-irtranslator", "", &I);
     169           0 :     R << "unable to translate memop: " << ore::NV("Opcode", &I);
     170           0 :     reportTranslationError(*MF, *TPC, *ORE, R);
     171           0 :     return 1;
     172             :   }
     173             : 
     174         304 :   return Alignment ? Alignment : DL->getABITypeAlignment(ValTy);
     175             : }
     176             : 
     177        2048 : MachineBasicBlock &IRTranslator::getMBB(const BasicBlock &BB) {
     178        4096 :   MachineBasicBlock *&MBB = BBToMBB[&BB];
     179             :   assert(MBB && "BasicBlock was not encountered before");
     180        2048 :   return *MBB;
     181             : }
     182             : 
     183          11 : void IRTranslator::addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred) {
     184             :   assert(NewPred && "new predecessor must be a real MachineBasicBlock");
     185          22 :   MachinePreds[Edge].push_back(NewPred);
     186          11 : }
     187             : 
     188         317 : bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U,
     189             :                                      MachineIRBuilder &MIRBuilder) {
     190             :   // FIXME: handle signed/unsigned wrapping flags.
     191             : 
     192             :   // Get or create a virtual register for each value.
     193             :   // Unless the value is a Constant => loadimm cst?
     194             :   // or inline constant each time?
     195             :   // Creation of a virtual register needs to have a size.
     196         317 :   unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
     197         317 :   unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
     198         317 :   unsigned Res = getOrCreateVReg(U);
     199        1268 :   MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op0).addUse(Op1);
     200         317 :   return true;
     201             : }
     202             : 
     203          17 : bool IRTranslator::translateFSub(const User &U, MachineIRBuilder &MIRBuilder) {
     204             :   // -0.0 - X --> G_FNEG
     205          19 :   if (isa<Constant>(U.getOperand(0)) &&
     206           2 :       U.getOperand(0) == ConstantFP::getZeroValueForNegation(U.getType())) {
     207           4 :     MIRBuilder.buildInstr(TargetOpcode::G_FNEG)
     208           4 :         .addDef(getOrCreateVReg(U))
     209           4 :         .addUse(getOrCreateVReg(*U.getOperand(1)));
     210           2 :     return true;
     211             :   }
     212          15 :   return translateBinaryOp(TargetOpcode::G_FSUB, U, MIRBuilder);
     213             : }
     214             : 
     215          36 : bool IRTranslator::translateCompare(const User &U,
     216             :                                     MachineIRBuilder &MIRBuilder) {
     217          36 :   const CmpInst *CI = dyn_cast<CmpInst>(&U);
     218          36 :   unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
     219          36 :   unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
     220          36 :   unsigned Res = getOrCreateVReg(U);
     221             :   CmpInst::Predicate Pred =
     222          72 :       CI ? CI->getPredicate() : static_cast<CmpInst::Predicate>(
     223          36 :                                     cast<ConstantExpr>(U).getPredicate());
     224          36 :   if (CmpInst::isIntPredicate(Pred))
     225          27 :     MIRBuilder.buildICmp(Pred, Res, Op0, Op1);
     226           9 :   else if (Pred == CmpInst::FCMP_FALSE)
     227           1 :     MIRBuilder.buildCopy(
     228           1 :         Res, getOrCreateVReg(*Constant::getNullValue(CI->getType())));
     229           8 :   else if (Pred == CmpInst::FCMP_TRUE)
     230           1 :     MIRBuilder.buildCopy(
     231           1 :         Res, getOrCreateVReg(*Constant::getAllOnesValue(CI->getType())));
     232             :   else
     233           7 :     MIRBuilder.buildFCmp(Pred, Res, Op0, Op1);
     234             : 
     235          36 :   return true;
     236             : }
     237             : 
     238         850 : bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) {
     239         850 :   const ReturnInst &RI = cast<ReturnInst>(U);
     240         850 :   const Value *Ret = RI.getReturnValue();
     241             :   // The target may mess up with the insertion point, but
     242             :   // this is not important as a return is the last instruction
     243             :   // of the block anyway.
     244         850 :   return CLI->lowerReturn(MIRBuilder, Ret, !Ret ? 0 : getOrCreateVReg(*Ret));
     245             : }
     246             : 
     247          59 : bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) {
     248          59 :   const BranchInst &BrInst = cast<BranchInst>(U);
     249          59 :   unsigned Succ = 0;
     250          59 :   if (!BrInst.isUnconditional()) {
     251             :     // We want a G_BRCOND to the true BB followed by an unconditional branch.
     252          15 :     unsigned Tst = getOrCreateVReg(*BrInst.getCondition());
     253          45 :     const BasicBlock &TrueTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ++));
     254          15 :     MachineBasicBlock &TrueBB = getMBB(TrueTgt);
     255          15 :     MIRBuilder.buildBrCond(Tst, TrueBB);
     256             :   }
     257             : 
     258         118 :   const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ));
     259          59 :   MachineBasicBlock &TgtBB = getMBB(BrTgt);
     260          59 :   MachineBasicBlock &CurBB = MIRBuilder.getMBB();
     261             : 
     262             :   // If the unconditional target is the layout successor, fallthrough.
     263          59 :   if (!CurBB.isLayoutSuccessor(&TgtBB))
     264          37 :     MIRBuilder.buildBr(TgtBB);
     265             : 
     266             :   // Link successors.
     267         325 :   for (const BasicBlock *Succ : BrInst.successors())
     268          74 :     CurBB.addSuccessor(&getMBB(*Succ));
     269          59 :   return true;
     270             : }
     271             : 
     272           3 : bool IRTranslator::translateSwitch(const User &U,
     273             :                                    MachineIRBuilder &MIRBuilder) {
     274             :   // For now, just translate as a chain of conditional branches.
     275             :   // FIXME: could we share most of the logic/code in
     276             :   // SelectionDAGBuilder::visitSwitch between SelectionDAG and GlobalISel?
     277             :   // At first sight, it seems most of the logic in there is independent of
     278             :   // SelectionDAG-specifics and a lot of work went in to optimize switch
     279             :   // lowering in there.
     280             : 
     281           3 :   const SwitchInst &SwInst = cast<SwitchInst>(U);
     282           3 :   const unsigned SwCondValue = getOrCreateVReg(*SwInst.getCondition());
     283           3 :   const BasicBlock *OrigBB = SwInst.getParent();
     284             : 
     285           3 :   LLT LLTi1 = getLLTForType(*Type::getInt1Ty(U.getContext()), *DL);
     286          14 :   for (auto &CaseIt : SwInst.cases()) {
     287           8 :     const unsigned CaseValueReg = getOrCreateVReg(*CaseIt.getCaseValue());
     288           8 :     const unsigned Tst = MRI->createGenericVirtualRegister(LLTi1);
     289           8 :     MIRBuilder.buildICmp(CmpInst::ICMP_EQ, Tst, CaseValueReg, SwCondValue);
     290           8 :     MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
     291           8 :     const BasicBlock *TrueBB = CaseIt.getCaseSuccessor();
     292           8 :     MachineBasicBlock &TrueMBB = getMBB(*TrueBB);
     293             : 
     294           8 :     MIRBuilder.buildBrCond(Tst, TrueMBB);
     295           8 :     CurMBB.addSuccessor(&TrueMBB);
     296           8 :     addMachineCFGPred({OrigBB, TrueBB}, &CurMBB);
     297             : 
     298             :     MachineBasicBlock *FalseMBB =
     299           8 :         MF->CreateMachineBasicBlock(SwInst.getParent());
     300             :     // Insert the comparison blocks one after the other.
     301          32 :     MF->insert(std::next(CurMBB.getIterator()), FalseMBB);
     302           8 :     MIRBuilder.buildBr(*FalseMBB);
     303           8 :     CurMBB.addSuccessor(FalseMBB);
     304             : 
     305           8 :     MIRBuilder.setMBB(*FalseMBB);
     306             :   }
     307             :   // handle default case
     308           3 :   const BasicBlock *DefaultBB = SwInst.getDefaultDest();
     309           3 :   MachineBasicBlock &DefaultMBB = getMBB(*DefaultBB);
     310           3 :   MIRBuilder.buildBr(DefaultMBB);
     311           3 :   MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
     312           3 :   CurMBB.addSuccessor(&DefaultMBB);
     313           3 :   addMachineCFGPred({OrigBB, DefaultBB}, &CurMBB);
     314             : 
     315           3 :   return true;
     316             : }
     317             : 
     318           1 : bool IRTranslator::translateIndirectBr(const User &U,
     319             :                                        MachineIRBuilder &MIRBuilder) {
     320           1 :   const IndirectBrInst &BrInst = cast<IndirectBrInst>(U);
     321             : 
     322           1 :   const unsigned Tgt = getOrCreateVReg(*BrInst.getAddress());
     323           1 :   MIRBuilder.buildBrIndirect(Tgt);
     324             : 
     325             :   // Link successors.
     326           1 :   MachineBasicBlock &CurBB = MIRBuilder.getMBB();
     327           7 :   for (const BasicBlock *Succ : BrInst.successors())
     328           2 :     CurBB.addSuccessor(&getMBB(*Succ));
     329             : 
     330           1 :   return true;
     331             : }
     332             : 
     333         189 : bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) {
     334         189 :   const LoadInst &LI = cast<LoadInst>(U);
     335             : 
     336         189 :   auto Flags = LI.isVolatile() ? MachineMemOperand::MOVolatile
     337         189 :                                : MachineMemOperand::MONone;
     338         189 :   Flags |= MachineMemOperand::MOLoad;
     339             : 
     340         189 :   unsigned Res = getOrCreateVReg(LI);
     341         189 :   unsigned Addr = getOrCreateVReg(*LI.getPointerOperand());
     342             : 
     343         189 :   MIRBuilder.buildLoad(
     344             :       Res, Addr,
     345        1512 :       *MF->getMachineMemOperand(MachinePointerInfo(LI.getPointerOperand()),
     346         189 :                                 Flags, DL->getTypeStoreSize(LI.getType()),
     347         378 :                                 getMemOpAlignment(LI), AAMDNodes(), nullptr,
     348             :                                 LI.getSyncScopeID(), LI.getOrdering()));
     349         189 :   return true;
     350             : }
     351             : 
     352         115 : bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) {
     353         115 :   const StoreInst &SI = cast<StoreInst>(U);
     354         115 :   auto Flags = SI.isVolatile() ? MachineMemOperand::MOVolatile
     355         115 :                                : MachineMemOperand::MONone;
     356         115 :   Flags |= MachineMemOperand::MOStore;
     357             : 
     358         115 :   unsigned Val = getOrCreateVReg(*SI.getValueOperand());
     359         115 :   unsigned Addr = getOrCreateVReg(*SI.getPointerOperand());
     360             : 
     361         115 :   MIRBuilder.buildStore(
     362             :       Val, Addr,
     363         920 :       *MF->getMachineMemOperand(
     364             :           MachinePointerInfo(SI.getPointerOperand()), Flags,
     365         115 :           DL->getTypeStoreSize(SI.getValueOperand()->getType()),
     366         230 :           getMemOpAlignment(SI), AAMDNodes(), nullptr, SI.getSyncScopeID(),
     367             :           SI.getOrdering()));
     368         115 :   return true;
     369             : }
     370             : 
     371           9 : bool IRTranslator::translateExtractValue(const User &U,
     372             :                                          MachineIRBuilder &MIRBuilder) {
     373           9 :   const Value *Src = U.getOperand(0);
     374           9 :   Type *Int32Ty = Type::getInt32Ty(U.getContext());
     375          18 :   SmallVector<Value *, 1> Indices;
     376             : 
     377             :   // If Src is a single element ConstantStruct, translate extractvalue
     378             :   // to that element to avoid inserting a cast instruction.
     379           4 :   if (auto CS = dyn_cast<ConstantStruct>(Src))
     380           8 :     if (CS->getNumOperands() == 1) {
     381           4 :       unsigned Res = getOrCreateVReg(*CS->getOperand(0));
     382           4 :       ValToVReg[&U] = Res;
     383           2 :       return true;
     384             :     }
     385             : 
     386             :   // getIndexedOffsetInType is designed for GEPs, so the first index is the
     387             :   // usual array element rather than looking into the actual aggregate.
     388           7 :   Indices.push_back(ConstantInt::get(Int32Ty, 0));
     389             : 
     390           7 :   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) {
     391          15 :     for (auto Idx : EVI->indices())
     392           8 :       Indices.push_back(ConstantInt::get(Int32Ty, Idx));
     393             :   } else {
     394           0 :     for (unsigned i = 1; i < U.getNumOperands(); ++i)
     395           0 :       Indices.push_back(U.getOperand(i));
     396             :   }
     397             : 
     398          14 :   uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices);
     399             : 
     400           7 :   unsigned Res = getOrCreateVReg(U);
     401           7 :   MIRBuilder.buildExtract(Res, getOrCreateVReg(*Src), Offset);
     402             : 
     403           7 :   return true;
     404             : }
     405             : 
     406           5 : bool IRTranslator::translateInsertValue(const User &U,
     407             :                                         MachineIRBuilder &MIRBuilder) {
     408           5 :   const Value *Src = U.getOperand(0);
     409           5 :   Type *Int32Ty = Type::getInt32Ty(U.getContext());
     410          10 :   SmallVector<Value *, 1> Indices;
     411             : 
     412             :   // getIndexedOffsetInType is designed for GEPs, so the first index is the
     413             :   // usual array element rather than looking into the actual aggregate.
     414           5 :   Indices.push_back(ConstantInt::get(Int32Ty, 0));
     415             : 
     416           5 :   if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) {
     417          11 :     for (auto Idx : IVI->indices())
     418           6 :       Indices.push_back(ConstantInt::get(Int32Ty, Idx));
     419             :   } else {
     420           0 :     for (unsigned i = 2; i < U.getNumOperands(); ++i)
     421           0 :       Indices.push_back(U.getOperand(i));
     422             :   }
     423             : 
     424          10 :   uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices);
     425             : 
     426           5 :   unsigned Res = getOrCreateVReg(U);
     427           5 :   unsigned Inserted = getOrCreateVReg(*U.getOperand(1));
     428           5 :   MIRBuilder.buildInsert(Res, getOrCreateVReg(*Src), Inserted, Offset);
     429             : 
     430          10 :   return true;
     431             : }
     432             : 
     433           6 : bool IRTranslator::translateSelect(const User &U,
     434             :                                    MachineIRBuilder &MIRBuilder) {
     435           6 :   unsigned Res = getOrCreateVReg(U);
     436           6 :   unsigned Tst = getOrCreateVReg(*U.getOperand(0));
     437           6 :   unsigned Op0 = getOrCreateVReg(*U.getOperand(1));
     438           6 :   unsigned Op1 = getOrCreateVReg(*U.getOperand(2));
     439           6 :   MIRBuilder.buildSelect(Res, Tst, Op0, Op1);
     440           6 :   return true;
     441             : }
     442             : 
     443          13 : bool IRTranslator::translateBitCast(const User &U,
     444             :                                     MachineIRBuilder &MIRBuilder) {
     445             :   // If we're bitcasting to the source type, we can reuse the source vreg.
     446          39 :   if (getLLTForType(*U.getOperand(0)->getType(), *DL) ==
     447          26 :       getLLTForType(*U.getType(), *DL)) {
     448             :     // Get the source vreg now, to avoid invalidating ValToVReg.
     449          11 :     unsigned SrcReg = getOrCreateVReg(*U.getOperand(0));
     450          22 :     unsigned &Reg = ValToVReg[&U];
     451             :     // If we already assigned a vreg for this bitcast, we can't change that.
     452             :     // Emit a copy to satisfy the users we already emitted.
     453          11 :     if (Reg)
     454           1 :       MIRBuilder.buildCopy(Reg, SrcReg);
     455             :     else
     456          10 :       Reg = SrcReg;
     457             :     return true;
     458             :   }
     459           2 :   return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder);
     460             : }
     461             : 
     462          77 : bool IRTranslator::translateCast(unsigned Opcode, const User &U,
     463             :                                  MachineIRBuilder &MIRBuilder) {
     464          77 :   unsigned Op = getOrCreateVReg(*U.getOperand(0));
     465          77 :   unsigned Res = getOrCreateVReg(U);
     466         231 :   MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op);
     467          77 :   return true;
     468             : }
     469             : 
     470          31 : bool IRTranslator::translateGetElementPtr(const User &U,
     471             :                                           MachineIRBuilder &MIRBuilder) {
     472             :   // FIXME: support vector GEPs.
     473          62 :   if (U.getType()->isVectorTy())
     474             :     return false;
     475             : 
     476          31 :   Value &Op0 = *U.getOperand(0);
     477          31 :   unsigned BaseReg = getOrCreateVReg(Op0);
     478          31 :   Type *PtrIRTy = Op0.getType();
     479          31 :   LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
     480          31 :   Type *OffsetIRTy = DL->getIntPtrType(PtrIRTy);
     481          31 :   LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
     482             : 
     483          31 :   int64_t Offset = 0;
     484          67 :   for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U);
     485          67 :        GTI != E; ++GTI) {
     486          72 :     const Value *Idx = GTI.getOperand();
     487           0 :     if (StructType *StTy = GTI.getStructTypeOrNull()) {
     488           0 :       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
     489           0 :       Offset += DL->getStructLayout(StTy)->getElementOffset(Field);
     490           0 :       continue;
     491             :     } else {
     492          36 :       uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
     493             : 
     494             :       // If this is a scalar constant or a splat vector of constants,
     495             :       // handle it quickly.
     496          54 :       if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
     497          27 :         Offset += ElementSize * CI->getSExtValue();
     498          27 :         continue;
     499             :       }
     500             : 
     501           9 :       if (Offset != 0) {
     502           1 :         unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
     503             :         unsigned OffsetReg =
     504           1 :             getOrCreateVReg(*ConstantInt::get(OffsetIRTy, Offset));
     505           1 :         MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg);
     506             : 
     507           1 :         BaseReg = NewBaseReg;
     508           1 :         Offset = 0;
     509             :       }
     510             : 
     511             :       // N = N + Idx * ElementSize;
     512             :       unsigned ElementSizeReg =
     513           9 :           getOrCreateVReg(*ConstantInt::get(OffsetIRTy, ElementSize));
     514             : 
     515           9 :       unsigned IdxReg = getOrCreateVReg(*Idx);
     516          18 :       if (MRI->getType(IdxReg) != OffsetTy) {
     517           4 :         unsigned NewIdxReg = MRI->createGenericVirtualRegister(OffsetTy);
     518           4 :         MIRBuilder.buildSExtOrTrunc(NewIdxReg, IdxReg);
     519           4 :         IdxReg = NewIdxReg;
     520             :       }
     521             : 
     522           9 :       unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
     523           9 :       MIRBuilder.buildMul(OffsetReg, ElementSizeReg, IdxReg);
     524             : 
     525           9 :       unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
     526           9 :       MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg);
     527           9 :       BaseReg = NewBaseReg;
     528             :     }
     529             :   }
     530             : 
     531          31 :   if (Offset != 0) {
     532          22 :     unsigned OffsetReg = getOrCreateVReg(*ConstantInt::get(OffsetIRTy, Offset));
     533          22 :     MIRBuilder.buildGEP(getOrCreateVReg(U), BaseReg, OffsetReg);
     534          22 :     return true;
     535             :   }
     536             : 
     537           9 :   MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg);
     538           9 :   return true;
     539             : }
     540             : 
     541           3 : bool IRTranslator::translateMemfunc(const CallInst &CI,
     542             :                                     MachineIRBuilder &MIRBuilder,
     543             :                                     unsigned ID) {
     544           6 :   LLT SizeTy = getLLTForType(*CI.getArgOperand(2)->getType(), *DL);
     545           3 :   Type *DstTy = CI.getArgOperand(0)->getType();
     546           9 :   if (cast<PointerType>(DstTy)->getAddressSpace() != 0 ||
     547           6 :       SizeTy.getSizeInBits() != DL->getPointerSizeInBits(0))
     548             :     return false;
     549             : 
     550           3 :   SmallVector<CallLowering::ArgInfo, 8> Args;
     551          12 :   for (int i = 0; i < 3; ++i) {
     552          18 :     const auto &Arg = CI.getArgOperand(i);
     553           9 :     Args.emplace_back(getOrCreateVReg(*Arg), Arg->getType());
     554             :   }
     555             : 
     556             :   const char *Callee;
     557           3 :   switch (ID) {
     558           2 :   case Intrinsic::memmove:
     559             :   case Intrinsic::memcpy: {
     560           2 :     Type *SrcTy = CI.getArgOperand(1)->getType();
     561           4 :     if(cast<PointerType>(SrcTy)->getAddressSpace() != 0)
     562             :       return false;
     563           2 :     Callee = ID == Intrinsic::memcpy ? "memcpy" : "memmove";
     564             :     break;
     565             :   }
     566             :   case Intrinsic::memset:
     567             :     Callee = "memset";
     568             :     break;
     569             :   default:
     570             :     return false;
     571             :   }
     572             : 
     573          12 :   return CLI->lowerCall(MIRBuilder, CI.getCallingConv(),
     574           6 :                         MachineOperand::CreateES(Callee),
     575          15 :                         CallLowering::ArgInfo(0, CI.getType()), Args);
     576             : }
     577             : 
     578           1 : void IRTranslator::getStackGuard(unsigned DstReg,
     579             :                                  MachineIRBuilder &MIRBuilder) {
     580           1 :   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
     581           1 :   MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF));
     582           1 :   auto MIB = MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD);
     583           1 :   MIB.addDef(DstReg);
     584             : 
     585           1 :   auto &TLI = *MF->getSubtarget().getTargetLowering();
     586           1 :   Value *Global = TLI.getSDagStackGuard(*MF->getFunction()->getParent());
     587           1 :   if (!Global)
     588           0 :     return;
     589             : 
     590           1 :   MachinePointerInfo MPInfo(Global);
     591           1 :   MachineInstr::mmo_iterator MemRefs = MF->allocateMemRefsArray(1);
     592           1 :   auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
     593           1 :                MachineMemOperand::MODereferenceable;
     594           1 :   *MemRefs =
     595           5 :       MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8,
     596           1 :                                DL->getPointerABIAlignment());
     597           2 :   MIB.setMemRefs(MemRefs, MemRefs + 1);
     598             : }
     599             : 
     600           6 : bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op,
     601             :                                               MachineIRBuilder &MIRBuilder) {
     602          12 :   LLT Ty = getLLTForType(*CI.getOperand(0)->getType(), *DL);
     603           6 :   LLT s1 = LLT::scalar(1);
     604           6 :   unsigned Width = Ty.getSizeInBits();
     605           6 :   unsigned Res = MRI->createGenericVirtualRegister(Ty);
     606           6 :   unsigned Overflow = MRI->createGenericVirtualRegister(s1);
     607          12 :   auto MIB = MIRBuilder.buildInstr(Op)
     608           6 :                  .addDef(Res)
     609           6 :                  .addDef(Overflow)
     610          12 :                  .addUse(getOrCreateVReg(*CI.getOperand(0)))
     611          12 :                  .addUse(getOrCreateVReg(*CI.getOperand(1)));
     612             : 
     613           6 :   if (Op == TargetOpcode::G_UADDE || Op == TargetOpcode::G_USUBE) {
     614           2 :     unsigned Zero = getOrCreateVReg(
     615           4 :         *Constant::getNullValue(Type::getInt1Ty(CI.getContext())));
     616             :     MIB.addUse(Zero);
     617             :   }
     618             : 
     619          18 :   MIRBuilder.buildSequence(getOrCreateVReg(CI), {Res, Overflow}, {0, Width});
     620           6 :   return true;
     621             : }
     622             : 
     623          50 : bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID,
     624             :                                            MachineIRBuilder &MIRBuilder) {
     625          50 :   switch (ID) {
     626             :   default:
     627             :     break;
     628           2 :   case Intrinsic::lifetime_start:
     629             :   case Intrinsic::lifetime_end:
     630             :     // Stack coloring is not enabled in O0 (which we care about now) so we can
     631             :     // drop these. Make sure someone notices when we start compiling at higher
     632             :     // opts though.
     633           2 :     if (MF->getTarget().getOptLevel() != CodeGenOpt::None)
     634             :       return false;
     635           2 :     return true;
     636           3 :   case Intrinsic::dbg_declare: {
     637           3 :     const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI);
     638             :     assert(DI.getVariable() && "Missing variable");
     639             : 
     640           3 :     const Value *Address = DI.getAddress();
     641           6 :     if (!Address || isa<UndefValue>(Address)) {
     642             :       DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
     643             :       return true;
     644             :     }
     645             : 
     646             :     assert(DI.getVariable()->isValidLocationForIntrinsic(
     647             :                MIRBuilder.getDebugLoc()) &&
     648             :            "Expected inlined-at fields to agree");
     649           5 :     auto AI = dyn_cast<AllocaInst>(Address);
     650           2 :     if (AI && AI->isStaticAlloca()) {
     651             :       // Static allocas are tracked at the MF level, no need for DBG_VALUE
     652             :       // instructions (in fact, they get ignored if they *do* exist).
     653           4 :       MF->setVariableDbgInfo(DI.getVariable(), DI.getExpression(),
     654           3 :                              getOrCreateFrameIndex(*AI), DI.getDebugLoc());
     655             :     } else
     656           2 :       MIRBuilder.buildDirectDbgValue(getOrCreateVReg(*Address),
     657           6 :                                      DI.getVariable(), DI.getExpression());
     658             :     return true;
     659             :   }
     660             :   case Intrinsic::vaend:
     661             :     // No target I know of cares about va_end. Certainly no in-tree target
     662             :     // does. Simplest intrinsic ever!
     663             :     return true;
     664           3 :   case Intrinsic::vastart: {
     665           3 :     auto &TLI = *MF->getSubtarget().getTargetLowering();
     666           3 :     Value *Ptr = CI.getArgOperand(0);
     667           3 :     unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8;
     668             : 
     669           6 :     MIRBuilder.buildInstr(TargetOpcode::G_VASTART)
     670           6 :         .addUse(getOrCreateVReg(*Ptr))
     671           6 :         .addMemOperand(MF->getMachineMemOperand(
     672           9 :             MachinePointerInfo(Ptr), MachineMemOperand::MOStore, ListSize, 0));
     673           3 :     return true;
     674             :   }
     675           5 :   case Intrinsic::dbg_value: {
     676             :     // This form of DBG_VALUE is target-independent.
     677           5 :     const DbgValueInst &DI = cast<DbgValueInst>(CI);
     678           5 :     const Value *V = DI.getValue();
     679             :     assert(DI.getVariable()->isValidLocationForIntrinsic(
     680             :                MIRBuilder.getDebugLoc()) &&
     681             :            "Expected inlined-at fields to agree");
     682           5 :     if (!V) {
     683             :       // Currently the optimizer can produce this; insert an undef to
     684             :       // help debugging.  Probably the optimizer should not do this.
     685           0 :       MIRBuilder.buildIndirectDbgValue(0, DI.getVariable(), DI.getExpression());
     686           3 :     } else if (const auto *CI = dyn_cast<Constant>(V)) {
     687           9 :       MIRBuilder.buildConstDbgValue(*CI, DI.getVariable(), DI.getExpression());
     688             :     } else {
     689           2 :       unsigned Reg = getOrCreateVReg(*V);
     690             :       // FIXME: This does not handle register-indirect values at offset 0. The
     691             :       // direct/indirect thing shouldn't really be handled by something as
     692             :       // implicit as reg+noreg vs reg+imm in the first palce, but it seems
     693             :       // pretty baked in right now.
     694           6 :       MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(), DI.getExpression());
     695             :     }
     696             :     return true;
     697             :   }
     698           1 :   case Intrinsic::uadd_with_overflow:
     699           1 :     return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDE, MIRBuilder);
     700           1 :   case Intrinsic::sadd_with_overflow:
     701           1 :     return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder);
     702           1 :   case Intrinsic::usub_with_overflow:
     703           1 :     return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBE, MIRBuilder);
     704           1 :   case Intrinsic::ssub_with_overflow:
     705           1 :     return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder);
     706           1 :   case Intrinsic::umul_with_overflow:
     707           1 :     return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder);
     708           1 :   case Intrinsic::smul_with_overflow:
     709           1 :     return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder);
     710           7 :   case Intrinsic::pow:
     711          14 :     MIRBuilder.buildInstr(TargetOpcode::G_FPOW)
     712          14 :         .addDef(getOrCreateVReg(CI))
     713          14 :         .addUse(getOrCreateVReg(*CI.getArgOperand(0)))
     714          14 :         .addUse(getOrCreateVReg(*CI.getArgOperand(1)));
     715           7 :     return true;
     716           1 :   case Intrinsic::exp:
     717           2 :     MIRBuilder.buildInstr(TargetOpcode::G_FEXP)
     718           2 :         .addDef(getOrCreateVReg(CI))
     719           2 :         .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
     720           1 :     return true;
     721           1 :   case Intrinsic::exp2:
     722           2 :     MIRBuilder.buildInstr(TargetOpcode::G_FEXP2)
     723           2 :         .addDef(getOrCreateVReg(CI))
     724           2 :         .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
     725           1 :     return true;
     726           1 :   case Intrinsic::log:
     727           2 :     MIRBuilder.buildInstr(TargetOpcode::G_FLOG)
     728           2 :         .addDef(getOrCreateVReg(CI))
     729           2 :         .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
     730           1 :     return true;
     731           1 :   case Intrinsic::log2:
     732           2 :     MIRBuilder.buildInstr(TargetOpcode::G_FLOG2)
     733           2 :         .addDef(getOrCreateVReg(CI))
     734           2 :         .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
     735           1 :     return true;
     736           1 :   case Intrinsic::fma:
     737           2 :     MIRBuilder.buildInstr(TargetOpcode::G_FMA)
     738           2 :         .addDef(getOrCreateVReg(CI))
     739           2 :         .addUse(getOrCreateVReg(*CI.getArgOperand(0)))
     740           2 :         .addUse(getOrCreateVReg(*CI.getArgOperand(1)))
     741           2 :         .addUse(getOrCreateVReg(*CI.getArgOperand(2)));
     742           1 :     return true;
     743           3 :   case Intrinsic::memcpy:
     744             :   case Intrinsic::memmove:
     745             :   case Intrinsic::memset:
     746           3 :     return translateMemfunc(CI, MIRBuilder, ID);
     747           1 :   case Intrinsic::eh_typeid_for: {
     748           1 :     GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0));
     749           1 :     unsigned Reg = getOrCreateVReg(CI);
     750           1 :     unsigned TypeID = MF->getTypeIDFor(GV);
     751           1 :     MIRBuilder.buildConstant(Reg, TypeID);
     752           1 :     return true;
     753             :   }
     754           4 :   case Intrinsic::objectsize: {
     755             :     // If we don't know by now, we're never going to know.
     756           8 :     const ConstantInt *Min = cast<ConstantInt>(CI.getArgOperand(1));
     757             : 
     758           4 :     MIRBuilder.buildConstant(getOrCreateVReg(CI), Min->isZero() ? -1ULL : 0);
     759           4 :     return true;
     760             :   }
     761           0 :   case Intrinsic::stackguard:
     762           0 :     getStackGuard(getOrCreateVReg(CI), MIRBuilder);
     763           0 :     return true;
     764           1 :   case Intrinsic::stackprotector: {
     765           2 :     LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
     766           1 :     unsigned GuardVal = MRI->createGenericVirtualRegister(PtrTy);
     767           1 :     getStackGuard(GuardVal, MIRBuilder);
     768             : 
     769           2 :     AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1));
     770           1 :     MIRBuilder.buildStore(
     771             :         GuardVal, getOrCreateVReg(*Slot),
     772           6 :         *MF->getMachineMemOperand(
     773           1 :             MachinePointerInfo::getFixedStack(*MF,
     774             :                                               getOrCreateFrameIndex(*Slot)),
     775           1 :             MachineMemOperand::MOStore | MachineMemOperand::MOVolatile,
     776           2 :             PtrTy.getSizeInBits() / 8, 8));
     777             :     return true;
     778             :   }
     779             :   }
     780           9 :   return false;
     781             : }
     782             : 
     783           3 : bool IRTranslator::translateInlineAsm(const CallInst &CI,
     784             :                                       MachineIRBuilder &MIRBuilder) {
     785           6 :   const InlineAsm &IA = cast<InlineAsm>(*CI.getCalledValue());
     786           3 :   if (!IA.getConstraintString().empty())
     787             :     return false;
     788             : 
     789           2 :   unsigned ExtraInfo = 0;
     790           2 :   if (IA.hasSideEffects())
     791           1 :     ExtraInfo |= InlineAsm::Extra_HasSideEffects;
     792           2 :   if (IA.getDialect() == InlineAsm::AD_Intel)
     793           0 :     ExtraInfo |= InlineAsm::Extra_AsmDialect;
     794             : 
     795           2 :   MIRBuilder.buildInstr(TargetOpcode::INLINEASM)
     796           4 :     .addExternalSymbol(IA.getAsmString().c_str())
     797           4 :     .addImm(ExtraInfo);
     798             : 
     799           2 :   return true;
     800             : }
     801             : 
     802         165 : bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) {
     803         165 :   const CallInst &CI = cast<CallInst>(U);
     804         165 :   auto TII = MF->getTarget().getIntrinsicInfo();
     805         165 :   const Function *F = CI.getCalledFunction();
     806             : 
     807         165 :   if (CI.isInlineAsm())
     808           3 :     return translateInlineAsm(CI, MIRBuilder);
     809             : 
     810         317 :   if (!F || !F->isIntrinsic()) {
     811         268 :     unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI);
     812         224 :     SmallVector<unsigned, 8> Args;
     813         327 :     for (auto &Arg: CI.arg_operands())
     814         215 :       Args.push_back(getOrCreateVReg(*Arg));
     815             : 
     816         224 :     MF->getFrameInfo().setHasCalls(true);
     817         672 :     return CLI->lowerCall(MIRBuilder, &CI, Res, Args, [&]() {
     818          14 :       return getOrCreateVReg(*CI.getCalledValue());
     819         119 :     });
     820             :   }
     821             : 
     822          50 :   Intrinsic::ID ID = F->getIntrinsicID();
     823          50 :   if (TII && ID == Intrinsic::not_intrinsic)
     824           0 :     ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F));
     825             : 
     826             :   assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
     827             : 
     828          50 :   if (translateKnownIntrinsic(CI, ID, MIRBuilder))
     829             :     return true;
     830             : 
     831          18 :   unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI);
     832             :   MachineInstrBuilder MIB =
     833           9 :       MIRBuilder.buildIntrinsic(ID, Res, !CI.doesNotAccessMemory());
     834             : 
     835          46 :   for (auto &Arg : CI.arg_operands()) {
     836             :     // Some intrinsics take metadata parameters. Reject them.
     837          39 :     if (isa<MetadataAsValue>(Arg))
     838             :       return false;
     839          74 :     MIB.addUse(getOrCreateVReg(*Arg));
     840             :   }
     841             : 
     842             :   // Add a MachineMemOperand if it is a target mem intrinsic.
     843           7 :   const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
     844           7 :   TargetLowering::IntrinsicInfo Info;
     845             :   // TODO: Add a GlobalISel version of getTgtMemIntrinsic.
     846           7 :   if (TLI.getTgtMemIntrinsic(Info, CI, ID)) {
     847           2 :     MachineMemOperand::Flags Flags =
     848           2 :         Info.vol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
     849           2 :     Flags |=
     850           2 :         Info.readMem ? MachineMemOperand::MOLoad : MachineMemOperand::MOStore;
     851           2 :     uint64_t Size = Info.memVT.getSizeInBits() >> 3;
     852           4 :     MIB.addMemOperand(MF->getMachineMemOperand(MachinePointerInfo(Info.ptrVal),
     853           6 :                                                Flags, Size, Info.align));
     854             :   }
     855             : 
     856             :   return true;
     857             : }
     858             : 
     859           6 : bool IRTranslator::translateInvoke(const User &U,
     860             :                                    MachineIRBuilder &MIRBuilder) {
     861           6 :   const InvokeInst &I = cast<InvokeInst>(U);
     862           6 :   MCContext &Context = MF->getContext();
     863             : 
     864           6 :   const BasicBlock *ReturnBB = I.getSuccessor(0);
     865           6 :   const BasicBlock *EHPadBB = I.getSuccessor(1);
     866             : 
     867           6 :   const Value *Callee = I.getCalledValue();
     868          12 :   const Function *Fn = dyn_cast<Function>(Callee);
     869          12 :   if (isa<InlineAsm>(Callee))
     870             :     return false;
     871             : 
     872             :   // FIXME: support invoking patchpoint and statepoint intrinsics.
     873           9 :   if (Fn && Fn->isIntrinsic())
     874             :     return false;
     875             : 
     876             :   // FIXME: support whatever these are.
     877           6 :   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
     878             :     return false;
     879             : 
     880             :   // FIXME: support Windows exception handling.
     881          12 :   if (!isa<LandingPadInst>(EHPadBB->front()))
     882             :     return false;
     883             : 
     884             :   // Emit the actual call, bracketed by EH_LABELs so that the MF knows about
     885             :   // the region covered by the try.
     886           6 :   MCSymbol *BeginSymbol = Context.createTempSymbol();
     887          12 :   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol);
     888             : 
     889          12 :   unsigned Res = I.getType()->isVoidTy() ? 0 : getOrCreateVReg(I);
     890           6 :   SmallVector<unsigned, 8> Args;
     891          13 :   for (auto &Arg: I.arg_operands())
     892           7 :     Args.push_back(getOrCreateVReg(*Arg));
     893             : 
     894          30 :   if (!CLI->lowerCall(MIRBuilder, &I, Res, Args,
     895           6 :                       [&]() { return getOrCreateVReg(*I.getCalledValue()); }))
     896             :     return false;
     897             : 
     898           4 :   MCSymbol *EndSymbol = Context.createTempSymbol();
     899           8 :   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol);
     900             : 
     901             :   // FIXME: track probabilities.
     902           4 :   MachineBasicBlock &EHPadMBB = getMBB(*EHPadBB),
     903           4 :                     &ReturnMBB = getMBB(*ReturnBB);
     904           4 :   MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
     905           8 :   MIRBuilder.getMBB().addSuccessor(&ReturnMBB);
     906           8 :   MIRBuilder.getMBB().addSuccessor(&EHPadMBB);
     907           4 :   MIRBuilder.buildBr(ReturnMBB);
     908             : 
     909           4 :   return true;
     910             : }
     911             : 
     912           4 : bool IRTranslator::translateLandingPad(const User &U,
     913             :                                        MachineIRBuilder &MIRBuilder) {
     914           4 :   const LandingPadInst &LP = cast<LandingPadInst>(U);
     915             : 
     916           4 :   MachineBasicBlock &MBB = MIRBuilder.getMBB();
     917           4 :   addLandingPadInfo(LP, MBB);
     918             : 
     919           4 :   MBB.setIsEHPad();
     920             : 
     921             :   // If there aren't registers to copy the values into (e.g., during SjLj
     922             :   // exceptions), then don't bother.
     923           4 :   auto &TLI = *MF->getSubtarget().getTargetLowering();
     924           4 :   const Constant *PersonalityFn = MF->getFunction()->getPersonalityFn();
     925           4 :   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
     926           0 :       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
     927             :     return true;
     928             : 
     929             :   // If landingpad's return type is token type, we don't create DAG nodes
     930             :   // for its exception pointer and selector value. The extraction of exception
     931             :   // pointer or selector value from token type landingpads is not currently
     932             :   // supported.
     933           8 :   if (LP.getType()->isTokenTy())
     934             :     return true;
     935             : 
     936             :   // Add a label to mark the beginning of the landing pad.  Deletion of the
     937             :   // landing pad can thus be detected via the MachineModuleInfo.
     938           8 :   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL)
     939           8 :     .addSym(MF->addLandingPad(&MBB));
     940             : 
     941           4 :   LLT Ty = getLLTForType(*LP.getType(), *DL);
     942           4 :   unsigned Undef = MRI->createGenericVirtualRegister(Ty);
     943           4 :   MIRBuilder.buildUndef(Undef);
     944             : 
     945           4 :   SmallVector<LLT, 2> Tys;
     946          20 :   for (Type *Ty : cast<StructType>(LP.getType())->elements())
     947           8 :     Tys.push_back(getLLTForType(*Ty, *DL));
     948             :   assert(Tys.size() == 2 && "Only two-valued landingpads are supported");
     949             : 
     950             :   // Mark exception register as live in.
     951           4 :   unsigned ExceptionReg = TLI.getExceptionPointerRegister(PersonalityFn);
     952           4 :   if (!ExceptionReg)
     953             :     return false;
     954             : 
     955           8 :   MBB.addLiveIn(ExceptionReg);
     956           8 :   unsigned VReg = MRI->createGenericVirtualRegister(Tys[0]),
     957           4 :            Tmp = MRI->createGenericVirtualRegister(Ty);
     958           4 :   MIRBuilder.buildCopy(VReg, ExceptionReg);
     959           4 :   MIRBuilder.buildInsert(Tmp, Undef, VReg, 0);
     960             : 
     961           4 :   unsigned SelectorReg = TLI.getExceptionSelectorRegister(PersonalityFn);
     962           4 :   if (!SelectorReg)
     963             :     return false;
     964             : 
     965           8 :   MBB.addLiveIn(SelectorReg);
     966             : 
     967             :   // N.b. the exception selector register always has pointer type and may not
     968             :   // match the actual IR-level type in the landingpad so an extra cast is
     969             :   // needed.
     970           8 :   unsigned PtrVReg = MRI->createGenericVirtualRegister(Tys[0]);
     971           4 :   MIRBuilder.buildCopy(PtrVReg, SelectorReg);
     972             : 
     973           8 :   VReg = MRI->createGenericVirtualRegister(Tys[1]);
     974          12 :   MIRBuilder.buildInstr(TargetOpcode::G_PTRTOINT).addDef(VReg).addUse(PtrVReg);
     975           4 :   MIRBuilder.buildInsert(getOrCreateVReg(LP), Tmp, VReg,
     976           4 :                          Tys[0].getSizeInBits());
     977           4 :   return true;
     978             : }
     979             : 
     980          21 : bool IRTranslator::translateAlloca(const User &U,
     981             :                                    MachineIRBuilder &MIRBuilder) {
     982          21 :   auto &AI = cast<AllocaInst>(U);
     983             : 
     984          21 :   if (AI.isStaticAlloca()) {
     985          17 :     unsigned Res = getOrCreateVReg(AI);
     986          17 :     int FI = getOrCreateFrameIndex(AI);
     987          17 :     MIRBuilder.buildFrameIndex(Res, FI);
     988          17 :     return true;
     989             :   }
     990             : 
     991             :   // Now we're in the harder dynamic case.
     992           4 :   Type *Ty = AI.getAllocatedType();
     993             :   unsigned Align =
     994           8 :       std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI.getAlignment());
     995             : 
     996           4 :   unsigned NumElts = getOrCreateVReg(*AI.getArraySize());
     997             : 
     998           8 :   Type *IntPtrIRTy = DL->getIntPtrType(AI.getType());
     999           4 :   LLT IntPtrTy = getLLTForType(*IntPtrIRTy, *DL);
    1000           8 :   if (MRI->getType(NumElts) != IntPtrTy) {
    1001           4 :     unsigned ExtElts = MRI->createGenericVirtualRegister(IntPtrTy);
    1002           4 :     MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts);
    1003           4 :     NumElts = ExtElts;
    1004             :   }
    1005             : 
    1006           4 :   unsigned AllocSize = MRI->createGenericVirtualRegister(IntPtrTy);
    1007             :   unsigned TySize =
    1008           4 :       getOrCreateVReg(*ConstantInt::get(IntPtrIRTy, -DL->getTypeAllocSize(Ty)));
    1009           4 :   MIRBuilder.buildMul(AllocSize, NumElts, TySize);
    1010             : 
    1011           8 :   LLT PtrTy = getLLTForType(*AI.getType(), *DL);
    1012           4 :   auto &TLI = *MF->getSubtarget().getTargetLowering();
    1013           4 :   unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
    1014             : 
    1015           4 :   unsigned SPTmp = MRI->createGenericVirtualRegister(PtrTy);
    1016           4 :   MIRBuilder.buildCopy(SPTmp, SPReg);
    1017             : 
    1018           4 :   unsigned AllocTmp = MRI->createGenericVirtualRegister(PtrTy);
    1019           4 :   MIRBuilder.buildGEP(AllocTmp, SPTmp, AllocSize);
    1020             : 
    1021             :   // Handle alignment. We have to realign if the allocation granule was smaller
    1022             :   // than stack alignment, or the specific alloca requires more than stack
    1023             :   // alignment.
    1024             :   unsigned StackAlign =
    1025           4 :       MF->getSubtarget().getFrameLowering()->getStackAlignment();
    1026           4 :   Align = std::max(Align, StackAlign);
    1027           4 :   if (Align > StackAlign || DL->getTypeAllocSize(Ty) % StackAlign != 0) {
    1028             :     // Round the size of the allocation up to the stack alignment size
    1029             :     // by add SA-1 to the size. This doesn't overflow because we're computing
    1030             :     // an address inside an alloca.
    1031           3 :     unsigned AlignedAlloc = MRI->createGenericVirtualRegister(PtrTy);
    1032           6 :     MIRBuilder.buildPtrMask(AlignedAlloc, AllocTmp, Log2_32(Align));
    1033           3 :     AllocTmp = AlignedAlloc;
    1034             :   }
    1035             : 
    1036           4 :   MIRBuilder.buildCopy(SPReg, AllocTmp);
    1037           4 :   MIRBuilder.buildCopy(getOrCreateVReg(AI), AllocTmp);
    1038             : 
    1039           4 :   MF->getFrameInfo().CreateVariableSizedObject(Align ? Align : 1, &AI);
    1040             :   assert(MF->getFrameInfo().hasVarSizedObjects());
    1041           4 :   return true;
    1042             : }
    1043             : 
    1044           3 : bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) {
    1045             :   // FIXME: We may need more info about the type. Because of how LLT works,
    1046             :   // we're completely discarding the i64/double distinction here (amongst
    1047             :   // others). Fortunately the ABIs I know of where that matters don't use va_arg
    1048             :   // anyway but that's not guaranteed.
    1049           6 :   MIRBuilder.buildInstr(TargetOpcode::G_VAARG)
    1050           6 :     .addDef(getOrCreateVReg(U))
    1051           6 :     .addUse(getOrCreateVReg(*U.getOperand(0)))
    1052           6 :     .addImm(DL->getABITypeAlignment(U.getType()));
    1053           3 :   return true;
    1054             : }
    1055             : 
    1056          25 : bool IRTranslator::translateInsertElement(const User &U,
    1057             :                                           MachineIRBuilder &MIRBuilder) {
    1058             :   // If it is a <1 x Ty> vector, use the scalar as it is
    1059             :   // not a legal vector type in LLT.
    1060          50 :   if (U.getType()->getVectorNumElements() == 1) {
    1061           6 :     unsigned Elt = getOrCreateVReg(*U.getOperand(1));
    1062          12 :     ValToVReg[&U] = Elt;
    1063           6 :     return true;
    1064             :   }
    1065          19 :   unsigned Res = getOrCreateVReg(U);
    1066          19 :   unsigned Val = getOrCreateVReg(*U.getOperand(0));
    1067          19 :   unsigned Elt = getOrCreateVReg(*U.getOperand(1));
    1068          19 :   unsigned Idx = getOrCreateVReg(*U.getOperand(2));
    1069          19 :   MIRBuilder.buildInsertVectorElement(Res, Val, Elt, Idx);
    1070          19 :   return true;
    1071             : }
    1072             : 
    1073          22 : bool IRTranslator::translateExtractElement(const User &U,
    1074             :                                            MachineIRBuilder &MIRBuilder) {
    1075             :   // If it is a <1 x Ty> vector, use the scalar as it is
    1076             :   // not a legal vector type in LLT.
    1077          44 :   if (U.getOperand(0)->getType()->getVectorNumElements() == 1) {
    1078           4 :     unsigned Elt = getOrCreateVReg(*U.getOperand(0));
    1079           8 :     ValToVReg[&U] = Elt;
    1080           4 :     return true;
    1081             :   }
    1082          18 :   unsigned Res = getOrCreateVReg(U);
    1083          18 :   unsigned Val = getOrCreateVReg(*U.getOperand(0));
    1084          18 :   unsigned Idx = getOrCreateVReg(*U.getOperand(1));
    1085          18 :   MIRBuilder.buildExtractVectorElement(Res, Val, Idx);
    1086          18 :   return true;
    1087             : }
    1088             : 
    1089          15 : bool IRTranslator::translateShuffleVector(const User &U,
    1090             :                                           MachineIRBuilder &MIRBuilder) {
    1091          30 :   MIRBuilder.buildInstr(TargetOpcode::G_SHUFFLE_VECTOR)
    1092          30 :       .addDef(getOrCreateVReg(U))
    1093          30 :       .addUse(getOrCreateVReg(*U.getOperand(0)))
    1094          30 :       .addUse(getOrCreateVReg(*U.getOperand(1)))
    1095          30 :       .addUse(getOrCreateVReg(*U.getOperand(2)));
    1096          15 :   return true;
    1097             : }
    1098             : 
    1099          13 : bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) {
    1100          13 :   const PHINode &PI = cast<PHINode>(U);
    1101          13 :   auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_PHI);
    1102          26 :   MIB.addDef(getOrCreateVReg(PI));
    1103             : 
    1104          13 :   PendingPHIs.emplace_back(&PI, MIB.getInstr());
    1105          13 :   return true;
    1106             : }
    1107             : 
    1108         842 : void IRTranslator::finishPendingPhis() {
    1109        2539 :   for (std::pair<const PHINode *, MachineInstr *> &Phi : PendingPHIs) {
    1110          13 :     const PHINode *PI = Phi.first;
    1111          26 :     MachineInstrBuilder MIB(*MF, Phi.second);
    1112             : 
    1113             :     // All MachineBasicBlocks exist, add them to the PHI. We assume IRTranslator
    1114             :     // won't create extra control flow here, otherwise we need to find the
    1115             :     // dominating predecessor here (or perhaps force the weirder IRTranslators
    1116             :     // to provide a simple boundary).
    1117          26 :     SmallSet<const BasicBlock *, 4> HandledPreds;
    1118             : 
    1119          82 :     for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
    1120          28 :       auto IRPred = PI->getIncomingBlock(i);
    1121          28 :       if (HandledPreds.count(IRPred))
    1122           1 :         continue;
    1123             : 
    1124          27 :       HandledPreds.insert(IRPred);
    1125          27 :       unsigned ValReg = getOrCreateVReg(*PI->getIncomingValue(i));
    1126         163 :       for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) {
    1127             :         assert(Pred->isSuccessor(MIB->getParent()) &&
    1128             :                "incorrect CFG at MachineBasicBlock level");
    1129          28 :         MIB.addUse(ValReg);
    1130          28 :         MIB.addMBB(Pred);
    1131             :       }
    1132             :     }
    1133             :   }
    1134         842 : }
    1135             : 
    1136        1986 : bool IRTranslator::translate(const Instruction &Inst) {
    1137        3972 :   CurBuilder.setDebugLoc(Inst.getDebugLoc());
    1138        1986 :   switch(Inst.getOpcode()) {
    1139             : #define HANDLE_INST(NUM, OPCODE, CLASS) \
    1140             :     case Instruction::OPCODE: return translate##OPCODE(Inst, CurBuilder);
    1141             : #include "llvm/IR/Instruction.def"
    1142             :   default:
    1143             :     return false;
    1144             :   }
    1145             : }
    1146             : 
    1147         428 : bool IRTranslator::translate(const Constant &C, unsigned Reg) {
    1148         428 :   if (auto CI = dyn_cast<ConstantInt>(&C))
    1149         250 :     EntryBuilder.buildConstant(Reg, *CI);
    1150         178 :   else if (auto CF = dyn_cast<ConstantFP>(&C))
    1151          15 :     EntryBuilder.buildFConstant(Reg, *CF);
    1152         163 :   else if (isa<UndefValue>(C))
    1153          35 :     EntryBuilder.buildUndef(Reg);
    1154         128 :   else if (isa<ConstantPointerNull>(C))
    1155          10 :     EntryBuilder.buildConstant(Reg, 0);
    1156         118 :   else if (auto GV = dyn_cast<GlobalValue>(&C))
    1157          83 :     EntryBuilder.buildGlobalValue(Reg, GV);
    1158          35 :   else if (auto CAZ = dyn_cast<ConstantAggregateZero>(&C)) {
    1159          18 :     if (!CAZ->getType()->isVectorTy())
    1160           1 :       return false;
    1161             :     // Return the scalar if it is a <1 x Ty> vector.
    1162           9 :     if (CAZ->getNumElements() == 1)
    1163           1 :       return translate(*CAZ->getElementValue(0u), Reg);
    1164          16 :     std::vector<unsigned> Ops;
    1165          29 :     for (unsigned i = 0; i < CAZ->getNumElements(); ++i) {
    1166          21 :       Constant &Elt = *CAZ->getElementValue(i);
    1167          42 :       Ops.push_back(getOrCreateVReg(Elt));
    1168             :     }
    1169          16 :     EntryBuilder.buildMerge(Reg, Ops);
    1170          26 :   } else if (auto CV = dyn_cast<ConstantDataVector>(&C)) {
    1171             :     // Return the scalar if it is a <1 x Ty> vector.
    1172          19 :     if (CV->getNumElements() == 1)
    1173           2 :       return translate(*CV->getElementAsConstant(0), Reg);
    1174          34 :     std::vector<unsigned> Ops;
    1175          73 :     for (unsigned i = 0; i < CV->getNumElements(); ++i) {
    1176          56 :       Constant &Elt = *CV->getElementAsConstant(i);
    1177         112 :       Ops.push_back(getOrCreateVReg(Elt));
    1178             :     }
    1179          34 :     EntryBuilder.buildMerge(Reg, Ops);
    1180           7 :   } else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
    1181           2 :     switch(CE->getOpcode()) {
    1182             : #define HANDLE_INST(NUM, OPCODE, CLASS)                         \
    1183             :       case Instruction::OPCODE: return translate##OPCODE(*CE, EntryBuilder);
    1184             : #include "llvm/IR/Instruction.def"
    1185             :     default:
    1186             :       return false;
    1187             :     }
    1188           5 :   } else if (auto CS = dyn_cast<ConstantStruct>(&C)) {
    1189             :     // Return the element if it is a single element ConstantStruct.
    1190           4 :     if (CS->getNumOperands() == 1) {
    1191           0 :       unsigned EltReg = getOrCreateVReg(*CS->getOperand(0));
    1192           0 :       EntryBuilder.buildCast(Reg, EltReg);
    1193           0 :       return true;
    1194             :     }
    1195           4 :     SmallVector<unsigned, 4> Ops;
    1196           4 :     SmallVector<uint64_t, 4> Indices;
    1197           2 :     uint64_t Offset = 0;
    1198          16 :     for (unsigned i = 0; i < CS->getNumOperands(); ++i) {
    1199          12 :       unsigned OpReg = getOrCreateVReg(*CS->getOperand(i));
    1200           6 :       Ops.push_back(OpReg);
    1201           6 :       Indices.push_back(Offset);
    1202           6 :       Offset += MRI->getType(OpReg).getSizeInBits();
    1203             :     }
    1204           6 :     EntryBuilder.buildSequence(Reg, Ops, Indices);
    1205           1 :   } else if (auto CV = dyn_cast<ConstantVector>(&C)) {
    1206           2 :     if (CV->getNumOperands() == 1)
    1207           0 :       return translate(*CV->getOperand(0), Reg);
    1208           2 :     SmallVector<unsigned, 4> Ops;
    1209          10 :     for (unsigned i = 0; i < CV->getNumOperands(); ++i) {
    1210           8 :       Ops.push_back(getOrCreateVReg(*CV->getOperand(i)));
    1211             :     }
    1212           2 :     EntryBuilder.buildMerge(Reg, Ops);
    1213             :   } else
    1214             :     return false;
    1215             : 
    1216             :   return true;
    1217             : }
    1218             : 
    1219         912 : void IRTranslator::finalizeFunction() {
    1220             :   // Release the memory used by the different maps we
    1221             :   // needed during the translation.
    1222        1824 :   PendingPHIs.clear();
    1223         912 :   ValToVReg.clear();
    1224         912 :   FrameIndices.clear();
    1225         912 :   MachinePreds.clear();
    1226             :   // MachineIRBuilder::DebugLoc can outlive the DILocation it holds. Clear it
    1227             :   // to avoid accessing free’d memory (in runOnMachineFunction) and to avoid
    1228             :   // destroying it twice (in ~IRTranslator() and ~LLVMContext())
    1229        1824 :   EntryBuilder = MachineIRBuilder();
    1230        1824 :   CurBuilder = MachineIRBuilder();
    1231         912 : }
    1232             : 
    1233         913 : bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) {
    1234         913 :   MF = &CurMF;
    1235         913 :   const Function &F = *MF->getFunction();
    1236         913 :   if (F.empty())
    1237             :     return false;
    1238         913 :   CLI = MF->getSubtarget().getCallLowering();
    1239         913 :   CurBuilder.setMF(*MF);
    1240         913 :   EntryBuilder.setMF(*MF);
    1241         913 :   MRI = &MF->getRegInfo();
    1242         913 :   DL = &F.getParent()->getDataLayout();
    1243         913 :   TPC = &getAnalysis<TargetPassConfig>();
    1244        1826 :   ORE = llvm::make_unique<OptimizationRemarkEmitter>(&F);
    1245             : 
    1246             :   assert(PendingPHIs.empty() && "stale PHIs");
    1247             : 
    1248             :   // Release the per-function state when we return, whether we succeeded or not.
    1249        2738 :   auto FinalizeOnReturn = make_scope_exit([this]() { finalizeFunction(); });
    1250             : 
    1251             :   // Setup a separate basic-block for the arguments and constants
    1252         913 :   MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock();
    1253        1826 :   MF->push_back(EntryBB);
    1254         913 :   EntryBuilder.setMBB(*EntryBB);
    1255             : 
    1256             :   // Create all blocks, in IR order, to preserve the layout.
    1257        3732 :   for (const BasicBlock &BB: F) {
    1258        1986 :     auto *&MBB = BBToMBB[&BB];
    1259             : 
    1260         993 :     MBB = MF->CreateMachineBasicBlock(&BB);
    1261        1986 :     MF->push_back(MBB);
    1262             : 
    1263         993 :     if (BB.hasAddressTaken())
    1264           2 :       MBB->setHasAddressTaken();
    1265             :   }
    1266             : 
    1267             :   // Make our arguments/constants entry block fallthrough to the IR entry block.
    1268        1826 :   EntryBB->addSuccessor(&getMBB(F.front()));
    1269             : 
    1270             :   // Lower the actual args into this basic block.
    1271        1825 :   SmallVector<unsigned, 8> VRegArgs;
    1272        2460 :   for (const Argument &Arg: F.args())
    1273        1547 :     VRegArgs.push_back(getOrCreateVReg(Arg));
    1274        1826 :   if (!CLI->lowerFormalArguments(EntryBuilder, F, VRegArgs)) {
    1275             :     OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
    1276          48 :                                MF->getFunction()->getSubprogram(),
    1277         239 :                                &MF->getFunction()->getEntryBlock());
    1278         144 :     R << "unable to lower arguments: " << ore::NV("Prototype", F.getType());
    1279          96 :     reportTranslationError(*MF, *TPC, *ORE, R);
    1280          47 :     return false;
    1281             :   }
    1282             : 
    1283             :   // And translate the function!
    1284        3536 :   for (const BasicBlock &BB: F) {
    1285         941 :     MachineBasicBlock &MBB = getMBB(BB);
    1286             :     // Set the insertion point of all the following translations to
    1287             :     // the end of this basic block.
    1288         941 :     CurBuilder.setMBB(MBB);
    1289             : 
    1290        4809 :     for (const Instruction &Inst: BB) {
    1291        1986 :       if (translate(Inst))
    1292        1963 :         continue;
    1293             : 
    1294          46 :       std::string InstStrStorage;
    1295          46 :       raw_string_ostream InstStr(InstStrStorage);
    1296          46 :       InstStr << Inst;
    1297             : 
    1298             :       OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
    1299          92 :                                  Inst.getDebugLoc(), &BB);
    1300          69 :       R << "unable to translate instruction: " << ore::NV("Opcode", &Inst)
    1301          92 :         << ": '" << InstStr.str() << "'";
    1302          46 :       reportTranslationError(*MF, *TPC, *ORE, R);
    1303          23 :       return false;
    1304             :     }
    1305             :   }
    1306             : 
    1307         842 :   finishPendingPhis();
    1308             : 
    1309             :   // Merge the argument lowering and constants block with its single
    1310             :   // successor, the LLVM-IR entry block.  We want the basic block to
    1311             :   // be maximal.
    1312             :   assert(EntryBB->succ_size() == 1 &&
    1313             :          "Custom BB used for lowering should have only one successor");
    1314             :   // Get the successor of the current entry block.
    1315         842 :   MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin();
    1316             :   assert(NewEntryBB.pred_size() == 1 &&
    1317             :          "LLVM-IR entry block has a predecessor!?");
    1318             :   // Move all the instruction from the current entry block to the
    1319             :   // new entry block.
    1320        3368 :   NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(),
    1321             :                     EntryBB->end());
    1322             : 
    1323             :   // Update the live-in information for the new entry block.
    1324        3060 :   for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins())
    1325        1376 :     NewEntryBB.addLiveIn(LiveIn);
    1326         842 :   NewEntryBB.sortUniqueLiveIns();
    1327             : 
    1328             :   // Get rid of the now empty basic block.
    1329         842 :   EntryBB->removeSuccessor(&NewEntryBB);
    1330        1684 :   MF->remove(EntryBB);
    1331         842 :   MF->DeleteMachineBasicBlock(EntryBB);
    1332             : 
    1333             :   assert(&MF->front() == &NewEntryBB &&
    1334             :          "New entry wasn't next in the list of basic block!");
    1335             : 
    1336         842 :   return false;
    1337             : }

Generated by: LCOV version 1.13