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

Generated by: LCOV version 1.13