LLVM API Documentation

FastISel.cpp
Go to the documentation of this file.
00001 //===-- FastISel.cpp - Implementation of the FastISel class ---------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains the implementation of the FastISel class.
00011 //
00012 // "Fast" instruction selection is designed to emit very poor code quickly.
00013 // Also, it is not designed to be able to do much lowering, so most illegal
00014 // types (e.g. i64 on 32-bit targets) and operations are not supported.  It is
00015 // also not intended to be able to do much optimization, except in a few cases
00016 // where doing optimizations reduces overall compile time.  For example, folding
00017 // constants into immediate fields is often done, because it's cheap and it
00018 // reduces the number of instructions later phases have to examine.
00019 //
00020 // "Fast" instruction selection is able to fail gracefully and transfer
00021 // control to the SelectionDAG selector for operations that it doesn't
00022 // support.  In many cases, this allows us to avoid duplicating a lot of
00023 // the complicated lowering logic that SelectionDAG currently has.
00024 //
00025 // The intended use for "fast" instruction selection is "-O0" mode
00026 // compilation, where the quality of the generated code is irrelevant when
00027 // weighed against the speed at which the code can be generated.  Also,
00028 // at -O0, the LLVM optimizers are not running, and this makes the
00029 // compile time of codegen a much higher portion of the overall compile
00030 // time.  Despite its limitations, "fast" instruction selection is able to
00031 // handle enough code on its own to provide noticeable overall speedups
00032 // in -O0 compiles.
00033 //
00034 // Basic operations are supported in a target-independent way, by reading
00035 // the same instruction descriptions that the SelectionDAG selector reads,
00036 // and identifying simple arithmetic operations that can be directly selected
00037 // from simple operators.  More complicated operations currently require
00038 // target-specific code.
00039 //
00040 //===----------------------------------------------------------------------===//
00041 
00042 #include "llvm/CodeGen/FastISel.h"
00043 #include "llvm/ADT/Optional.h"
00044 #include "llvm/ADT/Statistic.h"
00045 #include "llvm/Analysis/Loads.h"
00046 #include "llvm/CodeGen/Analysis.h"
00047 #include "llvm/CodeGen/FunctionLoweringInfo.h"
00048 #include "llvm/CodeGen/MachineInstrBuilder.h"
00049 #include "llvm/CodeGen/MachineModuleInfo.h"
00050 #include "llvm/CodeGen/MachineRegisterInfo.h"
00051 #include "llvm/IR/DataLayout.h"
00052 #include "llvm/IR/DebugInfo.h"
00053 #include "llvm/IR/Function.h"
00054 #include "llvm/IR/GlobalVariable.h"
00055 #include "llvm/IR/Instructions.h"
00056 #include "llvm/IR/IntrinsicInst.h"
00057 #include "llvm/IR/Operator.h"
00058 #include "llvm/Support/Debug.h"
00059 #include "llvm/Support/ErrorHandling.h"
00060 #include "llvm/Target/TargetInstrInfo.h"
00061 #include "llvm/Target/TargetLibraryInfo.h"
00062 #include "llvm/Target/TargetLowering.h"
00063 #include "llvm/Target/TargetMachine.h"
00064 using namespace llvm;
00065 
00066 #define DEBUG_TYPE "isel"
00067 
00068 STATISTIC(NumFastIselSuccessIndependent, "Number of insts selected by "
00069           "target-independent selector");
00070 STATISTIC(NumFastIselSuccessTarget, "Number of insts selected by "
00071           "target-specific selector");
00072 STATISTIC(NumFastIselDead, "Number of dead insts removed on failure");
00073 
00074 /// startNewBlock - Set the current block to which generated machine
00075 /// instructions will be appended, and clear the local CSE map.
00076 ///
00077 void FastISel::startNewBlock() {
00078   LocalValueMap.clear();
00079 
00080   // Instructions are appended to FuncInfo.MBB. If the basic block already
00081   // contains labels or copies, use the last instruction as the last local
00082   // value.
00083   EmitStartPt = nullptr;
00084   if (!FuncInfo.MBB->empty())
00085     EmitStartPt = &FuncInfo.MBB->back();
00086   LastLocalValue = EmitStartPt;
00087 }
00088 
00089 bool FastISel::LowerArguments() {
00090   if (!FuncInfo.CanLowerReturn)
00091     // Fallback to SDISel argument lowering code to deal with sret pointer
00092     // parameter.
00093     return false;
00094 
00095   if (!FastLowerArguments())
00096     return false;
00097 
00098   // Enter arguments into ValueMap for uses in non-entry BBs.
00099   for (Function::const_arg_iterator I = FuncInfo.Fn->arg_begin(),
00100          E = FuncInfo.Fn->arg_end(); I != E; ++I) {
00101     DenseMap<const Value *, unsigned>::iterator VI = LocalValueMap.find(I);
00102     assert(VI != LocalValueMap.end() && "Missed an argument?");
00103     FuncInfo.ValueMap[I] = VI->second;
00104   }
00105   return true;
00106 }
00107 
00108 void FastISel::flushLocalValueMap() {
00109   LocalValueMap.clear();
00110   LastLocalValue = EmitStartPt;
00111   recomputeInsertPt();
00112 }
00113 
00114 bool FastISel::hasTrivialKill(const Value *V) const {
00115   // Don't consider constants or arguments to have trivial kills.
00116   const Instruction *I = dyn_cast<Instruction>(V);
00117   if (!I)
00118     return false;
00119 
00120   // No-op casts are trivially coalesced by fast-isel.
00121   if (const CastInst *Cast = dyn_cast<CastInst>(I))
00122     if (Cast->isNoopCast(DL.getIntPtrType(Cast->getContext())) &&
00123         !hasTrivialKill(Cast->getOperand(0)))
00124       return false;
00125 
00126   // GEPs with all zero indices are trivially coalesced by fast-isel.
00127   if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
00128     if (GEP->hasAllZeroIndices() && !hasTrivialKill(GEP->getOperand(0)))
00129       return false;
00130 
00131   // Only instructions with a single use in the same basic block are considered
00132   // to have trivial kills.
00133   return I->hasOneUse() &&
00134          !(I->getOpcode() == Instruction::BitCast ||
00135            I->getOpcode() == Instruction::PtrToInt ||
00136            I->getOpcode() == Instruction::IntToPtr) &&
00137          cast<Instruction>(*I->user_begin())->getParent() == I->getParent();
00138 }
00139 
00140 unsigned FastISel::getRegForValue(const Value *V) {
00141   EVT RealVT = TLI.getValueType(V->getType(), /*AllowUnknown=*/true);
00142   // Don't handle non-simple values in FastISel.
00143   if (!RealVT.isSimple())
00144     return 0;
00145 
00146   // Ignore illegal types. We must do this before looking up the value
00147   // in ValueMap because Arguments are given virtual registers regardless
00148   // of whether FastISel can handle them.
00149   MVT VT = RealVT.getSimpleVT();
00150   if (!TLI.isTypeLegal(VT)) {
00151     // Handle integer promotions, though, because they're common and easy.
00152     if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
00153       VT = TLI.getTypeToTransformTo(V->getContext(), VT).getSimpleVT();
00154     else
00155       return 0;
00156   }
00157 
00158   // Look up the value to see if we already have a register for it.
00159   unsigned Reg = lookUpRegForValue(V);
00160   if (Reg != 0)
00161     return Reg;
00162 
00163   // In bottom-up mode, just create the virtual register which will be used
00164   // to hold the value. It will be materialized later.
00165   if (isa<Instruction>(V) &&
00166       (!isa<AllocaInst>(V) ||
00167        !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(V))))
00168     return FuncInfo.InitializeRegForValue(V);
00169 
00170   SavePoint SaveInsertPt = enterLocalValueArea();
00171 
00172   // Materialize the value in a register. Emit any instructions in the
00173   // local value area.
00174   Reg = materializeRegForValue(V, VT);
00175 
00176   leaveLocalValueArea(SaveInsertPt);
00177 
00178   return Reg;
00179 }
00180 
00181 /// materializeRegForValue - Helper for getRegForValue. This function is
00182 /// called when the value isn't already available in a register and must
00183 /// be materialized with new instructions.
00184 unsigned FastISel::materializeRegForValue(const Value *V, MVT VT) {
00185   unsigned Reg = 0;
00186 
00187   if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
00188     if (CI->getValue().getActiveBits() <= 64)
00189       Reg = FastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
00190   } else if (isa<AllocaInst>(V)) {
00191     Reg = TargetMaterializeAlloca(cast<AllocaInst>(V));
00192   } else if (isa<ConstantPointerNull>(V)) {
00193     // Translate this as an integer zero so that it can be
00194     // local-CSE'd with actual integer zeros.
00195     Reg =
00196       getRegForValue(Constant::getNullValue(DL.getIntPtrType(V->getContext())));
00197   } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
00198     if (CF->isNullValue()) {
00199       Reg = TargetMaterializeFloatZero(CF);
00200     } else {
00201       // Try to emit the constant directly.
00202       Reg = FastEmit_f(VT, VT, ISD::ConstantFP, CF);
00203     }
00204 
00205     if (!Reg) {
00206       // Try to emit the constant by using an integer constant with a cast.
00207       const APFloat &Flt = CF->getValueAPF();
00208       EVT IntVT = TLI.getPointerTy();
00209 
00210       uint64_t x[2];
00211       uint32_t IntBitWidth = IntVT.getSizeInBits();
00212       bool isExact;
00213       (void) Flt.convertToInteger(x, IntBitWidth, /*isSigned=*/true,
00214                                   APFloat::rmTowardZero, &isExact);
00215       if (isExact) {
00216         APInt IntVal(IntBitWidth, x);
00217 
00218         unsigned IntegerReg =
00219           getRegForValue(ConstantInt::get(V->getContext(), IntVal));
00220         if (IntegerReg != 0)
00221           Reg = FastEmit_r(IntVT.getSimpleVT(), VT, ISD::SINT_TO_FP,
00222                            IntegerReg, /*Kill=*/false);
00223       }
00224     }
00225   } else if (const Operator *Op = dyn_cast<Operator>(V)) {
00226     if (!SelectOperator(Op, Op->getOpcode()))
00227       if (!isa<Instruction>(Op) ||
00228           !TargetSelectInstruction(cast<Instruction>(Op)))
00229         return 0;
00230     Reg = lookUpRegForValue(Op);
00231   } else if (isa<UndefValue>(V)) {
00232     Reg = createResultReg(TLI.getRegClassFor(VT));
00233     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
00234             TII.get(TargetOpcode::IMPLICIT_DEF), Reg);
00235   }
00236 
00237   // If target-independent code couldn't handle the value, give target-specific
00238   // code a try.
00239   if (!Reg && isa<Constant>(V))
00240     Reg = TargetMaterializeConstant(cast<Constant>(V));
00241 
00242   // Don't cache constant materializations in the general ValueMap.
00243   // To do so would require tracking what uses they dominate.
00244   if (Reg != 0) {
00245     LocalValueMap[V] = Reg;
00246     LastLocalValue = MRI.getVRegDef(Reg);
00247   }
00248   return Reg;
00249 }
00250 
00251 unsigned FastISel::lookUpRegForValue(const Value *V) {
00252   // Look up the value to see if we already have a register for it. We
00253   // cache values defined by Instructions across blocks, and other values
00254   // only locally. This is because Instructions already have the SSA
00255   // def-dominates-use requirement enforced.
00256   DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(V);
00257   if (I != FuncInfo.ValueMap.end())
00258     return I->second;
00259   return LocalValueMap[V];
00260 }
00261 
00262 /// UpdateValueMap - Update the value map to include the new mapping for this
00263 /// instruction, or insert an extra copy to get the result in a previous
00264 /// determined register.
00265 /// NOTE: This is only necessary because we might select a block that uses
00266 /// a value before we select the block that defines the value.  It might be
00267 /// possible to fix this by selecting blocks in reverse postorder.
00268 void FastISel::UpdateValueMap(const Value *I, unsigned Reg, unsigned NumRegs) {
00269   if (!isa<Instruction>(I)) {
00270     LocalValueMap[I] = Reg;
00271     return;
00272   }
00273 
00274   unsigned &AssignedReg = FuncInfo.ValueMap[I];
00275   if (AssignedReg == 0)
00276     // Use the new register.
00277     AssignedReg = Reg;
00278   else if (Reg != AssignedReg) {
00279     // Arrange for uses of AssignedReg to be replaced by uses of Reg.
00280     for (unsigned i = 0; i < NumRegs; i++)
00281       FuncInfo.RegFixups[AssignedReg+i] = Reg+i;
00282 
00283     AssignedReg = Reg;
00284   }
00285 }
00286 
00287 std::pair<unsigned, bool> FastISel::getRegForGEPIndex(const Value *Idx) {
00288   unsigned IdxN = getRegForValue(Idx);
00289   if (IdxN == 0)
00290     // Unhandled operand. Halt "fast" selection and bail.
00291     return std::pair<unsigned, bool>(0, false);
00292 
00293   bool IdxNIsKill = hasTrivialKill(Idx);
00294 
00295   // If the index is smaller or larger than intptr_t, truncate or extend it.
00296   MVT PtrVT = TLI.getPointerTy();
00297   EVT IdxVT = EVT::getEVT(Idx->getType(), /*HandleUnknown=*/false);
00298   if (IdxVT.bitsLT(PtrVT)) {
00299     IdxN = FastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::SIGN_EXTEND,
00300                       IdxN, IdxNIsKill);
00301     IdxNIsKill = true;
00302   }
00303   else if (IdxVT.bitsGT(PtrVT)) {
00304     IdxN = FastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::TRUNCATE,
00305                       IdxN, IdxNIsKill);
00306     IdxNIsKill = true;
00307   }
00308   return std::pair<unsigned, bool>(IdxN, IdxNIsKill);
00309 }
00310 
00311 void FastISel::recomputeInsertPt() {
00312   if (getLastLocalValue()) {
00313     FuncInfo.InsertPt = getLastLocalValue();
00314     FuncInfo.MBB = FuncInfo.InsertPt->getParent();
00315     ++FuncInfo.InsertPt;
00316   } else
00317     FuncInfo.InsertPt = FuncInfo.MBB->getFirstNonPHI();
00318 
00319   // Now skip past any EH_LABELs, which must remain at the beginning.
00320   while (FuncInfo.InsertPt != FuncInfo.MBB->end() &&
00321          FuncInfo.InsertPt->getOpcode() == TargetOpcode::EH_LABEL)
00322     ++FuncInfo.InsertPt;
00323 }
00324 
00325 void FastISel::removeDeadCode(MachineBasicBlock::iterator I,
00326                               MachineBasicBlock::iterator E) {
00327   assert (I && E && std::distance(I, E) > 0 && "Invalid iterator!");
00328   while (I != E) {
00329     MachineInstr *Dead = &*I;
00330     ++I;
00331     Dead->eraseFromParent();
00332     ++NumFastIselDead;
00333   }
00334   recomputeInsertPt();
00335 }
00336 
00337 FastISel::SavePoint FastISel::enterLocalValueArea() {
00338   MachineBasicBlock::iterator OldInsertPt = FuncInfo.InsertPt;
00339   DebugLoc OldDL = DbgLoc;
00340   recomputeInsertPt();
00341   DbgLoc = DebugLoc();
00342   SavePoint SP = { OldInsertPt, OldDL };
00343   return SP;
00344 }
00345 
00346 void FastISel::leaveLocalValueArea(SavePoint OldInsertPt) {
00347   if (FuncInfo.InsertPt != FuncInfo.MBB->begin())
00348     LastLocalValue = std::prev(FuncInfo.InsertPt);
00349 
00350   // Restore the previous insert position.
00351   FuncInfo.InsertPt = OldInsertPt.InsertPt;
00352   DbgLoc = OldInsertPt.DL;
00353 }
00354 
00355 /// SelectBinaryOp - Select and emit code for a binary operator instruction,
00356 /// which has an opcode which directly corresponds to the given ISD opcode.
00357 ///
00358 bool FastISel::SelectBinaryOp(const User *I, unsigned ISDOpcode) {
00359   EVT VT = EVT::getEVT(I->getType(), /*HandleUnknown=*/true);
00360   if (VT == MVT::Other || !VT.isSimple())
00361     // Unhandled type. Halt "fast" selection and bail.
00362     return false;
00363 
00364   // We only handle legal types. For example, on x86-32 the instruction
00365   // selector contains all of the 64-bit instructions from x86-64,
00366   // under the assumption that i64 won't be used if the target doesn't
00367   // support it.
00368   if (!TLI.isTypeLegal(VT)) {
00369     // MVT::i1 is special. Allow AND, OR, or XOR because they
00370     // don't require additional zeroing, which makes them easy.
00371     if (VT == MVT::i1 &&
00372         (ISDOpcode == ISD::AND || ISDOpcode == ISD::OR ||
00373          ISDOpcode == ISD::XOR))
00374       VT = TLI.getTypeToTransformTo(I->getContext(), VT);
00375     else
00376       return false;
00377   }
00378 
00379   // Check if the first operand is a constant, and handle it as "ri".  At -O0,
00380   // we don't have anything that canonicalizes operand order.
00381   if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(0)))
00382     if (isa<Instruction>(I) && cast<Instruction>(I)->isCommutative()) {
00383       unsigned Op1 = getRegForValue(I->getOperand(1));
00384       if (Op1 == 0) return false;
00385 
00386       bool Op1IsKill = hasTrivialKill(I->getOperand(1));
00387 
00388       unsigned ResultReg = FastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op1,
00389                                         Op1IsKill, CI->getZExtValue(),
00390                                         VT.getSimpleVT());
00391       if (ResultReg == 0) return false;
00392 
00393       // We successfully emitted code for the given LLVM Instruction.
00394       UpdateValueMap(I, ResultReg);
00395       return true;
00396     }
00397 
00398 
00399   unsigned Op0 = getRegForValue(I->getOperand(0));
00400   if (Op0 == 0)   // Unhandled operand. Halt "fast" selection and bail.
00401     return false;
00402 
00403   bool Op0IsKill = hasTrivialKill(I->getOperand(0));
00404 
00405   // Check if the second operand is a constant and handle it appropriately.
00406   if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
00407     uint64_t Imm = CI->getZExtValue();
00408 
00409     // Transform "sdiv exact X, 8" -> "sra X, 3".
00410     if (ISDOpcode == ISD::SDIV && isa<BinaryOperator>(I) &&
00411         cast<BinaryOperator>(I)->isExact() &&
00412         isPowerOf2_64(Imm)) {
00413       Imm = Log2_64(Imm);
00414       ISDOpcode = ISD::SRA;
00415     }
00416 
00417     // Transform "urem x, pow2" -> "and x, pow2-1".
00418     if (ISDOpcode == ISD::UREM && isa<BinaryOperator>(I) &&
00419         isPowerOf2_64(Imm)) {
00420       --Imm;
00421       ISDOpcode = ISD::AND;
00422     }
00423 
00424     unsigned ResultReg = FastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op0,
00425                                       Op0IsKill, Imm, VT.getSimpleVT());
00426     if (ResultReg == 0) return false;
00427 
00428     // We successfully emitted code for the given LLVM Instruction.
00429     UpdateValueMap(I, ResultReg);
00430     return true;
00431   }
00432 
00433   // Check if the second operand is a constant float.
00434   if (ConstantFP *CF = dyn_cast<ConstantFP>(I->getOperand(1))) {
00435     unsigned ResultReg = FastEmit_rf(VT.getSimpleVT(), VT.getSimpleVT(),
00436                                      ISDOpcode, Op0, Op0IsKill, CF);
00437     if (ResultReg != 0) {
00438       // We successfully emitted code for the given LLVM Instruction.
00439       UpdateValueMap(I, ResultReg);
00440       return true;
00441     }
00442   }
00443 
00444   unsigned Op1 = getRegForValue(I->getOperand(1));
00445   if (Op1 == 0)
00446     // Unhandled operand. Halt "fast" selection and bail.
00447     return false;
00448 
00449   bool Op1IsKill = hasTrivialKill(I->getOperand(1));
00450 
00451   // Now we have both operands in registers. Emit the instruction.
00452   unsigned ResultReg = FastEmit_rr(VT.getSimpleVT(), VT.getSimpleVT(),
00453                                    ISDOpcode,
00454                                    Op0, Op0IsKill,
00455                                    Op1, Op1IsKill);
00456   if (ResultReg == 0)
00457     // Target-specific code wasn't able to find a machine opcode for
00458     // the given ISD opcode and type. Halt "fast" selection and bail.
00459     return false;
00460 
00461   // We successfully emitted code for the given LLVM Instruction.
00462   UpdateValueMap(I, ResultReg);
00463   return true;
00464 }
00465 
00466 bool FastISel::SelectGetElementPtr(const User *I) {
00467   unsigned N = getRegForValue(I->getOperand(0));
00468   if (N == 0)
00469     // Unhandled operand. Halt "fast" selection and bail.
00470     return false;
00471 
00472   bool NIsKill = hasTrivialKill(I->getOperand(0));
00473 
00474   // Keep a running tab of the total offset to coalesce multiple N = N + Offset
00475   // into a single N = N + TotalOffset.
00476   uint64_t TotalOffs = 0;
00477   // FIXME: What's a good SWAG number for MaxOffs?
00478   uint64_t MaxOffs = 2048;
00479   Type *Ty = I->getOperand(0)->getType();
00480   MVT VT = TLI.getPointerTy();
00481   for (GetElementPtrInst::const_op_iterator OI = I->op_begin()+1,
00482        E = I->op_end(); OI != E; ++OI) {
00483     const Value *Idx = *OI;
00484     if (StructType *StTy = dyn_cast<StructType>(Ty)) {
00485       unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
00486       if (Field) {
00487         // N = N + Offset
00488         TotalOffs += DL.getStructLayout(StTy)->getElementOffset(Field);
00489         if (TotalOffs >= MaxOffs) {
00490           N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
00491           if (N == 0)
00492             // Unhandled operand. Halt "fast" selection and bail.
00493             return false;
00494           NIsKill = true;
00495           TotalOffs = 0;
00496         }
00497       }
00498       Ty = StTy->getElementType(Field);
00499     } else {
00500       Ty = cast<SequentialType>(Ty)->getElementType();
00501 
00502       // If this is a constant subscript, handle it quickly.
00503       if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
00504         if (CI->isZero()) continue;
00505         // N = N + Offset
00506         TotalOffs +=
00507           DL.getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
00508         if (TotalOffs >= MaxOffs) {
00509           N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
00510           if (N == 0)
00511             // Unhandled operand. Halt "fast" selection and bail.
00512             return false;
00513           NIsKill = true;
00514           TotalOffs = 0;
00515         }
00516         continue;
00517       }
00518       if (TotalOffs) {
00519         N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
00520         if (N == 0)
00521           // Unhandled operand. Halt "fast" selection and bail.
00522           return false;
00523         NIsKill = true;
00524         TotalOffs = 0;
00525       }
00526 
00527       // N = N + Idx * ElementSize;
00528       uint64_t ElementSize = DL.getTypeAllocSize(Ty);
00529       std::pair<unsigned, bool> Pair = getRegForGEPIndex(Idx);
00530       unsigned IdxN = Pair.first;
00531       bool IdxNIsKill = Pair.second;
00532       if (IdxN == 0)
00533         // Unhandled operand. Halt "fast" selection and bail.
00534         return false;
00535 
00536       if (ElementSize != 1) {
00537         IdxN = FastEmit_ri_(VT, ISD::MUL, IdxN, IdxNIsKill, ElementSize, VT);
00538         if (IdxN == 0)
00539           // Unhandled operand. Halt "fast" selection and bail.
00540           return false;
00541         IdxNIsKill = true;
00542       }
00543       N = FastEmit_rr(VT, VT, ISD::ADD, N, NIsKill, IdxN, IdxNIsKill);
00544       if (N == 0)
00545         // Unhandled operand. Halt "fast" selection and bail.
00546         return false;
00547     }
00548   }
00549   if (TotalOffs) {
00550     N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
00551     if (N == 0)
00552       // Unhandled operand. Halt "fast" selection and bail.
00553       return false;
00554   }
00555 
00556   // We successfully emitted code for the given LLVM Instruction.
00557   UpdateValueMap(I, N);
00558   return true;
00559 }
00560 
00561 bool FastISel::SelectCall(const User *I) {
00562   const CallInst *Call = cast<CallInst>(I);
00563 
00564   // Handle simple inline asms.
00565   if (const InlineAsm *IA = dyn_cast<InlineAsm>(Call->getCalledValue())) {
00566     // Don't attempt to handle constraints.
00567     if (!IA->getConstraintString().empty())
00568       return false;
00569 
00570     unsigned ExtraInfo = 0;
00571     if (IA->hasSideEffects())
00572       ExtraInfo |= InlineAsm::Extra_HasSideEffects;
00573     if (IA->isAlignStack())
00574       ExtraInfo |= InlineAsm::Extra_IsAlignStack;
00575 
00576     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
00577             TII.get(TargetOpcode::INLINEASM))
00578       .addExternalSymbol(IA->getAsmString().c_str())
00579       .addImm(ExtraInfo);
00580     return true;
00581   }
00582 
00583   MachineModuleInfo &MMI = FuncInfo.MF->getMMI();
00584   ComputeUsesVAFloatArgument(*Call, &MMI);
00585 
00586   const Function *F = Call->getCalledFunction();
00587   if (!F) return false;
00588 
00589   // Handle selected intrinsic function calls.
00590   switch (F->getIntrinsicID()) {
00591   default: break;
00592     // At -O0 we don't care about the lifetime intrinsics.
00593   case Intrinsic::lifetime_start:
00594   case Intrinsic::lifetime_end:
00595     // The donothing intrinsic does, well, nothing.
00596   case Intrinsic::donothing:
00597     return true;
00598 
00599   case Intrinsic::dbg_declare: {
00600     const DbgDeclareInst *DI = cast<DbgDeclareInst>(Call);
00601     DIVariable DIVar(DI->getVariable());
00602     assert((!DIVar || DIVar.isVariable()) &&
00603       "Variable in DbgDeclareInst should be either null or a DIVariable.");
00604     if (!DIVar ||
00605         !FuncInfo.MF->getMMI().hasDebugInfo()) {
00606       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
00607       return true;
00608     }
00609 
00610     const Value *Address = DI->getAddress();
00611     if (!Address || isa<UndefValue>(Address)) {
00612       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
00613       return true;
00614     }
00615 
00616     unsigned Offset = 0;
00617     Optional<MachineOperand> Op;
00618     if (const Argument *Arg = dyn_cast<Argument>(Address))
00619       // Some arguments' frame index is recorded during argument lowering.
00620       Offset = FuncInfo.getArgumentFrameIndex(Arg);
00621     if (Offset)
00622         Op = MachineOperand::CreateFI(Offset);
00623     if (!Op)
00624       if (unsigned Reg = lookUpRegForValue(Address))
00625         Op = MachineOperand::CreateReg(Reg, false);
00626 
00627     // If we have a VLA that has a "use" in a metadata node that's then used
00628     // here but it has no other uses, then we have a problem. E.g.,
00629     //
00630     //   int foo (const int *x) {
00631     //     char a[*x];
00632     //     return 0;
00633     //   }
00634     //
00635     // If we assign 'a' a vreg and fast isel later on has to use the selection
00636     // DAG isel, it will want to copy the value to the vreg. However, there are
00637     // no uses, which goes counter to what selection DAG isel expects.
00638     if (!Op && !Address->use_empty() && isa<Instruction>(Address) &&
00639         (!isa<AllocaInst>(Address) ||
00640          !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(Address))))
00641       Op = MachineOperand::CreateReg(FuncInfo.InitializeRegForValue(Address),
00642                                      false);
00643 
00644     if (Op) {
00645       if (Op->isReg()) {
00646         Op->setIsDebug(true);
00647         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
00648                 TII.get(TargetOpcode::DBG_VALUE), false, Op->getReg(), 0,
00649                 DI->getVariable());
00650       } else
00651         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
00652                 TII.get(TargetOpcode::DBG_VALUE))
00653             .addOperand(*Op)
00654             .addImm(0)
00655             .addMetadata(DI->getVariable());
00656     } else {
00657       // We can't yet handle anything else here because it would require
00658       // generating code, thus altering codegen because of debug info.
00659       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
00660     }
00661     return true;
00662   }
00663   case Intrinsic::dbg_value: {
00664     // This form of DBG_VALUE is target-independent.
00665     const DbgValueInst *DI = cast<DbgValueInst>(Call);
00666     const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
00667     const Value *V = DI->getValue();
00668     if (!V) {
00669       // Currently the optimizer can produce this; insert an undef to
00670       // help debugging.  Probably the optimizer should not do this.
00671       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
00672         .addReg(0U).addImm(DI->getOffset())
00673         .addMetadata(DI->getVariable());
00674     } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
00675       if (CI->getBitWidth() > 64)
00676         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
00677           .addCImm(CI).addImm(DI->getOffset())
00678           .addMetadata(DI->getVariable());
00679       else
00680         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
00681           .addImm(CI->getZExtValue()).addImm(DI->getOffset())
00682           .addMetadata(DI->getVariable());
00683     } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
00684       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
00685         .addFPImm(CF).addImm(DI->getOffset())
00686         .addMetadata(DI->getVariable());
00687     } else if (unsigned Reg = lookUpRegForValue(V)) {
00688       // FIXME: This does not handle register-indirect values at offset 0.
00689       bool IsIndirect = DI->getOffset() != 0;
00690       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, IsIndirect,
00691               Reg, DI->getOffset(), DI->getVariable());
00692     } else {
00693       // We can't yet handle anything else here because it would require
00694       // generating code, thus altering codegen because of debug info.
00695       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
00696     }
00697     return true;
00698   }
00699   case Intrinsic::objectsize: {
00700     ConstantInt *CI = cast<ConstantInt>(Call->getArgOperand(1));
00701     unsigned long long Res = CI->isZero() ? -1ULL : 0;
00702     Constant *ResCI = ConstantInt::get(Call->getType(), Res);
00703     unsigned ResultReg = getRegForValue(ResCI);
00704     if (ResultReg == 0)
00705       return false;
00706     UpdateValueMap(Call, ResultReg);
00707     return true;
00708   }
00709   case Intrinsic::expect: {
00710     unsigned ResultReg = getRegForValue(Call->getArgOperand(0));
00711     if (ResultReg == 0)
00712       return false;
00713     UpdateValueMap(Call, ResultReg);
00714     return true;
00715   }
00716   }
00717 
00718   // Usually, it does not make sense to initialize a value,
00719   // make an unrelated function call and use the value, because
00720   // it tends to be spilled on the stack. So, we move the pointer
00721   // to the last local value to the beginning of the block, so that
00722   // all the values which have already been materialized,
00723   // appear after the call. It also makes sense to skip intrinsics
00724   // since they tend to be inlined.
00725   if (!isa<IntrinsicInst>(Call))
00726     flushLocalValueMap();
00727 
00728   // An arbitrary call. Bail.
00729   return false;
00730 }
00731 
00732 bool FastISel::SelectCast(const User *I, unsigned Opcode) {
00733   EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
00734   EVT DstVT = TLI.getValueType(I->getType());
00735 
00736   if (SrcVT == MVT::Other || !SrcVT.isSimple() ||
00737       DstVT == MVT::Other || !DstVT.isSimple())
00738     // Unhandled type. Halt "fast" selection and bail.
00739     return false;
00740 
00741   // Check if the destination type is legal.
00742   if (!TLI.isTypeLegal(DstVT))
00743     return false;
00744 
00745   // Check if the source operand is legal.
00746   if (!TLI.isTypeLegal(SrcVT))
00747     return false;
00748 
00749   unsigned InputReg = getRegForValue(I->getOperand(0));
00750   if (!InputReg)
00751     // Unhandled operand.  Halt "fast" selection and bail.
00752     return false;
00753 
00754   bool InputRegIsKill = hasTrivialKill(I->getOperand(0));
00755 
00756   unsigned ResultReg = FastEmit_r(SrcVT.getSimpleVT(),
00757                                   DstVT.getSimpleVT(),
00758                                   Opcode,
00759                                   InputReg, InputRegIsKill);
00760   if (!ResultReg)
00761     return false;
00762 
00763   UpdateValueMap(I, ResultReg);
00764   return true;
00765 }
00766 
00767 bool FastISel::SelectBitCast(const User *I) {
00768   // If the bitcast doesn't change the type, just use the operand value.
00769   if (I->getType() == I->getOperand(0)->getType()) {
00770     unsigned Reg = getRegForValue(I->getOperand(0));
00771     if (Reg == 0)
00772       return false;
00773     UpdateValueMap(I, Reg);
00774     return true;
00775   }
00776 
00777   // Bitcasts of other values become reg-reg copies or BITCAST operators.
00778   EVT SrcEVT = TLI.getValueType(I->getOperand(0)->getType());
00779   EVT DstEVT = TLI.getValueType(I->getType());
00780   if (SrcEVT == MVT::Other || DstEVT == MVT::Other ||
00781       !TLI.isTypeLegal(SrcEVT) || !TLI.isTypeLegal(DstEVT))
00782     // Unhandled type. Halt "fast" selection and bail.
00783     return false;
00784 
00785   MVT SrcVT = SrcEVT.getSimpleVT();
00786   MVT DstVT = DstEVT.getSimpleVT();
00787   unsigned Op0 = getRegForValue(I->getOperand(0));
00788   if (Op0 == 0)
00789     // Unhandled operand. Halt "fast" selection and bail.
00790     return false;
00791 
00792   bool Op0IsKill = hasTrivialKill(I->getOperand(0));
00793 
00794   // First, try to perform the bitcast by inserting a reg-reg copy.
00795   unsigned ResultReg = 0;
00796   if (SrcVT == DstVT) {
00797     const TargetRegisterClass* SrcClass = TLI.getRegClassFor(SrcVT);
00798     const TargetRegisterClass* DstClass = TLI.getRegClassFor(DstVT);
00799     // Don't attempt a cross-class copy. It will likely fail.
00800     if (SrcClass == DstClass) {
00801       ResultReg = createResultReg(DstClass);
00802       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
00803               TII.get(TargetOpcode::COPY), ResultReg).addReg(Op0);
00804     }
00805   }
00806 
00807   // If the reg-reg copy failed, select a BITCAST opcode.
00808   if (!ResultReg)
00809     ResultReg = FastEmit_r(SrcVT, DstVT, ISD::BITCAST, Op0, Op0IsKill);
00810 
00811   if (!ResultReg)
00812     return false;
00813 
00814   UpdateValueMap(I, ResultReg);
00815   return true;
00816 }
00817 
00818 bool
00819 FastISel::SelectInstruction(const Instruction *I) {
00820   // Just before the terminator instruction, insert instructions to
00821   // feed PHI nodes in successor blocks.
00822   if (isa<TerminatorInst>(I))
00823     if (!HandlePHINodesInSuccessorBlocks(I->getParent()))
00824       return false;
00825 
00826   DbgLoc = I->getDebugLoc();
00827 
00828   MachineBasicBlock::iterator SavedInsertPt = FuncInfo.InsertPt;
00829 
00830   if (const CallInst *Call = dyn_cast<CallInst>(I)) {
00831     const Function *F = Call->getCalledFunction();
00832     LibFunc::Func Func;
00833 
00834     // As a special case, don't handle calls to builtin library functions that
00835     // may be translated directly to target instructions.
00836     if (F && !F->hasLocalLinkage() && F->hasName() &&
00837         LibInfo->getLibFunc(F->getName(), Func) &&
00838         LibInfo->hasOptimizedCodeGen(Func))
00839       return false;
00840 
00841     // Don't handle Intrinsic::trap if a trap funciton is specified.
00842     if (F && F->getIntrinsicID() == Intrinsic::trap &&
00843         !TM.Options.getTrapFunctionName().empty())
00844       return false;
00845   }
00846 
00847   // First, try doing target-independent selection.
00848   if (SelectOperator(I, I->getOpcode())) {
00849     ++NumFastIselSuccessIndependent;
00850     DbgLoc = DebugLoc();
00851     return true;
00852   }
00853   // Remove dead code.  However, ignore call instructions since we've flushed
00854   // the local value map and recomputed the insert point.
00855   if (!isa<CallInst>(I)) {
00856     recomputeInsertPt();
00857     if (SavedInsertPt != FuncInfo.InsertPt)
00858       removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
00859   }
00860 
00861   // Next, try calling the target to attempt to handle the instruction.
00862   SavedInsertPt = FuncInfo.InsertPt;
00863   if (TargetSelectInstruction(I)) {
00864     ++NumFastIselSuccessTarget;
00865     DbgLoc = DebugLoc();
00866     return true;
00867   }
00868   // Check for dead code and remove as necessary.
00869   recomputeInsertPt();
00870   if (SavedInsertPt != FuncInfo.InsertPt)
00871     removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
00872 
00873   DbgLoc = DebugLoc();
00874   return false;
00875 }
00876 
00877 /// FastEmitBranch - Emit an unconditional branch to the given block,
00878 /// unless it is the immediate (fall-through) successor, and update
00879 /// the CFG.
00880 void
00881 FastISel::FastEmitBranch(MachineBasicBlock *MSucc, DebugLoc DbgLoc) {
00882 
00883   if (FuncInfo.MBB->getBasicBlock()->size() > 1 &&
00884       FuncInfo.MBB->isLayoutSuccessor(MSucc)) {
00885     // For more accurate line information if this is the only instruction
00886     // in the block then emit it, otherwise we have the unconditional
00887     // fall-through case, which needs no instructions.
00888   } else {
00889     // The unconditional branch case.
00890     TII.InsertBranch(*FuncInfo.MBB, MSucc, nullptr,
00891                      SmallVector<MachineOperand, 0>(), DbgLoc);
00892   }
00893   FuncInfo.MBB->addSuccessor(MSucc);
00894 }
00895 
00896 /// SelectFNeg - Emit an FNeg operation.
00897 ///
00898 bool
00899 FastISel::SelectFNeg(const User *I) {
00900   unsigned OpReg = getRegForValue(BinaryOperator::getFNegArgument(I));
00901   if (OpReg == 0) return false;
00902 
00903   bool OpRegIsKill = hasTrivialKill(I);
00904 
00905   // If the target has ISD::FNEG, use it.
00906   EVT VT = TLI.getValueType(I->getType());
00907   unsigned ResultReg = FastEmit_r(VT.getSimpleVT(), VT.getSimpleVT(),
00908                                   ISD::FNEG, OpReg, OpRegIsKill);
00909   if (ResultReg != 0) {
00910     UpdateValueMap(I, ResultReg);
00911     return true;
00912   }
00913 
00914   // Bitcast the value to integer, twiddle the sign bit with xor,
00915   // and then bitcast it back to floating-point.
00916   if (VT.getSizeInBits() > 64) return false;
00917   EVT IntVT = EVT::getIntegerVT(I->getContext(), VT.getSizeInBits());
00918   if (!TLI.isTypeLegal(IntVT))
00919     return false;
00920 
00921   unsigned IntReg = FastEmit_r(VT.getSimpleVT(), IntVT.getSimpleVT(),
00922                                ISD::BITCAST, OpReg, OpRegIsKill);
00923   if (IntReg == 0)
00924     return false;
00925 
00926   unsigned IntResultReg = FastEmit_ri_(IntVT.getSimpleVT(), ISD::XOR,
00927                                        IntReg, /*Kill=*/true,
00928                                        UINT64_C(1) << (VT.getSizeInBits()-1),
00929                                        IntVT.getSimpleVT());
00930   if (IntResultReg == 0)
00931     return false;
00932 
00933   ResultReg = FastEmit_r(IntVT.getSimpleVT(), VT.getSimpleVT(),
00934                          ISD::BITCAST, IntResultReg, /*Kill=*/true);
00935   if (ResultReg == 0)
00936     return false;
00937 
00938   UpdateValueMap(I, ResultReg);
00939   return true;
00940 }
00941 
00942 bool
00943 FastISel::SelectExtractValue(const User *U) {
00944   const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(U);
00945   if (!EVI)
00946     return false;
00947 
00948   // Make sure we only try to handle extracts with a legal result.  But also
00949   // allow i1 because it's easy.
00950   EVT RealVT = TLI.getValueType(EVI->getType(), /*AllowUnknown=*/true);
00951   if (!RealVT.isSimple())
00952     return false;
00953   MVT VT = RealVT.getSimpleVT();
00954   if (!TLI.isTypeLegal(VT) && VT != MVT::i1)
00955     return false;
00956 
00957   const Value *Op0 = EVI->getOperand(0);
00958   Type *AggTy = Op0->getType();
00959 
00960   // Get the base result register.
00961   unsigned ResultReg;
00962   DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(Op0);
00963   if (I != FuncInfo.ValueMap.end())
00964     ResultReg = I->second;
00965   else if (isa<Instruction>(Op0))
00966     ResultReg = FuncInfo.InitializeRegForValue(Op0);
00967   else
00968     return false; // fast-isel can't handle aggregate constants at the moment
00969 
00970   // Get the actual result register, which is an offset from the base register.
00971   unsigned VTIndex = ComputeLinearIndex(AggTy, EVI->getIndices());
00972 
00973   SmallVector<EVT, 4> AggValueVTs;
00974   ComputeValueVTs(TLI, AggTy, AggValueVTs);
00975 
00976   for (unsigned i = 0; i < VTIndex; i++)
00977     ResultReg += TLI.getNumRegisters(FuncInfo.Fn->getContext(), AggValueVTs[i]);
00978 
00979   UpdateValueMap(EVI, ResultReg);
00980   return true;
00981 }
00982 
00983 bool
00984 FastISel::SelectOperator(const User *I, unsigned Opcode) {
00985   switch (Opcode) {
00986   case Instruction::Add:
00987     return SelectBinaryOp(I, ISD::ADD);
00988   case Instruction::FAdd:
00989     return SelectBinaryOp(I, ISD::FADD);
00990   case Instruction::Sub:
00991     return SelectBinaryOp(I, ISD::SUB);
00992   case Instruction::FSub:
00993     // FNeg is currently represented in LLVM IR as a special case of FSub.
00994     if (BinaryOperator::isFNeg(I))
00995       return SelectFNeg(I);
00996     return SelectBinaryOp(I, ISD::FSUB);
00997   case Instruction::Mul:
00998     return SelectBinaryOp(I, ISD::MUL);
00999   case Instruction::FMul:
01000     return SelectBinaryOp(I, ISD::FMUL);
01001   case Instruction::SDiv:
01002     return SelectBinaryOp(I, ISD::SDIV);
01003   case Instruction::UDiv:
01004     return SelectBinaryOp(I, ISD::UDIV);
01005   case Instruction::FDiv:
01006     return SelectBinaryOp(I, ISD::FDIV);
01007   case Instruction::SRem:
01008     return SelectBinaryOp(I, ISD::SREM);
01009   case Instruction::URem:
01010     return SelectBinaryOp(I, ISD::UREM);
01011   case Instruction::FRem:
01012     return SelectBinaryOp(I, ISD::FREM);
01013   case Instruction::Shl:
01014     return SelectBinaryOp(I, ISD::SHL);
01015   case Instruction::LShr:
01016     return SelectBinaryOp(I, ISD::SRL);
01017   case Instruction::AShr:
01018     return SelectBinaryOp(I, ISD::SRA);
01019   case Instruction::And:
01020     return SelectBinaryOp(I, ISD::AND);
01021   case Instruction::Or:
01022     return SelectBinaryOp(I, ISD::OR);
01023   case Instruction::Xor:
01024     return SelectBinaryOp(I, ISD::XOR);
01025 
01026   case Instruction::GetElementPtr:
01027     return SelectGetElementPtr(I);
01028 
01029   case Instruction::Br: {
01030     const BranchInst *BI = cast<BranchInst>(I);
01031 
01032     if (BI->isUnconditional()) {
01033       const BasicBlock *LLVMSucc = BI->getSuccessor(0);
01034       MachineBasicBlock *MSucc = FuncInfo.MBBMap[LLVMSucc];
01035       FastEmitBranch(MSucc, BI->getDebugLoc());
01036       return true;
01037     }
01038 
01039     // Conditional branches are not handed yet.
01040     // Halt "fast" selection and bail.
01041     return false;
01042   }
01043 
01044   case Instruction::Unreachable:
01045     if (TM.Options.TrapUnreachable)
01046       return FastEmit_(MVT::Other, MVT::Other, ISD::TRAP) != 0;
01047     else
01048       return true;
01049 
01050   case Instruction::Alloca:
01051     // FunctionLowering has the static-sized case covered.
01052     if (FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(I)))
01053       return true;
01054 
01055     // Dynamic-sized alloca is not handled yet.
01056     return false;
01057 
01058   case Instruction::Call:
01059     return SelectCall(I);
01060 
01061   case Instruction::BitCast:
01062     return SelectBitCast(I);
01063 
01064   case Instruction::FPToSI:
01065     return SelectCast(I, ISD::FP_TO_SINT);
01066   case Instruction::ZExt:
01067     return SelectCast(I, ISD::ZERO_EXTEND);
01068   case Instruction::SExt:
01069     return SelectCast(I, ISD::SIGN_EXTEND);
01070   case Instruction::Trunc:
01071     return SelectCast(I, ISD::TRUNCATE);
01072   case Instruction::SIToFP:
01073     return SelectCast(I, ISD::SINT_TO_FP);
01074 
01075   case Instruction::IntToPtr: // Deliberate fall-through.
01076   case Instruction::PtrToInt: {
01077     EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
01078     EVT DstVT = TLI.getValueType(I->getType());
01079     if (DstVT.bitsGT(SrcVT))
01080       return SelectCast(I, ISD::ZERO_EXTEND);
01081     if (DstVT.bitsLT(SrcVT))
01082       return SelectCast(I, ISD::TRUNCATE);
01083     unsigned Reg = getRegForValue(I->getOperand(0));
01084     if (Reg == 0) return false;
01085     UpdateValueMap(I, Reg);
01086     return true;
01087   }
01088 
01089   case Instruction::ExtractValue:
01090     return SelectExtractValue(I);
01091 
01092   case Instruction::PHI:
01093     llvm_unreachable("FastISel shouldn't visit PHI nodes!");
01094 
01095   default:
01096     // Unhandled instruction. Halt "fast" selection and bail.
01097     return false;
01098   }
01099 }
01100 
01101 FastISel::FastISel(FunctionLoweringInfo &funcInfo,
01102                    const TargetLibraryInfo *libInfo)
01103   : FuncInfo(funcInfo),
01104     MRI(FuncInfo.MF->getRegInfo()),
01105     MFI(*FuncInfo.MF->getFrameInfo()),
01106     MCP(*FuncInfo.MF->getConstantPool()),
01107     TM(FuncInfo.MF->getTarget()),
01108     DL(*TM.getDataLayout()),
01109     TII(*TM.getInstrInfo()),
01110     TLI(*TM.getTargetLowering()),
01111     TRI(*TM.getRegisterInfo()),
01112     LibInfo(libInfo) {
01113 }
01114 
01115 FastISel::~FastISel() {}
01116 
01117 bool FastISel::FastLowerArguments() {
01118   return false;
01119 }
01120 
01121 unsigned FastISel::FastEmit_(MVT, MVT,
01122                              unsigned) {
01123   return 0;
01124 }
01125 
01126 unsigned FastISel::FastEmit_r(MVT, MVT,
01127                               unsigned,
01128                               unsigned /*Op0*/, bool /*Op0IsKill*/) {
01129   return 0;
01130 }
01131 
01132 unsigned FastISel::FastEmit_rr(MVT, MVT,
01133                                unsigned,
01134                                unsigned /*Op0*/, bool /*Op0IsKill*/,
01135                                unsigned /*Op1*/, bool /*Op1IsKill*/) {
01136   return 0;
01137 }
01138 
01139 unsigned FastISel::FastEmit_i(MVT, MVT, unsigned, uint64_t /*Imm*/) {
01140   return 0;
01141 }
01142 
01143 unsigned FastISel::FastEmit_f(MVT, MVT,
01144                               unsigned, const ConstantFP * /*FPImm*/) {
01145   return 0;
01146 }
01147 
01148 unsigned FastISel::FastEmit_ri(MVT, MVT,
01149                                unsigned,
01150                                unsigned /*Op0*/, bool /*Op0IsKill*/,
01151                                uint64_t /*Imm*/) {
01152   return 0;
01153 }
01154 
01155 unsigned FastISel::FastEmit_rf(MVT, MVT,
01156                                unsigned,
01157                                unsigned /*Op0*/, bool /*Op0IsKill*/,
01158                                const ConstantFP * /*FPImm*/) {
01159   return 0;
01160 }
01161 
01162 unsigned FastISel::FastEmit_rri(MVT, MVT,
01163                                 unsigned,
01164                                 unsigned /*Op0*/, bool /*Op0IsKill*/,
01165                                 unsigned /*Op1*/, bool /*Op1IsKill*/,
01166                                 uint64_t /*Imm*/) {
01167   return 0;
01168 }
01169 
01170 /// FastEmit_ri_ - This method is a wrapper of FastEmit_ri. It first tries
01171 /// to emit an instruction with an immediate operand using FastEmit_ri.
01172 /// If that fails, it materializes the immediate into a register and try
01173 /// FastEmit_rr instead.
01174 unsigned FastISel::FastEmit_ri_(MVT VT, unsigned Opcode,
01175                                 unsigned Op0, bool Op0IsKill,
01176                                 uint64_t Imm, MVT ImmType) {
01177   // If this is a multiply by a power of two, emit this as a shift left.
01178   if (Opcode == ISD::MUL && isPowerOf2_64(Imm)) {
01179     Opcode = ISD::SHL;
01180     Imm = Log2_64(Imm);
01181   } else if (Opcode == ISD::UDIV && isPowerOf2_64(Imm)) {
01182     // div x, 8 -> srl x, 3
01183     Opcode = ISD::SRL;
01184     Imm = Log2_64(Imm);
01185   }
01186 
01187   // Horrible hack (to be removed), check to make sure shift amounts are
01188   // in-range.
01189   if ((Opcode == ISD::SHL || Opcode == ISD::SRA || Opcode == ISD::SRL) &&
01190       Imm >= VT.getSizeInBits())
01191     return 0;
01192 
01193   // First check if immediate type is legal. If not, we can't use the ri form.
01194   unsigned ResultReg = FastEmit_ri(VT, VT, Opcode, Op0, Op0IsKill, Imm);
01195   if (ResultReg != 0)
01196     return ResultReg;
01197   unsigned MaterialReg = FastEmit_i(ImmType, ImmType, ISD::Constant, Imm);
01198   if (MaterialReg == 0) {
01199     // This is a bit ugly/slow, but failing here means falling out of
01200     // fast-isel, which would be very slow.
01201     IntegerType *ITy = IntegerType::get(FuncInfo.Fn->getContext(),
01202                                               VT.getSizeInBits());
01203     MaterialReg = getRegForValue(ConstantInt::get(ITy, Imm));
01204     assert (MaterialReg != 0 && "Unable to materialize imm.");
01205     if (MaterialReg == 0) return 0;
01206   }
01207   return FastEmit_rr(VT, VT, Opcode,
01208                      Op0, Op0IsKill,
01209                      MaterialReg, /*Kill=*/true);
01210 }
01211 
01212 unsigned FastISel::createResultReg(const TargetRegisterClass* RC) {
01213   return MRI.createVirtualRegister(RC);
01214 }
01215 
01216 unsigned FastISel::constrainOperandRegClass(const MCInstrDesc &II,
01217                                             unsigned Op, unsigned OpNum) {
01218   if (TargetRegisterInfo::isVirtualRegister(Op)) {
01219     const TargetRegisterClass *RegClass =
01220         TII.getRegClass(II, OpNum, &TRI, *FuncInfo.MF);
01221     if (!MRI.constrainRegClass(Op, RegClass)) {
01222       // If it's not legal to COPY between the register classes, something
01223       // has gone very wrong before we got here.
01224       unsigned NewOp = createResultReg(RegClass);
01225       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01226               TII.get(TargetOpcode::COPY), NewOp).addReg(Op);
01227       return NewOp;
01228     }
01229   }
01230   return Op;
01231 }
01232 
01233 unsigned FastISel::FastEmitInst_(unsigned MachineInstOpcode,
01234                                  const TargetRegisterClass* RC) {
01235   unsigned ResultReg = createResultReg(RC);
01236   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01237 
01238   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg);
01239   return ResultReg;
01240 }
01241 
01242 unsigned FastISel::FastEmitInst_r(unsigned MachineInstOpcode,
01243                                   const TargetRegisterClass *RC,
01244                                   unsigned Op0, bool Op0IsKill) {
01245   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01246 
01247   unsigned ResultReg = createResultReg(RC);
01248   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
01249 
01250   if (II.getNumDefs() >= 1)
01251     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
01252       .addReg(Op0, Op0IsKill * RegState::Kill);
01253   else {
01254     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01255       .addReg(Op0, Op0IsKill * RegState::Kill);
01256     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01257             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01258   }
01259 
01260   return ResultReg;
01261 }
01262 
01263 unsigned FastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
01264                                    const TargetRegisterClass *RC,
01265                                    unsigned Op0, bool Op0IsKill,
01266                                    unsigned Op1, bool Op1IsKill) {
01267   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01268 
01269   unsigned ResultReg = createResultReg(RC);
01270   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
01271   Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
01272 
01273   if (II.getNumDefs() >= 1)
01274     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
01275       .addReg(Op0, Op0IsKill * RegState::Kill)
01276       .addReg(Op1, Op1IsKill * RegState::Kill);
01277   else {
01278     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01279       .addReg(Op0, Op0IsKill * RegState::Kill)
01280       .addReg(Op1, Op1IsKill * RegState::Kill);
01281     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01282             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01283   }
01284   return ResultReg;
01285 }
01286 
01287 unsigned FastISel::FastEmitInst_rrr(unsigned MachineInstOpcode,
01288                                    const TargetRegisterClass *RC,
01289                                    unsigned Op0, bool Op0IsKill,
01290                                    unsigned Op1, bool Op1IsKill,
01291                                    unsigned Op2, bool Op2IsKill) {
01292   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01293 
01294   unsigned ResultReg = createResultReg(RC);
01295   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
01296   Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
01297   Op2 = constrainOperandRegClass(II, Op2, II.getNumDefs() + 2);
01298 
01299   if (II.getNumDefs() >= 1)
01300     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
01301       .addReg(Op0, Op0IsKill * RegState::Kill)
01302       .addReg(Op1, Op1IsKill * RegState::Kill)
01303       .addReg(Op2, Op2IsKill * RegState::Kill);
01304   else {
01305     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01306       .addReg(Op0, Op0IsKill * RegState::Kill)
01307       .addReg(Op1, Op1IsKill * RegState::Kill)
01308       .addReg(Op2, Op2IsKill * RegState::Kill);
01309     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01310             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01311   }
01312   return ResultReg;
01313 }
01314 
01315 unsigned FastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
01316                                    const TargetRegisterClass *RC,
01317                                    unsigned Op0, bool Op0IsKill,
01318                                    uint64_t Imm) {
01319   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01320 
01321   unsigned ResultReg = createResultReg(RC);
01322   RC = TII.getRegClass(II, II.getNumDefs(), &TRI, *FuncInfo.MF);
01323   MRI.constrainRegClass(Op0, RC);
01324 
01325   if (II.getNumDefs() >= 1)
01326     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
01327       .addReg(Op0, Op0IsKill * RegState::Kill)
01328       .addImm(Imm);
01329   else {
01330     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01331       .addReg(Op0, Op0IsKill * RegState::Kill)
01332       .addImm(Imm);
01333     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01334             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01335   }
01336   return ResultReg;
01337 }
01338 
01339 unsigned FastISel::FastEmitInst_rii(unsigned MachineInstOpcode,
01340                                    const TargetRegisterClass *RC,
01341                                    unsigned Op0, bool Op0IsKill,
01342                                    uint64_t Imm1, uint64_t Imm2) {
01343   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01344 
01345   unsigned ResultReg = createResultReg(RC);
01346   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
01347 
01348   if (II.getNumDefs() >= 1)
01349     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
01350       .addReg(Op0, Op0IsKill * RegState::Kill)
01351       .addImm(Imm1)
01352       .addImm(Imm2);
01353   else {
01354     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01355       .addReg(Op0, Op0IsKill * RegState::Kill)
01356       .addImm(Imm1)
01357       .addImm(Imm2);
01358     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01359             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01360   }
01361   return ResultReg;
01362 }
01363 
01364 unsigned FastISel::FastEmitInst_rf(unsigned MachineInstOpcode,
01365                                    const TargetRegisterClass *RC,
01366                                    unsigned Op0, bool Op0IsKill,
01367                                    const ConstantFP *FPImm) {
01368   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01369 
01370   unsigned ResultReg = createResultReg(RC);
01371   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
01372 
01373   if (II.getNumDefs() >= 1)
01374     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
01375       .addReg(Op0, Op0IsKill * RegState::Kill)
01376       .addFPImm(FPImm);
01377   else {
01378     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01379       .addReg(Op0, Op0IsKill * RegState::Kill)
01380       .addFPImm(FPImm);
01381     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01382             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01383   }
01384   return ResultReg;
01385 }
01386 
01387 unsigned FastISel::FastEmitInst_rri(unsigned MachineInstOpcode,
01388                                     const TargetRegisterClass *RC,
01389                                     unsigned Op0, bool Op0IsKill,
01390                                     unsigned Op1, bool Op1IsKill,
01391                                     uint64_t Imm) {
01392   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01393 
01394   unsigned ResultReg = createResultReg(RC);
01395   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
01396   Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
01397 
01398   if (II.getNumDefs() >= 1)
01399     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
01400       .addReg(Op0, Op0IsKill * RegState::Kill)
01401       .addReg(Op1, Op1IsKill * RegState::Kill)
01402       .addImm(Imm);
01403   else {
01404     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01405       .addReg(Op0, Op0IsKill * RegState::Kill)
01406       .addReg(Op1, Op1IsKill * RegState::Kill)
01407       .addImm(Imm);
01408     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01409             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01410   }
01411   return ResultReg;
01412 }
01413 
01414 unsigned FastISel::FastEmitInst_rrii(unsigned MachineInstOpcode,
01415                                      const TargetRegisterClass *RC,
01416                                      unsigned Op0, bool Op0IsKill,
01417                                      unsigned Op1, bool Op1IsKill,
01418                                      uint64_t Imm1, uint64_t Imm2) {
01419   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01420 
01421   unsigned ResultReg = createResultReg(RC);
01422   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
01423   Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
01424 
01425   if (II.getNumDefs() >= 1)
01426     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
01427       .addReg(Op0, Op0IsKill * RegState::Kill)
01428       .addReg(Op1, Op1IsKill * RegState::Kill)
01429       .addImm(Imm1).addImm(Imm2);
01430   else {
01431     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
01432       .addReg(Op0, Op0IsKill * RegState::Kill)
01433       .addReg(Op1, Op1IsKill * RegState::Kill)
01434       .addImm(Imm1).addImm(Imm2);
01435     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01436             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01437   }
01438   return ResultReg;
01439 }
01440 
01441 unsigned FastISel::FastEmitInst_i(unsigned MachineInstOpcode,
01442                                   const TargetRegisterClass *RC,
01443                                   uint64_t Imm) {
01444   unsigned ResultReg = createResultReg(RC);
01445   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01446 
01447   if (II.getNumDefs() >= 1)
01448     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg).addImm(Imm);
01449   else {
01450     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addImm(Imm);
01451     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01452             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01453   }
01454   return ResultReg;
01455 }
01456 
01457 unsigned FastISel::FastEmitInst_ii(unsigned MachineInstOpcode,
01458                                   const TargetRegisterClass *RC,
01459                                   uint64_t Imm1, uint64_t Imm2) {
01460   unsigned ResultReg = createResultReg(RC);
01461   const MCInstrDesc &II = TII.get(MachineInstOpcode);
01462 
01463   if (II.getNumDefs() >= 1)
01464     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
01465       .addImm(Imm1).addImm(Imm2);
01466   else {
01467     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addImm(Imm1).addImm(Imm2);
01468     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
01469             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
01470   }
01471   return ResultReg;
01472 }
01473 
01474 unsigned FastISel::FastEmitInst_extractsubreg(MVT RetVT,
01475                                               unsigned Op0, bool Op0IsKill,
01476                                               uint32_t Idx) {
01477   unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
01478   assert(TargetRegisterInfo::isVirtualRegister(Op0) &&
01479          "Cannot yet extract from physregs");
01480   const TargetRegisterClass *RC = MRI.getRegClass(Op0);
01481   MRI.constrainRegClass(Op0, TRI.getSubClassWithSubReg(RC, Idx));
01482   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
01483           DbgLoc, TII.get(TargetOpcode::COPY), ResultReg)
01484     .addReg(Op0, getKillRegState(Op0IsKill), Idx);
01485   return ResultReg;
01486 }
01487 
01488 /// FastEmitZExtFromI1 - Emit MachineInstrs to compute the value of Op
01489 /// with all but the least significant bit set to zero.
01490 unsigned FastISel::FastEmitZExtFromI1(MVT VT, unsigned Op0, bool Op0IsKill) {
01491   return FastEmit_ri(VT, VT, ISD::AND, Op0, Op0IsKill, 1);
01492 }
01493 
01494 /// HandlePHINodesInSuccessorBlocks - Handle PHI nodes in successor blocks.
01495 /// Emit code to ensure constants are copied into registers when needed.
01496 /// Remember the virtual registers that need to be added to the Machine PHI
01497 /// nodes as input.  We cannot just directly add them, because expansion
01498 /// might result in multiple MBB's for one BB.  As such, the start of the
01499 /// BB might correspond to a different MBB than the end.
01500 bool FastISel::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
01501   const TerminatorInst *TI = LLVMBB->getTerminator();
01502 
01503   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
01504   unsigned OrigNumPHINodesToUpdate = FuncInfo.PHINodesToUpdate.size();
01505 
01506   // Check successor nodes' PHI nodes that expect a constant to be available
01507   // from this block.
01508   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
01509     const BasicBlock *SuccBB = TI->getSuccessor(succ);
01510     if (!isa<PHINode>(SuccBB->begin())) continue;
01511     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
01512 
01513     // If this terminator has multiple identical successors (common for
01514     // switches), only handle each succ once.
01515     if (!SuccsHandled.insert(SuccMBB)) continue;
01516 
01517     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
01518 
01519     // At this point we know that there is a 1-1 correspondence between LLVM PHI
01520     // nodes and Machine PHI nodes, but the incoming operands have not been
01521     // emitted yet.
01522     for (BasicBlock::const_iterator I = SuccBB->begin();
01523          const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
01524 
01525       // Ignore dead phi's.
01526       if (PN->use_empty()) continue;
01527 
01528       // Only handle legal types. Two interesting things to note here. First,
01529       // by bailing out early, we may leave behind some dead instructions,
01530       // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
01531       // own moves. Second, this check is necessary because FastISel doesn't
01532       // use CreateRegs to create registers, so it always creates
01533       // exactly one register for each non-void instruction.
01534       EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
01535       if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
01536         // Handle integer promotions, though, because they're common and easy.
01537         if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
01538           VT = TLI.getTypeToTransformTo(LLVMBB->getContext(), VT);
01539         else {
01540           FuncInfo.PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
01541           return false;
01542         }
01543       }
01544 
01545       const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
01546 
01547       // Set the DebugLoc for the copy. Prefer the location of the operand
01548       // if there is one; use the location of the PHI otherwise.
01549       DbgLoc = PN->getDebugLoc();
01550       if (const Instruction *Inst = dyn_cast<Instruction>(PHIOp))
01551         DbgLoc = Inst->getDebugLoc();
01552 
01553       unsigned Reg = getRegForValue(PHIOp);
01554       if (Reg == 0) {
01555         FuncInfo.PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
01556         return false;
01557       }
01558       FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
01559       DbgLoc = DebugLoc();
01560     }
01561   }
01562 
01563   return true;
01564 }
01565 
01566 bool FastISel::tryToFoldLoad(const LoadInst *LI, const Instruction *FoldInst) {
01567   assert(LI->hasOneUse() &&
01568       "tryToFoldLoad expected a LoadInst with a single use");
01569   // We know that the load has a single use, but don't know what it is.  If it
01570   // isn't one of the folded instructions, then we can't succeed here.  Handle
01571   // this by scanning the single-use users of the load until we get to FoldInst.
01572   unsigned MaxUsers = 6;  // Don't scan down huge single-use chains of instrs.
01573 
01574   const Instruction *TheUser = LI->user_back();
01575   while (TheUser != FoldInst &&   // Scan up until we find FoldInst.
01576          // Stay in the right block.
01577          TheUser->getParent() == FoldInst->getParent() &&
01578          --MaxUsers) {  // Don't scan too far.
01579     // If there are multiple or no uses of this instruction, then bail out.
01580     if (!TheUser->hasOneUse())
01581       return false;
01582 
01583     TheUser = TheUser->user_back();
01584   }
01585 
01586   // If we didn't find the fold instruction, then we failed to collapse the
01587   // sequence.
01588   if (TheUser != FoldInst)
01589     return false;
01590 
01591   // Don't try to fold volatile loads.  Target has to deal with alignment
01592   // constraints.
01593   if (LI->isVolatile())
01594     return false;
01595 
01596   // Figure out which vreg this is going into.  If there is no assigned vreg yet
01597   // then there actually was no reference to it.  Perhaps the load is referenced
01598   // by a dead instruction.
01599   unsigned LoadReg = getRegForValue(LI);
01600   if (LoadReg == 0)
01601     return false;
01602 
01603   // We can't fold if this vreg has no uses or more than one use.  Multiple uses
01604   // may mean that the instruction got lowered to multiple MIs, or the use of
01605   // the loaded value ended up being multiple operands of the result.
01606   if (!MRI.hasOneUse(LoadReg))
01607     return false;
01608 
01609   MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(LoadReg);
01610   MachineInstr *User = RI->getParent();
01611 
01612   // Set the insertion point properly.  Folding the load can cause generation of
01613   // other random instructions (like sign extends) for addressing modes; make
01614   // sure they get inserted in a logical place before the new instruction.
01615   FuncInfo.InsertPt = User;
01616   FuncInfo.MBB = User->getParent();
01617 
01618   // Ask the target to try folding the load.
01619   return tryToFoldLoadIntoMI(User, RI.getOperandNo(), LI);
01620 }
01621 
01622 bool FastISel::canFoldAddIntoGEP(const User *GEP, const Value *Add) {
01623   // Must be an add.
01624   if (!isa<AddOperator>(Add))
01625     return false;
01626   // Type size needs to match.
01627   if (DL.getTypeSizeInBits(GEP->getType()) !=
01628       DL.getTypeSizeInBits(Add->getType()))
01629     return false;
01630   // Must be in the same basic block.
01631   if (isa<Instruction>(Add) &&
01632       FuncInfo.MBBMap[cast<Instruction>(Add)->getParent()] != FuncInfo.MBB)
01633     return false;
01634   // Must have a constant operand.
01635   return isa<ConstantInt>(cast<AddOperator>(Add)->getOperand(1));
01636 }
01637