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->getSExtValue();
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::eh_actions: {
01083     unsigned ResultReg = getRegForValue(UndefValue::get(II->getType()));
01084     if (!ResultReg)
01085       return false;
01086     updateValueMap(II, ResultReg);
01087     return true;
01088   }
01089   case Intrinsic::dbg_declare: {
01090     const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
01091     DIVariable DIVar = DI->getVariable();
01092     if (!DIVar || !FuncInfo.MF->getMMI().hasDebugInfo()) {
01093       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
01094       return true;
01095     }
01096 
01097     const Value *Address = DI->getAddress();
01098     if (!Address || isa<UndefValue>(Address)) {
01099       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
01100       return true;
01101     }
01102 
01103     unsigned Offset = 0;
01104     Optional<MachineOperand> Op;
01105     if (const auto *Arg = dyn_cast<Argument>(Address))
01106       // Some arguments' frame index is recorded during argument lowering.
01107       Offset = FuncInfo.getArgumentFrameIndex(Arg);
01108     if (Offset)
01109       Op = MachineOperand::CreateFI(Offset);
01110     if (!Op)
01111       if (unsigned Reg = lookUpRegForValue(Address))
01112         Op = MachineOperand::CreateReg(Reg, false);
01113 
01114     // If we have a VLA that has a "use" in a metadata node that's then used
01115     // here but it has no other uses, then we have a problem. E.g.,
01116     //
01117     //   int foo (const int *x) {
01118     //     char a[*x];
01119     //     return 0;
01120     //   }
01121     //
01122     // If we assign 'a' a vreg and fast isel later on has to use the selection
01123     // DAG isel, it will want to copy the value to the vreg. However, there are
01124     // no uses, which goes counter to what selection DAG isel expects.
01125     if (!Op && !Address->use_empty() && isa<Instruction>(Address) &&
01126         (!isa<AllocaInst>(Address) ||
01127          !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(Address))))
01128       Op = MachineOperand::CreateReg(FuncInfo.InitializeRegForValue(Address),
01129                                      false);
01130 
01131     if (Op) {
01132       assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) &&
01133              "Expected inlined-at fields to agree");
01134       if (Op->isReg()) {
01135         Op->setIsDebug(true);
01136         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01137                 TII.get(TargetOpcode::DBG_VALUE), false, Op->getReg(), 0,
01138                 DI->getVariable(), DI->getExpression());
01139       } else
01140         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01141                 TII.get(TargetOpcode::DBG_VALUE))
01142             .addOperand(*Op)
01143             .addImm(0)
01144             .addMetadata(DI->getVariable())
01145             .addMetadata(DI->getExpression());
01146     } else {
01147       // We can't yet handle anything else here because it would require
01148       // generating code, thus altering codegen because of debug info.
01149       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
01150     }
01151     return true;
01152   }
01153   case Intrinsic::dbg_value: {
01154     // This form of DBG_VALUE is target-independent.
01155     const DbgValueInst *DI = cast<DbgValueInst>(II);
01156     const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
01157     const Value *V = DI->getValue();
01158     assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) &&
01159            "Expected inlined-at fields to agree");
01160     if (!V) {
01161       // Currently the optimizer can produce this; insert an undef to
01162       // help debugging.  Probably the optimizer should not do this.
01163       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01164           .addReg(0U)
01165           .addImm(DI->getOffset())
01166           .addMetadata(DI->getVariable())
01167           .addMetadata(DI->getExpression());
01168     } else if (const auto *CI = dyn_cast<ConstantInt>(V)) {
01169       if (CI->getBitWidth() > 64)
01170         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01171             .addCImm(CI)
01172             .addImm(DI->getOffset())
01173             .addMetadata(DI->getVariable())
01174             .addMetadata(DI->getExpression());
01175       else
01176         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01177             .addImm(CI->getZExtValue())
01178             .addImm(DI->getOffset())
01179             .addMetadata(DI->getVariable())
01180             .addMetadata(DI->getExpression());
01181     } else if (const auto *CF = dyn_cast<ConstantFP>(V)) {
01182       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01183           .addFPImm(CF)
01184           .addImm(DI->getOffset())
01185           .addMetadata(DI->getVariable())
01186           .addMetadata(DI->getExpression());
01187     } else if (unsigned Reg = lookUpRegForValue(V)) {
01188       // FIXME: This does not handle register-indirect values at offset 0.
01189       bool IsIndirect = DI->getOffset() != 0;
01190       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, IsIndirect, Reg,
01191               DI->getOffset(), DI->getVariable(), DI->getExpression());
01192     } else {
01193       // We can't yet handle anything else here because it would require
01194       // generating code, thus altering codegen because of debug info.
01195       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
01196     }
01197     return true;
01198   }
01199   case Intrinsic::objectsize: {
01200     ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1));
01201     unsigned long long Res = CI->isZero() ? -1ULL : 0;
01202     Constant *ResCI = ConstantInt::get(II->getType(), Res);
01203     unsigned ResultReg = getRegForValue(ResCI);
01204     if (!ResultReg)
01205       return false;
01206     updateValueMap(II, ResultReg);
01207     return true;
01208   }
01209   case Intrinsic::expect: {
01210     unsigned ResultReg = getRegForValue(II->getArgOperand(0));
01211     if (!ResultReg)
01212       return false;
01213     updateValueMap(II, ResultReg);
01214     return true;
01215   }
01216   case Intrinsic::experimental_stackmap:
01217     return selectStackmap(II);
01218   case Intrinsic::experimental_patchpoint_void:
01219   case Intrinsic::experimental_patchpoint_i64:
01220     return selectPatchpoint(II);
01221   }
01222 
01223   return fastLowerIntrinsicCall(II);
01224 }
01225 
01226 bool FastISel::selectCast(const User *I, unsigned Opcode) {
01227   EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
01228   EVT DstVT = TLI.getValueType(I->getType());
01229 
01230   if (SrcVT == MVT::Other || !SrcVT.isSimple() || DstVT == MVT::Other ||
01231       !DstVT.isSimple())
01232     // Unhandled type. Halt "fast" selection and bail.
01233     return false;
01234 
01235   // Check if the destination type is legal.
01236   if (!TLI.isTypeLegal(DstVT))
01237     return false;
01238 
01239   // Check if the source operand is legal.
01240   if (!TLI.isTypeLegal(SrcVT))
01241     return false;
01242 
01243   unsigned InputReg = getRegForValue(I->getOperand(0));
01244   if (!InputReg)
01245     // Unhandled operand.  Halt "fast" selection and bail.
01246     return false;
01247 
01248   bool InputRegIsKill = hasTrivialKill(I->getOperand(0));
01249 
01250   unsigned ResultReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(),
01251                                   Opcode, InputReg, InputRegIsKill);
01252   if (!ResultReg)
01253     return false;
01254 
01255   updateValueMap(I, ResultReg);
01256   return true;
01257 }
01258 
01259 bool FastISel::selectBitCast(const User *I) {
01260   // If the bitcast doesn't change the type, just use the operand value.
01261   if (I->getType() == I->getOperand(0)->getType()) {
01262     unsigned Reg = getRegForValue(I->getOperand(0));
01263     if (!Reg)
01264       return false;
01265     updateValueMap(I, Reg);
01266     return true;
01267   }
01268 
01269   // Bitcasts of other values become reg-reg copies or BITCAST operators.
01270   EVT SrcEVT = TLI.getValueType(I->getOperand(0)->getType());
01271   EVT DstEVT = TLI.getValueType(I->getType());
01272   if (SrcEVT == MVT::Other || DstEVT == MVT::Other ||
01273       !TLI.isTypeLegal(SrcEVT) || !TLI.isTypeLegal(DstEVT))
01274     // Unhandled type. Halt "fast" selection and bail.
01275     return false;
01276 
01277   MVT SrcVT = SrcEVT.getSimpleVT();
01278   MVT DstVT = DstEVT.getSimpleVT();
01279   unsigned Op0 = getRegForValue(I->getOperand(0));
01280   if (!Op0) // Unhandled operand. Halt "fast" selection and bail.
01281     return false;
01282   bool Op0IsKill = hasTrivialKill(I->getOperand(0));
01283 
01284   // First, try to perform the bitcast by inserting a reg-reg copy.
01285   unsigned ResultReg = 0;
01286   if (SrcVT == DstVT) {
01287     const TargetRegisterClass *SrcClass = TLI.getRegClassFor(SrcVT);
01288     const TargetRegisterClass *DstClass = TLI.getRegClassFor(DstVT);
01289     // Don't attempt a cross-class copy. It will likely fail.
01290     if (SrcClass == DstClass) {
01291       ResultReg = createResultReg(DstClass);
01292       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01293               TII.get(TargetOpcode::COPY), ResultReg).addReg(Op0);
01294     }
01295   }
01296 
01297   // If the reg-reg copy failed, select a BITCAST opcode.
01298   if (!ResultReg)
01299     ResultReg = fastEmit_r(SrcVT, DstVT, ISD::BITCAST, Op0, Op0IsKill);
01300 
01301   if (!ResultReg)
01302     return false;
01303 
01304   updateValueMap(I, ResultReg);
01305   return true;
01306 }
01307 
01308 bool FastISel::selectInstruction(const Instruction *I) {
01309   // Just before the terminator instruction, insert instructions to
01310   // feed PHI nodes in successor blocks.
01311   if (isa<TerminatorInst>(I))
01312     if (!handlePHINodesInSuccessorBlocks(I->getParent()))
01313       return false;
01314 
01315   DbgLoc = I->getDebugLoc();
01316 
01317   SavedInsertPt = FuncInfo.InsertPt;
01318 
01319   if (const auto *Call = dyn_cast<CallInst>(I)) {
01320     const Function *F = Call->getCalledFunction();
01321     LibFunc::Func Func;
01322 
01323     // As a special case, don't handle calls to builtin library functions that
01324     // may be translated directly to target instructions.
01325     if (F && !F->hasLocalLinkage() && F->hasName() &&
01326         LibInfo->getLibFunc(F->getName(), Func) &&
01327         LibInfo->hasOptimizedCodeGen(Func))
01328       return false;
01329 
01330     // Don't handle Intrinsic::trap if a trap funciton is specified.
01331     if (F && F->getIntrinsicID() == Intrinsic::trap &&
01332         !TM.Options.getTrapFunctionName().empty())
01333       return false;
01334   }
01335 
01336   // First, try doing target-independent selection.
01337   if (!SkipTargetIndependentISel) {
01338     if (selectOperator(I, I->getOpcode())) {
01339       ++NumFastIselSuccessIndependent;
01340       DbgLoc = DebugLoc();
01341       return true;
01342     }
01343     // Remove dead code.
01344     recomputeInsertPt();
01345     if (SavedInsertPt != FuncInfo.InsertPt)
01346       removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
01347     SavedInsertPt = FuncInfo.InsertPt;
01348   }
01349   // Next, try calling the target to attempt to handle the instruction.
01350   if (fastSelectInstruction(I)) {
01351     ++NumFastIselSuccessTarget;
01352     DbgLoc = DebugLoc();
01353     return true;
01354   }
01355   // Remove dead code.
01356   recomputeInsertPt();
01357   if (SavedInsertPt != FuncInfo.InsertPt)
01358     removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
01359 
01360   DbgLoc = DebugLoc();
01361   // Undo phi node updates, because they will be added again by SelectionDAG.
01362   if (isa<TerminatorInst>(I))
01363     FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate);
01364   return false;
01365 }
01366 
01367 /// Emit an unconditional branch to the given block, unless it is the immediate
01368 /// (fall-through) successor, and update the CFG.
01369 void FastISel::fastEmitBranch(MachineBasicBlock *MSucc, DebugLoc DbgLoc) {
01370   if (FuncInfo.MBB->getBasicBlock()->size() > 1 &&
01371       FuncInfo.MBB->isLayoutSuccessor(MSucc)) {
01372     // For more accurate line information if this is the only instruction
01373     // in the block then emit it, otherwise we have the unconditional
01374     // fall-through case, which needs no instructions.
01375   } else {
01376     // The unconditional branch case.
01377     TII.InsertBranch(*FuncInfo.MBB, MSucc, nullptr,
01378                      SmallVector<MachineOperand, 0>(), DbgLoc);
01379   }
01380   uint32_t BranchWeight = 0;
01381   if (FuncInfo.BPI)
01382     BranchWeight = FuncInfo.BPI->getEdgeWeight(FuncInfo.MBB->getBasicBlock(),
01383                                                MSucc->getBasicBlock());
01384   FuncInfo.MBB->addSuccessor(MSucc, BranchWeight);
01385 }
01386 
01387 /// Emit an FNeg operation.
01388 bool FastISel::selectFNeg(const User *I) {
01389   unsigned OpReg = getRegForValue(BinaryOperator::getFNegArgument(I));
01390   if (!OpReg)
01391     return false;
01392   bool OpRegIsKill = hasTrivialKill(I);
01393 
01394   // If the target has ISD::FNEG, use it.
01395   EVT VT = TLI.getValueType(I->getType());
01396   unsigned ResultReg = fastEmit_r(VT.getSimpleVT(), VT.getSimpleVT(), ISD::FNEG,
01397                                   OpReg, OpRegIsKill);
01398   if (ResultReg) {
01399     updateValueMap(I, ResultReg);
01400     return true;
01401   }
01402 
01403   // Bitcast the value to integer, twiddle the sign bit with xor,
01404   // and then bitcast it back to floating-point.
01405   if (VT.getSizeInBits() > 64)
01406     return false;
01407   EVT IntVT = EVT::getIntegerVT(I->getContext(), VT.getSizeInBits());
01408   if (!TLI.isTypeLegal(IntVT))
01409     return false;
01410 
01411   unsigned IntReg = fastEmit_r(VT.getSimpleVT(), IntVT.getSimpleVT(),
01412                                ISD::BITCAST, OpReg, OpRegIsKill);
01413   if (!IntReg)
01414     return false;
01415 
01416   unsigned IntResultReg = fastEmit_ri_(
01417       IntVT.getSimpleVT(), ISD::XOR, IntReg, /*IsKill=*/true,
01418       UINT64_C(1) << (VT.getSizeInBits() - 1), IntVT.getSimpleVT());
01419   if (!IntResultReg)
01420     return false;
01421 
01422   ResultReg = fastEmit_r(IntVT.getSimpleVT(), VT.getSimpleVT(), ISD::BITCAST,
01423                          IntResultReg, /*IsKill=*/true);
01424   if (!ResultReg)
01425     return false;
01426 
01427   updateValueMap(I, ResultReg);
01428   return true;
01429 }
01430 
01431 bool FastISel::selectExtractValue(const User *U) {
01432   const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(U);
01433   if (!EVI)
01434     return false;
01435 
01436   // Make sure we only try to handle extracts with a legal result.  But also
01437   // allow i1 because it's easy.
01438   EVT RealVT = TLI.getValueType(EVI->getType(), /*AllowUnknown=*/true);
01439   if (!RealVT.isSimple())
01440     return false;
01441   MVT VT = RealVT.getSimpleVT();
01442   if (!TLI.isTypeLegal(VT) && VT != MVT::i1)
01443     return false;
01444 
01445   const Value *Op0 = EVI->getOperand(0);
01446   Type *AggTy = Op0->getType();
01447 
01448   // Get the base result register.
01449   unsigned ResultReg;
01450   DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(Op0);
01451   if (I != FuncInfo.ValueMap.end())
01452     ResultReg = I->second;
01453   else if (isa<Instruction>(Op0))
01454     ResultReg = FuncInfo.InitializeRegForValue(Op0);
01455   else
01456     return false; // fast-isel can't handle aggregate constants at the moment
01457 
01458   // Get the actual result register, which is an offset from the base register.
01459   unsigned VTIndex = ComputeLinearIndex(AggTy, EVI->getIndices());
01460 
01461   SmallVector<EVT, 4> AggValueVTs;
01462   ComputeValueVTs(TLI, AggTy, AggValueVTs);
01463 
01464   for (unsigned i = 0; i < VTIndex; i++)
01465     ResultReg += TLI.getNumRegisters(FuncInfo.Fn->getContext(), AggValueVTs[i]);
01466 
01467   updateValueMap(EVI, ResultReg);
01468   return true;
01469 }
01470 
01471 bool FastISel::selectOperator(const User *I, unsigned Opcode) {
01472   switch (Opcode) {
01473   case Instruction::Add:
01474     return selectBinaryOp(I, ISD::ADD);
01475   case Instruction::FAdd:
01476     return selectBinaryOp(I, ISD::FADD);
01477   case Instruction::Sub:
01478     return selectBinaryOp(I, ISD::SUB);
01479   case Instruction::FSub:
01480     // FNeg is currently represented in LLVM IR as a special case of FSub.
01481     if (BinaryOperator::isFNeg(I))
01482       return selectFNeg(I);
01483     return selectBinaryOp(I, ISD::FSUB);
01484   case Instruction::Mul:
01485     return selectBinaryOp(I, ISD::MUL);
01486   case Instruction::FMul:
01487     return selectBinaryOp(I, ISD::FMUL);
01488   case Instruction::SDiv:
01489     return selectBinaryOp(I, ISD::SDIV);
01490   case Instruction::UDiv:
01491     return selectBinaryOp(I, ISD::UDIV);
01492   case Instruction::FDiv:
01493     return selectBinaryOp(I, ISD::FDIV);
01494   case Instruction::SRem:
01495     return selectBinaryOp(I, ISD::SREM);
01496   case Instruction::URem:
01497     return selectBinaryOp(I, ISD::UREM);
01498   case Instruction::FRem:
01499     return selectBinaryOp(I, ISD::FREM);
01500   case Instruction::Shl:
01501     return selectBinaryOp(I, ISD::SHL);
01502   case Instruction::LShr:
01503     return selectBinaryOp(I, ISD::SRL);
01504   case Instruction::AShr:
01505     return selectBinaryOp(I, ISD::SRA);
01506   case Instruction::And:
01507     return selectBinaryOp(I, ISD::AND);
01508   case Instruction::Or:
01509     return selectBinaryOp(I, ISD::OR);
01510   case Instruction::Xor:
01511     return selectBinaryOp(I, ISD::XOR);
01512 
01513   case Instruction::GetElementPtr:
01514     return selectGetElementPtr(I);
01515 
01516   case Instruction::Br: {
01517     const BranchInst *BI = cast<BranchInst>(I);
01518 
01519     if (BI->isUnconditional()) {
01520       const BasicBlock *LLVMSucc = BI->getSuccessor(0);
01521       MachineBasicBlock *MSucc = FuncInfo.MBBMap[LLVMSucc];
01522       fastEmitBranch(MSucc, BI->getDebugLoc());
01523       return true;
01524     }
01525 
01526     // Conditional branches are not handed yet.
01527     // Halt "fast" selection and bail.
01528     return false;
01529   }
01530 
01531   case Instruction::Unreachable:
01532     if (TM.Options.TrapUnreachable)
01533       return fastEmit_(MVT::Other, MVT::Other, ISD::TRAP) != 0;
01534     else
01535       return true;
01536 
01537   case Instruction::Alloca:
01538     // FunctionLowering has the static-sized case covered.
01539     if (FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(I)))
01540       return true;
01541 
01542     // Dynamic-sized alloca is not handled yet.
01543     return false;
01544 
01545   case Instruction::Call:
01546     return selectCall(I);
01547 
01548   case Instruction::BitCast:
01549     return selectBitCast(I);
01550 
01551   case Instruction::FPToSI:
01552     return selectCast(I, ISD::FP_TO_SINT);
01553   case Instruction::ZExt:
01554     return selectCast(I, ISD::ZERO_EXTEND);
01555   case Instruction::SExt:
01556     return selectCast(I, ISD::SIGN_EXTEND);
01557   case Instruction::Trunc:
01558     return selectCast(I, ISD::TRUNCATE);
01559   case Instruction::SIToFP:
01560     return selectCast(I, ISD::SINT_TO_FP);
01561 
01562   case Instruction::IntToPtr: // Deliberate fall-through.
01563   case Instruction::PtrToInt: {
01564     EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
01565     EVT DstVT = TLI.getValueType(I->getType());
01566     if (DstVT.bitsGT(SrcVT))
01567       return selectCast(I, ISD::ZERO_EXTEND);
01568     if (DstVT.bitsLT(SrcVT))
01569       return selectCast(I, ISD::TRUNCATE);
01570     unsigned Reg = getRegForValue(I->getOperand(0));
01571     if (!Reg)
01572       return false;
01573     updateValueMap(I, Reg);
01574     return true;
01575   }
01576 
01577   case Instruction::ExtractValue:
01578     return selectExtractValue(I);
01579 
01580   case Instruction::PHI:
01581     llvm_unreachable("FastISel shouldn't visit PHI nodes!");
01582 
01583   default:
01584     // Unhandled instruction. Halt "fast" selection and bail.
01585     return false;
01586   }
01587 }
01588 
01589 FastISel::FastISel(FunctionLoweringInfo &FuncInfo,
01590                    const TargetLibraryInfo *LibInfo,
01591                    bool SkipTargetIndependentISel)
01592     : FuncInfo(FuncInfo), MF(FuncInfo.MF), MRI(FuncInfo.MF->getRegInfo()),
01593       MFI(*FuncInfo.MF->getFrameInfo()), MCP(*FuncInfo.MF->getConstantPool()),
01594       TM(FuncInfo.MF->getTarget()), DL(*TM.getDataLayout()),
01595       TII(*MF->getSubtarget().getInstrInfo()),
01596       TLI(*MF->getSubtarget().getTargetLowering()),
01597       TRI(*MF->getSubtarget().getRegisterInfo()), LibInfo(LibInfo),
01598       SkipTargetIndependentISel(SkipTargetIndependentISel) {}
01599 
01600 FastISel::~FastISel() {}
01601 
01602 bool FastISel::fastLowerArguments() { return false; }
01603 
01604 bool FastISel::fastLowerCall(CallLoweringInfo & /*CLI*/) { return false; }
01605 
01606 bool FastISel::fastLowerIntrinsicCall(const IntrinsicInst * /*II*/) {
01607   return false;
01608 }
01609 
01610 unsigned FastISel::fastEmit_(MVT, MVT, unsigned) { return 0; }
01611 
01612 unsigned FastISel::fastEmit_r(MVT, MVT, unsigned, unsigned /*Op0*/,
01613                               bool /*Op0IsKill*/) {
01614   return 0;
01615 }
01616 
01617 unsigned FastISel::fastEmit_rr(MVT, MVT, unsigned, unsigned /*Op0*/,
01618                                bool /*Op0IsKill*/, unsigned /*Op1*/,
01619                                bool /*Op1IsKill*/) {
01620   return 0;
01621 }
01622 
01623 unsigned FastISel::fastEmit_i(MVT, MVT, unsigned, uint64_t /*Imm*/) {
01624   return 0;
01625 }
01626 
01627 unsigned FastISel::fastEmit_f(MVT, MVT, unsigned,
01628                               const ConstantFP * /*FPImm*/) {
01629   return 0;
01630 }
01631 
01632 unsigned FastISel::fastEmit_ri(MVT, MVT, unsigned, unsigned /*Op0*/,
01633                                bool /*Op0IsKill*/, uint64_t /*Imm*/) {
01634   return 0;
01635 }
01636 
01637 unsigned FastISel::fastEmit_rf(MVT, MVT, unsigned, unsigned /*Op0*/,
01638                                bool /*Op0IsKill*/,
01639                                const ConstantFP * /*FPImm*/) {
01640   return 0;
01641 }
01642 
01643 unsigned FastISel::fastEmit_rri(MVT, MVT, unsigned, unsigned /*Op0*/,
01644                                 bool /*Op0IsKill*/, unsigned /*Op1*/,
01645                                 bool /*Op1IsKill*/, uint64_t /*Imm*/) {
01646   return 0;
01647 }
01648 
01649 /// This method is a wrapper of fastEmit_ri. It first tries to emit an
01650 /// instruction with an immediate operand using fastEmit_ri.
01651 /// If that fails, it materializes the immediate into a register and try
01652 /// fastEmit_rr instead.
01653 unsigned FastISel::fastEmit_ri_(MVT VT, unsigned Opcode, unsigned Op0,
01654                                 bool Op0IsKill, uint64_t Imm, MVT ImmType) {
01655   // If this is a multiply by a power of two, emit this as a shift left.
01656   if (Opcode == ISD::MUL && isPowerOf2_64(Imm)) {
01657     Opcode = ISD::SHL;
01658     Imm = Log2_64(Imm);
01659   } else if (Opcode == ISD::UDIV && isPowerOf2_64(Imm)) {
01660     // div x, 8 -> srl x, 3
01661     Opcode = ISD::SRL;
01662     Imm = Log2_64(Imm);
01663   }
01664 
01665   // Horrible hack (to be removed), check to make sure shift amounts are
01666   // in-range.
01667   if ((Opcode == ISD::SHL || Opcode == ISD::SRA || Opcode == ISD::SRL) &&
01668       Imm >= VT.getSizeInBits())
01669     return 0;
01670 
01671   // First check if immediate type is legal. If not, we can't use the ri form.
01672   unsigned ResultReg = fastEmit_ri(VT, VT, Opcode, Op0, Op0IsKill, Imm);
01673   if (ResultReg)
01674     return ResultReg;
01675   unsigned MaterialReg = fastEmit_i(ImmType, ImmType, ISD::Constant, Imm);
01676   if (!MaterialReg) {
01677     // This is a bit ugly/slow, but failing here means falling out of
01678     // fast-isel, which would be very slow.
01679     IntegerType *ITy =
01680         IntegerType::get(FuncInfo.Fn->getContext(), VT.getSizeInBits());
01681     MaterialReg = getRegForValue(ConstantInt::get(ITy, Imm));
01682     if (!MaterialReg)
01683       return 0;
01684   }
01685   return fastEmit_rr(VT, VT, Opcode, Op0, Op0IsKill, MaterialReg,
01686                      /*IsKill=*/true);
01687 }
01688 
01689 unsigned FastISel::createResultReg(const TargetRegisterClass *RC) {
01690   return MRI.createVirtualRegister(RC);
01691 }
01692 
01693 unsigned FastISel::constrainOperandRegClass(const MCInstrDesc &II, unsigned Op,
01694                                             unsigned OpNum) {
01695   if (TargetRegisterInfo::isVirtualRegister(Op)) {
01696     const TargetRegisterClass *RegClass =
01697         TII.getRegClass(II, OpNum, &TRI, *FuncInfo.MF);
01698     if (!MRI.constrainRegClass(Op, RegClass)) {
01699       // If it's not legal to COPY between the register classes, something
01700       // has gone very wrong before we got here.
01701       unsigned NewOp = createResultReg(RegClass);
01702       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01703               TII.get(TargetOpcode::COPY), NewOp).addReg(Op);
01704       return NewOp;
01705     }
01706   }
01707   return Op;
01708 }
01709 
01710 unsigned FastISel::fastEmitInst_(unsigned MachineInstOpcode,
01711                                  const TargetRegisterClass *RC) {
01712   unsigned ResultReg = createResultReg(RC);
01713   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01714 
01715   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg);
01716   return ResultReg;
01717 }
01718 
01719 unsigned FastISel::fastEmitInst_r(unsigned MachineInstOpcode,
01720                                   const TargetRegisterClass *RC, unsigned Op0,
01721                                   bool Op0IsKill) {
01722   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01723 
01724   unsigned ResultReg = createResultReg(RC);
01725   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
01726 
01727   if (II.getNumDefs() >= 1)
01728     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
01729         .addReg(Op0, getKillRegState(Op0IsKill));
01730   else {
01731     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01732         .addReg(Op0, getKillRegState(Op0IsKill));
01733     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01734             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01735   }
01736 
01737   return ResultReg;
01738 }
01739 
01740 unsigned FastISel::fastEmitInst_rr(unsigned MachineInstOpcode,
01741                                    const TargetRegisterClass *RC, unsigned Op0,
01742                                    bool Op0IsKill, unsigned Op1,
01743                                    bool Op1IsKill) {
01744   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01745 
01746   unsigned ResultReg = createResultReg(RC);
01747   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
01748   Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
01749 
01750   if (II.getNumDefs() >= 1)
01751     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
01752         .addReg(Op0, getKillRegState(Op0IsKill))
01753         .addReg(Op1, getKillRegState(Op1IsKill));
01754   else {
01755     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01756         .addReg(Op0, getKillRegState(Op0IsKill))
01757         .addReg(Op1, getKillRegState(Op1IsKill));
01758     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01759             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01760   }
01761   return ResultReg;
01762 }
01763 
01764 unsigned FastISel::fastEmitInst_rrr(unsigned MachineInstOpcode,
01765                                     const TargetRegisterClass *RC, unsigned Op0,
01766                                     bool Op0IsKill, unsigned Op1,
01767                                     bool Op1IsKill, unsigned Op2,
01768                                     bool Op2IsKill) {
01769   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01770 
01771   unsigned ResultReg = createResultReg(RC);
01772   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
01773   Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
01774   Op2 = constrainOperandRegClass(II, Op2, II.getNumDefs() + 2);
01775 
01776   if (II.getNumDefs() >= 1)
01777     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
01778         .addReg(Op0, getKillRegState(Op0IsKill))
01779         .addReg(Op1, getKillRegState(Op1IsKill))
01780         .addReg(Op2, getKillRegState(Op2IsKill));
01781   else {
01782     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01783         .addReg(Op0, getKillRegState(Op0IsKill))
01784         .addReg(Op1, getKillRegState(Op1IsKill))
01785         .addReg(Op2, getKillRegState(Op2IsKill));
01786     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01787             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01788   }
01789   return ResultReg;
01790 }
01791 
01792 unsigned FastISel::fastEmitInst_ri(unsigned MachineInstOpcode,
01793                                    const TargetRegisterClass *RC, unsigned Op0,
01794                                    bool Op0IsKill, uint64_t Imm) {
01795   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01796 
01797   unsigned ResultReg = createResultReg(RC);
01798   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
01799 
01800   if (II.getNumDefs() >= 1)
01801     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
01802         .addReg(Op0, getKillRegState(Op0IsKill))
01803         .addImm(Imm);
01804   else {
01805     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01806         .addReg(Op0, getKillRegState(Op0IsKill))
01807         .addImm(Imm);
01808     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01809             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01810   }
01811   return ResultReg;
01812 }
01813 
01814 unsigned FastISel::fastEmitInst_rii(unsigned MachineInstOpcode,
01815                                     const TargetRegisterClass *RC, unsigned Op0,
01816                                     bool Op0IsKill, uint64_t Imm1,
01817                                     uint64_t Imm2) {
01818   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01819 
01820   unsigned ResultReg = createResultReg(RC);
01821   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
01822 
01823   if (II.getNumDefs() >= 1)
01824     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
01825         .addReg(Op0, getKillRegState(Op0IsKill))
01826         .addImm(Imm1)
01827         .addImm(Imm2);
01828   else {
01829     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01830         .addReg(Op0, getKillRegState(Op0IsKill))
01831         .addImm(Imm1)
01832         .addImm(Imm2);
01833     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01834             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01835   }
01836   return ResultReg;
01837 }
01838 
01839 unsigned FastISel::fastEmitInst_rf(unsigned MachineInstOpcode,
01840                                    const TargetRegisterClass *RC, unsigned Op0,
01841                                    bool Op0IsKill, const ConstantFP *FPImm) {
01842   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01843 
01844   unsigned ResultReg = createResultReg(RC);
01845   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
01846 
01847   if (II.getNumDefs() >= 1)
01848     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
01849         .addReg(Op0, getKillRegState(Op0IsKill))
01850         .addFPImm(FPImm);
01851   else {
01852     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01853         .addReg(Op0, getKillRegState(Op0IsKill))
01854         .addFPImm(FPImm);
01855     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01856             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01857   }
01858   return ResultReg;
01859 }
01860 
01861 unsigned FastISel::fastEmitInst_rri(unsigned MachineInstOpcode,
01862                                     const TargetRegisterClass *RC, unsigned Op0,
01863                                     bool Op0IsKill, unsigned Op1,
01864                                     bool Op1IsKill, uint64_t Imm) {
01865   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01866 
01867   unsigned ResultReg = createResultReg(RC);
01868   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
01869   Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
01870 
01871   if (II.getNumDefs() >= 1)
01872     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
01873         .addReg(Op0, getKillRegState(Op0IsKill))
01874         .addReg(Op1, getKillRegState(Op1IsKill))
01875         .addImm(Imm);
01876   else {
01877     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01878         .addReg(Op0, getKillRegState(Op0IsKill))
01879         .addReg(Op1, getKillRegState(Op1IsKill))
01880         .addImm(Imm);
01881     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01882             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01883   }
01884   return ResultReg;
01885 }
01886 
01887 unsigned FastISel::fastEmitInst_rrii(unsigned MachineInstOpcode,
01888                                      const TargetRegisterClass *RC,
01889                                      unsigned Op0, bool Op0IsKill, unsigned Op1,
01890                                      bool Op1IsKill, uint64_t Imm1,
01891                                      uint64_t Imm2) {
01892   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01893 
01894   unsigned ResultReg = createResultReg(RC);
01895   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
01896   Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
01897 
01898   if (II.getNumDefs() >= 1)
01899     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
01900         .addReg(Op0, getKillRegState(Op0IsKill))
01901         .addReg(Op1, getKillRegState(Op1IsKill))
01902         .addImm(Imm1)
01903         .addImm(Imm2);
01904   else {
01905     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01906         .addReg(Op0, getKillRegState(Op0IsKill))
01907         .addReg(Op1, getKillRegState(Op1IsKill))
01908         .addImm(Imm1)
01909         .addImm(Imm2);
01910     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01911             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01912   }
01913   return ResultReg;
01914 }
01915 
01916 unsigned FastISel::fastEmitInst_i(unsigned MachineInstOpcode,
01917                                   const TargetRegisterClass *RC, uint64_t Imm) {
01918   unsigned ResultReg = createResultReg(RC);
01919   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01920 
01921   if (II.getNumDefs() >= 1)
01922     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
01923         .addImm(Imm);
01924   else {
01925     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addImm(Imm);
01926     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01927             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01928   }
01929   return ResultReg;
01930 }
01931 
01932 unsigned FastISel::fastEmitInst_ii(unsigned MachineInstOpcode,
01933                                    const TargetRegisterClass *RC, uint64_t Imm1,
01934                                    uint64_t Imm2) {
01935   unsigned ResultReg = createResultReg(RC);
01936   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01937 
01938   if (II.getNumDefs() >= 1)
01939     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
01940         .addImm(Imm1)
01941         .addImm(Imm2);
01942   else {
01943     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addImm(Imm1)
01944         .addImm(Imm2);
01945     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01946             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01947   }
01948   return ResultReg;
01949 }
01950 
01951 unsigned FastISel::fastEmitInst_extractsubreg(MVT RetVT, unsigned Op0,
01952                                               bool Op0IsKill, uint32_t Idx) {
01953   unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
01954   assert(TargetRegisterInfo::isVirtualRegister(Op0) &&
01955          "Cannot yet extract from physregs");
01956   const TargetRegisterClass *RC = MRI.getRegClass(Op0);
01957   MRI.constrainRegClass(Op0, TRI.getSubClassWithSubReg(RC, Idx));
01958   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
01959           ResultReg).addReg(Op0, getKillRegState(Op0IsKill), Idx);
01960   return ResultReg;
01961 }
01962 
01963 /// Emit MachineInstrs to compute the value of Op with all but the least
01964 /// significant bit set to zero.
01965 unsigned FastISel::fastEmitZExtFromI1(MVT VT, unsigned Op0, bool Op0IsKill) {
01966   return fastEmit_ri(VT, VT, ISD::AND, Op0, Op0IsKill, 1);
01967 }
01968 
01969 /// HandlePHINodesInSuccessorBlocks - Handle PHI nodes in successor blocks.
01970 /// Emit code to ensure constants are copied into registers when needed.
01971 /// Remember the virtual registers that need to be added to the Machine PHI
01972 /// nodes as input.  We cannot just directly add them, because expansion
01973 /// might result in multiple MBB's for one BB.  As such, the start of the
01974 /// BB might correspond to a different MBB than the end.
01975 bool FastISel::handlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
01976   const TerminatorInst *TI = LLVMBB->getTerminator();
01977 
01978   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
01979   FuncInfo.OrigNumPHINodesToUpdate = FuncInfo.PHINodesToUpdate.size();
01980 
01981   // Check successor nodes' PHI nodes that expect a constant to be available
01982   // from this block.
01983   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
01984     const BasicBlock *SuccBB = TI->getSuccessor(succ);
01985     if (!isa<PHINode>(SuccBB->begin()))
01986       continue;
01987     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
01988 
01989     // If this terminator has multiple identical successors (common for
01990     // switches), only handle each succ once.
01991     if (!SuccsHandled.insert(SuccMBB).second)
01992       continue;
01993 
01994     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
01995 
01996     // At this point we know that there is a 1-1 correspondence between LLVM PHI
01997     // nodes and Machine PHI nodes, but the incoming operands have not been
01998     // emitted yet.
01999     for (BasicBlock::const_iterator I = SuccBB->begin();
02000          const auto *PN = dyn_cast<PHINode>(I); ++I) {
02001 
02002       // Ignore dead phi's.
02003       if (PN->use_empty())
02004         continue;
02005 
02006       // Only handle legal types. Two interesting things to note here. First,
02007       // by bailing out early, we may leave behind some dead instructions,
02008       // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
02009       // own moves. Second, this check is necessary because FastISel doesn't
02010       // use CreateRegs to create registers, so it always creates
02011       // exactly one register for each non-void instruction.
02012       EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
02013       if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
02014         // Handle integer promotions, though, because they're common and easy.
02015         if (!(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)) {
02016           FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate);
02017           return false;
02018         }
02019       }
02020 
02021       const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
02022 
02023       // Set the DebugLoc for the copy. Prefer the location of the operand
02024       // if there is one; use the location of the PHI otherwise.
02025       DbgLoc = PN->getDebugLoc();
02026       if (const auto *Inst = dyn_cast<Instruction>(PHIOp))
02027         DbgLoc = Inst->getDebugLoc();
02028 
02029       unsigned Reg = getRegForValue(PHIOp);
02030       if (!Reg) {
02031         FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate);
02032         return false;
02033       }
02034       FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
02035       DbgLoc = DebugLoc();
02036     }
02037   }
02038 
02039   return true;
02040 }
02041 
02042 bool FastISel::tryToFoldLoad(const LoadInst *LI, const Instruction *FoldInst) {
02043   assert(LI->hasOneUse() &&
02044          "tryToFoldLoad expected a LoadInst with a single use");
02045   // We know that the load has a single use, but don't know what it is.  If it
02046   // isn't one of the folded instructions, then we can't succeed here.  Handle
02047   // this by scanning the single-use users of the load until we get to FoldInst.
02048   unsigned MaxUsers = 6; // Don't scan down huge single-use chains of instrs.
02049 
02050   const Instruction *TheUser = LI->user_back();
02051   while (TheUser != FoldInst && // Scan up until we find FoldInst.
02052          // Stay in the right block.
02053          TheUser->getParent() == FoldInst->getParent() &&
02054          --MaxUsers) { // Don't scan too far.
02055     // If there are multiple or no uses of this instruction, then bail out.
02056     if (!TheUser->hasOneUse())
02057       return false;
02058 
02059     TheUser = TheUser->user_back();
02060   }
02061 
02062   // If we didn't find the fold instruction, then we failed to collapse the
02063   // sequence.
02064   if (TheUser != FoldInst)
02065     return false;
02066 
02067   // Don't try to fold volatile loads.  Target has to deal with alignment
02068   // constraints.
02069   if (LI->isVolatile())
02070     return false;
02071 
02072   // Figure out which vreg this is going into.  If there is no assigned vreg yet
02073   // then there actually was no reference to it.  Perhaps the load is referenced
02074   // by a dead instruction.
02075   unsigned LoadReg = getRegForValue(LI);
02076   if (!LoadReg)
02077     return false;
02078 
02079   // We can't fold if this vreg has no uses or more than one use.  Multiple uses
02080   // may mean that the instruction got lowered to multiple MIs, or the use of
02081   // the loaded value ended up being multiple operands of the result.
02082   if (!MRI.hasOneUse(LoadReg))
02083     return false;
02084 
02085   MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(LoadReg);
02086   MachineInstr *User = RI->getParent();
02087 
02088   // Set the insertion point properly.  Folding the load can cause generation of
02089   // other random instructions (like sign extends) for addressing modes; make
02090   // sure they get inserted in a logical place before the new instruction.
02091   FuncInfo.InsertPt = User;
02092   FuncInfo.MBB = User->getParent();
02093 
02094   // Ask the target to try folding the load.
02095   return tryToFoldLoadIntoMI(User, RI.getOperandNo(), LI);
02096 }
02097 
02098 bool FastISel::canFoldAddIntoGEP(const User *GEP, const Value *Add) {
02099   // Must be an add.
02100   if (!isa<AddOperator>(Add))
02101     return false;
02102   // Type size needs to match.
02103   if (DL.getTypeSizeInBits(GEP->getType()) !=
02104       DL.getTypeSizeInBits(Add->getType()))
02105     return false;
02106   // Must be in the same basic block.
02107   if (isa<Instruction>(Add) &&
02108       FuncInfo.MBBMap[cast<Instruction>(Add)->getParent()] != FuncInfo.MBB)
02109     return false;
02110   // Must have a constant operand.
02111   return isa<ConstantInt>(cast<AddOperator>(Add)->getOperand(1));
02112 }
02113 
02114 MachineMemOperand *
02115 FastISel::createMachineMemOperandFor(const Instruction *I) const {
02116   const Value *Ptr;
02117   Type *ValTy;
02118   unsigned Alignment;
02119   unsigned Flags;
02120   bool IsVolatile;
02121 
02122   if (const auto *LI = dyn_cast<LoadInst>(I)) {
02123     Alignment = LI->getAlignment();
02124     IsVolatile = LI->isVolatile();
02125     Flags = MachineMemOperand::MOLoad;
02126     Ptr = LI->getPointerOperand();
02127     ValTy = LI->getType();
02128   } else if (const auto *SI = dyn_cast<StoreInst>(I)) {
02129     Alignment = SI->getAlignment();
02130     IsVolatile = SI->isVolatile();
02131     Flags = MachineMemOperand::MOStore;
02132     Ptr = SI->getPointerOperand();
02133     ValTy = SI->getValueOperand()->getType();
02134   } else
02135     return nullptr;
02136 
02137   bool IsNonTemporal = I->getMetadata(LLVMContext::MD_nontemporal) != nullptr;
02138   bool IsInvariant = I->getMetadata(LLVMContext::MD_invariant_load) != nullptr;
02139   const MDNode *Ranges = I->getMetadata(LLVMContext::MD_range);
02140 
02141   AAMDNodes AAInfo;
02142   I->getAAMetadata(AAInfo);
02143 
02144   if (Alignment == 0) // Ensure that codegen never sees alignment 0.
02145     Alignment = DL.getABITypeAlignment(ValTy);
02146 
02147   unsigned Size = DL.getTypeStoreSize(ValTy);
02148 
02149   if (IsVolatile)
02150     Flags |= MachineMemOperand::MOVolatile;
02151   if (IsNonTemporal)
02152     Flags |= MachineMemOperand::MONonTemporal;
02153   if (IsInvariant)
02154     Flags |= MachineMemOperand::MOInvariant;
02155 
02156   return FuncInfo.MF->getMachineMemOperand(MachinePointerInfo(Ptr), Flags, Size,
02157                                            Alignment, AAInfo, Ranges);
02158 }
02159 
02160 CmpInst::Predicate FastISel::optimizeCmpPredicate(const CmpInst *CI) const {
02161   // If both operands are the same, then try to optimize or fold the cmp.
02162   CmpInst::Predicate Predicate = CI->getPredicate();
02163   if (CI->getOperand(0) != CI->getOperand(1))
02164     return Predicate;
02165 
02166   switch (Predicate) {
02167   default: llvm_unreachable("Invalid predicate!");
02168   case CmpInst::FCMP_FALSE: Predicate = CmpInst::FCMP_FALSE; break;
02169   case CmpInst::FCMP_OEQ:   Predicate = CmpInst::FCMP_ORD;   break;
02170   case CmpInst::FCMP_OGT:   Predicate = CmpInst::FCMP_FALSE; break;
02171   case CmpInst::FCMP_OGE:   Predicate = CmpInst::FCMP_ORD;   break;
02172   case CmpInst::FCMP_OLT:   Predicate = CmpInst::FCMP_FALSE; break;
02173   case CmpInst::FCMP_OLE:   Predicate = CmpInst::FCMP_ORD;   break;
02174   case CmpInst::FCMP_ONE:   Predicate = CmpInst::FCMP_FALSE; break;
02175   case CmpInst::FCMP_ORD:   Predicate = CmpInst::FCMP_ORD;   break;
02176   case CmpInst::FCMP_UNO:   Predicate = CmpInst::FCMP_UNO;   break;
02177   case CmpInst::FCMP_UEQ:   Predicate = CmpInst::FCMP_TRUE;  break;
02178   case CmpInst::FCMP_UGT:   Predicate = CmpInst::FCMP_UNO;   break;
02179   case CmpInst::FCMP_UGE:   Predicate = CmpInst::FCMP_TRUE;  break;
02180   case CmpInst::FCMP_ULT:   Predicate = CmpInst::FCMP_UNO;   break;
02181   case CmpInst::FCMP_ULE:   Predicate = CmpInst::FCMP_TRUE;  break;
02182   case CmpInst::FCMP_UNE:   Predicate = CmpInst::FCMP_UNO;   break;
02183   case CmpInst::FCMP_TRUE:  Predicate = CmpInst::FCMP_TRUE;  break;
02184 
02185   case CmpInst::ICMP_EQ:    Predicate = CmpInst::FCMP_TRUE;  break;
02186   case CmpInst::ICMP_NE:    Predicate = CmpInst::FCMP_FALSE; break;
02187   case CmpInst::ICMP_UGT:   Predicate = CmpInst::FCMP_FALSE; break;
02188   case CmpInst::ICMP_UGE:   Predicate = CmpInst::FCMP_TRUE;  break;
02189   case CmpInst::ICMP_ULT:   Predicate = CmpInst::FCMP_FALSE; break;
02190   case CmpInst::ICMP_ULE:   Predicate = CmpInst::FCMP_TRUE;  break;
02191   case CmpInst::ICMP_SGT:   Predicate = CmpInst::FCMP_FALSE; break;
02192   case CmpInst::ICMP_SGE:   Predicate = CmpInst::FCMP_TRUE;  break;
02193   case CmpInst::ICMP_SLT:   Predicate = CmpInst::FCMP_FALSE; break;
02194   case CmpInst::ICMP_SLE:   Predicate = CmpInst::FCMP_TRUE;  break;
02195   }
02196 
02197   return Predicate;
02198 }