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