LLVM API Documentation

FastISel.cpp
Go to the documentation of this file.
00001 //===-- FastISel.cpp - Implementation of the FastISel class ---------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains the implementation of the FastISel class.
00011 //
00012 // "Fast" instruction selection is designed to emit very poor code quickly.
00013 // Also, it is not designed to be able to do much lowering, so most illegal
00014 // types (e.g. i64 on 32-bit targets) and operations are not supported.  It is
00015 // also not intended to be able to do much optimization, except in a few cases
00016 // where doing optimizations reduces overall compile time.  For example, folding
00017 // constants into immediate fields is often done, because it's cheap and it
00018 // reduces the number of instructions later phases have to examine.
00019 //
00020 // "Fast" instruction selection is able to fail gracefully and transfer
00021 // control to the SelectionDAG selector for operations that it doesn't
00022 // support.  In many cases, this allows us to avoid duplicating a lot of
00023 // the complicated lowering logic that SelectionDAG currently has.
00024 //
00025 // The intended use for "fast" instruction selection is "-O0" mode
00026 // compilation, where the quality of the generated code is irrelevant when
00027 // weighed against the speed at which the code can be generated.  Also,
00028 // at -O0, the LLVM optimizers are not running, and this makes the
00029 // compile time of codegen a much higher portion of the overall compile
00030 // time.  Despite its limitations, "fast" instruction selection is able to
00031 // handle enough code on its own to provide noticeable overall speedups
00032 // in -O0 compiles.
00033 //
00034 // Basic operations are supported in a target-independent way, by reading
00035 // the same instruction descriptions that the SelectionDAG selector reads,
00036 // and identifying simple arithmetic operations that can be directly selected
00037 // from simple operators.  More complicated operations currently require
00038 // target-specific code.
00039 //
00040 //===----------------------------------------------------------------------===//
00041 
00042 #include "llvm/CodeGen/Analysis.h"
00043 #include "llvm/CodeGen/FastISel.h"
00044 #include "llvm/ADT/Optional.h"
00045 #include "llvm/ADT/Statistic.h"
00046 #include "llvm/Analysis/BranchProbabilityInfo.h"
00047 #include "llvm/Analysis/Loads.h"
00048 #include "llvm/CodeGen/Analysis.h"
00049 #include "llvm/CodeGen/FunctionLoweringInfo.h"
00050 #include "llvm/CodeGen/MachineFrameInfo.h"
00051 #include "llvm/CodeGen/MachineInstrBuilder.h"
00052 #include "llvm/CodeGen/MachineModuleInfo.h"
00053 #include "llvm/CodeGen/MachineRegisterInfo.h"
00054 #include "llvm/CodeGen/StackMaps.h"
00055 #include "llvm/IR/DataLayout.h"
00056 #include "llvm/IR/DebugInfo.h"
00057 #include "llvm/IR/Function.h"
00058 #include "llvm/IR/GlobalVariable.h"
00059 #include "llvm/IR/Instructions.h"
00060 #include "llvm/IR/IntrinsicInst.h"
00061 #include "llvm/IR/Operator.h"
00062 #include "llvm/Support/Debug.h"
00063 #include "llvm/Support/ErrorHandling.h"
00064 #include "llvm/Target/TargetInstrInfo.h"
00065 #include "llvm/Target/TargetLibraryInfo.h"
00066 #include "llvm/Target/TargetLowering.h"
00067 #include "llvm/Target/TargetMachine.h"
00068 #include "llvm/Target/TargetSubtargetInfo.h"
00069 using namespace llvm;
00070 
00071 #define DEBUG_TYPE "isel"
00072 
00073 STATISTIC(NumFastIselSuccessIndependent, "Number of insts selected by "
00074                                          "target-independent selector");
00075 STATISTIC(NumFastIselSuccessTarget, "Number of insts selected by "
00076                                     "target-specific selector");
00077 STATISTIC(NumFastIselDead, "Number of dead insts removed on failure");
00078 
00079 void FastISel::ArgListEntry::setAttributes(ImmutableCallSite *CS,
00080                                            unsigned AttrIdx) {
00081   IsSExt = CS->paramHasAttr(AttrIdx, Attribute::SExt);
00082   IsZExt = CS->paramHasAttr(AttrIdx, Attribute::ZExt);
00083   IsInReg = CS->paramHasAttr(AttrIdx, Attribute::InReg);
00084   IsSRet = CS->paramHasAttr(AttrIdx, Attribute::StructRet);
00085   IsNest = CS->paramHasAttr(AttrIdx, Attribute::Nest);
00086   IsByVal = CS->paramHasAttr(AttrIdx, Attribute::ByVal);
00087   IsInAlloca = CS->paramHasAttr(AttrIdx, Attribute::InAlloca);
00088   IsReturned = CS->paramHasAttr(AttrIdx, Attribute::Returned);
00089   Alignment = CS->getParamAlignment(AttrIdx);
00090 }
00091 
00092 /// Set the current block to which generated machine instructions will be
00093 /// appended, and clear the local CSE map.
00094 void FastISel::startNewBlock() {
00095   LocalValueMap.clear();
00096 
00097   // Instructions are appended to FuncInfo.MBB. If the basic block already
00098   // contains labels or copies, use the last instruction as the last local
00099   // value.
00100   EmitStartPt = nullptr;
00101   if (!FuncInfo.MBB->empty())
00102     EmitStartPt = &FuncInfo.MBB->back();
00103   LastLocalValue = EmitStartPt;
00104 }
00105 
00106 bool FastISel::lowerArguments() {
00107   if (!FuncInfo.CanLowerReturn)
00108     // Fallback to SDISel argument lowering code to deal with sret pointer
00109     // parameter.
00110     return false;
00111 
00112   if (!fastLowerArguments())
00113     return false;
00114 
00115   // Enter arguments into ValueMap for uses in non-entry BBs.
00116   for (Function::const_arg_iterator I = FuncInfo.Fn->arg_begin(),
00117                                     E = FuncInfo.Fn->arg_end();
00118        I != E; ++I) {
00119     DenseMap<const Value *, unsigned>::iterator VI = LocalValueMap.find(I);
00120     assert(VI != LocalValueMap.end() && "Missed an argument?");
00121     FuncInfo.ValueMap[I] = VI->second;
00122   }
00123   return true;
00124 }
00125 
00126 void FastISel::flushLocalValueMap() {
00127   LocalValueMap.clear();
00128   LastLocalValue = EmitStartPt;
00129   recomputeInsertPt();
00130   SavedInsertPt = FuncInfo.InsertPt;
00131 }
00132 
00133 bool FastISel::hasTrivialKill(const Value *V) {
00134   // Don't consider constants or arguments to have trivial kills.
00135   const Instruction *I = dyn_cast<Instruction>(V);
00136   if (!I)
00137     return false;
00138 
00139   // No-op casts are trivially coalesced by fast-isel.
00140   if (const auto *Cast = dyn_cast<CastInst>(I))
00141     if (Cast->isNoopCast(DL.getIntPtrType(Cast->getContext())) &&
00142         !hasTrivialKill(Cast->getOperand(0)))
00143       return false;
00144 
00145   // Even the value might have only one use in the LLVM IR, it is possible that
00146   // FastISel might fold the use into another instruction and now there is more
00147   // than one use at the Machine Instruction level.
00148   unsigned Reg = lookUpRegForValue(V);
00149   if (Reg && !MRI.use_empty(Reg))
00150     return false;
00151 
00152   // GEPs with all zero indices are trivially coalesced by fast-isel.
00153   if (const auto *GEP = dyn_cast<GetElementPtrInst>(I))
00154     if (GEP->hasAllZeroIndices() && !hasTrivialKill(GEP->getOperand(0)))
00155       return false;
00156 
00157   // Only instructions with a single use in the same basic block are considered
00158   // to have trivial kills.
00159   return I->hasOneUse() &&
00160          !(I->getOpcode() == Instruction::BitCast ||
00161            I->getOpcode() == Instruction::PtrToInt ||
00162            I->getOpcode() == Instruction::IntToPtr) &&
00163          cast<Instruction>(*I->user_begin())->getParent() == I->getParent();
00164 }
00165 
00166 unsigned FastISel::getRegForValue(const Value *V) {
00167   EVT RealVT = TLI.getValueType(V->getType(), /*AllowUnknown=*/true);
00168   // Don't handle non-simple values in FastISel.
00169   if (!RealVT.isSimple())
00170     return 0;
00171 
00172   // Ignore illegal types. We must do this before looking up the value
00173   // in ValueMap because Arguments are given virtual registers regardless
00174   // of whether FastISel can handle them.
00175   MVT VT = RealVT.getSimpleVT();
00176   if (!TLI.isTypeLegal(VT)) {
00177     // Handle integer promotions, though, because they're common and easy.
00178     if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
00179       VT = TLI.getTypeToTransformTo(V->getContext(), VT).getSimpleVT();
00180     else
00181       return 0;
00182   }
00183 
00184   // Look up the value to see if we already have a register for it.
00185   unsigned Reg = lookUpRegForValue(V);
00186   if (Reg)
00187     return Reg;
00188 
00189   // In bottom-up mode, just create the virtual register which will be used
00190   // to hold the value. It will be materialized later.
00191   if (isa<Instruction>(V) &&
00192       (!isa<AllocaInst>(V) ||
00193        !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(V))))
00194     return FuncInfo.InitializeRegForValue(V);
00195 
00196   SavePoint SaveInsertPt = enterLocalValueArea();
00197 
00198   // Materialize the value in a register. Emit any instructions in the
00199   // local value area.
00200   Reg = materializeRegForValue(V, VT);
00201 
00202   leaveLocalValueArea(SaveInsertPt);
00203 
00204   return Reg;
00205 }
00206 
00207 unsigned FastISel::materializeConstant(const Value *V, MVT VT) {
00208   unsigned Reg = 0;
00209   if (const auto *CI = dyn_cast<ConstantInt>(V)) {
00210     if (CI->getValue().getActiveBits() <= 64)
00211       Reg = fastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
00212   } else if (isa<AllocaInst>(V))
00213     Reg = fastMaterializeAlloca(cast<AllocaInst>(V));
00214   else if (isa<ConstantPointerNull>(V))
00215     // Translate this as an integer zero so that it can be
00216     // local-CSE'd with actual integer zeros.
00217     Reg = getRegForValue(
00218         Constant::getNullValue(DL.getIntPtrType(V->getContext())));
00219   else if (const auto *CF = dyn_cast<ConstantFP>(V)) {
00220     if (CF->isNullValue())
00221       Reg = fastMaterializeFloatZero(CF);
00222     else
00223       // Try to emit the constant directly.
00224       Reg = fastEmit_f(VT, VT, ISD::ConstantFP, CF);
00225 
00226     if (!Reg) {
00227       // Try to emit the constant by using an integer constant with a cast.
00228       const APFloat &Flt = CF->getValueAPF();
00229       EVT IntVT = TLI.getPointerTy();
00230 
00231       uint64_t x[2];
00232       uint32_t IntBitWidth = IntVT.getSizeInBits();
00233       bool isExact;
00234       (void)Flt.convertToInteger(x, IntBitWidth, /*isSigned=*/true,
00235                                  APFloat::rmTowardZero, &isExact);
00236       if (isExact) {
00237         APInt IntVal(IntBitWidth, x);
00238 
00239         unsigned IntegerReg =
00240             getRegForValue(ConstantInt::get(V->getContext(), IntVal));
00241         if (IntegerReg != 0)
00242           Reg = fastEmit_r(IntVT.getSimpleVT(), VT, ISD::SINT_TO_FP, IntegerReg,
00243                            /*Kill=*/false);
00244       }
00245     }
00246   } else if (const auto *Op = dyn_cast<Operator>(V)) {
00247     if (!selectOperator(Op, Op->getOpcode()))
00248       if (!isa<Instruction>(Op) ||
00249           !fastSelectInstruction(cast<Instruction>(Op)))
00250         return 0;
00251     Reg = lookUpRegForValue(Op);
00252   } else if (isa<UndefValue>(V)) {
00253     Reg = createResultReg(TLI.getRegClassFor(VT));
00254     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
00255             TII.get(TargetOpcode::IMPLICIT_DEF), Reg);
00256   }
00257   return Reg;
00258 }
00259 
00260 /// Helper for getRegForValue. This function is called when the value isn't
00261 /// already available in a register and must be materialized with new
00262 /// instructions.
00263 unsigned FastISel::materializeRegForValue(const Value *V, MVT VT) {
00264   unsigned Reg = 0;
00265   // Give the target-specific code a try first.
00266   if (isa<Constant>(V))
00267     Reg = fastMaterializeConstant(cast<Constant>(V));
00268 
00269   // If target-specific code couldn't or didn't want to handle the value, then
00270   // give target-independent code a try.
00271   if (!Reg)
00272     Reg = materializeConstant(V, VT);
00273 
00274   // Don't cache constant materializations in the general ValueMap.
00275   // To do so would require tracking what uses they dominate.
00276   if (Reg) {
00277     LocalValueMap[V] = Reg;
00278     LastLocalValue = MRI.getVRegDef(Reg);
00279   }
00280   return Reg;
00281 }
00282 
00283 unsigned FastISel::lookUpRegForValue(const Value *V) {
00284   // Look up the value to see if we already have a register for it. We
00285   // cache values defined by Instructions across blocks, and other values
00286   // only locally. This is because Instructions already have the SSA
00287   // def-dominates-use requirement enforced.
00288   DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(V);
00289   if (I != FuncInfo.ValueMap.end())
00290     return I->second;
00291   return LocalValueMap[V];
00292 }
00293 
00294 void FastISel::updateValueMap(const Value *I, unsigned Reg, unsigned NumRegs) {
00295   if (!isa<Instruction>(I)) {
00296     LocalValueMap[I] = Reg;
00297     return;
00298   }
00299 
00300   unsigned &AssignedReg = FuncInfo.ValueMap[I];
00301   if (AssignedReg == 0)
00302     // Use the new register.
00303     AssignedReg = Reg;
00304   else if (Reg != AssignedReg) {
00305     // Arrange for uses of AssignedReg to be replaced by uses of Reg.
00306     for (unsigned i = 0; i < NumRegs; i++)
00307       FuncInfo.RegFixups[AssignedReg + i] = Reg + i;
00308 
00309     AssignedReg = Reg;
00310   }
00311 }
00312 
00313 std::pair<unsigned, bool> FastISel::getRegForGEPIndex(const Value *Idx) {
00314   unsigned IdxN = getRegForValue(Idx);
00315   if (IdxN == 0)
00316     // Unhandled operand. Halt "fast" selection and bail.
00317     return std::pair<unsigned, bool>(0, false);
00318 
00319   bool IdxNIsKill = hasTrivialKill(Idx);
00320 
00321   // If the index is smaller or larger than intptr_t, truncate or extend it.
00322   MVT PtrVT = TLI.getPointerTy();
00323   EVT IdxVT = EVT::getEVT(Idx->getType(), /*HandleUnknown=*/false);
00324   if (IdxVT.bitsLT(PtrVT)) {
00325     IdxN = fastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::SIGN_EXTEND, IdxN,
00326                       IdxNIsKill);
00327     IdxNIsKill = true;
00328   } else if (IdxVT.bitsGT(PtrVT)) {
00329     IdxN =
00330         fastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::TRUNCATE, IdxN, IdxNIsKill);
00331     IdxNIsKill = true;
00332   }
00333   return std::pair<unsigned, bool>(IdxN, IdxNIsKill);
00334 }
00335 
00336 void FastISel::recomputeInsertPt() {
00337   if (getLastLocalValue()) {
00338     FuncInfo.InsertPt = getLastLocalValue();
00339     FuncInfo.MBB = FuncInfo.InsertPt->getParent();
00340     ++FuncInfo.InsertPt;
00341   } else
00342     FuncInfo.InsertPt = FuncInfo.MBB->getFirstNonPHI();
00343 
00344   // Now skip past any EH_LABELs, which must remain at the beginning.
00345   while (FuncInfo.InsertPt != FuncInfo.MBB->end() &&
00346          FuncInfo.InsertPt->getOpcode() == TargetOpcode::EH_LABEL)
00347     ++FuncInfo.InsertPt;
00348 }
00349 
00350 void FastISel::removeDeadCode(MachineBasicBlock::iterator I,
00351                               MachineBasicBlock::iterator E) {
00352   assert(I && E && std::distance(I, E) > 0 && "Invalid iterator!");
00353   while (I != E) {
00354     MachineInstr *Dead = &*I;
00355     ++I;
00356     Dead->eraseFromParent();
00357     ++NumFastIselDead;
00358   }
00359   recomputeInsertPt();
00360 }
00361 
00362 FastISel::SavePoint FastISel::enterLocalValueArea() {
00363   MachineBasicBlock::iterator OldInsertPt = FuncInfo.InsertPt;
00364   DebugLoc OldDL = DbgLoc;
00365   recomputeInsertPt();
00366   DbgLoc = DebugLoc();
00367   SavePoint SP = {OldInsertPt, OldDL};
00368   return SP;
00369 }
00370 
00371 void FastISel::leaveLocalValueArea(SavePoint OldInsertPt) {
00372   if (FuncInfo.InsertPt != FuncInfo.MBB->begin())
00373     LastLocalValue = std::prev(FuncInfo.InsertPt);
00374 
00375   // Restore the previous insert position.
00376   FuncInfo.InsertPt = OldInsertPt.InsertPt;
00377   DbgLoc = OldInsertPt.DL;
00378 }
00379 
00380 bool FastISel::selectBinaryOp(const User *I, unsigned ISDOpcode) {
00381   EVT VT = EVT::getEVT(I->getType(), /*HandleUnknown=*/true);
00382   if (VT == MVT::Other || !VT.isSimple())
00383     // Unhandled type. Halt "fast" selection and bail.
00384     return false;
00385 
00386   // We only handle legal types. For example, on x86-32 the instruction
00387   // selector contains all of the 64-bit instructions from x86-64,
00388   // under the assumption that i64 won't be used if the target doesn't
00389   // support it.
00390   if (!TLI.isTypeLegal(VT)) {
00391     // MVT::i1 is special. Allow AND, OR, or XOR because they
00392     // don't require additional zeroing, which makes them easy.
00393     if (VT == MVT::i1 && (ISDOpcode == ISD::AND || ISDOpcode == ISD::OR ||
00394                           ISDOpcode == ISD::XOR))
00395       VT = TLI.getTypeToTransformTo(I->getContext(), VT);
00396     else
00397       return false;
00398   }
00399 
00400   // Check if the first operand is a constant, and handle it as "ri".  At -O0,
00401   // we don't have anything that canonicalizes operand order.
00402   if (const auto *CI = dyn_cast<ConstantInt>(I->getOperand(0)))
00403     if (isa<Instruction>(I) && cast<Instruction>(I)->isCommutative()) {
00404       unsigned Op1 = getRegForValue(I->getOperand(1));
00405       if (!Op1)
00406         return false;
00407       bool Op1IsKill = hasTrivialKill(I->getOperand(1));
00408 
00409       unsigned ResultReg =
00410           fastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op1, Op1IsKill,
00411                        CI->getZExtValue(), VT.getSimpleVT());
00412       if (!ResultReg)
00413         return false;
00414 
00415       // We successfully emitted code for the given LLVM Instruction.
00416       updateValueMap(I, ResultReg);
00417       return true;
00418     }
00419 
00420   unsigned Op0 = getRegForValue(I->getOperand(0));
00421   if (!Op0) // Unhandled operand. Halt "fast" selection and bail.
00422     return false;
00423   bool Op0IsKill = hasTrivialKill(I->getOperand(0));
00424 
00425   // Check if the second operand is a constant and handle it appropriately.
00426   if (const auto *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
00427     uint64_t Imm = CI->getZExtValue();
00428 
00429     // Transform "sdiv exact X, 8" -> "sra X, 3".
00430     if (ISDOpcode == ISD::SDIV && isa<BinaryOperator>(I) &&
00431         cast<BinaryOperator>(I)->isExact() && isPowerOf2_64(Imm)) {
00432       Imm = Log2_64(Imm);
00433       ISDOpcode = ISD::SRA;
00434     }
00435 
00436     // Transform "urem x, pow2" -> "and x, pow2-1".
00437     if (ISDOpcode == ISD::UREM && isa<BinaryOperator>(I) &&
00438         isPowerOf2_64(Imm)) {
00439       --Imm;
00440       ISDOpcode = ISD::AND;
00441     }
00442 
00443     unsigned ResultReg = fastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op0,
00444                                       Op0IsKill, Imm, VT.getSimpleVT());
00445     if (!ResultReg)
00446       return false;
00447 
00448     // We successfully emitted code for the given LLVM Instruction.
00449     updateValueMap(I, ResultReg);
00450     return true;
00451   }
00452 
00453   // Check if the second operand is a constant float.
00454   if (const auto *CF = dyn_cast<ConstantFP>(I->getOperand(1))) {
00455     unsigned ResultReg = fastEmit_rf(VT.getSimpleVT(), VT.getSimpleVT(),
00456                                      ISDOpcode, Op0, Op0IsKill, CF);
00457     if (ResultReg) {
00458       // We successfully emitted code for the given LLVM Instruction.
00459       updateValueMap(I, ResultReg);
00460       return true;
00461     }
00462   }
00463 
00464   unsigned Op1 = getRegForValue(I->getOperand(1));
00465   if (!Op1) // Unhandled operand. Halt "fast" selection and bail.
00466     return false;
00467   bool Op1IsKill = hasTrivialKill(I->getOperand(1));
00468 
00469   // Now we have both operands in registers. Emit the instruction.
00470   unsigned ResultReg = fastEmit_rr(VT.getSimpleVT(), VT.getSimpleVT(),
00471                                    ISDOpcode, Op0, Op0IsKill, Op1, Op1IsKill);
00472   if (!ResultReg)
00473     // Target-specific code wasn't able to find a machine opcode for
00474     // the given ISD opcode and type. Halt "fast" selection and bail.
00475     return false;
00476 
00477   // We successfully emitted code for the given LLVM Instruction.
00478   updateValueMap(I, ResultReg);
00479   return true;
00480 }
00481 
00482 bool FastISel::selectGetElementPtr(const User *I) {
00483   unsigned N = getRegForValue(I->getOperand(0));
00484   if (!N) // Unhandled operand. Halt "fast" selection and bail.
00485     return false;
00486   bool NIsKill = hasTrivialKill(I->getOperand(0));
00487 
00488   // Keep a running tab of the total offset to coalesce multiple N = N + Offset
00489   // into a single N = N + TotalOffset.
00490   uint64_t TotalOffs = 0;
00491   // FIXME: What's a good SWAG number for MaxOffs?
00492   uint64_t MaxOffs = 2048;
00493   Type *Ty = I->getOperand(0)->getType();
00494   MVT VT = TLI.getPointerTy();
00495   for (GetElementPtrInst::const_op_iterator OI = I->op_begin() + 1,
00496                                             E = I->op_end();
00497        OI != E; ++OI) {
00498     const Value *Idx = *OI;
00499     if (auto *StTy = dyn_cast<StructType>(Ty)) {
00500       unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
00501       if (Field) {
00502         // N = N + Offset
00503         TotalOffs += DL.getStructLayout(StTy)->getElementOffset(Field);
00504         if (TotalOffs >= MaxOffs) {
00505           N = fastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
00506           if (!N) // Unhandled operand. Halt "fast" selection and bail.
00507             return false;
00508           NIsKill = true;
00509           TotalOffs = 0;
00510         }
00511       }
00512       Ty = StTy->getElementType(Field);
00513     } else {
00514       Ty = cast<SequentialType>(Ty)->getElementType();
00515 
00516       // If this is a constant subscript, handle it quickly.
00517       if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
00518         if (CI->isZero())
00519           continue;
00520         // N = N + Offset
00521         TotalOffs +=
00522             DL.getTypeAllocSize(Ty) * cast<ConstantInt>(CI)->getSExtValue();
00523         if (TotalOffs >= MaxOffs) {
00524           N = fastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
00525           if (!N) // Unhandled operand. Halt "fast" selection and bail.
00526             return false;
00527           NIsKill = true;
00528           TotalOffs = 0;
00529         }
00530         continue;
00531       }
00532       if (TotalOffs) {
00533         N = fastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
00534         if (!N) // Unhandled operand. Halt "fast" selection and bail.
00535           return false;
00536         NIsKill = true;
00537         TotalOffs = 0;
00538       }
00539 
00540       // N = N + Idx * ElementSize;
00541       uint64_t ElementSize = DL.getTypeAllocSize(Ty);
00542       std::pair<unsigned, bool> Pair = getRegForGEPIndex(Idx);
00543       unsigned IdxN = Pair.first;
00544       bool IdxNIsKill = Pair.second;
00545       if (!IdxN) // Unhandled operand. Halt "fast" selection and bail.
00546         return false;
00547 
00548       if (ElementSize != 1) {
00549         IdxN = fastEmit_ri_(VT, ISD::MUL, IdxN, IdxNIsKill, ElementSize, VT);
00550         if (!IdxN) // Unhandled operand. Halt "fast" selection and bail.
00551           return false;
00552         IdxNIsKill = true;
00553       }
00554       N = fastEmit_rr(VT, VT, ISD::ADD, N, NIsKill, IdxN, IdxNIsKill);
00555       if (!N) // Unhandled operand. Halt "fast" selection and bail.
00556         return false;
00557     }
00558   }
00559   if (TotalOffs) {
00560     N = fastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
00561     if (!N) // Unhandled operand. Halt "fast" selection and bail.
00562       return false;
00563   }
00564 
00565   // We successfully emitted code for the given LLVM Instruction.
00566   updateValueMap(I, N);
00567   return true;
00568 }
00569 
00570 bool FastISel::addStackMapLiveVars(SmallVectorImpl<MachineOperand> &Ops,
00571                                    const CallInst *CI, unsigned StartIdx) {
00572   for (unsigned i = StartIdx, e = CI->getNumArgOperands(); i != e; ++i) {
00573     Value *Val = CI->getArgOperand(i);
00574     // Check for constants and encode them with a StackMaps::ConstantOp prefix.
00575     if (const auto *C = dyn_cast<ConstantInt>(Val)) {
00576       Ops.push_back(MachineOperand::CreateImm(StackMaps::ConstantOp));
00577       Ops.push_back(MachineOperand::CreateImm(C->getSExtValue()));
00578     } else if (isa<ConstantPointerNull>(Val)) {
00579       Ops.push_back(MachineOperand::CreateImm(StackMaps::ConstantOp));
00580       Ops.push_back(MachineOperand::CreateImm(0));
00581     } else if (auto *AI = dyn_cast<AllocaInst>(Val)) {
00582       // Values coming from a stack location also require a sepcial encoding,
00583       // but that is added later on by the target specific frame index
00584       // elimination implementation.
00585       auto SI = FuncInfo.StaticAllocaMap.find(AI);
00586       if (SI != FuncInfo.StaticAllocaMap.end())
00587         Ops.push_back(MachineOperand::CreateFI(SI->second));
00588       else
00589         return false;
00590     } else {
00591       unsigned Reg = getRegForValue(Val);
00592       if (!Reg)
00593         return false;
00594       Ops.push_back(MachineOperand::CreateReg(Reg, /*IsDef=*/false));
00595     }
00596   }
00597   return true;
00598 }
00599 
00600 bool FastISel::selectStackmap(const CallInst *I) {
00601   // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
00602   //                                  [live variables...])
00603   assert(I->getCalledFunction()->getReturnType()->isVoidTy() &&
00604          "Stackmap cannot return a value.");
00605 
00606   // The stackmap intrinsic only records the live variables (the arguments
00607   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
00608   // intrinsic, this won't be lowered to a function call. This means we don't
00609   // have to worry about calling conventions and target-specific lowering code.
00610   // Instead we perform the call lowering right here.
00611   //
00612   // CALLSEQ_START(0)
00613   // STACKMAP(id, nbytes, ...)
00614   // CALLSEQ_END(0, 0)
00615   //
00616   SmallVector<MachineOperand, 32> Ops;
00617 
00618   // Add the <id> and <numBytes> constants.
00619   assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::IDPos)) &&
00620          "Expected a constant integer.");
00621   const auto *ID = cast<ConstantInt>(I->getOperand(PatchPointOpers::IDPos));
00622   Ops.push_back(MachineOperand::CreateImm(ID->getZExtValue()));
00623 
00624   assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos)) &&
00625          "Expected a constant integer.");
00626   const auto *NumBytes =
00627       cast<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos));
00628   Ops.push_back(MachineOperand::CreateImm(NumBytes->getZExtValue()));
00629 
00630   // Push live variables for the stack map (skipping the first two arguments
00631   // <id> and <numBytes>).
00632   if (!addStackMapLiveVars(Ops, I, 2))
00633     return false;
00634 
00635   // We are not adding any register mask info here, because the stackmap doesn't
00636   // clobber anything.
00637 
00638   // Add scratch registers as implicit def and early clobber.
00639   CallingConv::ID CC = I->getCallingConv();
00640   const MCPhysReg *ScratchRegs = TLI.getScratchRegisters(CC);
00641   for (unsigned i = 0; ScratchRegs[i]; ++i)
00642     Ops.push_back(MachineOperand::CreateReg(
00643         ScratchRegs[i], /*IsDef=*/true, /*IsImp=*/true, /*IsKill=*/false,
00644         /*IsDead=*/false, /*IsUndef=*/false, /*IsEarlyClobber=*/true));
00645 
00646   // Issue CALLSEQ_START
00647   unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
00648   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
00649       .addImm(0);
00650 
00651   // Issue STACKMAP.
00652   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
00653                                     TII.get(TargetOpcode::STACKMAP));
00654   for (auto const &MO : Ops)
00655     MIB.addOperand(MO);
00656 
00657   // Issue CALLSEQ_END
00658   unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
00659   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
00660       .addImm(0)
00661       .addImm(0);
00662 
00663   // Inform the Frame Information that we have a stackmap in this function.
00664   FuncInfo.MF->getFrameInfo()->setHasStackMap();
00665 
00666   return true;
00667 }
00668 
00669 /// \brief Lower an argument list according to the target calling convention.
00670 ///
00671 /// This is a helper for lowering intrinsics that follow a target calling
00672 /// convention or require stack pointer adjustment. Only a subset of the
00673 /// intrinsic's operands need to participate in the calling convention.
00674 bool FastISel::lowerCallOperands(const CallInst *CI, unsigned ArgIdx,
00675                                  unsigned NumArgs, const Value *Callee,
00676                                  bool ForceRetVoidTy, CallLoweringInfo &CLI) {
00677   ArgListTy Args;
00678   Args.reserve(NumArgs);
00679 
00680   // Populate the argument list.
00681   // Attributes for args start at offset 1, after the return attribute.
00682   ImmutableCallSite CS(CI);
00683   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs, AttrI = ArgIdx + 1;
00684        ArgI != ArgE; ++ArgI) {
00685     Value *V = CI->getOperand(ArgI);
00686 
00687     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
00688 
00689     ArgListEntry Entry;
00690     Entry.Val = V;
00691     Entry.Ty = V->getType();
00692     Entry.setAttributes(&CS, AttrI);
00693     Args.push_back(Entry);
00694   }
00695 
00696   Type *RetTy = ForceRetVoidTy ? Type::getVoidTy(CI->getType()->getContext())
00697                                : CI->getType();
00698   CLI.setCallee(CI->getCallingConv(), RetTy, Callee, std::move(Args), NumArgs);
00699 
00700   return lowerCallTo(CLI);
00701 }
00702 
00703 bool FastISel::selectPatchpoint(const CallInst *I) {
00704   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
00705   //                                                 i32 <numBytes>,
00706   //                                                 i8* <target>,
00707   //                                                 i32 <numArgs>,
00708   //                                                 [Args...],
00709   //                                                 [live variables...])
00710   CallingConv::ID CC = I->getCallingConv();
00711   bool IsAnyRegCC = CC == CallingConv::AnyReg;
00712   bool HasDef = !I->getType()->isVoidTy();
00713   Value *Callee = I->getOperand(PatchPointOpers::TargetPos);
00714 
00715   // Get the real number of arguments participating in the call <numArgs>
00716   assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::NArgPos)) &&
00717          "Expected a constant integer.");
00718   const auto *NumArgsVal =
00719       cast<ConstantInt>(I->getOperand(PatchPointOpers::NArgPos));
00720   unsigned NumArgs = NumArgsVal->getZExtValue();
00721 
00722   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
00723   // This includes all meta-operands up to but not including CC.
00724   unsigned NumMetaOpers = PatchPointOpers::CCPos;
00725   assert(I->getNumArgOperands() >= NumMetaOpers + NumArgs &&
00726          "Not enough arguments provided to the patchpoint intrinsic");
00727 
00728   // For AnyRegCC the arguments are lowered later on manually.
00729   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
00730   CallLoweringInfo CLI;
00731   if (!lowerCallOperands(I, NumMetaOpers, NumCallArgs, Callee, IsAnyRegCC, CLI))
00732     return false;
00733 
00734   assert(CLI.Call && "No call instruction specified.");
00735 
00736   SmallVector<MachineOperand, 32> Ops;
00737 
00738   // Add an explicit result reg if we use the anyreg calling convention.
00739   if (IsAnyRegCC && HasDef) {
00740     assert(CLI.NumResultRegs == 0 && "Unexpected result register.");
00741     CLI.ResultReg = createResultReg(TLI.getRegClassFor(MVT::i64));
00742     CLI.NumResultRegs = 1;
00743     Ops.push_back(MachineOperand::CreateReg(CLI.ResultReg, /*IsDef=*/true));
00744   }
00745 
00746   // Add the <id> and <numBytes> constants.
00747   assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::IDPos)) &&
00748          "Expected a constant integer.");
00749   const auto *ID = cast<ConstantInt>(I->getOperand(PatchPointOpers::IDPos));
00750   Ops.push_back(MachineOperand::CreateImm(ID->getZExtValue()));
00751 
00752   assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos)) &&
00753          "Expected a constant integer.");
00754   const auto *NumBytes =
00755       cast<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos));
00756   Ops.push_back(MachineOperand::CreateImm(NumBytes->getZExtValue()));
00757 
00758   // Assume that the callee is a constant address or null pointer.
00759   // FIXME: handle function symbols in the future.
00760   uint64_t CalleeAddr;
00761   if (const auto *C = dyn_cast<IntToPtrInst>(Callee))
00762     CalleeAddr = cast<ConstantInt>(C->getOperand(0))->getZExtValue();
00763   else if (const auto *C = dyn_cast<ConstantExpr>(Callee)) {
00764     if (C->getOpcode() == Instruction::IntToPtr)
00765       CalleeAddr = cast<ConstantInt>(C->getOperand(0))->getZExtValue();
00766     else
00767       llvm_unreachable("Unsupported ConstantExpr.");
00768   } else if (isa<ConstantPointerNull>(Callee))
00769     CalleeAddr = 0;
00770   else
00771     llvm_unreachable("Unsupported callee address.");
00772 
00773   Ops.push_back(MachineOperand::CreateImm(CalleeAddr));
00774 
00775   // Adjust <numArgs> to account for any arguments that have been passed on
00776   // the stack instead.
00777   unsigned NumCallRegArgs = IsAnyRegCC ? NumArgs : CLI.OutRegs.size();
00778   Ops.push_back(MachineOperand::CreateImm(NumCallRegArgs));
00779 
00780   // Add the calling convention
00781   Ops.push_back(MachineOperand::CreateImm((unsigned)CC));
00782 
00783   // Add the arguments we omitted previously. The register allocator should
00784   // place these in any free register.
00785   if (IsAnyRegCC) {
00786     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) {
00787       unsigned Reg = getRegForValue(I->getArgOperand(i));
00788       if (!Reg)
00789         return false;
00790       Ops.push_back(MachineOperand::CreateReg(Reg, /*IsDef=*/false));
00791     }
00792   }
00793 
00794   // Push the arguments from the call instruction.
00795   for (auto Reg : CLI.OutRegs)
00796     Ops.push_back(MachineOperand::CreateReg(Reg, /*IsDef=*/false));
00797 
00798   // Push live variables for the stack map.
00799   if (!addStackMapLiveVars(Ops, I, NumMetaOpers + NumArgs))
00800     return false;
00801 
00802   // Push the register mask info.
00803   Ops.push_back(MachineOperand::CreateRegMask(TRI.getCallPreservedMask(CC)));
00804 
00805   // Add scratch registers as implicit def and early clobber.
00806   const MCPhysReg *ScratchRegs = TLI.getScratchRegisters(CC);
00807   for (unsigned i = 0; ScratchRegs[i]; ++i)
00808     Ops.push_back(MachineOperand::CreateReg(
00809         ScratchRegs[i], /*IsDef=*/true, /*IsImp=*/true, /*IsKill=*/false,
00810         /*IsDead=*/false, /*IsUndef=*/false, /*IsEarlyClobber=*/true));
00811 
00812   // Add implicit defs (return values).
00813   for (auto Reg : CLI.InRegs)
00814     Ops.push_back(MachineOperand::CreateReg(Reg, /*IsDef=*/true,
00815                                             /*IsImpl=*/true));
00816 
00817   // Insert the patchpoint instruction before the call generated by the target.
00818   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, CLI.Call, DbgLoc,
00819                                     TII.get(TargetOpcode::PATCHPOINT));
00820 
00821   for (auto &MO : Ops)
00822     MIB.addOperand(MO);
00823 
00824   MIB->setPhysRegsDeadExcept(CLI.InRegs, TRI);
00825 
00826   // Delete the original call instruction.
00827   CLI.Call->eraseFromParent();
00828 
00829   // Inform the Frame Information that we have a patchpoint in this function.
00830   FuncInfo.MF->getFrameInfo()->setHasPatchPoint();
00831 
00832   if (CLI.NumResultRegs)
00833     updateValueMap(I, CLI.ResultReg, CLI.NumResultRegs);
00834   return true;
00835 }
00836 
00837 /// Returns an AttributeSet representing the attributes applied to the return
00838 /// value of the given call.
00839 static AttributeSet getReturnAttrs(FastISel::CallLoweringInfo &CLI) {
00840   SmallVector<Attribute::AttrKind, 2> Attrs;
00841   if (CLI.RetSExt)
00842     Attrs.push_back(Attribute::SExt);
00843   if (CLI.RetZExt)
00844     Attrs.push_back(Attribute::ZExt);
00845   if (CLI.IsInReg)
00846     Attrs.push_back(Attribute::InReg);
00847 
00848   return AttributeSet::get(CLI.RetTy->getContext(), AttributeSet::ReturnIndex,
00849                            Attrs);
00850 }
00851 
00852 bool FastISel::lowerCallTo(const CallInst *CI, const char *SymName,
00853                            unsigned NumArgs) {
00854   ImmutableCallSite CS(CI);
00855 
00856   PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
00857   FunctionType *FTy = cast<FunctionType>(PT->getElementType());
00858   Type *RetTy = FTy->getReturnType();
00859 
00860   ArgListTy Args;
00861   Args.reserve(NumArgs);
00862 
00863   // Populate the argument list.
00864   // Attributes for args start at offset 1, after the return attribute.
00865   for (unsigned ArgI = 0; ArgI != NumArgs; ++ArgI) {
00866     Value *V = CI->getOperand(ArgI);
00867 
00868     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
00869 
00870     ArgListEntry Entry;
00871     Entry.Val = V;
00872     Entry.Ty = V->getType();
00873     Entry.setAttributes(&CS, ArgI + 1);
00874     Args.push_back(Entry);
00875   }
00876 
00877   CallLoweringInfo CLI;
00878   CLI.setCallee(RetTy, FTy, SymName, std::move(Args), CS, NumArgs);
00879 
00880   return lowerCallTo(CLI);
00881 }
00882 
00883 bool FastISel::lowerCallTo(CallLoweringInfo &CLI) {
00884   // Handle the incoming return values from the call.
00885   CLI.clearIns();
00886   SmallVector<EVT, 4> RetTys;
00887   ComputeValueVTs(TLI, CLI.RetTy, RetTys);
00888 
00889   SmallVector<ISD::OutputArg, 4> Outs;
00890   GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, TLI);
00891 
00892   bool CanLowerReturn = TLI.CanLowerReturn(
00893       CLI.CallConv, *FuncInfo.MF, CLI.IsVarArg, Outs, CLI.RetTy->getContext());
00894 
00895   // FIXME: sret demotion isn't supported yet - bail out.
00896   if (!CanLowerReturn)
00897     return false;
00898 
00899   for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
00900     EVT VT = RetTys[I];
00901     MVT RegisterVT = TLI.getRegisterType(CLI.RetTy->getContext(), VT);
00902     unsigned NumRegs = TLI.getNumRegisters(CLI.RetTy->getContext(), VT);
00903     for (unsigned i = 0; i != NumRegs; ++i) {
00904       ISD::InputArg MyFlags;
00905       MyFlags.VT = RegisterVT;
00906       MyFlags.ArgVT = VT;
00907       MyFlags.Used = CLI.IsReturnValueUsed;
00908       if (CLI.RetSExt)
00909         MyFlags.Flags.setSExt();
00910       if (CLI.RetZExt)
00911         MyFlags.Flags.setZExt();
00912       if (CLI.IsInReg)
00913         MyFlags.Flags.setInReg();
00914       CLI.Ins.push_back(MyFlags);
00915     }
00916   }
00917 
00918   // Handle all of the outgoing arguments.
00919   CLI.clearOuts();
00920   for (auto &Arg : CLI.getArgs()) {
00921     Type *FinalType = Arg.Ty;
00922     if (Arg.IsByVal)
00923       FinalType = cast<PointerType>(Arg.Ty)->getElementType();
00924     bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
00925         FinalType, CLI.CallConv, CLI.IsVarArg);
00926 
00927     ISD::ArgFlagsTy Flags;
00928     if (Arg.IsZExt)
00929       Flags.setZExt();
00930     if (Arg.IsSExt)
00931       Flags.setSExt();
00932     if (Arg.IsInReg)
00933       Flags.setInReg();
00934     if (Arg.IsSRet)
00935       Flags.setSRet();
00936     if (Arg.IsByVal)
00937       Flags.setByVal();
00938     if (Arg.IsInAlloca) {
00939       Flags.setInAlloca();
00940       // Set the byval flag for CCAssignFn callbacks that don't know about
00941       // inalloca. This way we can know how many bytes we should've allocated
00942       // and how many bytes a callee cleanup function will pop.  If we port
00943       // inalloca to more targets, we'll have to add custom inalloca handling in
00944       // the various CC lowering callbacks.
00945       Flags.setByVal();
00946     }
00947     if (Arg.IsByVal || Arg.IsInAlloca) {
00948       PointerType *Ty = cast<PointerType>(Arg.Ty);
00949       Type *ElementTy = Ty->getElementType();
00950       unsigned FrameSize = DL.getTypeAllocSize(ElementTy);
00951       // For ByVal, alignment should come from FE. BE will guess if this info is
00952       // not there, but there are cases it cannot get right.
00953       unsigned FrameAlign = Arg.Alignment;
00954       if (!FrameAlign)
00955         FrameAlign = TLI.getByValTypeAlignment(ElementTy);
00956       Flags.setByValSize(FrameSize);
00957       Flags.setByValAlign(FrameAlign);
00958     }
00959     if (Arg.IsNest)
00960       Flags.setNest();
00961     if (NeedsRegBlock)
00962       Flags.setInConsecutiveRegs();
00963     unsigned OriginalAlignment = DL.getABITypeAlignment(Arg.Ty);
00964     Flags.setOrigAlign(OriginalAlignment);
00965 
00966     CLI.OutVals.push_back(Arg.Val);
00967     CLI.OutFlags.push_back(Flags);
00968   }
00969 
00970   if (!fastLowerCall(CLI))
00971     return false;
00972 
00973   // Set all unused physreg defs as dead.
00974   assert(CLI.Call && "No call instruction specified.");
00975   CLI.Call->setPhysRegsDeadExcept(CLI.InRegs, TRI);
00976 
00977   if (CLI.NumResultRegs && CLI.CS)
00978     updateValueMap(CLI.CS->getInstruction(), CLI.ResultReg, CLI.NumResultRegs);
00979 
00980   return true;
00981 }
00982 
00983 bool FastISel::lowerCall(const CallInst *CI) {
00984   ImmutableCallSite CS(CI);
00985 
00986   PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
00987   FunctionType *FuncTy = cast<FunctionType>(PT->getElementType());
00988   Type *RetTy = FuncTy->getReturnType();
00989 
00990   ArgListTy Args;
00991   ArgListEntry Entry;
00992   Args.reserve(CS.arg_size());
00993 
00994   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
00995        i != e; ++i) {
00996     Value *V = *i;
00997 
00998     // Skip empty types
00999     if (V->getType()->isEmptyTy())
01000       continue;
01001 
01002     Entry.Val = V;
01003     Entry.Ty = V->getType();
01004 
01005     // Skip the first return-type Attribute to get to params.
01006     Entry.setAttributes(&CS, i - CS.arg_begin() + 1);
01007     Args.push_back(Entry);
01008   }
01009 
01010   // Check if target-independent constraints permit a tail call here.
01011   // Target-dependent constraints are checked within fastLowerCall.
01012   bool IsTailCall = CI->isTailCall();
01013   if (IsTailCall && !isInTailCallPosition(CS, TM))
01014     IsTailCall = false;
01015 
01016   CallLoweringInfo CLI;
01017   CLI.setCallee(RetTy, FuncTy, CI->getCalledValue(), std::move(Args), CS)
01018       .setTailCall(IsTailCall);
01019 
01020   return lowerCallTo(CLI);
01021 }
01022 
01023 bool FastISel::selectCall(const User *I) {
01024   const CallInst *Call = cast<CallInst>(I);
01025 
01026   // Handle simple inline asms.
01027   if (const InlineAsm *IA = dyn_cast<InlineAsm>(Call->getCalledValue())) {
01028     // If the inline asm has side effects, then make sure that no local value
01029     // lives across by flushing the local value map.
01030     if (IA->hasSideEffects())
01031       flushLocalValueMap();
01032 
01033     // Don't attempt to handle constraints.
01034     if (!IA->getConstraintString().empty())
01035       return false;
01036 
01037     unsigned ExtraInfo = 0;
01038     if (IA->hasSideEffects())
01039       ExtraInfo |= InlineAsm::Extra_HasSideEffects;
01040     if (IA->isAlignStack())
01041       ExtraInfo |= InlineAsm::Extra_IsAlignStack;
01042 
01043     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01044             TII.get(TargetOpcode::INLINEASM))
01045         .addExternalSymbol(IA->getAsmString().c_str())
01046         .addImm(ExtraInfo);
01047     return true;
01048   }
01049 
01050   MachineModuleInfo &MMI = FuncInfo.MF->getMMI();
01051   ComputeUsesVAFloatArgument(*Call, &MMI);
01052 
01053   // Handle intrinsic function calls.
01054   if (const auto *II = dyn_cast<IntrinsicInst>(Call))
01055     return selectIntrinsicCall(II);
01056 
01057   // Usually, it does not make sense to initialize a value,
01058   // make an unrelated function call and use the value, because
01059   // it tends to be spilled on the stack. So, we move the pointer
01060   // to the last local value to the beginning of the block, so that
01061   // all the values which have already been materialized,
01062   // appear after the call. It also makes sense to skip intrinsics
01063   // since they tend to be inlined.
01064   flushLocalValueMap();
01065 
01066   return lowerCall(Call);
01067 }
01068 
01069 bool FastISel::selectIntrinsicCall(const IntrinsicInst *II) {
01070   switch (II->getIntrinsicID()) {
01071   default:
01072     break;
01073   // At -O0 we don't care about the lifetime intrinsics.
01074   case Intrinsic::lifetime_start:
01075   case Intrinsic::lifetime_end:
01076   // The donothing intrinsic does, well, nothing.
01077   case Intrinsic::donothing:
01078     return true;
01079   case Intrinsic::dbg_declare: {
01080     const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
01081     DIVariable DIVar(DI->getVariable());
01082     assert((!DIVar || DIVar.isVariable()) &&
01083            "Variable in DbgDeclareInst should be either null or a DIVariable.");
01084     if (!DIVar || !FuncInfo.MF->getMMI().hasDebugInfo()) {
01085       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
01086       return true;
01087     }
01088 
01089     const Value *Address = DI->getAddress();
01090     if (!Address || isa<UndefValue>(Address)) {
01091       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
01092       return true;
01093     }
01094 
01095     unsigned Offset = 0;
01096     Optional<MachineOperand> Op;
01097     if (const auto *Arg = dyn_cast<Argument>(Address))
01098       // Some arguments' frame index is recorded during argument lowering.
01099       Offset = FuncInfo.getArgumentFrameIndex(Arg);
01100     if (Offset)
01101       Op = MachineOperand::CreateFI(Offset);
01102     if (!Op)
01103       if (unsigned Reg = lookUpRegForValue(Address))
01104         Op = MachineOperand::CreateReg(Reg, false);
01105 
01106     // If we have a VLA that has a "use" in a metadata node that's then used
01107     // here but it has no other uses, then we have a problem. E.g.,
01108     //
01109     //   int foo (const int *x) {
01110     //     char a[*x];
01111     //     return 0;
01112     //   }
01113     //
01114     // If we assign 'a' a vreg and fast isel later on has to use the selection
01115     // DAG isel, it will want to copy the value to the vreg. However, there are
01116     // no uses, which goes counter to what selection DAG isel expects.
01117     if (!Op && !Address->use_empty() && isa<Instruction>(Address) &&
01118         (!isa<AllocaInst>(Address) ||
01119          !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(Address))))
01120       Op = MachineOperand::CreateReg(FuncInfo.InitializeRegForValue(Address),
01121                                      false);
01122 
01123     if (Op) {
01124       if (Op->isReg()) {
01125         Op->setIsDebug(true);
01126         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01127                 TII.get(TargetOpcode::DBG_VALUE), false, Op->getReg(), 0,
01128                 DI->getVariable(), DI->getExpression());
01129       } else
01130         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01131                 TII.get(TargetOpcode::DBG_VALUE))
01132             .addOperand(*Op)
01133             .addImm(0)
01134             .addMetadata(DI->getVariable())
01135             .addMetadata(DI->getExpression());
01136     } else {
01137       // We can't yet handle anything else here because it would require
01138       // generating code, thus altering codegen because of debug info.
01139       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
01140     }
01141     return true;
01142   }
01143   case Intrinsic::dbg_value: {
01144     // This form of DBG_VALUE is target-independent.
01145     const DbgValueInst *DI = cast<DbgValueInst>(II);
01146     const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
01147     const Value *V = DI->getValue();
01148     if (!V) {
01149       // Currently the optimizer can produce this; insert an undef to
01150       // help debugging.  Probably the optimizer should not do this.
01151       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01152           .addReg(0U)
01153           .addImm(DI->getOffset())
01154           .addMetadata(DI->getVariable())
01155           .addMetadata(DI->getExpression());
01156     } else if (const auto *CI = dyn_cast<ConstantInt>(V)) {
01157       if (CI->getBitWidth() > 64)
01158         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01159             .addCImm(CI)
01160             .addImm(DI->getOffset())
01161             .addMetadata(DI->getVariable())
01162             .addMetadata(DI->getExpression());
01163       else
01164         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01165             .addImm(CI->getZExtValue())
01166             .addImm(DI->getOffset())
01167             .addMetadata(DI->getVariable())
01168             .addMetadata(DI->getExpression());
01169     } else if (const auto *CF = dyn_cast<ConstantFP>(V)) {
01170       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01171           .addFPImm(CF)
01172           .addImm(DI->getOffset())
01173           .addMetadata(DI->getVariable())
01174           .addMetadata(DI->getExpression());
01175     } else if (unsigned Reg = lookUpRegForValue(V)) {
01176       // FIXME: This does not handle register-indirect values at offset 0.
01177       bool IsIndirect = DI->getOffset() != 0;
01178       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, IsIndirect, Reg,
01179               DI->getOffset(), DI->getVariable(), DI->getExpression());
01180     } else {
01181       // We can't yet handle anything else here because it would require
01182       // generating code, thus altering codegen because of debug info.
01183       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
01184     }
01185     return true;
01186   }
01187   case Intrinsic::objectsize: {
01188     ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1));
01189     unsigned long long Res = CI->isZero() ? -1ULL : 0;
01190     Constant *ResCI = ConstantInt::get(II->getType(), Res);
01191     unsigned ResultReg = getRegForValue(ResCI);
01192     if (!ResultReg)
01193       return false;
01194     updateValueMap(II, ResultReg);
01195     return true;
01196   }
01197   case Intrinsic::expect: {
01198     unsigned ResultReg = getRegForValue(II->getArgOperand(0));
01199     if (!ResultReg)
01200       return false;
01201     updateValueMap(II, ResultReg);
01202     return true;
01203   }
01204   case Intrinsic::experimental_stackmap:
01205     return selectStackmap(II);
01206   case Intrinsic::experimental_patchpoint_void:
01207   case Intrinsic::experimental_patchpoint_i64:
01208     return selectPatchpoint(II);
01209   }
01210 
01211   return fastLowerIntrinsicCall(II);
01212 }
01213 
01214 bool FastISel::selectCast(const User *I, unsigned Opcode) {
01215   EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
01216   EVT DstVT = TLI.getValueType(I->getType());
01217 
01218   if (SrcVT == MVT::Other || !SrcVT.isSimple() || DstVT == MVT::Other ||
01219       !DstVT.isSimple())
01220     // Unhandled type. Halt "fast" selection and bail.
01221     return false;
01222 
01223   // Check if the destination type is legal.
01224   if (!TLI.isTypeLegal(DstVT))
01225     return false;
01226 
01227   // Check if the source operand is legal.
01228   if (!TLI.isTypeLegal(SrcVT))
01229     return false;
01230 
01231   unsigned InputReg = getRegForValue(I->getOperand(0));
01232   if (!InputReg)
01233     // Unhandled operand.  Halt "fast" selection and bail.
01234     return false;
01235 
01236   bool InputRegIsKill = hasTrivialKill(I->getOperand(0));
01237 
01238   unsigned ResultReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(),
01239                                   Opcode, InputReg, InputRegIsKill);
01240   if (!ResultReg)
01241     return false;
01242 
01243   updateValueMap(I, ResultReg);
01244   return true;
01245 }
01246 
01247 bool FastISel::selectBitCast(const User *I) {
01248   // If the bitcast doesn't change the type, just use the operand value.
01249   if (I->getType() == I->getOperand(0)->getType()) {
01250     unsigned Reg = getRegForValue(I->getOperand(0));
01251     if (!Reg)
01252       return false;
01253     updateValueMap(I, Reg);
01254     return true;
01255   }
01256 
01257   // Bitcasts of other values become reg-reg copies or BITCAST operators.
01258   EVT SrcEVT = TLI.getValueType(I->getOperand(0)->getType());
01259   EVT DstEVT = TLI.getValueType(I->getType());
01260   if (SrcEVT == MVT::Other || DstEVT == MVT::Other ||
01261       !TLI.isTypeLegal(SrcEVT) || !TLI.isTypeLegal(DstEVT))
01262     // Unhandled type. Halt "fast" selection and bail.
01263     return false;
01264 
01265   MVT SrcVT = SrcEVT.getSimpleVT();
01266   MVT DstVT = DstEVT.getSimpleVT();
01267   unsigned Op0 = getRegForValue(I->getOperand(0));
01268   if (!Op0) // Unhandled operand. Halt "fast" selection and bail.
01269     return false;
01270   bool Op0IsKill = hasTrivialKill(I->getOperand(0));
01271 
01272   // First, try to perform the bitcast by inserting a reg-reg copy.
01273   unsigned ResultReg = 0;
01274   if (SrcVT == DstVT) {
01275     const TargetRegisterClass *SrcClass = TLI.getRegClassFor(SrcVT);
01276     const TargetRegisterClass *DstClass = TLI.getRegClassFor(DstVT);
01277     // Don't attempt a cross-class copy. It will likely fail.
01278     if (SrcClass == DstClass) {
01279       ResultReg = createResultReg(DstClass);
01280       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01281               TII.get(TargetOpcode::COPY), ResultReg).addReg(Op0);
01282     }
01283   }
01284 
01285   // If the reg-reg copy failed, select a BITCAST opcode.
01286   if (!ResultReg)
01287     ResultReg = fastEmit_r(SrcVT, DstVT, ISD::BITCAST, Op0, Op0IsKill);
01288 
01289   if (!ResultReg)
01290     return false;
01291 
01292   updateValueMap(I, ResultReg);
01293   return true;
01294 }
01295 
01296 bool FastISel::selectInstruction(const Instruction *I) {
01297   // Just before the terminator instruction, insert instructions to
01298   // feed PHI nodes in successor blocks.
01299   if (isa<TerminatorInst>(I))
01300     if (!handlePHINodesInSuccessorBlocks(I->getParent()))
01301       return false;
01302 
01303   DbgLoc = I->getDebugLoc();
01304 
01305   SavedInsertPt = FuncInfo.InsertPt;
01306 
01307   if (const auto *Call = dyn_cast<CallInst>(I)) {
01308     const Function *F = Call->getCalledFunction();
01309     LibFunc::Func Func;
01310 
01311     // As a special case, don't handle calls to builtin library functions that
01312     // may be translated directly to target instructions.
01313     if (F && !F->hasLocalLinkage() && F->hasName() &&
01314         LibInfo->getLibFunc(F->getName(), Func) &&
01315         LibInfo->hasOptimizedCodeGen(Func))
01316       return false;
01317 
01318     // Don't handle Intrinsic::trap if a trap funciton is specified.
01319     if (F && F->getIntrinsicID() == Intrinsic::trap &&
01320         !TM.Options.getTrapFunctionName().empty())
01321       return false;
01322   }
01323 
01324   // First, try doing target-independent selection.
01325   if (!SkipTargetIndependentISel) {
01326     if (selectOperator(I, I->getOpcode())) {
01327       ++NumFastIselSuccessIndependent;
01328       DbgLoc = DebugLoc();
01329       return true;
01330     }
01331     // Remove dead code.
01332     recomputeInsertPt();
01333     if (SavedInsertPt != FuncInfo.InsertPt)
01334       removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
01335     SavedInsertPt = FuncInfo.InsertPt;
01336   }
01337   // Next, try calling the target to attempt to handle the instruction.
01338   if (fastSelectInstruction(I)) {
01339     ++NumFastIselSuccessTarget;
01340     DbgLoc = DebugLoc();
01341     return true;
01342   }
01343   // Remove dead code.
01344   recomputeInsertPt();
01345   if (SavedInsertPt != FuncInfo.InsertPt)
01346     removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
01347 
01348   DbgLoc = DebugLoc();
01349   // Undo phi node updates, because they will be added again by SelectionDAG.
01350   if (isa<TerminatorInst>(I))
01351     FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate);
01352   return false;
01353 }
01354 
01355 /// Emit an unconditional branch to the given block, unless it is the immediate
01356 /// (fall-through) successor, and update the CFG.
01357 void FastISel::fastEmitBranch(MachineBasicBlock *MSucc, DebugLoc DbgLoc) {
01358   if (FuncInfo.MBB->getBasicBlock()->size() > 1 &&
01359       FuncInfo.MBB->isLayoutSuccessor(MSucc)) {
01360     // For more accurate line information if this is the only instruction
01361     // in the block then emit it, otherwise we have the unconditional
01362     // fall-through case, which needs no instructions.
01363   } else {
01364     // The unconditional branch case.
01365     TII.InsertBranch(*FuncInfo.MBB, MSucc, nullptr,
01366                      SmallVector<MachineOperand, 0>(), DbgLoc);
01367   }
01368   uint32_t BranchWeight = 0;
01369   if (FuncInfo.BPI)
01370     BranchWeight = FuncInfo.BPI->getEdgeWeight(FuncInfo.MBB->getBasicBlock(),
01371                                                MSucc->getBasicBlock());
01372   FuncInfo.MBB->addSuccessor(MSucc, BranchWeight);
01373 }
01374 
01375 /// Emit an FNeg operation.
01376 bool FastISel::selectFNeg(const User *I) {
01377   unsigned OpReg = getRegForValue(BinaryOperator::getFNegArgument(I));
01378   if (!OpReg)
01379     return false;
01380   bool OpRegIsKill = hasTrivialKill(I);
01381 
01382   // If the target has ISD::FNEG, use it.
01383   EVT VT = TLI.getValueType(I->getType());
01384   unsigned ResultReg = fastEmit_r(VT.getSimpleVT(), VT.getSimpleVT(), ISD::FNEG,
01385                                   OpReg, OpRegIsKill);
01386   if (ResultReg) {
01387     updateValueMap(I, ResultReg);
01388     return true;
01389   }
01390 
01391   // Bitcast the value to integer, twiddle the sign bit with xor,
01392   // and then bitcast it back to floating-point.
01393   if (VT.getSizeInBits() > 64)
01394     return false;
01395   EVT IntVT = EVT::getIntegerVT(I->getContext(), VT.getSizeInBits());
01396   if (!TLI.isTypeLegal(IntVT))
01397     return false;
01398 
01399   unsigned IntReg = fastEmit_r(VT.getSimpleVT(), IntVT.getSimpleVT(),
01400                                ISD::BITCAST, OpReg, OpRegIsKill);
01401   if (!IntReg)
01402     return false;
01403 
01404   unsigned IntResultReg = fastEmit_ri_(
01405       IntVT.getSimpleVT(), ISD::XOR, IntReg, /*IsKill=*/true,
01406       UINT64_C(1) << (VT.getSizeInBits() - 1), IntVT.getSimpleVT());
01407   if (!IntResultReg)
01408     return false;
01409 
01410   ResultReg = fastEmit_r(IntVT.getSimpleVT(), VT.getSimpleVT(), ISD::BITCAST,
01411                          IntResultReg, /*IsKill=*/true);
01412   if (!ResultReg)
01413     return false;
01414 
01415   updateValueMap(I, ResultReg);
01416   return true;
01417 }
01418 
01419 bool FastISel::selectExtractValue(const User *U) {
01420   const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(U);
01421   if (!EVI)
01422     return false;
01423 
01424   // Make sure we only try to handle extracts with a legal result.  But also
01425   // allow i1 because it's easy.
01426   EVT RealVT = TLI.getValueType(EVI->getType(), /*AllowUnknown=*/true);
01427   if (!RealVT.isSimple())
01428     return false;
01429   MVT VT = RealVT.getSimpleVT();
01430   if (!TLI.isTypeLegal(VT) && VT != MVT::i1)
01431     return false;
01432 
01433   const Value *Op0 = EVI->getOperand(0);
01434   Type *AggTy = Op0->getType();
01435 
01436   // Get the base result register.
01437   unsigned ResultReg;
01438   DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(Op0);
01439   if (I != FuncInfo.ValueMap.end())
01440     ResultReg = I->second;
01441   else if (isa<Instruction>(Op0))
01442     ResultReg = FuncInfo.InitializeRegForValue(Op0);
01443   else
01444     return false; // fast-isel can't handle aggregate constants at the moment
01445 
01446   // Get the actual result register, which is an offset from the base register.
01447   unsigned VTIndex = ComputeLinearIndex(AggTy, EVI->getIndices());
01448 
01449   SmallVector<EVT, 4> AggValueVTs;
01450   ComputeValueVTs(TLI, AggTy, AggValueVTs);
01451 
01452   for (unsigned i = 0; i < VTIndex; i++)
01453     ResultReg += TLI.getNumRegisters(FuncInfo.Fn->getContext(), AggValueVTs[i]);
01454 
01455   updateValueMap(EVI, ResultReg);
01456   return true;
01457 }
01458 
01459 bool FastISel::selectOperator(const User *I, unsigned Opcode) {
01460   switch (Opcode) {
01461   case Instruction::Add:
01462     return selectBinaryOp(I, ISD::ADD);
01463   case Instruction::FAdd:
01464     return selectBinaryOp(I, ISD::FADD);
01465   case Instruction::Sub:
01466     return selectBinaryOp(I, ISD::SUB);
01467   case Instruction::FSub:
01468     // FNeg is currently represented in LLVM IR as a special case of FSub.
01469     if (BinaryOperator::isFNeg(I))
01470       return selectFNeg(I);
01471     return selectBinaryOp(I, ISD::FSUB);
01472   case Instruction::Mul:
01473     return selectBinaryOp(I, ISD::MUL);
01474   case Instruction::FMul:
01475     return selectBinaryOp(I, ISD::FMUL);
01476   case Instruction::SDiv:
01477     return selectBinaryOp(I, ISD::SDIV);
01478   case Instruction::UDiv:
01479     return selectBinaryOp(I, ISD::UDIV);
01480   case Instruction::FDiv:
01481     return selectBinaryOp(I, ISD::FDIV);
01482   case Instruction::SRem:
01483     return selectBinaryOp(I, ISD::SREM);
01484   case Instruction::URem:
01485     return selectBinaryOp(I, ISD::UREM);
01486   case Instruction::FRem:
01487     return selectBinaryOp(I, ISD::FREM);
01488   case Instruction::Shl:
01489     return selectBinaryOp(I, ISD::SHL);
01490   case Instruction::LShr:
01491     return selectBinaryOp(I, ISD::SRL);
01492   case Instruction::AShr:
01493     return selectBinaryOp(I, ISD::SRA);
01494   case Instruction::And:
01495     return selectBinaryOp(I, ISD::AND);
01496   case Instruction::Or:
01497     return selectBinaryOp(I, ISD::OR);
01498   case Instruction::Xor:
01499     return selectBinaryOp(I, ISD::XOR);
01500 
01501   case Instruction::GetElementPtr:
01502     return selectGetElementPtr(I);
01503 
01504   case Instruction::Br: {
01505     const BranchInst *BI = cast<BranchInst>(I);
01506 
01507     if (BI->isUnconditional()) {
01508       const BasicBlock *LLVMSucc = BI->getSuccessor(0);
01509       MachineBasicBlock *MSucc = FuncInfo.MBBMap[LLVMSucc];
01510       fastEmitBranch(MSucc, BI->getDebugLoc());
01511       return true;
01512     }
01513 
01514     // Conditional branches are not handed yet.
01515     // Halt "fast" selection and bail.
01516     return false;
01517   }
01518 
01519   case Instruction::Unreachable:
01520     if (TM.Options.TrapUnreachable)
01521       return fastEmit_(MVT::Other, MVT::Other, ISD::TRAP) != 0;
01522     else
01523       return true;
01524 
01525   case Instruction::Alloca:
01526     // FunctionLowering has the static-sized case covered.
01527     if (FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(I)))
01528       return true;
01529 
01530     // Dynamic-sized alloca is not handled yet.
01531     return false;
01532 
01533   case Instruction::Call:
01534     return selectCall(I);
01535 
01536   case Instruction::BitCast:
01537     return selectBitCast(I);
01538 
01539   case Instruction::FPToSI:
01540     return selectCast(I, ISD::FP_TO_SINT);
01541   case Instruction::ZExt:
01542     return selectCast(I, ISD::ZERO_EXTEND);
01543   case Instruction::SExt:
01544     return selectCast(I, ISD::SIGN_EXTEND);
01545   case Instruction::Trunc:
01546     return selectCast(I, ISD::TRUNCATE);
01547   case Instruction::SIToFP:
01548     return selectCast(I, ISD::SINT_TO_FP);
01549 
01550   case Instruction::IntToPtr: // Deliberate fall-through.
01551   case Instruction::PtrToInt: {
01552     EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
01553     EVT DstVT = TLI.getValueType(I->getType());
01554     if (DstVT.bitsGT(SrcVT))
01555       return selectCast(I, ISD::ZERO_EXTEND);
01556     if (DstVT.bitsLT(SrcVT))
01557       return selectCast(I, ISD::TRUNCATE);
01558     unsigned Reg = getRegForValue(I->getOperand(0));
01559     if (!Reg)
01560       return false;
01561     updateValueMap(I, Reg);
01562     return true;
01563   }
01564 
01565   case Instruction::ExtractValue:
01566     return selectExtractValue(I);
01567 
01568   case Instruction::PHI:
01569     llvm_unreachable("FastISel shouldn't visit PHI nodes!");
01570 
01571   default:
01572     // Unhandled instruction. Halt "fast" selection and bail.
01573     return false;
01574   }
01575 }
01576 
01577 FastISel::FastISel(FunctionLoweringInfo &FuncInfo,
01578                    const TargetLibraryInfo *LibInfo,
01579                    bool SkipTargetIndependentISel)
01580     : FuncInfo(FuncInfo), MF(FuncInfo.MF), MRI(FuncInfo.MF->getRegInfo()),
01581       MFI(*FuncInfo.MF->getFrameInfo()), MCP(*FuncInfo.MF->getConstantPool()),
01582       TM(FuncInfo.MF->getTarget()), DL(*MF->getSubtarget().getDataLayout()),
01583       TII(*MF->getSubtarget().getInstrInfo()),
01584       TLI(*MF->getSubtarget().getTargetLowering()),
01585       TRI(*MF->getSubtarget().getRegisterInfo()), LibInfo(LibInfo),
01586       SkipTargetIndependentISel(SkipTargetIndependentISel) {}
01587 
01588 FastISel::~FastISel() {}
01589 
01590 bool FastISel::fastLowerArguments() { return false; }
01591 
01592 bool FastISel::fastLowerCall(CallLoweringInfo & /*CLI*/) { return false; }
01593 
01594 bool FastISel::fastLowerIntrinsicCall(const IntrinsicInst * /*II*/) {
01595   return false;
01596 }
01597 
01598 unsigned FastISel::fastEmit_(MVT, MVT, unsigned) { return 0; }
01599 
01600 unsigned FastISel::fastEmit_r(MVT, MVT, unsigned, unsigned /*Op0*/,
01601                               bool /*Op0IsKill*/) {
01602   return 0;
01603 }
01604 
01605 unsigned FastISel::fastEmit_rr(MVT, MVT, unsigned, unsigned /*Op0*/,
01606                                bool /*Op0IsKill*/, unsigned /*Op1*/,
01607                                bool /*Op1IsKill*/) {
01608   return 0;
01609 }
01610 
01611 unsigned FastISel::fastEmit_i(MVT, MVT, unsigned, uint64_t /*Imm*/) {
01612   return 0;
01613 }
01614 
01615 unsigned FastISel::fastEmit_f(MVT, MVT, unsigned,
01616                               const ConstantFP * /*FPImm*/) {
01617   return 0;
01618 }
01619 
01620 unsigned FastISel::fastEmit_ri(MVT, MVT, unsigned, unsigned /*Op0*/,
01621                                bool /*Op0IsKill*/, uint64_t /*Imm*/) {
01622   return 0;
01623 }
01624 
01625 unsigned FastISel::fastEmit_rf(MVT, MVT, unsigned, unsigned /*Op0*/,
01626                                bool /*Op0IsKill*/,
01627                                const ConstantFP * /*FPImm*/) {
01628   return 0;
01629 }
01630 
01631 unsigned FastISel::fastEmit_rri(MVT, MVT, unsigned, unsigned /*Op0*/,
01632                                 bool /*Op0IsKill*/, unsigned /*Op1*/,
01633                                 bool /*Op1IsKill*/, uint64_t /*Imm*/) {
01634   return 0;
01635 }
01636 
01637 /// This method is a wrapper of fastEmit_ri. It first tries to emit an
01638 /// instruction with an immediate operand using fastEmit_ri.
01639 /// If that fails, it materializes the immediate into a register and try
01640 /// fastEmit_rr instead.
01641 unsigned FastISel::fastEmit_ri_(MVT VT, unsigned Opcode, unsigned Op0,
01642                                 bool Op0IsKill, uint64_t Imm, MVT ImmType) {
01643   // If this is a multiply by a power of two, emit this as a shift left.
01644   if (Opcode == ISD::MUL && isPowerOf2_64(Imm)) {
01645     Opcode = ISD::SHL;
01646     Imm = Log2_64(Imm);
01647   } else if (Opcode == ISD::UDIV && isPowerOf2_64(Imm)) {
01648     // div x, 8 -> srl x, 3
01649     Opcode = ISD::SRL;
01650     Imm = Log2_64(Imm);
01651   }
01652 
01653   // Horrible hack (to be removed), check to make sure shift amounts are
01654   // in-range.
01655   if ((Opcode == ISD::SHL || Opcode == ISD::SRA || Opcode == ISD::SRL) &&
01656       Imm >= VT.getSizeInBits())
01657     return 0;
01658 
01659   // First check if immediate type is legal. If not, we can't use the ri form.
01660   unsigned ResultReg = fastEmit_ri(VT, VT, Opcode, Op0, Op0IsKill, Imm);
01661   if (ResultReg)
01662     return ResultReg;
01663   unsigned MaterialReg = fastEmit_i(ImmType, ImmType, ISD::Constant, Imm);
01664   if (!MaterialReg) {
01665     // This is a bit ugly/slow, but failing here means falling out of
01666     // fast-isel, which would be very slow.
01667     IntegerType *ITy =
01668         IntegerType::get(FuncInfo.Fn->getContext(), VT.getSizeInBits());
01669     MaterialReg = getRegForValue(ConstantInt::get(ITy, Imm));
01670     if (!MaterialReg)
01671       return 0;
01672   }
01673   return fastEmit_rr(VT, VT, Opcode, Op0, Op0IsKill, MaterialReg,
01674                      /*IsKill=*/true);
01675 }
01676 
01677 unsigned FastISel::createResultReg(const TargetRegisterClass *RC) {
01678   return MRI.createVirtualRegister(RC);
01679 }
01680 
01681 unsigned FastISel::constrainOperandRegClass(const MCInstrDesc &II, unsigned Op,
01682                                             unsigned OpNum) {
01683   if (TargetRegisterInfo::isVirtualRegister(Op)) {
01684     const TargetRegisterClass *RegClass =
01685         TII.getRegClass(II, OpNum, &TRI, *FuncInfo.MF);
01686     if (!MRI.constrainRegClass(Op, RegClass)) {
01687       // If it's not legal to COPY between the register classes, something
01688       // has gone very wrong before we got here.
01689       unsigned NewOp = createResultReg(RegClass);
01690       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01691               TII.get(TargetOpcode::COPY), NewOp).addReg(Op);
01692       return NewOp;
01693     }
01694   }
01695   return Op;
01696 }
01697 
01698 unsigned FastISel::fastEmitInst_(unsigned MachineInstOpcode,
01699                                  const TargetRegisterClass *RC) {
01700   unsigned ResultReg = createResultReg(RC);
01701   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01702 
01703   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg);
01704   return ResultReg;
01705 }
01706 
01707 unsigned FastISel::fastEmitInst_r(unsigned MachineInstOpcode,
01708                                   const TargetRegisterClass *RC, unsigned Op0,
01709                                   bool Op0IsKill) {
01710   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01711 
01712   unsigned ResultReg = createResultReg(RC);
01713   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
01714 
01715   if (II.getNumDefs() >= 1)
01716     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
01717         .addReg(Op0, getKillRegState(Op0IsKill));
01718   else {
01719     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01720         .addReg(Op0, getKillRegState(Op0IsKill));
01721     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01722             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01723   }
01724 
01725   return ResultReg;
01726 }
01727 
01728 unsigned FastISel::fastEmitInst_rr(unsigned MachineInstOpcode,
01729                                    const TargetRegisterClass *RC, unsigned Op0,
01730                                    bool Op0IsKill, unsigned Op1,
01731                                    bool Op1IsKill) {
01732   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01733 
01734   unsigned ResultReg = createResultReg(RC);
01735   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
01736   Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
01737 
01738   if (II.getNumDefs() >= 1)
01739     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
01740         .addReg(Op0, getKillRegState(Op0IsKill))
01741         .addReg(Op1, getKillRegState(Op1IsKill));
01742   else {
01743     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01744         .addReg(Op0, getKillRegState(Op0IsKill))
01745         .addReg(Op1, getKillRegState(Op1IsKill));
01746     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01747             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01748   }
01749   return ResultReg;
01750 }
01751 
01752 unsigned FastISel::fastEmitInst_rrr(unsigned MachineInstOpcode,
01753                                     const TargetRegisterClass *RC, unsigned Op0,
01754                                     bool Op0IsKill, unsigned Op1,
01755                                     bool Op1IsKill, unsigned Op2,
01756                                     bool Op2IsKill) {
01757   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01758 
01759   unsigned ResultReg = createResultReg(RC);
01760   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
01761   Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
01762   Op2 = constrainOperandRegClass(II, Op2, II.getNumDefs() + 2);
01763 
01764   if (II.getNumDefs() >= 1)
01765     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
01766         .addReg(Op0, getKillRegState(Op0IsKill))
01767         .addReg(Op1, getKillRegState(Op1IsKill))
01768         .addReg(Op2, getKillRegState(Op2IsKill));
01769   else {
01770     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01771         .addReg(Op0, getKillRegState(Op0IsKill))
01772         .addReg(Op1, getKillRegState(Op1IsKill))
01773         .addReg(Op2, getKillRegState(Op2IsKill));
01774     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01775             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01776   }
01777   return ResultReg;
01778 }
01779 
01780 unsigned FastISel::fastEmitInst_ri(unsigned MachineInstOpcode,
01781                                    const TargetRegisterClass *RC, unsigned Op0,
01782                                    bool Op0IsKill, uint64_t Imm) {
01783   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01784 
01785   unsigned ResultReg = createResultReg(RC);
01786   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
01787 
01788   if (II.getNumDefs() >= 1)
01789     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
01790         .addReg(Op0, getKillRegState(Op0IsKill))
01791         .addImm(Imm);
01792   else {
01793     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01794         .addReg(Op0, getKillRegState(Op0IsKill))
01795         .addImm(Imm);
01796     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01797             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01798   }
01799   return ResultReg;
01800 }
01801 
01802 unsigned FastISel::fastEmitInst_rii(unsigned MachineInstOpcode,
01803                                     const TargetRegisterClass *RC, unsigned Op0,
01804                                     bool Op0IsKill, uint64_t Imm1,
01805                                     uint64_t Imm2) {
01806   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01807 
01808   unsigned ResultReg = createResultReg(RC);
01809   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
01810 
01811   if (II.getNumDefs() >= 1)
01812     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
01813         .addReg(Op0, getKillRegState(Op0IsKill))
01814         .addImm(Imm1)
01815         .addImm(Imm2);
01816   else {
01817     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01818         .addReg(Op0, getKillRegState(Op0IsKill))
01819         .addImm(Imm1)
01820         .addImm(Imm2);
01821     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01822             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01823   }
01824   return ResultReg;
01825 }
01826 
01827 unsigned FastISel::fastEmitInst_rf(unsigned MachineInstOpcode,
01828                                    const TargetRegisterClass *RC, unsigned Op0,
01829                                    bool Op0IsKill, const ConstantFP *FPImm) {
01830   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01831 
01832   unsigned ResultReg = createResultReg(RC);
01833   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
01834 
01835   if (II.getNumDefs() >= 1)
01836     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
01837         .addReg(Op0, getKillRegState(Op0IsKill))
01838         .addFPImm(FPImm);
01839   else {
01840     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01841         .addReg(Op0, getKillRegState(Op0IsKill))
01842         .addFPImm(FPImm);
01843     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01844             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01845   }
01846   return ResultReg;
01847 }
01848 
01849 unsigned FastISel::fastEmitInst_rri(unsigned MachineInstOpcode,
01850                                     const TargetRegisterClass *RC, unsigned Op0,
01851                                     bool Op0IsKill, unsigned Op1,
01852                                     bool Op1IsKill, uint64_t Imm) {
01853   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01854 
01855   unsigned ResultReg = createResultReg(RC);
01856   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
01857   Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
01858 
01859   if (II.getNumDefs() >= 1)
01860     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
01861         .addReg(Op0, getKillRegState(Op0IsKill))
01862         .addReg(Op1, getKillRegState(Op1IsKill))
01863         .addImm(Imm);
01864   else {
01865     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01866         .addReg(Op0, getKillRegState(Op0IsKill))
01867         .addReg(Op1, getKillRegState(Op1IsKill))
01868         .addImm(Imm);
01869     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01870             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01871   }
01872   return ResultReg;
01873 }
01874 
01875 unsigned FastISel::fastEmitInst_rrii(unsigned MachineInstOpcode,
01876                                      const TargetRegisterClass *RC,
01877                                      unsigned Op0, bool Op0IsKill, unsigned Op1,
01878                                      bool Op1IsKill, uint64_t Imm1,
01879                                      uint64_t Imm2) {
01880   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01881 
01882   unsigned ResultReg = createResultReg(RC);
01883   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
01884   Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
01885 
01886   if (II.getNumDefs() >= 1)
01887     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
01888         .addReg(Op0, getKillRegState(Op0IsKill))
01889         .addReg(Op1, getKillRegState(Op1IsKill))
01890         .addImm(Imm1)
01891         .addImm(Imm2);
01892   else {
01893     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01894         .addReg(Op0, getKillRegState(Op0IsKill))
01895         .addReg(Op1, getKillRegState(Op1IsKill))
01896         .addImm(Imm1)
01897         .addImm(Imm2);
01898     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01899             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01900   }
01901   return ResultReg;
01902 }
01903 
01904 unsigned FastISel::fastEmitInst_i(unsigned MachineInstOpcode,
01905                                   const TargetRegisterClass *RC, uint64_t Imm) {
01906   unsigned ResultReg = createResultReg(RC);
01907   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01908 
01909   if (II.getNumDefs() >= 1)
01910     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
01911         .addImm(Imm);
01912   else {
01913     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addImm(Imm);
01914     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01915             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01916   }
01917   return ResultReg;
01918 }
01919 
01920 unsigned FastISel::fastEmitInst_ii(unsigned MachineInstOpcode,
01921                                    const TargetRegisterClass *RC, uint64_t Imm1,
01922                                    uint64_t Imm2) {
01923   unsigned ResultReg = createResultReg(RC);
01924   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01925 
01926   if (II.getNumDefs() >= 1)
01927     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
01928         .addImm(Imm1)
01929         .addImm(Imm2);
01930   else {
01931     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addImm(Imm1)
01932         .addImm(Imm2);
01933     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01934             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01935   }
01936   return ResultReg;
01937 }
01938 
01939 unsigned FastISel::fastEmitInst_extractsubreg(MVT RetVT, unsigned Op0,
01940                                               bool Op0IsKill, uint32_t Idx) {
01941   unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
01942   assert(TargetRegisterInfo::isVirtualRegister(Op0) &&
01943          "Cannot yet extract from physregs");
01944   const TargetRegisterClass *RC = MRI.getRegClass(Op0);
01945   MRI.constrainRegClass(Op0, TRI.getSubClassWithSubReg(RC, Idx));
01946   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
01947           ResultReg).addReg(Op0, getKillRegState(Op0IsKill), Idx);
01948   return ResultReg;
01949 }
01950 
01951 /// Emit MachineInstrs to compute the value of Op with all but the least
01952 /// significant bit set to zero.
01953 unsigned FastISel::fastEmitZExtFromI1(MVT VT, unsigned Op0, bool Op0IsKill) {
01954   return fastEmit_ri(VT, VT, ISD::AND, Op0, Op0IsKill, 1);
01955 }
01956 
01957 /// HandlePHINodesInSuccessorBlocks - Handle PHI nodes in successor blocks.
01958 /// Emit code to ensure constants are copied into registers when needed.
01959 /// Remember the virtual registers that need to be added to the Machine PHI
01960 /// nodes as input.  We cannot just directly add them, because expansion
01961 /// might result in multiple MBB's for one BB.  As such, the start of the
01962 /// BB might correspond to a different MBB than the end.
01963 bool FastISel::handlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
01964   const TerminatorInst *TI = LLVMBB->getTerminator();
01965 
01966   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
01967   FuncInfo.OrigNumPHINodesToUpdate = FuncInfo.PHINodesToUpdate.size();
01968 
01969   // Check successor nodes' PHI nodes that expect a constant to be available
01970   // from this block.
01971   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
01972     const BasicBlock *SuccBB = TI->getSuccessor(succ);
01973     if (!isa<PHINode>(SuccBB->begin()))
01974       continue;
01975     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
01976 
01977     // If this terminator has multiple identical successors (common for
01978     // switches), only handle each succ once.
01979     if (!SuccsHandled.insert(SuccMBB))
01980       continue;
01981 
01982     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
01983 
01984     // At this point we know that there is a 1-1 correspondence between LLVM PHI
01985     // nodes and Machine PHI nodes, but the incoming operands have not been
01986     // emitted yet.
01987     for (BasicBlock::const_iterator I = SuccBB->begin();
01988          const auto *PN = dyn_cast<PHINode>(I); ++I) {
01989 
01990       // Ignore dead phi's.
01991       if (PN->use_empty())
01992         continue;
01993 
01994       // Only handle legal types. Two interesting things to note here. First,
01995       // by bailing out early, we may leave behind some dead instructions,
01996       // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
01997       // own moves. Second, this check is necessary because FastISel doesn't
01998       // use CreateRegs to create registers, so it always creates
01999       // exactly one register for each non-void instruction.
02000       EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
02001       if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
02002         // Handle integer promotions, though, because they're common and easy.
02003         if (!(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)) {
02004           FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate);
02005           return false;
02006         }
02007       }
02008 
02009       const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
02010 
02011       // Set the DebugLoc for the copy. Prefer the location of the operand
02012       // if there is one; use the location of the PHI otherwise.
02013       DbgLoc = PN->getDebugLoc();
02014       if (const auto *Inst = dyn_cast<Instruction>(PHIOp))
02015         DbgLoc = Inst->getDebugLoc();
02016 
02017       unsigned Reg = getRegForValue(PHIOp);
02018       if (!Reg) {
02019         FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate);
02020         return false;
02021       }
02022       FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
02023       DbgLoc = DebugLoc();
02024     }
02025   }
02026 
02027   return true;
02028 }
02029 
02030 bool FastISel::tryToFoldLoad(const LoadInst *LI, const Instruction *FoldInst) {
02031   assert(LI->hasOneUse() &&
02032          "tryToFoldLoad expected a LoadInst with a single use");
02033   // We know that the load has a single use, but don't know what it is.  If it
02034   // isn't one of the folded instructions, then we can't succeed here.  Handle
02035   // this by scanning the single-use users of the load until we get to FoldInst.
02036   unsigned MaxUsers = 6; // Don't scan down huge single-use chains of instrs.
02037 
02038   const Instruction *TheUser = LI->user_back();
02039   while (TheUser != FoldInst && // Scan up until we find FoldInst.
02040          // Stay in the right block.
02041          TheUser->getParent() == FoldInst->getParent() &&
02042          --MaxUsers) { // Don't scan too far.
02043     // If there are multiple or no uses of this instruction, then bail out.
02044     if (!TheUser->hasOneUse())
02045       return false;
02046 
02047     TheUser = TheUser->user_back();
02048   }
02049 
02050   // If we didn't find the fold instruction, then we failed to collapse the
02051   // sequence.
02052   if (TheUser != FoldInst)
02053     return false;
02054 
02055   // Don't try to fold volatile loads.  Target has to deal with alignment
02056   // constraints.
02057   if (LI->isVolatile())
02058     return false;
02059 
02060   // Figure out which vreg this is going into.  If there is no assigned vreg yet
02061   // then there actually was no reference to it.  Perhaps the load is referenced
02062   // by a dead instruction.
02063   unsigned LoadReg = getRegForValue(LI);
02064   if (!LoadReg)
02065     return false;
02066 
02067   // We can't fold if this vreg has no uses or more than one use.  Multiple uses
02068   // may mean that the instruction got lowered to multiple MIs, or the use of
02069   // the loaded value ended up being multiple operands of the result.
02070   if (!MRI.hasOneUse(LoadReg))
02071     return false;
02072 
02073   MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(LoadReg);
02074   MachineInstr *User = RI->getParent();
02075 
02076   // Set the insertion point properly.  Folding the load can cause generation of
02077   // other random instructions (like sign extends) for addressing modes; make
02078   // sure they get inserted in a logical place before the new instruction.
02079   FuncInfo.InsertPt = User;
02080   FuncInfo.MBB = User->getParent();
02081 
02082   // Ask the target to try folding the load.
02083   return tryToFoldLoadIntoMI(User, RI.getOperandNo(), LI);
02084 }
02085 
02086 bool FastISel::canFoldAddIntoGEP(const User *GEP, const Value *Add) {
02087   // Must be an add.
02088   if (!isa<AddOperator>(Add))
02089     return false;
02090   // Type size needs to match.
02091   if (DL.getTypeSizeInBits(GEP->getType()) !=
02092       DL.getTypeSizeInBits(Add->getType()))
02093     return false;
02094   // Must be in the same basic block.
02095   if (isa<Instruction>(Add) &&
02096       FuncInfo.MBBMap[cast<Instruction>(Add)->getParent()] != FuncInfo.MBB)
02097     return false;
02098   // Must have a constant operand.
02099   return isa<ConstantInt>(cast<AddOperator>(Add)->getOperand(1));
02100 }
02101 
02102 MachineMemOperand *
02103 FastISel::createMachineMemOperandFor(const Instruction *I) const {
02104   const Value *Ptr;
02105   Type *ValTy;
02106   unsigned Alignment;
02107   unsigned Flags;
02108   bool IsVolatile;
02109 
02110   if (const auto *LI = dyn_cast<LoadInst>(I)) {
02111     Alignment = LI->getAlignment();
02112     IsVolatile = LI->isVolatile();
02113     Flags = MachineMemOperand::MOLoad;
02114     Ptr = LI->getPointerOperand();
02115     ValTy = LI->getType();
02116   } else if (const auto *SI = dyn_cast<StoreInst>(I)) {
02117     Alignment = SI->getAlignment();
02118     IsVolatile = SI->isVolatile();
02119     Flags = MachineMemOperand::MOStore;
02120     Ptr = SI->getPointerOperand();
02121     ValTy = SI->getValueOperand()->getType();
02122   } else
02123     return nullptr;
02124 
02125   bool IsNonTemporal = I->getMetadata(LLVMContext::MD_nontemporal) != nullptr;
02126   bool IsInvariant = I->getMetadata(LLVMContext::MD_invariant_load) != nullptr;
02127   const MDNode *Ranges = I->getMetadata(LLVMContext::MD_range);
02128 
02129   AAMDNodes AAInfo;
02130   I->getAAMetadata(AAInfo);
02131 
02132   if (Alignment == 0) // Ensure that codegen never sees alignment 0.
02133     Alignment = DL.getABITypeAlignment(ValTy);
02134 
02135   unsigned Size = DL.getTypeStoreSize(ValTy);
02136 
02137   if (IsVolatile)
02138     Flags |= MachineMemOperand::MOVolatile;
02139   if (IsNonTemporal)
02140     Flags |= MachineMemOperand::MONonTemporal;
02141   if (IsInvariant)
02142     Flags |= MachineMemOperand::MOInvariant;
02143 
02144   return FuncInfo.MF->getMachineMemOperand(MachinePointerInfo(Ptr), Flags, Size,
02145                                            Alignment, AAInfo, Ranges);
02146 }
02147 
02148 CmpInst::Predicate FastISel::optimizeCmpPredicate(const CmpInst *CI) const {
02149   // If both operands are the same, then try to optimize or fold the cmp.
02150   CmpInst::Predicate Predicate = CI->getPredicate();
02151   if (CI->getOperand(0) != CI->getOperand(1))
02152     return Predicate;
02153 
02154   switch (Predicate) {
02155   default: llvm_unreachable("Invalid predicate!");
02156   case CmpInst::FCMP_FALSE: Predicate = CmpInst::FCMP_FALSE; break;
02157   case CmpInst::FCMP_OEQ:   Predicate = CmpInst::FCMP_ORD;   break;
02158   case CmpInst::FCMP_OGT:   Predicate = CmpInst::FCMP_FALSE; break;
02159   case CmpInst::FCMP_OGE:   Predicate = CmpInst::FCMP_ORD;   break;
02160   case CmpInst::FCMP_OLT:   Predicate = CmpInst::FCMP_FALSE; break;
02161   case CmpInst::FCMP_OLE:   Predicate = CmpInst::FCMP_ORD;   break;
02162   case CmpInst::FCMP_ONE:   Predicate = CmpInst::FCMP_FALSE; break;
02163   case CmpInst::FCMP_ORD:   Predicate = CmpInst::FCMP_ORD;   break;
02164   case CmpInst::FCMP_UNO:   Predicate = CmpInst::FCMP_UNO;   break;
02165   case CmpInst::FCMP_UEQ:   Predicate = CmpInst::FCMP_TRUE;  break;
02166   case CmpInst::FCMP_UGT:   Predicate = CmpInst::FCMP_UNO;   break;
02167   case CmpInst::FCMP_UGE:   Predicate = CmpInst::FCMP_TRUE;  break;
02168   case CmpInst::FCMP_ULT:   Predicate = CmpInst::FCMP_UNO;   break;
02169   case CmpInst::FCMP_ULE:   Predicate = CmpInst::FCMP_TRUE;  break;
02170   case CmpInst::FCMP_UNE:   Predicate = CmpInst::FCMP_UNO;   break;
02171   case CmpInst::FCMP_TRUE:  Predicate = CmpInst::FCMP_TRUE;  break;
02172 
02173   case CmpInst::ICMP_EQ:    Predicate = CmpInst::FCMP_TRUE;  break;
02174   case CmpInst::ICMP_NE:    Predicate = CmpInst::FCMP_FALSE; break;
02175   case CmpInst::ICMP_UGT:   Predicate = CmpInst::FCMP_FALSE; break;
02176   case CmpInst::ICMP_UGE:   Predicate = CmpInst::FCMP_TRUE;  break;
02177   case CmpInst::ICMP_ULT:   Predicate = CmpInst::FCMP_FALSE; break;
02178   case CmpInst::ICMP_ULE:   Predicate = CmpInst::FCMP_TRUE;  break;
02179   case CmpInst::ICMP_SGT:   Predicate = CmpInst::FCMP_FALSE; break;
02180   case CmpInst::ICMP_SGE:   Predicate = CmpInst::FCMP_TRUE;  break;
02181   case CmpInst::ICMP_SLT:   Predicate = CmpInst::FCMP_FALSE; break;
02182   case CmpInst::ICMP_SLE:   Predicate = CmpInst::FCMP_TRUE;  break;
02183   }
02184 
02185   return Predicate;
02186 }