LLVM API Documentation

SelectionDAGBuild.cpp

Go to the documentation of this file.
00001 //===-- SelectionDAGBuild.cpp - Selection-DAG building --------------------===//
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 implements routines for translating from LLVM IR into SelectionDAG IR.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #define DEBUG_TYPE "isel"
00015 #include "SelectionDAGBuild.h"
00016 #include "llvm/ADT/BitVector.h"
00017 #include "llvm/ADT/SmallSet.h"
00018 #include "llvm/Analysis/AliasAnalysis.h"
00019 #include "llvm/Constants.h"
00020 #include "llvm/CallingConv.h"
00021 #include "llvm/DerivedTypes.h"
00022 #include "llvm/Function.h"
00023 #include "llvm/GlobalVariable.h"
00024 #include "llvm/InlineAsm.h"
00025 #include "llvm/Instructions.h"
00026 #include "llvm/Intrinsics.h"
00027 #include "llvm/IntrinsicInst.h"
00028 #include "llvm/Module.h"
00029 #include "llvm/CodeGen/FastISel.h"
00030 #include "llvm/CodeGen/GCStrategy.h"
00031 #include "llvm/CodeGen/GCMetadata.h"
00032 #include "llvm/CodeGen/MachineFunction.h"
00033 #include "llvm/CodeGen/MachineFrameInfo.h"
00034 #include "llvm/CodeGen/MachineInstrBuilder.h"
00035 #include "llvm/CodeGen/MachineJumpTableInfo.h"
00036 #include "llvm/CodeGen/MachineModuleInfo.h"
00037 #include "llvm/CodeGen/MachineRegisterInfo.h"
00038 #include "llvm/CodeGen/PseudoSourceValue.h"
00039 #include "llvm/CodeGen/SelectionDAG.h"
00040 #include "llvm/CodeGen/DwarfWriter.h"
00041 #include "llvm/Analysis/DebugInfo.h"
00042 #include "llvm/Target/TargetRegisterInfo.h"
00043 #include "llvm/Target/TargetData.h"
00044 #include "llvm/Target/TargetFrameInfo.h"
00045 #include "llvm/Target/TargetInstrInfo.h"
00046 #include "llvm/Target/TargetLowering.h"
00047 #include "llvm/Target/TargetMachine.h"
00048 #include "llvm/Target/TargetOptions.h"
00049 #include "llvm/Support/Compiler.h"
00050 #include "llvm/Support/CommandLine.h"
00051 #include "llvm/Support/Debug.h"
00052 #include "llvm/Support/MathExtras.h"
00053 #include "llvm/Support/raw_ostream.h"
00054 #include <algorithm>
00055 using namespace llvm;
00056 
00057 /// LimitFloatPrecision - Generate low-precision inline sequences for
00058 /// some float libcalls (6, 8 or 12 bits).
00059 static unsigned LimitFloatPrecision;
00060 
00061 static cl::opt<unsigned, true>
00062 LimitFPPrecision("limit-float-precision",
00063                  cl::desc("Generate low-precision inline sequences "
00064                           "for some float libcalls"),
00065                  cl::location(LimitFloatPrecision),
00066                  cl::init(0));
00067 
00068 /// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
00069 /// of insertvalue or extractvalue indices that identify a member, return
00070 /// the linearized index of the start of the member.
00071 ///
00072 static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
00073                                    const unsigned *Indices,
00074                                    const unsigned *IndicesEnd,
00075                                    unsigned CurIndex = 0) {
00076   // Base case: We're done.
00077   if (Indices && Indices == IndicesEnd)
00078     return CurIndex;
00079 
00080   // Given a struct type, recursively traverse the elements.
00081   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
00082     for (StructType::element_iterator EB = STy->element_begin(),
00083                                       EI = EB,
00084                                       EE = STy->element_end();
00085         EI != EE; ++EI) {
00086       if (Indices && *Indices == unsigned(EI - EB))
00087         return ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd, CurIndex);
00088       CurIndex = ComputeLinearIndex(TLI, *EI, 0, 0, CurIndex);
00089     }
00090     return CurIndex;
00091   }
00092   // Given an array type, recursively traverse the elements.
00093   else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
00094     const Type *EltTy = ATy->getElementType();
00095     for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
00096       if (Indices && *Indices == i)
00097         return ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd, CurIndex);
00098       CurIndex = ComputeLinearIndex(TLI, EltTy, 0, 0, CurIndex);
00099     }
00100     return CurIndex;
00101   }
00102   // We haven't found the type we're looking for, so keep searching.
00103   return CurIndex + 1;
00104 }
00105 
00106 /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
00107 /// MVTs that represent all the individual underlying
00108 /// non-aggregate types that comprise it.
00109 ///
00110 /// If Offsets is non-null, it points to a vector to be filled in
00111 /// with the in-memory offsets of each of the individual values.
00112 ///
00113 static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
00114                             SmallVectorImpl<MVT> &ValueVTs,
00115                             SmallVectorImpl<uint64_t> *Offsets = 0,
00116                             uint64_t StartingOffset = 0) {
00117   // Given a struct type, recursively traverse the elements.
00118   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
00119     const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
00120     for (StructType::element_iterator EB = STy->element_begin(),
00121                                       EI = EB,
00122                                       EE = STy->element_end();
00123          EI != EE; ++EI)
00124       ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
00125                       StartingOffset + SL->getElementOffset(EI - EB));
00126     return;
00127   }
00128   // Given an array type, recursively traverse the elements.
00129   if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
00130     const Type *EltTy = ATy->getElementType();
00131     uint64_t EltSize = TLI.getTargetData()->getTypePaddedSize(EltTy);
00132     for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
00133       ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
00134                       StartingOffset + i * EltSize);
00135     return;
00136   }
00137   // Base case: we can get an MVT for this LLVM IR type.
00138   ValueVTs.push_back(TLI.getValueType(Ty));
00139   if (Offsets)
00140     Offsets->push_back(StartingOffset);
00141 }
00142 
00143 namespace llvm {
00144   /// RegsForValue - This struct represents the registers (physical or virtual)
00145   /// that a particular set of values is assigned, and the type information about
00146   /// the value. The most common situation is to represent one value at a time,
00147   /// but struct or array values are handled element-wise as multiple values.
00148   /// The splitting of aggregates is performed recursively, so that we never
00149   /// have aggregate-typed registers. The values at this point do not necessarily
00150   /// have legal types, so each value may require one or more registers of some
00151   /// legal type.
00152   ///
00153   struct VISIBILITY_HIDDEN RegsForValue {
00154     /// TLI - The TargetLowering object.
00155     ///
00156     const TargetLowering *TLI;
00157 
00158     /// ValueVTs - The value types of the values, which may not be legal, and
00159     /// may need be promoted or synthesized from one or more registers.
00160     ///
00161     SmallVector<MVT, 4> ValueVTs;
00162 
00163     /// RegVTs - The value types of the registers. This is the same size as
00164     /// ValueVTs and it records, for each value, what the type of the assigned
00165     /// register or registers are. (Individual values are never synthesized
00166     /// from more than one type of register.)
00167     ///
00168     /// With virtual registers, the contents of RegVTs is redundant with TLI's
00169     /// getRegisterType member function, however when with physical registers
00170     /// it is necessary to have a separate record of the types.
00171     ///
00172     SmallVector<MVT, 4> RegVTs;
00173 
00174     /// Regs - This list holds the registers assigned to the values.
00175     /// Each legal or promoted value requires one register, and each
00176     /// expanded value requires multiple registers.
00177     ///
00178     SmallVector<unsigned, 4> Regs;
00179 
00180     RegsForValue() : TLI(0) {}
00181 
00182     RegsForValue(const TargetLowering &tli,
00183                  const SmallVector<unsigned, 4> &regs,
00184                  MVT regvt, MVT valuevt)
00185       : TLI(&tli),  ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
00186     RegsForValue(const TargetLowering &tli,
00187                  const SmallVector<unsigned, 4> &regs,
00188                  const SmallVector<MVT, 4> &regvts,
00189                  const SmallVector<MVT, 4> &valuevts)
00190       : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
00191     RegsForValue(const TargetLowering &tli,
00192                  unsigned Reg, const Type *Ty) : TLI(&tli) {
00193       ComputeValueVTs(tli, Ty, ValueVTs);
00194 
00195       for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
00196         MVT ValueVT = ValueVTs[Value];
00197         unsigned NumRegs = TLI->getNumRegisters(ValueVT);
00198         MVT RegisterVT = TLI->getRegisterType(ValueVT);
00199         for (unsigned i = 0; i != NumRegs; ++i)
00200           Regs.push_back(Reg + i);
00201         RegVTs.push_back(RegisterVT);
00202         Reg += NumRegs;
00203       }
00204     }
00205 
00206     /// append - Add the specified values to this one.
00207     void append(const RegsForValue &RHS) {
00208       TLI = RHS.TLI;
00209       ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
00210       RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
00211       Regs.append(RHS.Regs.begin(), RHS.Regs.end());
00212     }
00213 
00214 
00215     /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
00216     /// this value and returns the result as a ValueVTs value.  This uses
00217     /// Chain/Flag as the input and updates them for the output Chain/Flag.
00218     /// If the Flag pointer is NULL, no flag is used.
00219     SDValue getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
00220                               SDValue &Chain, SDValue *Flag) const;
00221 
00222     /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
00223     /// specified value into the registers specified by this object.  This uses
00224     /// Chain/Flag as the input and updates them for the output Chain/Flag.
00225     /// If the Flag pointer is NULL, no flag is used.
00226     void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
00227                        SDValue &Chain, SDValue *Flag) const;
00228 
00229     /// AddInlineAsmOperands - Add this value to the specified inlineasm node
00230     /// operand list.  This adds the code marker and includes the number of
00231     /// values added into it.
00232     void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
00233                               std::vector<SDValue> &Ops) const;
00234   };
00235 }
00236 
00237 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
00238 /// PHI nodes or outside of the basic block that defines it, or used by a
00239 /// switch or atomic instruction, which may expand to multiple basic blocks.
00240 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
00241   if (isa<PHINode>(I)) return true;
00242   BasicBlock *BB = I->getParent();
00243   for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
00244     if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
00245         // FIXME: Remove switchinst special case.
00246         isa<SwitchInst>(*UI))
00247       return true;
00248   return false;
00249 }
00250 
00251 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
00252 /// entry block, return true.  This includes arguments used by switches, since
00253 /// the switch may expand into multiple basic blocks.
00254 static bool isOnlyUsedInEntryBlock(Argument *A, bool EnableFastISel) {
00255   // With FastISel active, we may be splitting blocks, so force creation
00256   // of virtual registers for all non-dead arguments.
00257   // Don't force virtual registers for byval arguments though, because
00258   // fast-isel can't handle those in all cases.
00259   if (EnableFastISel && !A->hasByValAttr())
00260     return A->use_empty();
00261 
00262   BasicBlock *Entry = A->getParent()->begin();
00263   for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
00264     if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
00265       return false;  // Use not in entry block.
00266   return true;
00267 }
00268 
00269 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli)
00270   : TLI(tli) {
00271 }
00272 
00273 void FunctionLoweringInfo::set(Function &fn, MachineFunction &mf,
00274                                SelectionDAG &DAG,
00275                                bool EnableFastISel) {
00276   Fn = &fn;
00277   MF = &mf;
00278   RegInfo = &MF->getRegInfo();
00279 
00280   // Create a vreg for each argument register that is not dead and is used
00281   // outside of the entry block for the function.
00282   for (Function::arg_iterator AI = Fn->arg_begin(), E = Fn->arg_end();
00283        AI != E; ++AI)
00284     if (!isOnlyUsedInEntryBlock(AI, EnableFastISel))
00285       InitializeRegForValue(AI);
00286 
00287   // Initialize the mapping of values to registers.  This is only set up for
00288   // instruction values that are used outside of the block that defines
00289   // them.
00290   Function::iterator BB = Fn->begin(), EB = Fn->end();
00291   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
00292     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
00293       if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
00294         const Type *Ty = AI->getAllocatedType();
00295         uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
00296         unsigned Align =
00297           std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
00298                    AI->getAlignment());
00299 
00300         TySize *= CUI->getZExtValue();   // Get total allocated size.
00301         if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
00302         StaticAllocaMap[AI] =
00303           MF->getFrameInfo()->CreateStackObject(TySize, Align);
00304       }
00305 
00306   for (; BB != EB; ++BB)
00307     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
00308       if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
00309         if (!isa<AllocaInst>(I) ||
00310             !StaticAllocaMap.count(cast<AllocaInst>(I)))
00311           InitializeRegForValue(I);
00312 
00313   // Create an initial MachineBasicBlock for each LLVM BasicBlock in F.  This
00314   // also creates the initial PHI MachineInstrs, though none of the input
00315   // operands are populated.
00316   for (BB = Fn->begin(), EB = Fn->end(); BB != EB; ++BB) {
00317     MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
00318     MBBMap[BB] = MBB;
00319     MF->push_back(MBB);
00320 
00321     // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
00322     // appropriate.
00323     PHINode *PN;
00324     DebugLoc DL;
00325     for (BasicBlock::iterator
00326            I = BB->begin(), E = BB->end(); I != E; ++I) {
00327       if (CallInst *CI = dyn_cast<CallInst>(I)) {
00328         if (Function *F = CI->getCalledFunction()) {
00329           switch (F->getIntrinsicID()) {
00330           default: break;
00331           case Intrinsic::dbg_stoppoint: {
00332             DwarfWriter *DW = DAG.getDwarfWriter();
00333             DbgStopPointInst *SPI = cast<DbgStopPointInst>(I);
00334 
00335             if (DW && DW->ValidDebugInfo(SPI->getContext())) {
00336               DICompileUnit CU(cast<GlobalVariable>(SPI->getContext()));
00337               unsigned SrcFile = DW->RecordSource(CU.getDirectory(),
00338                                                   CU.getFilename());
00339               unsigned idx = MF->getOrCreateDebugLocID(SrcFile,
00340                                                        SPI->getLine(), 
00341                                                        SPI->getColumn());
00342               DL = DebugLoc::get(idx);
00343             }
00344 
00345             break;
00346           }
00347           case Intrinsic::dbg_func_start: {
00348             DwarfWriter *DW = DAG.getDwarfWriter();
00349             if (DW) {
00350               DbgFuncStartInst *FSI = cast<DbgFuncStartInst>(I);
00351               Value *SP = FSI->getSubprogram();
00352 
00353               if (DW->ValidDebugInfo(SP)) {
00354                 DISubprogram Subprogram(cast<GlobalVariable>(SP));
00355                 DICompileUnit CU(Subprogram.getCompileUnit());
00356                 unsigned SrcFile = DW->RecordSource(CU.getDirectory(),
00357                                                     CU.getFilename());
00358                 unsigned Line = Subprogram.getLineNumber();
00359                 DL = DebugLoc::get(MF->getOrCreateDebugLocID(SrcFile, Line, 0));
00360               }
00361             }
00362           
00363             break;
00364           }
00365           }
00366         }
00367       }
00368 
00369       PN = dyn_cast<PHINode>(I);
00370       if (!PN || PN->use_empty()) continue;
00371 
00372       unsigned PHIReg = ValueMap[PN];
00373       assert(PHIReg && "PHI node does not have an assigned virtual register!");
00374 
00375       SmallVector<MVT, 4> ValueVTs;
00376       ComputeValueVTs(TLI, PN->getType(), ValueVTs);
00377       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
00378         MVT VT = ValueVTs[vti];
00379         unsigned NumRegisters = TLI.getNumRegisters(VT);
00380         const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
00381         for (unsigned i = 0; i != NumRegisters; ++i)
00382           BuildMI(MBB, DL, TII->get(TargetInstrInfo::PHI), PHIReg + i);
00383         PHIReg += NumRegisters;
00384       }
00385     }
00386   }
00387 }
00388 
00389 unsigned FunctionLoweringInfo::MakeReg(MVT VT) {
00390   return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
00391 }
00392 
00393 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
00394 /// the correctly promoted or expanded types.  Assign these registers
00395 /// consecutive vreg numbers and return the first assigned number.
00396 ///
00397 /// In the case that the given value has struct or array type, this function
00398 /// will assign registers for each member or element.
00399 ///
00400 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
00401   SmallVector<MVT, 4> ValueVTs;
00402   ComputeValueVTs(TLI, V->getType(), ValueVTs);
00403 
00404   unsigned FirstReg = 0;
00405   for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
00406     MVT ValueVT = ValueVTs[Value];
00407     MVT RegisterVT = TLI.getRegisterType(ValueVT);
00408 
00409     unsigned NumRegs = TLI.getNumRegisters(ValueVT);
00410     for (unsigned i = 0; i != NumRegs; ++i) {
00411       unsigned R = MakeReg(RegisterVT);
00412       if (!FirstReg) FirstReg = R;
00413     }
00414   }
00415   return FirstReg;
00416 }
00417 
00418 /// getCopyFromParts - Create a value that contains the specified legal parts
00419 /// combined into the value they represent.  If the parts combine to a type
00420 /// larger then ValueVT then AssertOp can be used to specify whether the extra
00421 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
00422 /// (ISD::AssertSext).
00423 static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc dl,
00424                                 const SDValue *Parts,
00425                                 unsigned NumParts, MVT PartVT, MVT ValueVT,
00426                                 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
00427   assert(NumParts > 0 && "No parts to assemble!");
00428   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
00429   SDValue Val = Parts[0];
00430 
00431   if (NumParts > 1) {
00432     // Assemble the value from multiple parts.
00433     if (!ValueVT.isVector()) {
00434       unsigned PartBits = PartVT.getSizeInBits();
00435       unsigned ValueBits = ValueVT.getSizeInBits();
00436 
00437       // Assemble the power of 2 part.
00438       unsigned RoundParts = NumParts & (NumParts - 1) ?
00439         1 << Log2_32(NumParts) : NumParts;
00440       unsigned RoundBits = PartBits * RoundParts;
00441       MVT RoundVT = RoundBits == ValueBits ?
00442         ValueVT : MVT::getIntegerVT(RoundBits);
00443       SDValue Lo, Hi;
00444 
00445       MVT HalfVT = ValueVT.isInteger() ?
00446         MVT::getIntegerVT(RoundBits/2) :
00447         MVT::getFloatingPointVT(RoundBits/2);
00448 
00449       if (RoundParts > 2) {
00450         Lo = getCopyFromParts(DAG, dl, Parts, RoundParts/2, PartVT, HalfVT);
00451         Hi = getCopyFromParts(DAG, dl, Parts+RoundParts/2, RoundParts/2,
00452                               PartVT, HalfVT);
00453       } else {
00454         Lo = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[0]);
00455         Hi = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[1]);
00456       }
00457       if (TLI.isBigEndian())
00458         std::swap(Lo, Hi);
00459       Val = DAG.getNode(ISD::BUILD_PAIR, dl, RoundVT, Lo, Hi);
00460 
00461       if (RoundParts < NumParts) {
00462         // Assemble the trailing non-power-of-2 part.
00463         unsigned OddParts = NumParts - RoundParts;
00464         MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
00465         Hi = getCopyFromParts(DAG, dl, 
00466                               Parts+RoundParts, OddParts, PartVT, OddVT);
00467 
00468         // Combine the round and odd parts.
00469         Lo = Val;
00470         if (TLI.isBigEndian())
00471           std::swap(Lo, Hi);
00472         MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
00473         Hi = DAG.getNode(ISD::ANY_EXTEND, dl, TotalVT, Hi);
00474         Hi = DAG.getNode(ISD::SHL, dl, TotalVT, Hi,
00475                          DAG.getConstant(Lo.getValueType().getSizeInBits(),
00476                                          TLI.getPointerTy()));
00477         Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, TotalVT, Lo);
00478         Val = DAG.getNode(ISD::OR, dl, TotalVT, Lo, Hi);
00479       }
00480     } else {
00481       // Handle a multi-element vector.
00482       MVT IntermediateVT, RegisterVT;
00483       unsigned NumIntermediates;
00484       unsigned NumRegs =
00485         TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
00486                                    RegisterVT);
00487       assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
00488       NumParts = NumRegs; // Silence a compiler warning.
00489       assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
00490       assert(RegisterVT == Parts[0].getValueType() &&
00491              "Part type doesn't match part!");
00492 
00493       // Assemble the parts into intermediate operands.
00494       SmallVector<SDValue, 8> Ops(NumIntermediates);
00495       if (NumIntermediates == NumParts) {
00496         // If the register was not expanded, truncate or copy the value,
00497         // as appropriate.
00498         for (unsigned i = 0; i != NumParts; ++i)
00499           Ops[i] = getCopyFromParts(DAG, dl, &Parts[i], 1,
00500                                     PartVT, IntermediateVT);
00501       } else if (NumParts > 0) {
00502         // If the intermediate type was expanded, build the intermediate operands
00503         // from the parts.
00504         assert(NumParts % NumIntermediates == 0 &&
00505                "Must expand into a divisible number of parts!");
00506         unsigned Factor = NumParts / NumIntermediates;
00507         for (unsigned i = 0; i != NumIntermediates; ++i)
00508           Ops[i] = getCopyFromParts(DAG, dl, &Parts[i * Factor], Factor,
00509                                     PartVT, IntermediateVT);
00510       }
00511 
00512       // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
00513       // operands.
00514       Val = DAG.getNode(IntermediateVT.isVector() ?
00515                         ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, dl,
00516                         ValueVT, &Ops[0], NumIntermediates);
00517     }
00518   }
00519 
00520   // There is now one part, held in Val.  Correct it to match ValueVT.
00521   PartVT = Val.getValueType();
00522 
00523   if (PartVT == ValueVT)
00524     return Val;
00525 
00526   if (PartVT.isVector()) {
00527     assert(ValueVT.isVector() && "Unknown vector conversion!");
00528     return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
00529   }
00530 
00531   if (ValueVT.isVector()) {
00532     assert(ValueVT.getVectorElementType() == PartVT &&
00533            ValueVT.getVectorNumElements() == 1 &&
00534            "Only trivial scalar-to-vector conversions should get here!");
00535     return DAG.getNode(ISD::BUILD_VECTOR, dl, ValueVT, Val);
00536   }
00537 
00538   if (PartVT.isInteger() &&
00539       ValueVT.isInteger()) {
00540     if (ValueVT.bitsLT(PartVT)) {
00541       // For a truncate, see if we have any information to
00542       // indicate whether the truncated bits will always be
00543       // zero or sign-extension.
00544       if (AssertOp != ISD::DELETED_NODE)
00545         Val = DAG.getNode(AssertOp, dl, PartVT, Val,
00546                           DAG.getValueType(ValueVT));
00547       return DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
00548     } else {
00549       return DAG.getNode(ISD::ANY_EXTEND, dl, ValueVT, Val);
00550     }
00551   }
00552 
00553   if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
00554     if (ValueVT.bitsLT(Val.getValueType()))
00555       // FP_ROUND's are always exact here.
00556       return DAG.getNode(ISD::FP_ROUND, dl, ValueVT, Val,
00557                          DAG.getIntPtrConstant(1));
00558     return DAG.getNode(ISD::FP_EXTEND, dl, ValueVT, Val);
00559   }
00560 
00561   if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
00562     return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
00563 
00564   assert(0 && "Unknown mismatch!");
00565   return SDValue();
00566 }
00567 
00568 /// getCopyToParts - Create a series of nodes that contain the specified value
00569 /// split into legal parts.  If the parts contain more bits than Val, then, for
00570 /// integers, ExtendKind can be used to specify how to generate the extra bits.
00571 static void getCopyToParts(SelectionDAG &DAG, DebugLoc dl, SDValue Val,
00572                            SDValue *Parts, unsigned NumParts, MVT PartVT,
00573                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
00574   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
00575   MVT PtrVT = TLI.getPointerTy();
00576   MVT ValueVT = Val.getValueType();
00577   unsigned PartBits = PartVT.getSizeInBits();
00578   assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
00579 
00580   if (!NumParts)
00581     return;
00582 
00583   if (!ValueVT.isVector()) {
00584     if (PartVT == ValueVT) {
00585       assert(NumParts == 1 && "No-op copy with multiple parts!");
00586       Parts[0] = Val;
00587       return;
00588     }
00589 
00590     if (NumParts * PartBits > ValueVT.getSizeInBits()) {
00591       // If the parts cover more bits than the value has, promote the value.
00592       if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
00593         assert(NumParts == 1 && "Do not know what to promote to!");
00594         Val = DAG.getNode(ISD::FP_EXTEND, dl, PartVT, Val);
00595       } else if (PartVT.isInteger() && ValueVT.isInteger()) {
00596         ValueVT = MVT::getIntegerVT(NumParts * PartBits);
00597         Val = DAG.getNode(ExtendKind, dl, ValueVT, Val);
00598       } else {
00599         assert(0 && "Unknown mismatch!");
00600       }
00601     } else if (PartBits == ValueVT.getSizeInBits()) {
00602       // Different types of the same size.
00603       assert(NumParts == 1 && PartVT != ValueVT);
00604       Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
00605     } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
00606       // If the parts cover less bits than value has, truncate the value.
00607       if (PartVT.isInteger() && ValueVT.isInteger()) {
00608         ValueVT = MVT::getIntegerVT(NumParts * PartBits);
00609         Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
00610       } else {
00611         assert(0 && "Unknown mismatch!");
00612       }
00613     }
00614 
00615     // The value may have changed - recompute ValueVT.
00616     ValueVT = Val.getValueType();
00617     assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
00618            "Failed to tile the value with PartVT!");
00619 
00620     if (NumParts == 1) {
00621       assert(PartVT == ValueVT && "Type conversion failed!");
00622       Parts[0] = Val;
00623       return;
00624     }
00625 
00626     // Expand the value into multiple parts.
00627     if (NumParts & (NumParts - 1)) {
00628       // The number of parts is not a power of 2.  Split off and copy the tail.
00629       assert(PartVT.isInteger() && ValueVT.isInteger() &&
00630              "Do not know what to expand to!");
00631       unsigned RoundParts = 1 << Log2_32(NumParts);
00632       unsigned RoundBits = RoundParts * PartBits;
00633       unsigned OddParts = NumParts - RoundParts;
00634       SDValue OddVal = DAG.getNode(ISD::SRL, dl, ValueVT, Val,
00635                                    DAG.getConstant(RoundBits,
00636                                                    TLI.getPointerTy()));
00637       getCopyToParts(DAG, dl, OddVal, Parts + RoundParts, OddParts, PartVT);
00638       if (TLI.isBigEndian())
00639         // The odd parts were reversed by getCopyToParts - unreverse them.
00640         std::reverse(Parts + RoundParts, Parts + NumParts);
00641       NumParts = RoundParts;
00642       ValueVT = MVT::getIntegerVT(NumParts * PartBits);
00643       Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
00644     }
00645 
00646     // The number of parts is a power of 2.  Repeatedly bisect the value using
00647     // EXTRACT_ELEMENT.
00648     Parts[0] = DAG.getNode(ISD::BIT_CONVERT, dl, 
00649                            MVT::getIntegerVT(ValueVT.getSizeInBits()),
00650                            Val);
00651     for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
00652       for (unsigned i = 0; i < NumParts; i += StepSize) {
00653         unsigned ThisBits = StepSize * PartBits / 2;
00654         MVT ThisVT = MVT::getIntegerVT (ThisBits);
00655         SDValue &Part0 = Parts[i];
00656         SDValue &Part1 = Parts[i+StepSize/2];
00657 
00658         Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 
00659                             ThisVT, Part0,
00660                             DAG.getConstant(1, PtrVT));
00661         Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 
00662                             ThisVT, Part0,
00663                             DAG.getConstant(0, PtrVT));
00664 
00665         if (ThisBits == PartBits && ThisVT != PartVT) {
00666           Part0 = DAG.getNode(ISD::BIT_CONVERT, dl, 
00667                                                 PartVT, Part0);
00668           Part1 = DAG.getNode(ISD::BIT_CONVERT, dl, 
00669                                                 PartVT, Part1);
00670         }
00671       }
00672     }
00673 
00674     if (TLI.isBigEndian())
00675       std::reverse(Parts, Parts + NumParts);
00676 
00677     return;
00678   }
00679 
00680   // Vector ValueVT.
00681   if (NumParts == 1) {
00682     if (PartVT != ValueVT) {
00683       if (PartVT.isVector()) {
00684         Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
00685       } else {
00686         assert(ValueVT.getVectorElementType() == PartVT &&
00687                ValueVT.getVectorNumElements() == 1 &&
00688                "Only trivial vector-to-scalar conversions should get here!");
00689         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, 
00690                           PartVT, Val,
00691                           DAG.getConstant(0, PtrVT));
00692       }
00693     }
00694 
00695     Parts[0] = Val;
00696     return;
00697   }
00698 
00699   // Handle a multi-element vector.
00700   MVT IntermediateVT, RegisterVT;
00701   unsigned NumIntermediates;
00702   unsigned NumRegs = TLI
00703       .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
00704                               RegisterVT);
00705   unsigned NumElements = ValueVT.getVectorNumElements();
00706 
00707   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
00708   NumParts = NumRegs; // Silence a compiler warning.
00709   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
00710 
00711   // Split the vector into intermediate operands.
00712   SmallVector<SDValue, 8> Ops(NumIntermediates);
00713   for (unsigned i = 0; i != NumIntermediates; ++i)
00714     if (IntermediateVT.isVector())
00715       Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, 
00716                            IntermediateVT, Val,
00717                            DAG.getConstant(i * (NumElements / NumIntermediates),
00718                                            PtrVT));
00719     else
00720       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, 
00721                            IntermediateVT, Val,
00722                            DAG.getConstant(i, PtrVT));
00723 
00724   // Split the intermediate operands into legal parts.
00725   if (NumParts == NumIntermediates) {
00726     // If the register was not expanded, promote or copy the value,
00727     // as appropriate.
00728     for (unsigned i = 0; i != NumParts; ++i)
00729       getCopyToParts(DAG, dl, Ops[i], &Parts[i], 1, PartVT);
00730   } else if (NumParts > 0) {
00731     // If the intermediate type was expanded, split each the value into
00732     // legal parts.
00733     assert(NumParts % NumIntermediates == 0 &&
00734            "Must expand into a divisible number of parts!");
00735     unsigned Factor = NumParts / NumIntermediates;
00736     for (unsigned i = 0; i != NumIntermediates; ++i)
00737       getCopyToParts(DAG, dl, Ops[i], &Parts[i * Factor], Factor, PartVT);
00738   }
00739 }
00740 
00741 
00742 void SelectionDAGLowering::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
00743   AA = &aa;
00744   GFI = gfi;
00745   TD = DAG.getTarget().getTargetData();
00746 }
00747 
00748 /// clear - Clear out the curret SelectionDAG and the associated
00749 /// state and prepare this SelectionDAGLowering object to be used
00750 /// for a new block. This doesn't clear out information about
00751 /// additional blocks that are needed to complete switch lowering
00752 /// or PHI node updating; that information is cleared out as it is
00753 /// consumed.
00754 void SelectionDAGLowering::clear() {
00755   NodeMap.clear();
00756   PendingLoads.clear();
00757   PendingExports.clear();
00758   DAG.clear();
00759 }
00760 
00761 /// getRoot - Return the current virtual root of the Selection DAG,
00762 /// flushing any PendingLoad items. This must be done before emitting
00763 /// a store or any other node that may need to be ordered after any
00764 /// prior load instructions.
00765 ///
00766 SDValue SelectionDAGLowering::getRoot() {
00767   if (PendingLoads.empty())
00768     return DAG.getRoot();
00769 
00770   if (PendingLoads.size() == 1) {
00771     SDValue Root = PendingLoads[0];
00772     DAG.setRoot(Root);
00773     PendingLoads.clear();
00774     return Root;
00775   }
00776 
00777   // Otherwise, we have to make a token factor node.
00778   SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
00779                                &PendingLoads[0], PendingLoads.size());
00780   PendingLoads.clear();
00781   DAG.setRoot(Root);
00782   return Root;
00783 }
00784 
00785 /// getControlRoot - Similar to getRoot, but instead of flushing all the
00786 /// PendingLoad items, flush all the PendingExports items. It is necessary
00787 /// to do this before emitting a terminator instruction.
00788 ///
00789 SDValue SelectionDAGLowering::getControlRoot() {
00790   SDValue Root = DAG.getRoot();
00791 
00792   if (PendingExports.empty())
00793     return Root;
00794 
00795   // Turn all of the CopyToReg chains into one factored node.
00796   if (Root.getOpcode() != ISD::EntryToken) {
00797     unsigned i = 0, e = PendingExports.size();
00798     for (; i != e; ++i) {
00799       assert(PendingExports[i].getNode()->getNumOperands() > 1);
00800       if (PendingExports[i].getNode()->getOperand(0) == Root)
00801         break;  // Don't add the root if we already indirectly depend on it.
00802     }
00803 
00804     if (i == e)
00805       PendingExports.push_back(Root);
00806   }
00807 
00808   Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
00809                      &PendingExports[0],
00810                      PendingExports.size());
00811   PendingExports.clear();
00812   DAG.setRoot(Root);
00813   return Root;
00814 }
00815 
00816 void SelectionDAGLowering::visit(Instruction &I) {
00817   visit(I.getOpcode(), I);
00818 }
00819 
00820 void SelectionDAGLowering::visit(unsigned Opcode, User &I) {
00821   // Note: this doesn't use InstVisitor, because it has to work with
00822   // ConstantExpr's in addition to instructions.
00823   switch (Opcode) {
00824   default: assert(0 && "Unknown instruction type encountered!");
00825            abort();
00826     // Build the switch statement using the Instruction.def file.
00827 #define HANDLE_INST(NUM, OPCODE, CLASS) \
00828   case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
00829 #include "llvm/Instruction.def"
00830   }
00831 }
00832 
00833 void SelectionDAGLowering::visitAdd(User &I) {
00834   if (I.getType()->isFPOrFPVector())
00835     visitBinary(I, ISD::FADD);
00836   else
00837     visitBinary(I, ISD::ADD);
00838 }
00839 
00840 void SelectionDAGLowering::visitMul(User &I) {
00841   if (I.getType()->isFPOrFPVector())
00842     visitBinary(I, ISD::FMUL);
00843   else
00844     visitBinary(I, ISD::MUL);
00845 }
00846 
00847 SDValue SelectionDAGLowering::getValue(const Value *V) {
00848   SDValue &N = NodeMap[V];
00849   if (N.getNode()) return N;
00850 
00851   if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
00852     MVT VT = TLI.getValueType(V->getType(), true);
00853 
00854     if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
00855       return N = DAG.getConstant(*CI, VT);
00856 
00857     if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
00858       return N = DAG.getGlobalAddress(GV, VT);
00859 
00860     if (isa<ConstantPointerNull>(C))
00861       return N = DAG.getConstant(0, TLI.getPointerTy());
00862 
00863     if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
00864       return N = DAG.getConstantFP(*CFP, VT);
00865 
00866     if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
00867         !V->getType()->isAggregateType())
00868       return N = DAG.getNode(ISD::UNDEF, getCurDebugLoc(), VT);
00869 
00870     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
00871       visit(CE->getOpcode(), *CE);
00872       SDValue N1 = NodeMap[V];
00873       assert(N1.getNode() && "visit didn't populate the ValueMap!");
00874       return N1;
00875     }
00876 
00877     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
00878       SmallVector<SDValue, 4> Constants;
00879       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
00880            OI != OE; ++OI) {
00881         SDNode *Val = getValue(*OI).getNode();
00882         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
00883           Constants.push_back(SDValue(Val, i));
00884       }
00885       return DAG.getMergeValues(&Constants[0], Constants.size());
00886     }
00887 
00888     if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
00889       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
00890              "Unknown struct or array constant!");
00891 
00892       SmallVector<MVT, 4> ValueVTs;
00893       ComputeValueVTs(TLI, C->getType(), ValueVTs);
00894       unsigned NumElts = ValueVTs.size();
00895       if (NumElts == 0)
00896         return SDValue(); // empty struct
00897       SmallVector<SDValue, 4> Constants(NumElts);
00898       for (unsigned i = 0; i != NumElts; ++i) {
00899         MVT EltVT = ValueVTs[i];
00900         if (isa<UndefValue>(C))
00901           Constants[i] = DAG.getNode(ISD::UNDEF, getCurDebugLoc(), EltVT);
00902         else if (EltVT.isFloatingPoint())
00903           Constants[i] = DAG.getConstantFP(0, EltVT);
00904         else
00905           Constants[i] = DAG.getConstant(0, EltVT);
00906       }
00907       return DAG.getMergeValues(&Constants[0], NumElts);
00908     }
00909 
00910     const VectorType *VecTy = cast<VectorType>(V->getType());
00911     unsigned NumElements = VecTy->getNumElements();
00912 
00913     // Now that we know the number and type of the elements, get that number of
00914     // elements into the Ops array based on what kind of constant it is.
00915     SmallVector<SDValue, 16> Ops;
00916     if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
00917       for (unsigned i = 0; i != NumElements; ++i)
00918         Ops.push_back(getValue(CP->getOperand(i)));
00919     } else {
00920       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
00921              "Unknown vector constant!");
00922       MVT EltVT = TLI.getValueType(VecTy->getElementType());
00923 
00924       SDValue Op;
00925       if (isa<UndefValue>(C))
00926         Op = DAG.getNode(ISD::UNDEF, getCurDebugLoc(), EltVT);
00927       else if (EltVT.isFloatingPoint())
00928         Op = DAG.getConstantFP(0, EltVT);
00929       else
00930         Op = DAG.getConstant(0, EltVT);
00931       Ops.assign(NumElements, Op);
00932     }
00933 
00934     // Create a BUILD_VECTOR node.
00935     return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(), 
00936                                     VT, &Ops[0], Ops.size());
00937   }
00938 
00939   // If this is a static alloca, generate it as the frameindex instead of
00940   // computation.
00941   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
00942     DenseMap<const AllocaInst*, int>::iterator SI =
00943       FuncInfo.StaticAllocaMap.find(AI);
00944     if (SI != FuncInfo.StaticAllocaMap.end())
00945       return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
00946   }
00947 
00948   unsigned InReg = FuncInfo.ValueMap[V];
00949   assert(InReg && "Value not in map!");
00950 
00951   RegsForValue RFV(TLI, InReg, V->getType());
00952   SDValue Chain = DAG.getEntryNode();
00953   return RFV.getCopyFromRegs(DAG, getCurDebugLoc(), Chain, NULL);
00954 }
00955 
00956 
00957 void SelectionDAGLowering::visitRet(ReturnInst &I) {
00958   if (I.getNumOperands() == 0) {
00959     DAG.setRoot(DAG.getNode(ISD::RET, getCurDebugLoc(), 
00960                             MVT::Other, getControlRoot()));
00961     return;
00962   }
00963 
00964   SmallVector<SDValue, 8> NewValues;
00965   NewValues.push_back(getControlRoot());
00966   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
00967     SmallVector<MVT, 4> ValueVTs;
00968     ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
00969     unsigned NumValues = ValueVTs.size();
00970     if (NumValues == 0) continue;
00971 
00972     SDValue RetOp = getValue(I.getOperand(i));
00973     for (unsigned j = 0, f = NumValues; j != f; ++j) {
00974       MVT VT = ValueVTs[j];
00975 
00976       // FIXME: C calling convention requires the return type to be promoted to
00977       // at least 32-bit. But this is not necessary for non-C calling
00978       // conventions.
00979       if (VT.isInteger()) {
00980         MVT MinVT = TLI.getRegisterType(MVT::i32);
00981         if (VT.bitsLT(MinVT))
00982           VT = MinVT;
00983       }
00984 
00985       unsigned NumParts = TLI.getNumRegisters(VT);
00986       MVT PartVT = TLI.getRegisterType(VT);
00987       SmallVector<SDValue, 4> Parts(NumParts);
00988       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
00989 
00990       const Function *F = I.getParent()->getParent();
00991       if (F->paramHasAttr(0, Attribute::SExt))
00992         ExtendKind = ISD::SIGN_EXTEND;
00993       else if (F->paramHasAttr(0, Attribute::ZExt))
00994         ExtendKind = ISD::ZERO_EXTEND;
00995 
00996       getCopyToParts(DAG, getCurDebugLoc(),
00997                      SDValue(RetOp.getNode(), RetOp.getResNo() + j),
00998                      &Parts[0], NumParts, PartVT, ExtendKind);
00999 
01000       // 'inreg' on function refers to return value
01001       ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
01002       if (F->paramHasAttr(0, Attribute::InReg))
01003         Flags.setInReg();
01004       for (unsigned i = 0; i < NumParts; ++i) {
01005         NewValues.push_back(Parts[i]);
01006         NewValues.push_back(DAG.getArgFlags(Flags));
01007       }
01008     }
01009   }
01010   DAG.setRoot(DAG.getNode(ISD::RET, getCurDebugLoc(), MVT::Other,
01011                           &NewValues[0], NewValues.size()));
01012 }
01013 
01014 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
01015 /// the current basic block, add it to ValueMap now so that we'll get a
01016 /// CopyTo/FromReg.
01017 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
01018   // No need to export constants.
01019   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
01020 
01021   // Already exported?
01022   if (FuncInfo.isExportedInst(V)) return;
01023 
01024   unsigned Reg = FuncInfo.InitializeRegForValue(V);
01025   CopyValueToVirtualRegister(V, Reg);
01026 }
01027 
01028 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
01029                                                     const BasicBlock *FromBB) {
01030   // The operands of the setcc have to be in this block.  We don't know
01031   // how to export them from some other block.
01032   if (Instruction *VI = dyn_cast<Instruction>(V)) {
01033     // Can export from current BB.
01034     if (VI->getParent() == FromBB)
01035       return true;
01036 
01037     // Is already exported, noop.
01038     return FuncInfo.isExportedInst(V);
01039   }
01040 
01041   // If this is an argument, we can export it if the BB is the entry block or
01042   // if it is already exported.
01043   if (isa<Argument>(V)) {
01044     if (FromBB == &FromBB->getParent()->getEntryBlock())
01045       return true;
01046 
01047     // Otherwise, can only export this if it is already exported.
01048     return FuncInfo.isExportedInst(V);
01049   }
01050 
01051   // Otherwise, constants can always be exported.
01052   return true;
01053 }
01054 
01055 static bool InBlock(const Value *V, const BasicBlock *BB) {
01056   if (const Instruction *I = dyn_cast<Instruction>(V))
01057     return I->getParent() == BB;
01058   return true;
01059 }
01060 
01061 /// getFCmpCondCode - Return the ISD condition code corresponding to
01062 /// the given LLVM IR floating-point condition code.  This includes
01063 /// consideration of global floating-point math flags.
01064 ///
01065 static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
01066   ISD::CondCode FPC, FOC;
01067   switch (Pred) {
01068   case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
01069   case FCmpInst::FCMP_OEQ:   FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
01070   case FCmpInst::FCMP_OGT:   FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
01071   case FCmpInst::FCMP_OGE:   FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
01072   case FCmpInst::FCMP_OLT:   FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
01073   case FCmpInst::FCMP_OLE:   FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
01074   case FCmpInst::FCMP_ONE:   FOC = ISD::SETNE; FPC = ISD::SETONE; break;
01075   case FCmpInst::FCMP_ORD:   FOC = FPC = ISD::SETO;   break;
01076   case FCmpInst::FCMP_UNO:   FOC = FPC = ISD::SETUO;  break;
01077   case FCmpInst::FCMP_UEQ:   FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
01078   case FCmpInst::FCMP_UGT:   FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
01079   case FCmpInst::FCMP_UGE:   FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
01080   case FCmpInst::FCMP_ULT:   FOC = ISD::SETLT; FPC = ISD::SETULT; break;
01081   case FCmpInst::FCMP_ULE:   FOC = ISD::SETLE; FPC = ISD::SETULE; break;
01082   case FCmpInst::FCMP_UNE:   FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
01083   case FCmpInst::FCMP_TRUE:  FOC = FPC = ISD::SETTRUE; break;
01084   default:
01085     assert(0 && "Invalid FCmp predicate opcode!");
01086     FOC = FPC = ISD::SETFALSE;
01087     break;
01088   }
01089   if (FiniteOnlyFPMath())
01090     return FOC;
01091   else
01092     return FPC;
01093 }
01094 
01095 /// getICmpCondCode - Return the ISD condition code corresponding to
01096 /// the given LLVM IR integer condition code.
01097 ///
01098 static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
01099   switch (Pred) {
01100   case ICmpInst::ICMP_EQ:  return ISD::SETEQ;
01101   case ICmpInst::ICMP_NE:  return ISD::SETNE;
01102   case ICmpInst::ICMP_SLE: return ISD::SETLE;
01103   case ICmpInst::ICMP_ULE: return ISD::SETULE;
01104   case ICmpInst::ICMP_SGE: return ISD::SETGE;
01105   case ICmpInst::ICMP_UGE: return ISD::SETUGE;
01106   case ICmpInst::ICMP_SLT: return ISD::SETLT;
01107   case ICmpInst::ICMP_ULT: return ISD::SETULT;
01108   case ICmpInst::ICMP_SGT: return ISD::SETGT;
01109   case ICmpInst::ICMP_UGT: return ISD::SETUGT;
01110   default:
01111     assert(0 && "Invalid ICmp predicate opcode!");
01112     return ISD::SETNE;
01113   }
01114 }
01115 
01116 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
01117 /// This function emits a branch and is used at the leaves of an OR or an
01118 /// AND operator tree.
01119 ///
01120 void
01121 SelectionDAGLowering::EmitBranchForMergedCondition(Value *Cond,
01122                                                    MachineBasicBlock *TBB,
01123                                                    MachineBasicBlock *FBB,
01124                                                    MachineBasicBlock *CurBB) {
01125   const BasicBlock *BB = CurBB->getBasicBlock();
01126 
01127   // If the leaf of the tree is a comparison, merge the condition into
01128   // the caseblock.
01129   if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
01130     // The operands of the cmp have to be in this block.  We don't know
01131     // how to export them from some other block.  If this is the first block
01132     // of the sequence, no exporting is needed.
01133     if (CurBB == CurMBB ||
01134         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
01135          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
01136       ISD::CondCode Condition;
01137       if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
01138         Condition = getICmpCondCode(IC->getPredicate());
01139       } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
01140         Condition = getFCmpCondCode(FC->getPredicate());
01141       } else {
01142         Condition = ISD::SETEQ; // silence warning.
01143         assert(0 && "Unknown compare instruction");
01144       }
01145 
01146       CaseBlock CB(Condition, BOp->getOperand(0),
01147                    BOp->getOperand(1), NULL, TBB, FBB, CurBB);
01148       SwitchCases.push_back(CB);
01149       return;
01150     }
01151   }
01152 
01153   // Create a CaseBlock record representing this branch.
01154   CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
01155                NULL, TBB, FBB, CurBB);
01156   SwitchCases.push_back(CB);
01157 }
01158 
01159 /// FindMergedConditions - If Cond is an expression like
01160 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
01161                                                 MachineBasicBlock *TBB,
01162                                                 MachineBasicBlock *FBB,
01163                                                 MachineBasicBlock *CurBB,
01164                                                 unsigned Opc) {
01165   // If this node is not part of the or/and tree, emit it as a branch.
01166   Instruction *BOp = dyn_cast<Instruction>(Cond);
01167   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
01168       (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
01169       BOp->getParent() != CurBB->getBasicBlock() ||
01170       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
01171       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
01172     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
01173     return;
01174   }
01175 
01176   //  Create TmpBB after CurBB.
01177   MachineFunction::iterator BBI = CurBB;
01178   MachineFunction &MF = DAG.getMachineFunction();
01179   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
01180   CurBB->getParent()->insert(++BBI, TmpBB);
01181 
01182   if (Opc == Instruction::Or) {
01183     // Codegen X | Y as:
01184     //   jmp_if_X TBB
01185     //   jmp TmpBB
01186     // TmpBB:
01187     //   jmp_if_Y TBB
01188     //   jmp FBB
01189     //
01190 
01191     // Emit the LHS condition.
01192     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
01193 
01194     // Emit the RHS condition into TmpBB.
01195     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
01196   } else {
01197     assert(Opc == Instruction::And && "Unknown merge op!");
01198     // Codegen X & Y as:
01199     //   jmp_if_X TmpBB
01200     //   jmp FBB
01201     // TmpBB:
01202     //   jmp_if_Y TBB
01203     //   jmp FBB
01204     //
01205     //  This requires creation of TmpBB after CurBB.
01206 
01207     // Emit the LHS condition.
01208     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
01209 
01210     // Emit the RHS condition into TmpBB.
01211     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
01212   }
01213 }
01214 
01215 /// If the set of cases should be emitted as a series of branches, return true.
01216 /// If we should emit this as a bunch of and/or'd together conditions, return
01217 /// false.
01218 bool
01219 SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
01220   if (Cases.size() != 2) return true;
01221 
01222   // If this is two comparisons of the same values or'd or and'd together, they
01223   // will get folded into a single comparison, so don't emit two blocks.
01224   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
01225        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
01226       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
01227        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
01228     return false;
01229   }
01230 
01231   return true;
01232 }
01233 
01234 void SelectionDAGLowering::visitBr(BranchInst &I) {
01235   // Update machine-CFG edges.
01236   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
01237 
01238   // Figure out which block is immediately after the current one.
01239   MachineBasicBlock *NextBlock = 0;
01240   MachineFunction::iterator BBI = CurMBB;
01241   if (++BBI != CurMBB->getParent()->end())
01242     NextBlock = BBI;
01243 
01244   if (I.isUnconditional()) {
01245     // Update machine-CFG edges.
01246     CurMBB->addSuccessor(Succ0MBB);
01247 
01248     // If this is not a fall-through branch, emit the branch.
01249     if (Succ0MBB != NextBlock)
01250       DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), 
01251                               MVT::Other, getControlRoot(),
01252                               DAG.getBasicBlock(Succ0MBB)));
01253     return;
01254   }
01255 
01256   // If this condition is one of the special cases we handle, do special stuff
01257   // now.
01258   Value *CondVal = I.getCondition();
01259   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
01260 
01261   // If this is a series of conditions that are or'd or and'd together, emit
01262   // this as a sequence of branches instead of setcc's with and/or operations.
01263   // For example, instead of something like:
01264   //     cmp A, B
01265   //     C = seteq
01266   //     cmp D, E
01267   //     F = setle
01268   //     or C, F
01269   //     jnz foo
01270   // Emit:
01271   //     cmp A, B
01272   //     je foo
01273   //     cmp D, E
01274   //     jle foo
01275   //
01276   if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
01277     if (BOp->hasOneUse() &&
01278         (BOp->getOpcode() == Instruction::And ||
01279          BOp->getOpcode() == Instruction::Or)) {
01280       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
01281       // If the compares in later blocks need to use values not currently
01282       // exported from this block, export them now.  This block should always
01283       // be the first entry.
01284       assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
01285 
01286       // Allow some cases to be rejected.
01287       if (ShouldEmitAsBranches(SwitchCases)) {
01288         for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
01289           ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
01290           ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
01291         }
01292 
01293         // Emit the branch for this block.
01294         visitSwitchCase(SwitchCases[0]);
01295         SwitchCases.erase(SwitchCases.begin());
01296         return;
01297       }
01298 
01299       // Okay, we decided not to do this, remove any inserted MBB's and clear
01300       // SwitchCases.
01301       for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
01302         CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
01303 
01304       SwitchCases.clear();
01305     }
01306   }
01307 
01308   // Create a CaseBlock record representing this branch.
01309   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
01310                NULL, Succ0MBB, Succ1MBB, CurMBB);
01311   // Use visitSwitchCase to actually insert the fast branch sequence for this
01312   // cond branch.
01313   visitSwitchCase(CB);
01314 }
01315 
01316 /// visitSwitchCase - Emits the necessary code to represent a single node in
01317 /// the binary search tree resulting from lowering a switch instruction.
01318 void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
01319   SDValue Cond;
01320   SDValue CondLHS = getValue(CB.CmpLHS);
01321 
01322   // Build the setcc now.
01323   if (CB.CmpMHS == NULL) {
01324     // Fold "(X == true)" to X and "(X == false)" to !X to
01325     // handle common cases produced by branch lowering.
01326     if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
01327       Cond = CondLHS;
01328     else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
01329       SDValue True = DAG.getConstant(1, CondLHS.getValueType());
01330       Cond = DAG.getNode(ISD::XOR, getCurDebugLoc(), 
01331                          CondLHS.getValueType(), CondLHS, True);
01332     } else
01333       Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
01334   } else {
01335     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
01336 
01337     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
01338     const APInt& High  = cast<ConstantInt>(CB.CmpRHS)->getValue();
01339 
01340     SDValue CmpOp = getValue(CB.CmpMHS);
01341     MVT VT = CmpOp.getValueType();
01342 
01343     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
01344       Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
01345     } else {
01346       SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), 
01347                                 VT, CmpOp, DAG.getConstant(Low, VT));
01348       Cond = DAG.getSetCC(MVT::i1, SUB,
01349                           DAG.getConstant(High-Low, VT), ISD::SETULE);
01350     }
01351   }
01352 
01353   // Update successor info
01354   CurMBB->addSuccessor(CB.TrueBB);
01355   CurMBB->addSuccessor(CB.FalseBB);
01356 
01357   // Set NextBlock to be the MBB immediately after the current one, if any.
01358   // This is used to avoid emitting unnecessary branches to the next block.
01359   MachineBasicBlock *NextBlock = 0;
01360   MachineFunction::iterator BBI = CurMBB;
01361   if (++BBI != CurMBB->getParent()->end())
01362     NextBlock = BBI;
01363 
01364   // If the lhs block is the next block, invert the condition so that we can
01365   // fall through to the lhs instead of the rhs block.
01366   if (CB.TrueBB == NextBlock) {
01367     std::swap(CB.TrueBB, CB.FalseBB);
01368     SDValue True = DAG.getConstant(1, Cond.getValueType());
01369     Cond = DAG.getNode(ISD::XOR, getCurDebugLoc(), 
01370                        Cond.getValueType(), Cond, True);
01371   }
01372   SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
01373                                MVT::Other, getControlRoot(), Cond,
01374                                DAG.getBasicBlock(CB.TrueBB));
01375 
01376   // If the branch was constant folded, fix up the CFG.
01377   if (BrCond.getOpcode() == ISD::BR) {
01378     CurMBB->removeSuccessor(CB.FalseBB);
01379     DAG.setRoot(BrCond);
01380   } else {
01381     // Otherwise, go ahead and insert the false branch.
01382     if (BrCond == getControlRoot())
01383       CurMBB->removeSuccessor(CB.TrueBB);
01384 
01385     if (CB.FalseBB == NextBlock)
01386       DAG.setRoot(BrCond);
01387     else
01388       DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
01389                               DAG.getBasicBlock(CB.FalseBB)));
01390   }
01391 }
01392 
01393 /// visitJumpTable - Emit JumpTable node in the current MBB
01394 void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
01395   // Emit the code for the jump table
01396   assert(JT.Reg != -1U && "Should lower JT Header first!");
01397   MVT PTy = TLI.getPointerTy();
01398   SDValue Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
01399   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
01400   DAG.setRoot(DAG.getNode(ISD::BR_JT, getCurDebugLoc(), 
01401                           MVT::Other, Index.getValue(1),
01402                           Table, Index));
01403 }
01404 
01405 /// visitJumpTableHeader - This function emits necessary code to produce index
01406 /// in the JumpTable from switch case.
01407 void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
01408                                                 JumpTableHeader &JTH) {
01409   // Subtract the lowest switch case value from the value being switched on and
01410   // conditional branch to default mbb if the result is greater than the
01411   // difference between smallest and largest cases.
01412   SDValue SwitchOp = getValue(JTH.SValue);
01413   MVT VT = SwitchOp.getValueType();
01414   SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
01415                             DAG.getConstant(JTH.First, VT));
01416 
01417   // The SDNode we just created, which holds the value being switched on minus
01418   // the the smallest case value, needs to be copied to a virtual register so it
01419   // can be used as an index into the jump table in a subsequent basic block.
01420   // This value may be smaller or larger than the target's pointer type, and
01421   // therefore require extension or truncating.
01422   if (VT.bitsGT(TLI.getPointerTy()))
01423     SwitchOp = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), 
01424                            TLI.getPointerTy(), SUB);
01425   else
01426     SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), 
01427                            TLI.getPointerTy(), SUB);
01428 
01429   unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
01430   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
01431   JT.Reg = JumpTableReg;
01432 
01433   // Emit the range check for the jump table, and branch to the default block
01434   // for the switch statement if the value being switched on exceeds the largest
01435   // case in the switch.
01436   SDValue CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB.getValueType()), SUB,
01437                              DAG.getConstant(JTH.Last-JTH.First,VT),
01438                              ISD::SETUGT);
01439 
01440   // Set NextBlock to be the MBB immediately after the current one, if any.
01441   // This is used to avoid emitting unnecessary branches to the next block.
01442   MachineBasicBlock *NextBlock = 0;
01443   MachineFunction::iterator BBI = CurMBB;
01444   if (++BBI != CurMBB->getParent()->end())
01445     NextBlock = BBI;
01446 
01447   SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
01448                                MVT::Other, CopyTo, CMP,
01449                                DAG.getBasicBlock(JT.Default));
01450 
01451   if (JT.MBB == NextBlock)
01452     DAG.setRoot(BrCond);
01453   else
01454     DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
01455                             DAG.getBasicBlock(JT.MBB)));
01456 }
01457 
01458 /// visitBitTestHeader - This function emits necessary code to produce value
01459 /// suitable for "bit tests"
01460 void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
01461   // Subtract the minimum value
01462   SDValue SwitchOp = getValue(B.SValue);
01463   MVT VT = SwitchOp.getValueType();
01464   SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
01465                             DAG.getConstant(B.First, VT));
01466 
01467   // Check range
01468   SDValue RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB.getValueType()), SUB,
01469                                   DAG.getConstant(B.Range, VT),
01470                                   ISD::SETUGT);
01471 
01472   SDValue ShiftOp;
01473   if (VT.bitsGT(TLI.getPointerTy()))
01474     ShiftOp = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), 
01475                           TLI.getPointerTy(), SUB);
01476   else
01477     ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), 
01478                           TLI.getPointerTy(), SUB);
01479 
01480   B.Reg = FuncInfo.MakeReg(TLI.getPointerTy());
01481   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), B.Reg, ShiftOp);
01482 
01483   // Set NextBlock to be the MBB immediately after the current one, if any.
01484   // This is used to avoid emitting unnecessary branches to the next block.
01485   MachineBasicBlock *NextBlock = 0;
01486   MachineFunction::iterator BBI = CurMBB;
01487   if (++BBI != CurMBB->getParent()->end())
01488     NextBlock = BBI;
01489 
01490   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
01491 
01492   CurMBB->addSuccessor(B.Default);
01493   CurMBB->addSuccessor(MBB);
01494 
01495   SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
01496                                 MVT::Other, CopyTo, RangeCmp,
01497                                 DAG.getBasicBlock(B.Default));
01498 
01499   if (MBB == NextBlock)
01500     DAG.setRoot(BrRange);
01501   else
01502     DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
01503                             DAG.getBasicBlock(MBB)));
01504 }
01505 
01506 /// visitBitTestCase - this function produces one "bit test"
01507 void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
01508                                             unsigned Reg,
01509                                             BitTestCase &B) {
01510   // Make desired shift
01511   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), Reg,
01512                                        TLI.getPointerTy());
01513   SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(), 
01514                                   TLI.getPointerTy(),
01515                                   DAG.getConstant(1, TLI.getPointerTy()),
01516                                   ShiftOp);
01517 
01518   // Emit bit tests and jumps
01519   SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(), 
01520                               TLI.getPointerTy(), SwitchVal,
01521                               DAG.getConstant(B.Mask, TLI.getPointerTy()));
01522   SDValue AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp.getValueType()),
01523                                 AndOp, DAG.getConstant(0, TLI.getPointerTy()),
01524                                 ISD::SETNE);
01525 
01526   CurMBB->addSuccessor(B.TargetBB);
01527   CurMBB->addSuccessor(NextMBB);
01528 
01529   SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
01530                               MVT::Other, getControlRoot(),
01531                               AndCmp, DAG.getBasicBlock(B.TargetBB));
01532 
01533   // Set NextBlock to be the MBB immediately after the current one, if any.
01534   // This is used to avoid emitting unnecessary branches to the next block.
01535   MachineBasicBlock *NextBlock = 0;
01536   MachineFunction::iterator BBI = CurMBB;
01537   if (++BBI != CurMBB->getParent()->end())
01538     NextBlock = BBI;
01539 
01540   if (NextMBB == NextBlock)
01541     DAG.setRoot(BrAnd);
01542   else
01543     DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
01544                             DAG.getBasicBlock(NextMBB)));
01545 }
01546 
01547 void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
01548   // Retrieve successors.
01549   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
01550   MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
01551 
01552   const Value *Callee(I.getCalledValue());
01553   if (isa<InlineAsm>(Callee))
01554     visitInlineAsm(&I);
01555   else
01556     LowerCallTo(&I, getValue(Callee), false, LandingPad);
01557 
01558   // If the value of the invoke is used outside of its defining block, make it
01559   // available as a virtual register.
01560   if (!I.use_empty()) {
01561     DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
01562     if (VMI != FuncInfo.ValueMap.end())
01563       CopyValueToVirtualRegister(&I, VMI->second);
01564   }
01565 
01566   // Update successor info
01567   CurMBB->addSuccessor(Return);
01568   CurMBB->addSuccessor(LandingPad);
01569 
01570   // Drop into normal successor.
01571   DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), 
01572                           MVT::Other, getControlRoot(),
01573                           DAG.getBasicBlock(Return)));
01574 }
01575 
01576 void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
01577 }
01578 
01579 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
01580 /// small case ranges).
01581 bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
01582                                                   CaseRecVector& WorkList,
01583                                                   Value* SV,
01584                                                   MachineBasicBlock* Default) {
01585   Case& BackCase  = *(CR.Range.second-1);
01586 
01587   // Size is the number of Cases represented by this range.
01588   size_t Size = CR.Range.second - CR.Range.first;
01589   if (Size > 3)
01590     return false;
01591 
01592   // Get the MachineFunction which holds the current MBB.  This is used when
01593   // inserting any additional MBBs necessary to represent the switch.
01594   MachineFunction *CurMF = CurMBB->getParent();
01595 
01596   // Figure out which block is immediately after the current one.
01597   MachineBasicBlock *NextBlock = 0;
01598   MachineFunction::iterator BBI = CR.CaseBB;
01599 
01600   if (++BBI != CurMBB->getParent()->end())
01601     NextBlock = BBI;
01602 
01603   // TODO: If any two of the cases has the same destination, and if one value
01604   // is the same as the other, but has one bit unset that the other has set,
01605   // use bit manipulation to do two compares at once.  For example:
01606   // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
01607 
01608   // Rearrange the case blocks so that the last one falls through if possible.
01609   if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
01610     // The last case block won't fall through into 'NextBlock' if we emit the
01611     // branches in this order.  See if rearranging a case value would help.
01612     for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
01613       if (I->BB == NextBlock) {
01614         std::swap(*I, BackCase);
01615         break;
01616       }
01617     }
01618   }
01619 
01620   // Create a CaseBlock record representing a conditional branch to
01621   // the Case's target mbb if the value being switched on SV is equal
01622   // to C.
01623   MachineBasicBlock *CurBlock = CR.CaseBB;
01624   for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
01625     MachineBasicBlock *FallThrough;
01626     if (I != E-1) {
01627       FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
01628       CurMF->insert(BBI, FallThrough);
01629     } else {
01630       // If the last case doesn't match, go to the default block.
01631       FallThrough = Default;
01632     }
01633 
01634     Value *RHS, *LHS, *MHS;
01635     ISD::CondCode CC;
01636     if (I->High == I->Low) {
01637       // This is just small small case range :) containing exactly 1 case
01638       CC = ISD::SETEQ;
01639       LHS = SV; RHS = I->High; MHS = NULL;
01640     } else {
01641       CC = ISD::SETLE;
01642       LHS = I->Low; MHS = SV; RHS = I->High;
01643     }
01644     CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
01645 
01646     // If emitting the first comparison, just call visitSwitchCase to emit the
01647     // code into the current block.  Otherwise, push the CaseBlock onto the
01648     // vector to be later processed by SDISel, and insert the node's MBB
01649     // before the next MBB.
01650     if (CurBlock == CurMBB)
01651       visitSwitchCase(CB);
01652     else
01653       SwitchCases.push_back(CB);
01654 
01655     CurBlock = FallThrough;
01656   }
01657 
01658   return true;
01659 }
01660 
01661 static inline bool areJTsAllowed(const TargetLowering &TLI) {
01662   return !DisableJumpTables &&
01663           (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
01664            TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
01665 }
01666 
01667 static APInt ComputeRange(const APInt &First, const APInt &Last) {
01668   APInt LastExt(Last), FirstExt(First);
01669   uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
01670   LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
01671   return (LastExt - FirstExt + 1ULL);
01672 }
01673 
01674 /// handleJTSwitchCase - Emit jumptable for current switch case range
01675 bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
01676                                               CaseRecVector& WorkList,
01677                                               Value* SV,
01678                                               MachineBasicBlock* Default) {
01679   Case& FrontCase = *CR.Range.first;
01680   Case& BackCase  = *(CR.Range.second-1);
01681 
01682   const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
01683   const APInt& Last  = cast<ConstantInt>(BackCase.High)->getValue();
01684 
01685   size_t TSize = 0;
01686   for (CaseItr I = CR.Range.first, E = CR.Range.second;
01687        I!=E; ++I)
01688     TSize += I->size();
01689 
01690   if (!areJTsAllowed(TLI) || TSize <= 3)
01691     return false;
01692 
01693   APInt Range = ComputeRange(First, Last);
01694   double Density = (double)TSize / Range.roundToDouble();
01695   if (Density < 0.4)
01696     return false;
01697 
01698   DEBUG(errs() << "Lowering jump table\n"
01699                << "First entry: " << First << ". Last entry: " << Last << '\n'
01700                << "Range: " << Range
01701                << "Size: " << TSize << ". Density: " << Density << "\n\n");
01702 
01703   // Get the MachineFunction which holds the current MBB.  This is used when
01704   // inserting any additional MBBs necessary to represent the switch.
01705   MachineFunction *CurMF = CurMBB->getParent();
01706 
01707   // Figure out which block is immediately after the current one.
01708   MachineBasicBlock *NextBlock = 0;
01709   MachineFunction::iterator BBI = CR.CaseBB;
01710 
01711   if (++BBI != CurMBB->getParent()->end())
01712     NextBlock = BBI;
01713 
01714   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
01715 
01716   // Create a new basic block to hold the code for loading the address
01717   // of the jump table, and jumping to it.  Update successor information;
01718   // we will either branch to the default case for the switch, or the jump
01719   // table.
01720   MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
01721   CurMF->insert(BBI, JumpTableBB);
01722   CR.CaseBB->addSuccessor(Default);
01723   CR.CaseBB->addSuccessor(JumpTableBB);
01724 
01725   // Build a vector of destination BBs, corresponding to each target
01726   // of the jump table. If the value of the jump table slot corresponds to
01727   // a case statement, push the case's BB onto the vector, otherwise, push
01728   // the default BB.
01729   std::vector<MachineBasicBlock*> DestBBs;
01730   APInt TEI = First;
01731   for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
01732     const APInt& Low = cast<ConstantInt>(I->Low)->getValue();
01733     const APInt& High = cast<ConstantInt>(I->High)->getValue();
01734 
01735     if (Low.sle(TEI) && TEI.sle(High)) {
01736       DestBBs.push_back(I->BB);
01737       if (TEI==High)
01738         ++I;
01739     } else {
01740       DestBBs.push_back(Default);
01741     }
01742   }
01743 
01744   // Update successor info. Add one edge to each unique successor.
01745   BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
01746   for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
01747          E = DestBBs.end(); I != E; ++I) {
01748     if (!SuccsHandled[(*I)->getNumber()]) {
01749       SuccsHandled[(*I)->getNumber()] = true;
01750       JumpTableBB->addSuccessor(*I);
01751     }
01752   }
01753 
01754   // Create a jump table index for this jump table, or return an existing
01755   // one.
01756   unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
01757 
01758   // Set the jump table information so that we can codegen it as a second
01759   // MachineBasicBlock
01760   JumpTable JT(-1U, JTI, JumpTableBB, Default);
01761   JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
01762   if (CR.CaseBB == CurMBB)
01763     visitJumpTableHeader(JT, JTH);
01764 
01765   JTCases.push_back(JumpTableBlock(JTH, JT));
01766 
01767   return true;
01768 }
01769 
01770 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
01771 /// 2 subtrees.
01772 bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
01773                                                    CaseRecVector& WorkList,
01774                                                    Value* SV,
01775                                                    MachineBasicBlock* Default) {
01776   // Get the MachineFunction which holds the current MBB.  This is used when
01777   // inserting any additional MBBs necessary to represent the switch.
01778   MachineFunction *CurMF = CurMBB->getParent();
01779 
01780   // Figure out which block is immediately after the current one.
01781   MachineBasicBlock *NextBlock = 0;
01782   MachineFunction::iterator BBI = CR.CaseBB;
01783 
01784   if (++BBI != CurMBB->getParent()->end())
01785     NextBlock = BBI;
01786 
01787   Case& FrontCase = *CR.Range.first;
01788   Case& BackCase  = *(CR.Range.second-1);
01789   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
01790 
01791   // Size is the number of Cases represented by this range.
01792   unsigned Size = CR.Range.second - CR.Range.first;
01793 
01794   const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
01795   const APInt& Last  = cast<ConstantInt>(BackCase.High)->getValue();
01796   double FMetric = 0;
01797   CaseItr Pivot = CR.Range.first + Size/2;
01798 
01799   // Select optimal pivot, maximizing sum density of LHS and RHS. This will
01800   // (heuristically) allow us to emit JumpTable's later.
01801   size_t TSize = 0;
01802   for (CaseItr I = CR.Range.first, E = CR.Range.second;
01803        I!=E; ++I)
01804     TSize += I->size();
01805 
01806   size_t LSize = FrontCase.size();
01807   size_t RSize = TSize-LSize;
01808   DEBUG(errs() << "Selecting best pivot: \n"
01809                << "First: " << First << ", Last: " << Last <<'\n'
01810                << "LSize: " << LSize << ", RSize: " << RSize << '\n');
01811   for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
01812        J!=E; ++I, ++J) {
01813     const APInt& LEnd = cast<ConstantInt>(I->High)->getValue();
01814     const APInt& RBegin = cast<ConstantInt>(J->Low)->getValue();
01815     APInt Range = ComputeRange(LEnd, RBegin);
01816     assert((Range - 2ULL).isNonNegative() &&
01817            "Invalid case distance");
01818     double LDensity = (double)LSize / (LEnd - First + 1ULL).roundToDouble();
01819     double RDensity = (double)RSize / (Last - RBegin + 1ULL).roundToDouble();
01820     double Metric = Range.logBase2()*(LDensity+RDensity);
01821     // Should always split in some non-trivial place
01822     DEBUG(errs() <<"=>Step\n"
01823                  << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
01824                  << "LDensity: " << LDensity
01825                  << ", RDensity: " << RDensity << '\n'
01826                  << "Metric: " << Metric << '\n');
01827     if (FMetric < Metric) {
01828       Pivot = J;
01829       FMetric = Metric;
01830       DEBUG(errs() << "Current metric set to: " << FMetric << '\n');
01831     }
01832 
01833     LSize += J->size();
01834     RSize -= J->size();
01835   }
01836   if (areJTsAllowed(TLI)) {
01837     // If our case is dense we *really* should handle it earlier!
01838     assert((FMetric > 0) && "Should handle dense range earlier!");
01839   } else {
01840     Pivot = CR.Range.first + Size/2;
01841   }
01842 
01843   CaseRange LHSR(CR.Range.first, Pivot);
01844   CaseRange RHSR(Pivot, CR.Range.second);
01845   Constant *C = Pivot->Low;
01846   MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
01847 
01848   // We know that we branch to the LHS if the Value being switched on is
01849   // less than the Pivot value, C.  We use this to optimize our binary
01850   // tree a bit, by recognizing that if SV is greater than or equal to the
01851   // LHS's Case Value, and that Case Value is exactly one less than the
01852   // Pivot's Value, then we can branch directly to the LHS's Target,
01853   // rather than creating a leaf node for it.
01854   if ((LHSR.second - LHSR.first) == 1 &&
01855       LHSR.first->High == CR.GE &&
01856       cast<ConstantInt>(C)->getValue() ==
01857       (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
01858     TrueBB = LHSR.first->BB;
01859   } else {
01860     TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
01861     CurMF->insert(BBI, TrueBB);
01862     WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
01863   }
01864 
01865   // Similar to the optimization above, if the Value being switched on is
01866   // known to be less than the Constant CR.LT, and the current Case Value
01867   // is CR.LT - 1, then we can branch directly to the target block for
01868   // the current Case Value, rather than emitting a RHS leaf node for it.
01869   if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
01870       cast<ConstantInt>(RHSR.first->Low)->getValue() ==
01871       (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
01872     FalseBB = RHSR.first->BB;
01873   } else {
01874     FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
01875     CurMF->insert(BBI, FalseBB);
01876     WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
01877   }
01878 
01879   // Create a CaseBlock record representing a conditional branch to
01880   // the LHS node if the value being switched on SV is less than C.
01881   // Otherwise, branch to LHS.
01882   CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
01883 
01884   if (CR.CaseBB == CurMBB)
01885     visitSwitchCase(CB);
01886   else
01887     SwitchCases.push_back(CB);
01888 
01889   return true;
01890 }
01891 
01892 /// handleBitTestsSwitchCase - if current case range has few destination and
01893 /// range span less, than machine word bitwidth, encode case range into series
01894 /// of masks and emit bit tests with these masks.
01895 bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
01896                                                     CaseRecVector& WorkList,
01897                                                     Value* SV,
01898                                                     MachineBasicBlock* Default){
01899   unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
01900 
01901   Case& FrontCase = *CR.Range.first;
01902   Case& BackCase  = *(CR.Range.second-1);
01903 
01904   // Get the MachineFunction which holds the current MBB.  This is used when
01905   // inserting any additional MBBs necessary to represent the switch.
01906   MachineFunction *CurMF = CurMBB->getParent();
01907 
01908   size_t numCmps = 0;
01909   for (CaseItr I = CR.Range.first, E = CR.Range.second;
01910        I!=E; ++I) {
01911     // Single case counts one, case range - two.
01912     numCmps += (I->Low == I->High ? 1 : 2);
01913   }
01914 
01915   // Count unique destinations
01916   SmallSet<MachineBasicBlock*, 4> Dests;
01917   for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
01918     Dests.insert(I->BB);
01919     if (Dests.size() > 3)
01920       // Don't bother the code below, if there are too much unique destinations
01921       return false;
01922   }
01923   DEBUG(errs() << "Total number of unique destinations: " << Dests.size() << '\n'
01924                << "Total number of comparisons: " << numCmps << '\n');
01925 
01926   // Compute span of values.
01927   const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
01928   const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
01929   APInt cmpRange = maxValue - minValue;
01930 
01931   DEBUG(errs() << "Compare range: " << cmpRange << '\n'
01932                << "Low bound: " << minValue << '\n'
01933                << "High bound: " << maxValue << '\n');
01934 
01935   if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
01936       (!(Dests.size() == 1 && numCmps >= 3) &&
01937        !(Dests.size() == 2 && numCmps >= 5) &&
01938        !(Dests.size() >= 3 && numCmps >= 6)))
01939     return false;
01940 
01941   DEBUG(errs() << "Emitting bit tests\n");
01942   APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
01943 
01944   // Optimize the case where all the case values fit in a
01945   // word without having to subtract minValue. In this case,
01946   // we can optimize away the subtraction.
01947   if (minValue.isNonNegative() &&
01948       maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
01949     cmpRange = maxValue;
01950   } else {
01951     lowBound = minValue;
01952   }
01953 
01954   CaseBitsVector CasesBits;
01955   unsigned i, count = 0;
01956 
01957   for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
01958     MachineBasicBlock* Dest = I->BB;
01959     for (i = 0; i < count; ++i)
01960       if (Dest == CasesBits[i].BB)
01961         break;
01962 
01963     if (i == count) {
01964       assert((count < 3) && "Too much destinations to test!");
01965       CasesBits.push_back(CaseBits(0, Dest, 0));
01966       count++;
01967     }
01968 
01969     const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
01970     const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
01971 
01972     uint64_t lo = (lowValue - lowBound).getZExtValue();
01973     uint64_t hi = (highValue - lowBound).getZExtValue();
01974 
01975     for (uint64_t j = lo; j <= hi; j++) {
01976       CasesBits[i].Mask |=  1ULL << j;
01977       CasesBits[i].Bits++;
01978     }
01979 
01980   }
01981   std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
01982 
01983   BitTestInfo BTC;
01984 
01985   // Figure out which block is immediately after the current one.
01986   MachineFunction::iterator BBI = CR.CaseBB;
01987   ++BBI;
01988 
01989   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
01990 
01991   DEBUG(errs() << "Cases:\n");
01992   for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
01993     DEBUG(errs() << "Mask: " << CasesBits[i].Mask
01994                  << ", Bits: " << CasesBits[i].Bits
01995                  << ", BB: " << CasesBits[i].BB << '\n');
01996 
01997     MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
01998     CurMF->insert(BBI, CaseBB);
01999     BTC.push_back(BitTestCase(CasesBits[i].Mask,
02000                               CaseBB,
02001                               CasesBits[i].BB));
02002   }
02003 
02004   BitTestBlock BTB(lowBound, cmpRange, SV,
02005                    -1U, (CR.CaseBB == CurMBB),
02006                    CR.CaseBB, Default, BTC);
02007 
02008   if (CR.CaseBB == CurMBB)
02009     visitBitTestHeader(BTB);
02010 
02011   BitTestCases.push_back(BTB);
02012 
02013   return true;
02014 }
02015 
02016 
02017 /// Clusterify - Transform simple list of Cases into list of CaseRange's
02018 size_t SelectionDAGLowering::Clusterify(CaseVector& Cases,
02019                                           const SwitchInst& SI) {
02020   size_t numCmps = 0;
02021 
02022   // Start with "simple" cases
02023   for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
02024     MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
02025     Cases.push_back(Case(SI.getSuccessorValue(i),
02026                          SI.getSuccessorValue(i),
02027                          SMBB));
02028   }
02029   std::sort(Cases.begin(), Cases.end(), CaseCmp());
02030 
02031   // Merge case into clusters
02032   if (Cases.size() >= 2)
02033     // Must recompute end() each iteration because it may be
02034     // invalidated by erase if we hold on to it
02035     for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
02036       const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
02037       const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
02038       MachineBasicBlock* nextBB = J->BB;
02039       MachineBasicBlock* currentBB = I->BB;
02040 
02041       // If the two neighboring cases go to the same destination, merge them
02042       // into a single case.
02043       if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
02044         I->High = J->High;
02045         J = Cases.erase(J);
02046       } else {
02047         I = J++;
02048       }
02049     }
02050 
02051   for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
02052     if (I->Low != I->High)
02053       // A range counts double, since it requires two compares.
02054       ++numCmps;
02055   }
02056 
02057   return numCmps;
02058 }
02059 
02060 void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
02061   // Figure out which block is immediately after the current one.
02062   MachineBasicBlock *NextBlock = 0;
02063   MachineFunction::iterator BBI = CurMBB;
02064 
02065   MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
02066 
02067   // If there is only the default destination, branch to it if it is not the
02068   // next basic block.  Otherwise, just fall through.
02069   if (SI.getNumOperands() == 2) {
02070     // Update machine-CFG edges.
02071 
02072     // If this is not a fall-through branch, emit the branch.
02073     CurMBB->addSuccessor(Default);
02074     if (Default != NextBlock)
02075       DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
02076                               MVT::Other, getControlRoot(),
02077                               DAG.getBasicBlock(Default)));
02078     return;
02079   }
02080 
02081   // If there are any non-default case statements, create a vector of Cases
02082   // representing each one, and sort the vector so that we can efficiently
02083   // create a binary search tree from them.
02084   CaseVector Cases;
02085   size_t numCmps = Clusterify(Cases, SI);
02086   DEBUG(errs() << "Clusterify finished. Total clusters: " << Cases.size()
02087                << ". Total compares: " << numCmps << '\n');
02088   numCmps = 0;
02089 
02090   // Get the Value to be switched on and default basic blocks, which will be
02091   // inserted into CaseBlock records, representing basic blocks in the binary
02092   // search tree.
02093   Value *SV = SI.getOperand(0);
02094 
02095   // Push the initial CaseRec onto the worklist
02096   CaseRecVector WorkList;
02097   WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
02098 
02099   while (!WorkList.empty()) {
02100     // Grab a record representing a case range to process off the worklist
02101     CaseRec CR = WorkList.back();
02102     WorkList.pop_back();
02103 
02104     if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
02105       continue;
02106 
02107     // If the range has few cases (two or less) emit a series of specific
02108     // tests.
02109     if (handleSmallSwitchRange(CR, WorkList, SV, Default))
02110       continue;
02111 
02112     // If the switch has more than 5 blocks, and at least 40% dense, and the
02113     // target supports indirect branches, then emit a jump table rather than
02114     // lowering the switch to a binary tree of conditional branches.
02115     if (handleJTSwitchCase(CR, WorkList, SV, Default))
02116       continue;
02117 
02118     // Emit binary tree. We need to pick a pivot, and push left and right ranges
02119     // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
02120     handleBTSplitSwitchCase(CR, WorkList, SV, Default);
02121   }
02122 }
02123 
02124 
02125 void SelectionDAGLowering::visitSub(User &I) {
02126   // -0.0 - X --> fneg
02127   const Type *Ty = I.getType();
02128   if (isa<VectorType>(Ty)) {
02129     if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
02130       const VectorType *DestTy = cast<VectorType>(I.getType());
02131       const Type *ElTy = DestTy->getElementType();
02132       if (ElTy->isFloatingPoint()) {
02133         unsigned VL = DestTy->getNumElements();
02134         std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
02135         Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
02136         if (CV == CNZ) {
02137           SDValue Op2 = getValue(I.getOperand(1));
02138           setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(), 
02139                                    Op2.getValueType(), Op2));
02140           return;
02141         }
02142       }
02143     }
02144   }
02145   if (Ty->isFloatingPoint()) {
02146     if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
02147       if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
02148         SDValue Op2 = getValue(I.getOperand(1));
02149         setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(), 
02150                                  Op2.getValueType(), Op2));
02151         return;
02152       }
02153   }
02154 
02155   visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
02156 }
02157 
02158 void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
02159   SDValue Op1 = getValue(I.getOperand(0));
02160   SDValue Op2 = getValue(I.getOperand(1));
02161 
02162   setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(), 
02163                            Op1.getValueType(), Op1, Op2));
02164 }
02165 
02166 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
02167   SDValue Op1 = getValue(I.getOperand(0));
02168   SDValue Op2 = getValue(I.getOperand(1));
02169   if (!isa<VectorType>(I.getType())) {
02170     if (TLI.getPointerTy().bitsLT(Op2.getValueType()))
02171       Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), 
02172                         TLI.getPointerTy(), Op2);
02173     else if (TLI.getPointerTy().bitsGT(Op2.getValueType()))
02174       Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(), 
02175                         TLI.getPointerTy(), Op2);
02176   }
02177 
02178   setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(), 
02179                            Op1.getValueType(), Op1, Op2));
02180 }
02181 
02182 void SelectionDAGLowering::visitICmp(User &I) {
02183   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
02184   if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
02185     predicate = IC->getPredicate();
02186   else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
02187     predicate = ICmpInst::Predicate(IC->getPredicate());
02188   SDValue Op1 = getValue(I.getOperand(0));
02189   SDValue Op2 = getValue(I.getOperand(1));
02190   ISD::CondCode Opcode = getICmpCondCode(predicate);
02191   setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
02192 }
02193 
02194 void SelectionDAGLowering::visitFCmp(User &I) {
02195   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
02196   if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
02197     predicate = FC->getPredicate();
02198   else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
02199     predicate = FCmpInst::Predicate(FC->getPredicate());
02200   SDValue Op1 = getValue(I.getOperand(0));
02201   SDValue Op2 = getValue(I.getOperand(1));
02202   ISD::CondCode Condition = getFCmpCondCode(predicate);
02203   setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
02204 }
02205 
02206 void SelectionDAGLowering::visitVICmp(User &I) {
02207   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
02208   if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
02209     predicate = IC->getPredicate();
02210   else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
02211     predicate = ICmpInst::Predicate(IC->getPredicate());
02212   SDValue Op1 = getValue(I.getOperand(0));
02213   SDValue Op2 = getValue(I.getOperand(1));
02214   ISD::CondCode Opcode = getICmpCondCode(predicate);
02215   setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
02216 }
02217 
02218 void SelectionDAGLowering::visitVFCmp(User &I) {
02219   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
02220   if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
02221     predicate = FC->getPredicate();
02222   else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
02223     predicate = FCmpInst::Predicate(FC->getPredicate());
02224   SDValue Op1 = getValue(I.getOperand(0));
02225   SDValue Op2 = getValue(I.getOperand(1));
02226   ISD::CondCode Condition = getFCmpCondCode(predicate);
02227   MVT DestVT = TLI.getValueType(I.getType());
02228 
02229   setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
02230 }
02231 
02232 void SelectionDAGLowering::visitSelect(User &I) {
02233   SmallVector<MVT, 4> ValueVTs;
02234   ComputeValueVTs(TLI, I.getType(), ValueVTs);
02235   unsigned NumValues = ValueVTs.size();
02236   if (NumValues != 0) {
02237     SmallVector<SDValue, 4> Values(NumValues);
02238     SDValue Cond     = getValue(I.getOperand(0));
02239     SDValue TrueVal  = getValue(I.getOperand(1));
02240     SDValue FalseVal = getValue(I.getOperand(2));
02241 
02242     for (unsigned i = 0; i != NumValues; ++i)
02243       Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(), 
02244                               TrueVal.getValueType(), Cond,
02245                               SDValue(TrueVal.getNode(), TrueVal.getResNo() + i),
02246                               SDValue(FalseVal.getNode(), FalseVal.getResNo() + i));
02247 
02248     setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(), 
02249                              DAG.getVTList(&ValueVTs[0], NumValues),
02250                              &Values[0], NumValues));
02251   }
02252 }
02253 
02254 
02255 void SelectionDAGLowering::visitTrunc(User &I) {
02256   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
02257   SDValue N = getValue(I.getOperand(0));
02258   MVT DestVT = TLI.getValueType(I.getType());
02259   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
02260 }
02261 
02262 void SelectionDAGLowering::visitZExt(User &I) {
02263   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
02264   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
02265   SDValue N = getValue(I.getOperand(0));
02266   MVT DestVT = TLI.getValueType(I.getType());
02267   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
02268 }
02269 
02270 void SelectionDAGLowering::visitSExt(User &I) {
02271   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
02272   // SExt also can't be a cast to bool for same reason. So, nothing much to do
02273   SDValue N = getValue(I.getOperand(0));
02274   MVT DestVT = TLI.getValueType(I.getType());
02275   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
02276 }
02277 
02278 void SelectionDAGLowering::visitFPTrunc(User &I) {
02279   // FPTrunc is never a no-op cast, no need to check
02280   SDValue N = getValue(I.getOperand(0));
02281   MVT DestVT = TLI.getValueType(I.getType());
02282   setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(), 
02283                            DestVT, N, DAG.getIntPtrConstant(0)));
02284 }
02285 
02286 void SelectionDAGLowering::visitFPExt(User &I){
02287   // FPTrunc is never a no-op cast, no need to check
02288   SDValue N = getValue(I.getOperand(0));
02289   MVT DestVT = TLI.getValueType(I.getType());
02290   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
02291 }
02292 
02293 void SelectionDAGLowering::visitFPToUI(User &I) {
02294   // FPToUI is never a no-op cast, no need to check
02295   SDValue N = getValue(I.getOperand(0));
02296   MVT DestVT = TLI.getValueType(I.getType());
02297   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
02298 }
02299 
02300 void SelectionDAGLowering::visitFPToSI(User &I) {
02301   // FPToSI is never a no-op cast, no need to check
02302   SDValue N = getValue(I.getOperand(0));
02303   MVT DestVT = TLI.getValueType(I.getType());
02304   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
02305 }
02306 
02307 void SelectionDAGLowering::visitUIToFP(User &I) {
02308   // UIToFP is never a no-op cast, no need to check
02309   SDValue N = getValue(I.getOperand(0));
02310   MVT DestVT = TLI.getValueType(I.getType());
02311   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
02312 }
02313 
02314 void SelectionDAGLowering::visitSIToFP(User &I){
02315   // SIToFP is never a no-op cast, no need to check
02316   SDValue N = getValue(I.getOperand(0));
02317   MVT DestVT = TLI.getValueType(I.getType());
02318   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
02319 }
02320 
02321 void SelectionDAGLowering::visitPtrToInt(User &I) {
02322   // What to do depends on the size of the integer and the size of the pointer.
02323   // We can either truncate, zero extend, or no-op, accordingly.
02324   SDValue N = getValue(I.getOperand(0));
02325   MVT SrcVT = N.getValueType();
02326   MVT DestVT = TLI.getValueType(I.getType());
02327   SDValue Result;
02328   if (DestVT.bitsLT(SrcVT))
02329     Result = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N);
02330   else
02331     // Note: ZERO_EXTEND can handle cases where the sizes are equal too
02332     Result = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N);
02333   setValue(&I, Result);
02334 }
02335 
02336 void SelectionDAGLowering::visitIntToPtr(User &I) {
02337   // What to do depends on the size of the integer and the size of the pointer.
02338   // We can either truncate, zero extend, or no-op, accordingly.
02339   SDValue N = getValue(I.getOperand(0));
02340   MVT SrcVT = N.getValueType();
02341   MVT DestVT = TLI.getValueType(I.getType());
02342   if (DestVT.bitsLT(SrcVT))
02343     setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
02344   else
02345     // Note: ZERO_EXTEND can handle cases where the sizes are equal too
02346     setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), 
02347                              DestVT, N));
02348 }
02349 
02350 void SelectionDAGLowering::visitBitCast(User &I) {
02351   SDValue N = getValue(I.getOperand(0));
02352   MVT DestVT = TLI.getValueType(I.getType());
02353 
02354   // BitCast assures us that source and destination are the same size so this
02355   // is either a BIT_CONVERT or a no-op.
02356   if (DestVT != N.getValueType())
02357     setValue(&I, DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), 
02358                              DestVT, N)); // convert types
02359   else
02360     setValue(&I, N); // noop cast.
02361 }
02362 
02363 void SelectionDAGLowering::visitInsertElement(User &I) {
02364   SDValue InVec = getValue(I.getOperand(0));
02365   SDValue InVal = getValue(I.getOperand(1));
02366   SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), 
02367                                 TLI.getPointerTy(),
02368                                 getValue(I.getOperand(2)));
02369 
02370   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(), 
02371                            TLI.getValueType(I.getType()),
02372                            InVec, InVal, InIdx));
02373 }
02374 
02375 void SelectionDAGLowering::visitExtractElement(User &I) {
02376   SDValue InVec = getValue(I.getOperand(0));
02377   SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), 
02378                                 TLI.getPointerTy(),
02379                                 getValue(I.getOperand(1)));
02380   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
02381                            TLI.getValueType(I.getType()), InVec, InIdx));
02382 }
02383 
02384 
02385 // Utility for visitShuffleVector - Returns true if the mask is mask starting
02386 // from SIndx and increasing to the element length (undefs are allowed).
02387 static bool SequentialMask(SDValue Mask, unsigned SIndx) {
02388   unsigned MaskNumElts = Mask.getNumOperands();
02389   for (unsigned i = 0; i != MaskNumElts; ++i) {
02390     if (Mask.getOperand(i).getOpcode() != ISD::UNDEF) {
02391       unsigned Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
02392       if (Idx != i + SIndx)
02393         return false;
02394     }
02395   }
02396   return true;
02397 }
02398 
02399 void SelectionDAGLowering::visitShuffleVector(User &I) {
02400   SDValue Src1 = getValue(I.getOperand(0));
02401   SDValue Src2 = getValue(I.getOperand(1));
02402   SDValue Mask = getValue(I.getOperand(2));
02403 
02404   MVT VT = TLI.getValueType(I.getType());
02405   MVT SrcVT = Src1.getValueType();
02406   int MaskNumElts = Mask.getNumOperands();
02407   int SrcNumElts = SrcVT.getVectorNumElements();
02408 
02409   if (SrcNumElts == MaskNumElts) {
02410     setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, getCurDebugLoc(), 
02411                              VT, Src1, Src2, Mask));
02412     return;
02413   }
02414 
02415   // Normalize the shuffle vector since mask and vector length don't match.
02416   MVT MaskEltVT = Mask.getValueType().getVectorElementType();
02417 
02418   if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
02419     // Mask is longer than the source vectors and is a multiple of the source
02420     // vectors.  We can use concatenate vector to make the mask and vectors
02421     // lengths match.
02422     if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
02423       // The shuffle is concatenating two vectors together.
02424       setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(), 
02425                                VT, Src1, Src2));
02426       return;
02427     }
02428 
02429     // Pad both vectors with undefs to make them the same length as the mask.
02430     unsigned NumConcat = MaskNumElts / SrcNumElts;
02431     SDValue UndefVal = DAG.getNode(ISD::UNDEF, getCurDebugLoc(), SrcVT);
02432 
02433     SDValue* MOps1 = new SDValue[NumConcat];
02434     SDValue* MOps2 = new SDValue[NumConcat];
02435     MOps1[0] = Src1;
02436     MOps2[0] = Src2;
02437     for (unsigned i = 1; i != NumConcat; ++i) {
02438       MOps1[i] = UndefVal;
02439       MOps2[i] = UndefVal;
02440     }
02441     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(), 
02442                        VT, MOps1, NumConcat);
02443     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(), 
02444                        VT, MOps2, NumConcat);
02445 
02446     delete [] MOps1;
02447     delete [] MOps2;
02448 
02449     // Readjust mask for new input vector length.
02450     SmallVector<SDValue, 8> MappedOps;
02451     for (int i = 0; i != MaskNumElts; ++i) {
02452       if (Mask.getOperand(i).getOpcode() == ISD::UNDEF) {
02453         MappedOps.push_back(Mask.getOperand(i));
02454       } else {
02455         int Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
02456         if (Idx < SrcNumElts)
02457           MappedOps.push_back(DAG.getConstant(Idx, MaskEltVT));
02458         else
02459           MappedOps.push_back(DAG.getConstant(Idx + MaskNumElts - SrcNumElts,
02460                                               MaskEltVT));
02461       }
02462     }
02463     Mask = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(), 
02464                        Mask.getValueType(),
02465                        &MappedOps[0], MappedOps.size());
02466 
02467     setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, getCurDebugLoc(), 
02468                              VT, Src1, Src2, Mask));
02469     return;
02470   }
02471 
02472   if (SrcNumElts > MaskNumElts) {
02473     // Resulting vector is shorter than the incoming vector.
02474     if (SrcNumElts == MaskNumElts && SequentialMask(Mask,0)) {
02475       // Shuffle extracts 1st vector.
02476       setValue(&I, Src1);
02477       return;
02478     }
02479 
02480     if (SrcNumElts == MaskNumElts && SequentialMask(Mask,MaskNumElts)) {
02481       // Shuffle extracts 2nd vector.
02482       setValue(&I, Src2);
02483       return;
02484     }
02485 
02486     // Analyze the access pattern of the vector to see if we can extract
02487     // two subvectors and do the shuffle. The analysis is done by calculating
02488     // the range of elements the mask access on both vectors.
02489     int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
02490     int MaxRange[2] = {-1, -1};
02491 
02492     for (int i = 0; i != MaskNumElts; ++i) {
02493       SDValue Arg = Mask.getOperand(i);
02494       if (Arg.getOpcode() != ISD::UNDEF) {
02495         assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
02496         int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
02497         int Input = 0;
02498         if (Idx >= SrcNumElts) {
02499           Input = 1;
02500           Idx -= SrcNumElts;
02501         }
02502         if (Idx > MaxRange[Input])
02503           MaxRange[Input] = Idx;
02504         if (Idx < MinRange[Input])
02505           MinRange[Input] = Idx;
02506       }
02507     }
02508 
02509     // Check if the access is smaller than the vector size and can we find
02510     // a reasonable extract index.
02511     int RangeUse[2] = { 2, 2 };  // 0 = Unused, 1 = Extract, 2 = Can not Extract.
02512     int StartIdx[2];  // StartIdx to extract from
02513     for (int Input=0; Input < 2; ++Input) {
02514       if (MinRange[Input] == SrcNumElts+1 && MaxRange[Input] == -1) {
02515         RangeUse[Input] = 0; // Unused
02516         StartIdx[Input] = 0;
02517       } else if (MaxRange[Input] - MinRange[Input] < MaskNumElts) {
02518         // Fits within range but we should see if we can find a good
02519         // start index that is a multiple of the mask length.
02520         if (MaxRange[Input] < MaskNumElts) {
02521           RangeUse[Input] = 1; // Extract from beginning of the vector
02522           StartIdx[Input] = 0;
02523         } else {
02524           StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
02525           if (MaxRange[Input] - StartIdx[Input] < MaskNumElts &&
02526               StartIdx[Input] + MaskNumElts < SrcNumElts)
02527             RangeUse[Input] = 1; // Extract from a multiple of the mask length.
02528         }
02529       }
02530     }
02531 
02532     if (RangeUse[0] == 0 && RangeUse[0] == 0) {
02533       setValue(&I, DAG.getNode(ISD::UNDEF, 
02534                           getCurDebugLoc(), VT));  // Vectors are not used.
02535       return;
02536     }
02537     else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
02538       // Extract appropriate subvector and generate a vector shuffle
02539       for (int Input=0; Input < 2; ++Input) {
02540         SDValue& Src = Input == 0 ? Src1 : Src2;
02541         if (RangeUse[Input] == 0) {
02542           Src = DAG.getNode(ISD::UNDEF, getCurDebugLoc(), VT);
02543         } else {
02544           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
02545                             Src, DAG.getIntPtrConstant(StartIdx[Input]));
02546         }
02547       }
02548       // Calculate new mask.
02549       SmallVector<SDValue, 8> MappedOps;
02550       for (int i = 0; i != MaskNumElts; ++i) {
02551         SDValue Arg = Mask.getOperand(i);
02552         if (Arg.getOpcode() == ISD::UNDEF) {
02553           MappedOps.push_back(Arg);
02554         } else {
02555           int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
02556           if (Idx < SrcNumElts)
02557             MappedOps.push_back(DAG.getConstant(Idx - StartIdx[0], MaskEltVT));
02558           else {
02559             Idx = Idx - SrcNumElts - StartIdx[1] + MaskNumElts;
02560             MappedOps.push_back(DAG.getConstant(Idx, MaskEltVT));
02561           }
02562         }
02563       }
02564       Mask = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(), 
02565                          Mask.getValueType(),
02566                          &MappedOps[0], MappedOps.size());
02567       setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, getCurDebugLoc(), 
02568                                VT, Src1, Src2, Mask));
02569       return;
02570     }
02571   }
02572 
02573   // We can't use either concat vectors or extract subvectors so fall back to
02574   // replacing the shuffle with extract and build vector.
02575   // to insert and build vector.
02576   MVT EltVT = VT.getVectorElementType();
02577   MVT PtrVT = TLI.getPointerTy();
02578   SmallVector<SDValue,8> Ops;
02579   for (int i = 0; i != MaskNumElts; ++i) {
02580     SDValue Arg = Mask.getOperand(i);
02581     if (Arg.getOpcode() == ISD::UNDEF) {
02582       Ops.push_back(DAG.getNode(ISD::UNDEF, getCurDebugLoc(), EltVT));
02583     } else {
02584       assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
02585       int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
02586       if (Idx < SrcNumElts)
02587         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
02588                                   EltVT, Src1, DAG.getConstant(Idx, PtrVT)));
02589       else
02590         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
02591                                   EltVT, Src2, 
02592                                   DAG.getConstant(Idx - SrcNumElts, PtrVT)));
02593     }
02594   }
02595   setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(), 
02596                            VT, &Ops[0], Ops.size()));
02597 }
02598 
02599 void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
02600   const Value *Op0 = I.getOperand(0);
02601   const Value *Op1 = I.getOperand(1);
02602   const Type *AggTy = I.getType();
02603   const Type *ValTy = Op1->getType();
02604   bool IntoUndef = isa<UndefValue>(Op0);
02605   bool FromUndef = isa<UndefValue>(Op1);
02606 
02607   unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
02608                                             I.idx_begin(), I.idx_end());
02609 
02610   SmallVector<MVT, 4> AggValueVTs;
02611   ComputeValueVTs(TLI, AggTy, AggValueVTs);
02612   SmallVector<MVT, 4> ValValueVTs;
02613   ComputeValueVTs(TLI, ValTy, ValValueVTs);
02614 
02615   unsigned NumAggValues = AggValueVTs.size();
02616   unsigned NumValValues = ValValueVTs.size();
02617   SmallVector<SDValue, 4> Values(NumAggValues);
02618 
02619   SDValue Agg = getValue(Op0);
02620   SDValue Val = getValue(Op1);
02621   unsigned i = 0;
02622   // Copy the beginning value(s) from the original aggregate.
02623   for (; i != LinearIndex; ++i)
02624     Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, getCurDebugLoc(), 
02625                                         AggValueVTs[i]) :
02626                 SDValue(Agg.getNode(), Agg.getResNo() + i);
02627   // Copy values from the inserted value(s).
02628   for (; i != LinearIndex + NumValValues; ++i)
02629     Values[i] = FromUndef ? DAG.getNode(ISD::UNDEF, getCurDebugLoc(), 
02630                                         AggValueVTs[i]) :
02631                 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
02632   // Copy remaining value(s) from the original aggregate.
02633   for (; i != NumAggValues; ++i)
02634     Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, getCurDebugLoc(), 
02635                                         AggValueVTs[i]) :
02636                 SDValue(Agg.getNode(), Agg.getResNo() + i);
02637 
02638   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(), 
02639                            DAG.getVTList(&AggValueVTs[0], NumAggValues),
02640                            &Values[0], NumAggValues));
02641 }
02642 
02643 void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
02644   const Value *Op0 = I.getOperand(0);
02645   const Type *AggTy = Op0->getType();
02646   const Type *ValTy = I.getType();
02647   bool OutOfUndef = isa<UndefValue>(Op0);
02648 
02649   unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
02650                                             I.idx_begin(), I.idx_end());
02651 
02652   SmallVector<MVT, 4> ValValueVTs;
02653   ComputeValueVTs(TLI, ValTy, ValValueVTs);
02654 
02655   unsigned NumValValues = ValValueVTs.size();
02656   SmallVector<SDValue, 4> Values(NumValValues);
02657 
02658   SDValue Agg = getValue(Op0);
02659   // Copy out the selected value(s).
02660   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
02661     Values[i - LinearIndex] =
02662       OutOfUndef ?
02663         DAG.getNode(ISD::UNDEF, getCurDebugLoc(), 
02664                     Agg.getNode()->getValueType(Agg.getResNo() + i)) :
02665         SDValue(Agg.getNode(), Agg.getResNo() + i);
02666 
02667   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(), 
02668                            DAG.getVTList(&ValValueVTs[0], NumValValues),
02669                            &Values[0], NumValValues));
02670 }
02671 
02672 
02673 void SelectionDAGLowering::visitGetElementPtr(User &I) {
02674   SDValue N = getValue(I.getOperand(0));
02675   const Type *Ty = I.getOperand(0)->getType();
02676 
02677   for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
02678        OI != E; ++OI) {
02679     Value *Idx = *OI;
02680     if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
02681       unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
02682       if (Field) {
02683         // N = N + Offset
02684         uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
02685         N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
02686                         DAG.getIntPtrConstant(Offset));
02687       }
02688       Ty = StTy->getElementType(Field);
02689     } else {
02690       Ty = cast<SequentialType>(Ty)->getElementType();
02691 
02692       // If this is a constant subscript, handle it quickly.
02693       if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
02694         if (CI->getZExtValue() == 0) continue;
02695         uint64_t Offs =
02696             TD->getTypePaddedSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
02697         N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
02698                         DAG.getIntPtrConstant(Offs));
02699         continue;
02700       }
02701 
02702       // N = N + Idx * ElementSize;
02703       uint64_t ElementSize = TD->getTypePaddedSize(Ty);
02704       SDValue IdxN = getValue(Idx);
02705 
02706       // If the index is smaller or larger than intptr_t, truncate or extend
02707       // it.
02708       if (IdxN.getValueType().bitsLT(N.getValueType()))
02709         IdxN = DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), 
02710                            N.getValueType(), IdxN);
02711       else if (IdxN.getValueType().bitsGT(N.getValueType()))
02712         IdxN = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), 
02713                            N.getValueType(), IdxN);
02714 
02715       // If this is a multiply by a power of two, turn it into a shl
02716       // immediately.  This is a very common case.
02717       if (ElementSize != 1) {
02718         if (isPowerOf2_64(ElementSize)) {
02719           unsigned Amt = Log2_64(ElementSize);
02720           IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(), 
02721                              N.getValueType(), IdxN,
02722                              DAG.getConstant(Amt, TLI.getPointerTy()));
02723         } else {
02724           SDValue Scale = DAG.getIntPtrConstant(ElementSize);
02725           IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(), 
02726                              N.getValueType(), IdxN, Scale);
02727         }
02728       }
02729 
02730       N = DAG.getNode(ISD::ADD, getCurDebugLoc(), 
02731                       N.getValueType(), N, IdxN);
02732     }
02733   }
02734   setValue(&I, N);
02735 }
02736 
02737 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
02738   // If this is a fixed sized alloca in the entry block of the function,
02739   // allocate it statically on the stack.
02740   if (FuncInfo.StaticAllocaMap.count(&I))
02741     return;   // getValue will auto-populate this.
02742 
02743   const Type *Ty = I.getAllocatedType();
02744   uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
02745   unsigned Align =
02746     std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
02747              I.getAlignment());
02748 
02749   SDValue AllocSize = getValue(I.getArraySize());
02750   MVT IntPtr = TLI.getPointerTy();
02751   if (IntPtr.bitsLT(AllocSize.getValueType()))
02752     AllocSize = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), 
02753                             IntPtr, AllocSize);
02754   else if (IntPtr.bitsGT(AllocSize.getValueType()))
02755     AllocSize = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), 
02756                             IntPtr, AllocSize);
02757 
02758   AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), IntPtr, AllocSize,
02759                           DAG.getIntPtrConstant(TySize));
02760 
02761   // Handle alignment.  If the requested alignment is less than or equal to
02762   // the stack alignment, ignore it.  If the size is greater than or equal to
02763   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
02764   unsigned StackAlign =
02765     TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
02766   if (Align <= StackAlign)
02767     Align = 0;
02768 
02769   // Round the size of the allocation up to the stack alignment size
02770   // by add SA-1 to the size.
02771   AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(), 
02772                           AllocSize.getValueType(), AllocSize,
02773                           DAG.getIntPtrConstant(StackAlign-1));
02774   // Mask out the low bits for alignment purposes.
02775   AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(), 
02776                           AllocSize.getValueType(), AllocSize,
02777                           DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
02778 
02779   SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
02780   const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
02781                                                     MVT::Other);
02782   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(), 
02783                             VTs, 2, Ops, 3);
02784   setValue(&I, DSA);
02785   DAG.setRoot(DSA.getValue(1));
02786 
02787   // Inform the Frame Information that we have just allocated a variable-sized
02788   // object.
02789   CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
02790 }
02791 
02792 void SelectionDAGLowering::visitLoad(LoadInst &I) {
02793   const Value *SV = I.getOperand(0);
02794   SDValue Ptr = getValue(SV);
02795 
02796   const Type *Ty = I.getType();
02797   bool isVolatile = I.isVolatile();
02798   unsigned Alignment = I.getAlignment();
02799 
02800   SmallVector<MVT, 4> ValueVTs;
02801   SmallVector<uint64_t, 4> Offsets;
02802   ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
02803   unsigned NumValues = ValueVTs.size();
02804   if (NumValues == 0)
02805     return;
02806 
02807   SDValue Root;
02808   bool ConstantMemory = false;
02809   if (I.isVolatile())
02810     // Serialize volatile loads with other side effects.
02811     Root = getRoot();
02812   else if (AA->pointsToConstantMemory(SV)) {
02813     // Do not serialize (non-volatile) loads of constant memory with anything.
02814     Root = DAG.getEntryNode();
02815     ConstantMemory = true;
02816   } else {
02817     // Do not serialize non-volatile loads against each other.
02818     Root = DAG.getRoot();
02819   }
02820 
02821   SmallVector<SDValue, 4> Values(NumValues);
02822   SmallVector<SDValue, 4> Chains(NumValues);
02823   MVT PtrVT = Ptr.getValueType();
02824   for (unsigned i = 0; i != NumValues; ++i) {
02825     SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
02826                               DAG.getNode(ISD::ADD, getCurDebugLoc(), 
02827                                           PtrVT, Ptr,
02828                                           DAG.getConstant(Offsets[i], PtrVT)),
02829                               SV, Offsets[i],
02830                               isVolatile, Alignment);
02831     Values[i] = L;
02832     Chains[i] = L.getValue(1);
02833   }
02834 
02835   if (!ConstantMemory) {
02836     SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), 
02837                                   MVT::Other,
02838                                   &Chains[0], NumValues);
02839     if (isVolatile)
02840       DAG.setRoot(Chain);
02841     else
02842       PendingLoads.push_back(Chain);
02843   }
02844 
02845   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(), 
02846                            DAG.getVTList(&ValueVTs[0], NumValues),
02847                            &Values[0], NumValues));
02848 }
02849 
02850 
02851 void SelectionDAGLowering::visitStore(StoreInst &I) {
02852   Value *SrcV = I.getOperand(0);
02853   Value *PtrV = I.getOperand(1);
02854 
02855   SmallVector<MVT, 4> ValueVTs;
02856   SmallVector<uint64_t, 4> Offsets;
02857   ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
02858   unsigned NumValues = ValueVTs.size();
02859   if (NumValues == 0)
02860     return;
02861 
02862   // Get the lowered operands. Note that we do this after
02863   // checking if NumResults is zero, because with zero results
02864   // the operands won't have values in the map.
02865   SDValue Src = getValue(SrcV);
02866   SDValue Ptr = getValue(PtrV);
02867 
02868   SDValue Root = getRoot();
02869   SmallVector<SDValue, 4> Chains(NumValues);
02870   MVT PtrVT = Ptr.getValueType();
02871   bool isVolatile = I.isVolatile();
02872   unsigned Alignment = I.getAlignment();
02873   for (unsigned i = 0; i != NumValues; ++i)
02874     Chains[i] = DAG.getStore(Root, getCurDebugLoc(),
02875                              SDValue(Src.getNode(), Src.getResNo() + i),
02876                              DAG.getNode(ISD::ADD, getCurDebugLoc(), 
02877                                          PtrVT, Ptr,
02878                                          DAG.getConstant(Offsets[i], PtrVT)),
02879                              PtrV, Offsets[i],
02880                              isVolatile, Alignment);
02881 
02882   DAG.setRoot(DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), 
02883                           MVT::Other, &Chains[0], NumValues));
02884 }
02885 
02886 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
02887 /// node.
02888 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
02889                                                 unsigned Intrinsic) {
02890   bool HasChain = !I.doesNotAccessMemory();
02891   bool OnlyLoad = HasChain && I.onlyReadsMemory();
02892 
02893   // Build the operand list.
02894   SmallVector<SDValue, 8> Ops;
02895   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
02896     if (OnlyLoad) {
02897       // We don't need to serialize loads against other loads.
02898       Ops.push_back(DAG.getRoot());
02899     } else {
02900       Ops.push_back(getRoot());
02901     }
02902   }
02903 
02904   // Info is set by getTgtMemInstrinsic
02905   TargetLowering::IntrinsicInfo Info;
02906   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
02907 
02908   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
02909   if (!IsTgtIntrinsic)
02910     Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
02911 
02912   // Add all operands of the call to the operand list.
02913   for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
02914     SDValue Op = getValue(I.getOperand(i));
02915     assert(TLI.isTypeLegal(Op.getValueType()) &&
02916            "Intrinsic uses a non-legal type?");
02917     Ops.push_back(Op);
02918   }
02919 
02920   std::vector<MVT> VTs;
02921   if (I.getType() != Type::VoidTy) {
02922     MVT VT = TLI.getValueType(I.getType());
02923     if (VT.isVector()) {
02924       const VectorType *DestTy = cast<VectorType>(I.getType());
02925       MVT EltVT = TLI.getValueType(DestTy->getElementType());
02926 
02927       VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
02928       assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
02929     }
02930 
02931     assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
02932     VTs.push_back(VT);
02933   }
02934   if (HasChain)
02935     VTs.push_back(MVT::Other);
02936 
02937   const MVT *VTList = DAG.getNodeValueTypes(VTs);
02938 
02939   // Create the node.
02940   SDValue Result;
02941   if (IsTgtIntrinsic) {
02942     // This is target intrinsic that touches memory
02943     Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
02944                                      VTList, VTs.size(),
02945                                      &Ops[0], Ops.size(),
02946                                      Info.memVT, Info.ptrVal, Info.offset,
02947                                      Info.align, Info.vol,
02948                                      Info.readMem, Info.writeMem);
02949   }
02950   else if (!HasChain)
02951     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(), 
02952                          VTList, VTs.size(),
02953                          &Ops[0], Ops.size());
02954   else if (I.getType() != Type::VoidTy)
02955     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(), 
02956                          VTList, VTs.size(),
02957                          &Ops[0], Ops.size());
02958   else
02959     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(), 
02960                          VTList, VTs.size(),
02961                          &Ops[0], Ops.size());
02962 
02963   if (HasChain) {
02964     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
02965     if (OnlyLoad)
02966       PendingLoads.push_back(Chain);
02967     else
02968       DAG.setRoot(Chain);
02969   }
02970   if (I.getType() != Type::VoidTy) {
02971     if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
02972       MVT VT = TLI.getValueType(PTy);
02973       Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result);
02974     }
02975     setValue(&I, Result);
02976   }
02977 }
02978 
02979 /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
02980 static GlobalVariable *ExtractTypeInfo(Value *V) {
02981   V = V->stripPointerCasts();
02982   GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
02983   assert ((GV || isa<ConstantPointerNull>(V)) &&
02984           "TypeInfo must be a global variable or NULL");
02985   return GV;
02986 }
02987 
02988 namespace llvm {
02989 
02990 /// AddCatchInfo - Extract the personality and type infos from an eh.selector
02991 /// call, and add them to the specified machine basic block.
02992 void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
02993                   MachineBasicBlock *MBB) {
02994   // Inform the MachineModuleInfo of the personality for this landing pad.
02995   ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
02996   assert(CE->getOpcode() == Instruction::BitCast &&
02997          isa<Function>(CE->getOperand(0)) &&
02998          "Personality should be a function");
02999   MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
03000 
03001   // Gather all the type infos for this landing pad and pass them along to
03002   // MachineModuleInfo.
03003   std::vector<GlobalVariable *> TyInfo;
03004   unsigned N = I.getNumOperands();
03005 
03006   for (unsigned i = N - 1; i > 2; --i) {
03007     if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
03008       unsigned FilterLength = CI->getZExtValue();
03009       unsigned FirstCatch = i + FilterLength + !FilterLength;
03010       assert (FirstCatch <= N && "Invalid filter length");
03011 
03012       if (FirstCatch < N) {
03013         TyInfo.reserve(N - FirstCatch);
03014         for (unsigned j = FirstCatch; j < N; ++j)
03015           TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
03016         MMI->addCatchTypeInfo(MBB, TyInfo);
03017         TyInfo.clear();
03018       }
03019 
03020       if (!FilterLength) {
03021         // Cleanup.
03022         MMI->addCleanup(MBB);
03023       } else {
03024         // Filter.
03025         TyInfo.reserve(FilterLength - 1);
03026         for (unsigned j = i + 1; j < FirstCatch; ++j)
03027           TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
03028         MMI->addFilterTypeInfo(MBB, TyInfo);
03029         TyInfo.clear();
03030       }
03031 
03032       N = i;
03033     }
03034   }
03035 
03036   if (N > 3) {
03037     TyInfo.reserve(N - 3);
03038     for (unsigned j = 3; j < N; ++j)
03039       TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
03040     MMI->addCatchTypeInfo(MBB, TyInfo);
03041   }
03042 }
03043 
03044 }
03045 
03046 /// GetSignificand - Get the significand and build it into a floating-point
03047 /// number with exponent of 1:
03048 ///
03049 ///   Op = (Op & 0x007fffff) | 0x3f800000;
03050 ///
03051 /// where Op is the hexidecimal representation of floating point value.
03052 static SDValue
03053 GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) {
03054   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
03055                            DAG.getConstant(0x007fffff, MVT::i32));
03056   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
03057                            DAG.getConstant(0x3f800000, MVT::i32));
03058   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2);
03059 }
03060 
03061 /// GetExponent - Get the exponent:
03062 ///
03063 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
03064 ///
03065 /// where Op is the hexidecimal representation of floating point value.
03066 static SDValue
03067 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
03068             DebugLoc dl) {
03069   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
03070                            DAG.getConstant(0x7f800000, MVT::i32));
03071   SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
03072                            DAG.getConstant(23, TLI.getPointerTy()));
03073   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
03074                            DAG.getConstant(127, MVT::i32));
03075   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
03076 }
03077 
03078 /// getF32Constant - Get 32-bit floating point constant.
03079 static SDValue
03080 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
03081   return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
03082 }
03083 
03084 /// Inlined utility function to implement binary input atomic intrinsics for
03085 /// visitIntrinsicCall: I is a call instruction
03086 ///                     Op is the associated NodeType for I
03087 const char *
03088 SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
03089   SDValue Root = getRoot();
03090   SDValue L =
03091     DAG.getAtomic(Op, getCurDebugLoc(),
03092                   getValue(I.getOperand(2)).getValueType().getSimpleVT(),
03093                   Root,
03094                   getValue(I.getOperand(1)),
03095                   getValue(I.getOperand(2)),
03096                   I.getOperand(1));
03097   setValue(&I, L);
03098   DAG.setRoot(L.getValue(1));
03099   return 0;
03100 }
03101 
03102 // implVisitAluOverflow - Lower arithmetic overflow instrinsics.
03103 const char *
03104 SelectionDAGLowering::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
03105   SDValue Op1 = getValue(I.getOperand(1));
03106   SDValue Op2 = getValue(I.getOperand(2));
03107 
03108   MVT ValueVTs[] = { Op1.getValueType(), MVT::i1 };
03109   SDValue Ops[] = { Op1, Op2 };
03110 
03111   SDValue Result = DAG.getNode(Op, getCurDebugLoc(), 
03112                                DAG.getVTList(&ValueVTs[0], 2), &Ops[0], 2);
03113 
03114   setValue(&I, Result);
03115   return 0;
03116 }
03117 
03118 /// visitExp - Lower an exp intrinsic. Handles the special sequences for
03119 /// limited-precision mode.
03120 void
03121 SelectionDAGLowering::visitExp(CallInst &I) {
03122   SDValue result;
03123   DebugLoc dl = getCurDebugLoc();
03124 
03125   if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
03126       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
03127     SDValue Op = getValue(I.getOperand(1));
03128 
03129     // Put the exponent in the right bit position for later addition to the
03130     // final result:
03131     //
03132     //   #define LOG2OFe 1.4426950f
03133     //   IntegerPartOfX = ((int32_t)(X * LOG2OFe));
03134     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
03135                              getF32Constant(DAG, 0x3fb8aa3b));
03136     SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
03137 
03138     //   FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
03139     SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
03140     SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
03141 
03142     //   IntegerPartOfX <<= 23;
03143     IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
03144                                  DAG.getConstant(23, TLI.getPointerTy()));
03145 
03146     if (LimitFloatPrecision <= 6) {
03147       // For floating-point precision of 6:
03148       //
03149       //   TwoToFractionalPartOfX =
03150       //     0.997535578f +
03151       //       (0.735607626f + 0.252464424f * x) * x;
03152       //
03153       // error 0.0144103317, which is 6 bits
03154       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
03155                                getF32Constant(DAG, 0x3e814304));
03156       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
03157                                getF32Constant(DAG, 0x3f3c50c8));
03158       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
03159       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
03160                                getF32Constant(DAG, 0x3f7f5e7e));
03161       SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5);
03162 
03163       // Add the exponent into the result in integer domain.
03164       SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
03165                                TwoToFracPartOfX, IntegerPartOfX);
03166 
03167       result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6);
03168     } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
03169       // For floating-point precision of 12:
03170       //
03171       //   TwoToFractionalPartOfX =
03172       //     0.999892986f +
03173       //       (0.696457318f +
03174       //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
03175       //
03176       // 0.000107046256 error, which is 13 to 14 bits
03177       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
03178                                getF32Constant(DAG, 0x3da235e3));
03179       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
03180                                getF32Constant(DAG, 0x3e65b8f3));
03181       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
03182       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
03183                                getF32Constant(DAG, 0x3f324b07));
03184       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
03185       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
03186                                getF32Constant(DAG, 0x3f7ff8fd));
03187       SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7);
03188 
03189       // Add the exponent into the result in integer domain.
03190       SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
03191                                TwoToFracPartOfX, IntegerPartOfX);
03192 
03193       result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8);
03194     } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
03195       // For floating-point precision of 18:
03196       //
03197       //   TwoToFractionalPartOfX =
03198       //     0.999999982f +
03199       //       (0.693148872f +
03200       //         (0.240227044f +
03201       //           (0.554906021e-1f +
03202       //             (0.961591928e-2f +
03203       //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
03204       //
03205       // error 2.47208000*10^(-7), which is better than 18 bits
03206       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
03207                                getF32Constant(DAG, 0x3924b03e));
03208       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
03209                                getF32Constant(DAG, 0x3ab24b87));
03210       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
03211       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
03212                                getF32Constant(DAG, 0x3c1d8c17));
03213       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
03214       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
03215                                getF32Constant(DAG, 0x3d634a1d));
03216       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
03217       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
03218                                getF32Constant(DAG, 0x3e75fe14));
03219       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
03220       SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
03221                                 getF32Constant(DAG, 0x3f317234));
03222       SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
03223       SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
03224                                 getF32Constant(DAG, 0x3f800000));
03225       SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl, 
03226                                              MVT::i32, t13);
03227 
03228       // Add the exponent into the result in integer domain.
03229       SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
03230                                 TwoToFracPartOfX, IntegerPartOfX);
03231 
03232       result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14);
03233     }
03234   } else {
03235     // No special expansion.
03236     result = DAG.getNode(ISD::FEXP, dl,
03237                          getValue(I.getOperand(1)).getValueType(),
03238                          getValue(I.getOperand(1)));
03239   }
03240 
03241   setValue(&I, result);
03242 }
03243 
03244 /// visitLog - Lower a log intrinsic. Handles the special sequences for
03245 /// limited-precision mode.
03246 void
03247 SelectionDAGLowering::visitLog(CallInst &I) {
03248   SDValue result;
03249   DebugLoc dl = getCurDebugLoc();
03250 
03251   if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
03252       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
03253     SDValue Op = getValue(I.getOperand(1));
03254     SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
03255 
03256     // Scale the exponent by log(2) [0.69314718f].
03257     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
03258     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
03259                                         getF32Constant(DAG, 0x3f317218));
03260 
03261     // Get the significand and build it into a floating-point number with
03262     // exponent of 1.
03263     SDValue X = GetSignificand(DAG, Op1, dl);
03264 
03265     if (LimitFloatPrecision <= 6) {
03266       // For floating-point precision of 6:
03267       //
03268       //   LogofMantissa =
03269       //     -1.1609546f +
03270       //       (1.4034025f - 0.23903021f * x) * x;
03271       //
03272       // error 0.0034276066, which is better than 8 bits
03273       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
03274                                getF32Constant(DAG, 0xbe74c456));
03275       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
03276                                getF32Constant(DAG, 0x3fb3a2b1));
03277       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
03278       SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
03279                                           getF32Constant(DAG, 0x3f949a29));
03280 
03281       result = DAG.getNode(ISD::FADD, dl, 
03282                            MVT::f32, LogOfExponent, LogOfMantissa);
03283     } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
03284       // For floating-point precision of 12:
03285       //
03286       //   LogOfMantissa =
03287       //     -1.7417939f +
03288       //       (2.8212026f +
03289       //         (-1.4699568f +
03290       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
03291       //
03292       // error 0.000061011436, which is 14 bits
03293       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
03294                                getF32Constant(DAG, 0xbd67b6d6));
03295       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
03296                                getF32Constant(DAG, 0x3ee4f4b8));
03297       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
03298       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
03299                                getF32Constant(DAG, 0x3fbc278b));
03300       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
03301       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
03302                                getF32Constant(DAG, 0x40348e95));
03303       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
03304       SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
03305                                           getF32Constant(DAG, 0x3fdef31a));
03306 
03307       result = DAG.getNode(ISD::FADD, dl, 
03308                            MVT::f32, LogOfExponent, LogOfMantissa);
03309     } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
03310       // For floating-point precision of 18:
03311       //
03312       //   LogOfMantissa =
03313       //     -2.1072184f +
03314       //       (4.2372794f +
03315       //         (-3.7029485f +
03316       //           (2.2781945f +
03317       //             (-0.87823314f +
03318       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
03319       //
03320       // error 0.0000023660568, which is better than 18 bits
03321       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
03322                                getF32Constant(DAG, 0xbc91e5ac));
03323       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
03324                                getF32Constant(DAG, 0x3e4350aa));
03325       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
03326       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
03327                                getF32Constant(DAG, 0x3f60d3e3));
03328       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
03329       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
03330                                getF32Constant(DAG, 0x4011cdf0));
03331       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
03332       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
03333                                getF32Constant(DAG, 0x406cfd1c));
03334       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
03335       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
03336                                getF32Constant(DAG, 0x408797cb));
03337       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
03338       SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
03339                                           getF32Constant(DAG, 0x4006dcab));
03340 
03341       result = DAG.getNode(ISD::FADD, dl, 
03342                            MVT::f32, LogOfExponent, LogOfMantissa);
03343     }
03344   } else {
03345     // No special expansion.
03346     result = DAG.getNode(ISD::FLOG, dl,
03347                          getValue(I.getOperand(1)).getValueType(),
03348                          getValue(I.getOperand(1)));
03349   }
03350 
03351   setValue(&I, result);
03352 }
03353 
03354 /// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
03355 /// limited-precision mode.
03356 void
03357 SelectionDAGLowering::visitLog2(CallInst &I) {
03358   SDValue result;
03359   DebugLoc dl = getCurDebugLoc();
03360 
03361   if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
03362       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
03363     SDValue Op = getValue(I.getOperand(1));
03364     SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
03365 
03366     // Get the exponent.
03367     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
03368 
03369     // Get the significand and build it into a floating-point number with
03370     // exponent of 1.
03371     SDValue X = GetSignificand(DAG, Op1, dl);
03372 
03373     // Different possible minimax approximations of significand in
03374     // floating-point for various degrees of accuracy over [1,2].
03375     if (LimitFloatPrecision <= 6) {
03376       // For floating-point precision of 6:
03377       //
03378       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
03379       //
03380       // error 0.0049451742, which is more than 7 bits
03381       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
03382                                getF32Constant(DAG, 0xbeb08fe0));
03383       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
03384                                getF32Constant(DAG, 0x40019463));
03385       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
03386       SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
03387                                            getF32Constant(DAG, 0x3fd6633d));
03388 
03389       result = DAG.getNode(ISD::FADD, dl, 
03390                            MVT::f32, LogOfExponent, Log2ofMantissa);
03391     } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
03392       // For floating-point precision of 12:
03393       //
03394       //   Log2ofMantissa =
03395       //     -2.51285454f +
03396       //       (4.07009056f +
03397       //         (-2.12067489f +
03398       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
03399       //
03400       // error 0.0000876136000, which is better than 13 bits
03401       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
03402                                getF32Constant(DAG, 0xbda7262e));
03403       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
03404                                getF32Constant(DAG, 0x3f25280b));
03405       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
03406       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
03407                                getF32Constant(DAG, 0x4007b923));
03408       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
03409       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
03410                                getF32Constant(DAG, 0x40823e2f));
03411       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
03412       SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
03413                                            getF32Constant(DAG, 0x4020d29c));
03414 
03415       result = DAG.getNode(ISD::FADD, dl, 
03416                            MVT::f32, LogOfExponent, Log2ofMantissa);
03417     } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
03418       // For floating-point precision of 18:
03419       //
03420       //   Log2ofMantissa =
03421       //     -3.0400495f +
03422       //       (6.1129976f +
03423       //         (-5.3420409f +
03424       //           (3.2865683f +
03425       //             (-1.2669343f +
03426       //               (0.27515199f -
03427       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
03428       //
03429       // error 0.0000018516, which is better than 18 bits
03430       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
03431                                getF32Constant(DAG, 0xbcd2769e));
03432       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
03433                                getF32Constant(DAG, 0x3e8ce0b9));
03434       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
03435       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
03436                                getF32Constant(DAG, 0x3fa22ae7));
03437       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
03438       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
03439                                getF32Constant(DAG, 0x40525723));
03440       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
03441       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
03442                                getF32Constant(DAG, 0x40aaf200));
03443       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
03444       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
03445                                getF32Constant(DAG, 0x40c39dad));
03446       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
03447       SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
03448                                            getF32Constant(DAG, 0x4042902c));
03449 
03450       result = DAG.getNode(ISD::FADD, dl, 
03451                            MVT::f32, LogOfExponent, Log2ofMantissa);
03452     }
03453   } else {
03454     // No special expansion.
03455     result = DAG.getNode(ISD::FLOG2, dl,
03456                          getValue(I.getOperand(1)).getValueType(),
03457                          getValue(I.getOperand(1)));
03458   }
03459 
03460   setValue(&I, result);
03461 }
03462 
03463 /// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
03464 /// limited-precision mode.
03465 void
03466 SelectionDAGLowering::visitLog10(CallInst &I) {
03467   SDValue result;
03468   DebugLoc dl = getCurDebugLoc();
03469 
03470   if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
03471       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
03472     SDValue Op = getValue(I.getOperand(1));
03473     SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
03474 
03475     // Scale the exponent by log10(2) [0.30102999f].
03476     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
03477     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
03478                                         getF32Constant(DAG, 0x3e9a209a));
03479 
03480     // Get the significand and build it into a floating-point number with
03481     // exponent of 1.
03482     SDValue X = GetSignificand(DAG, Op1, dl);
03483 
03484     if (LimitFloatPrecision <= 6) {
03485       // For floating-point precision of 6:
03486       //
03487       //   Log10ofMantissa =
03488       //     -0.50419619f +
03489       //       (0.60948995f - 0.10380950f * x) * x;
03490       //
03491       // error 0.0014886165, which is 6 bits
03492       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
03493                                getF32Constant(DAG, 0xbdd49a13));
03494       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
03495                                getF32Constant(DAG, 0x3f1c0789));
03496       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
03497       SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
03498                                             getF32Constant(DAG, 0x3f011300));
03499 
03500       result = DAG.getNode(ISD::FADD, dl, 
03501                            MVT::f32, LogOfExponent, Log10ofMantissa);
03502     } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
03503       // For floating-point precision of 12:
03504       //
03505       //   Log10ofMantissa =
03506       //     -0.64831180f +
03507       //       (0.91751397f +
03508       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
03509       //
03510       // error 0.00019228036, which is better than 12 bits
03511       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
03512                                getF32Constant(DAG, 0x3d431f31));
03513       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
03514                                getF32Constant(DAG, 0x3ea21fb2));
03515       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
03516       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
03517                                getF32Constant(DAG, 0x3f6ae232));
03518       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
03519       SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
03520                                             getF32Constant(DAG, 0x3f25f7c3));
03521 
03522       result = DAG.getNode(ISD::FADD, dl, 
03523                            MVT::f32, LogOfExponent, Log10ofMantissa);
03524     } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
03525       // For floating-point precision of 18:
03526       //
03527       //   Log10ofMantissa =
03528       //     -0.84299375f +
03529       //       (1.5327582f +
03530       //         (-1.0688956f +
03531       //           (0.49102474f +
03532       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
03533       //
03534       // error 0.0000037995730, which is better than 18 bits
03535       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
03536                                getF32Constant(DAG, 0x3c5d51ce));
03537       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
03538                                getF32Constant(DAG, 0x3e00685a));
03539       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
03540       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
03541                                getF32Constant(DAG, 0x3efb6798));
03542       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
03543       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
03544                                getF32Constant(DAG, 0x3f88d192));
03545       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
03546       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
03547                                getF32Constant(DAG, 0x3fc4316c));
03548       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
03549       SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
03550                                             getF32Constant(DAG, 0x3f57ce70));
03551 
03552       result = DAG.getNode(ISD::FADD, dl, 
03553                            MVT::f32, LogOfExponent, Log10ofMantissa);
03554     }
03555   } else {
03556     // No special expansion.
03557     result = DAG.getNode(ISD::FLOG10, dl,
03558                          getValue(I.getOperand(1)).getValueType(),
03559                          getValue(I.getOperand(1)));
03560   }
03561 
03562   setValue(&I, result);
03563 }
03564 
03565 /// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
03566 /// limited-precision mode.
03567 void
03568 SelectionDAGLowering::visitExp2(CallInst &I) {
03569   SDValue result;
03570   DebugLoc dl = getCurDebugLoc();
03571 
03572   if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
03573       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
03574     SDValue Op = getValue(I.getOperand(1));
03575 
03576     SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
03577 
03578     //   FractionalPartOfX = x - (float)IntegerPartOfX;
03579     SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
03580     SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
03581 
03582     //   IntegerPartOfX <<= 23;
03583     IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
03584                                  DAG.getConstant(23, TLI.getPointerTy()));
03585 
03586     if (LimitFloatPrecision <= 6) {
03587       // For floating-point precision of 6:
03588       //
03589       //   TwoToFractionalPartOfX =
03590       //     0.997535578f +
03591       //       (0.735607626f + 0.252464424f * x) * x;
03592       //
03593       // error 0.0144103317, which is 6 bits
03594       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
03595                                getF32Constant(DAG, 0x3e814304));
03596       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
03597                                getF32Constant(DAG, 0x3f3c50c8));
03598       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
03599       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
03600                                getF32Constant(DAG, 0x3f7f5e7e));
03601       SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
03602       SDValue TwoToFractionalPartOfX =
03603         DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
03604 
03605       result = DAG.getNode(ISD::BIT_CONVERT, dl, 
03606                            MVT::f32, TwoToFractionalPartOfX);
03607     } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
03608       // For floating-point precision of 12:
03609       //
03610       //   TwoToFractionalPartOfX =
03611       //     0.999892986f +
03612       //       (0.696457318f +
03613       //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
03614       //
03615       // error 0.000107046256, which is 13 to 14 bits
03616       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
03617                                getF32Constant(DAG, 0x3da235e3));
03618       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
03619                                getF32Constant(DAG, 0x3e65b8f3));
03620       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
03621       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
03622                                getF32Constant(DAG, 0x3f324b07));
03623       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
03624       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
03625                                getF32Constant(DAG, 0x3f7ff8fd));
03626       SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
03627       SDValue TwoToFractionalPartOfX =
03628         DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
03629 
03630       result = DAG.getNode(ISD::BIT_CONVERT, dl, 
03631                            MVT::f32, TwoToFractionalPartOfX);
03632     } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
03633       // For floating-point precision of 18:
03634       //
03635       //   TwoToFractionalPartOfX =
03636       //     0.999999982f +
03637       //       (0.693148872f +
03638       //         (0.240227044f +
03639       //           (0.554906021e-1f +
03640       //             (0.961591928e-2f +
03641       //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
03642       // error 2.47208000*10^(-7), which is better than 18 bits
03643       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
03644                                getF32Constant(DAG, 0x3924b03e));
03645       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
03646                                getF32Constant(DAG, 0x3ab24b87));
03647       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
03648       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
03649                                getF32Constant(DAG, 0x3c1d8c17));
03650       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
03651       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
03652                                getF32Constant(DAG, 0x3d634a1d));
03653       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
03654       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
03655                                getF32Constant(DAG, 0x3e75fe14));
03656       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
03657       SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
03658                                 getF32Constant(DAG, 0x3f317234));
03659       SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
03660       SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
03661                                 getF32Constant(DAG, 0x3f800000));
03662       SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
03663       SDValue TwoToFractionalPartOfX =
03664         DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
03665 
03666       result = DAG.getNode(ISD::BIT_CONVERT, dl, 
03667                            MVT::f32, TwoToFractionalPartOfX);
03668     }
03669   } else {
03670     // No special expansion.
03671     result = DAG.getNode(ISD::FEXP2, dl,
03672                          getValue(I.getOperand(1)).getValueType(),
03673                          getValue(I.getOperand(1)));
03674   }
03675 
03676   setValue(&I, result);
03677 }
03678 
03679 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
03680 /// limited-precision mode with x == 10.0f.
03681 void
03682 SelectionDAGLowering::visitPow(CallInst &I) {
03683   SDValue result;
03684   Value *Val = I.getOperand(1);
03685   DebugLoc dl = getCurDebugLoc();
03686   bool IsExp10 = false;
03687 
03688   if (getValue(Val).getValueType() == MVT::f32 &&
03689       getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
03690       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
03691     if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
03692       if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
03693         APFloat Ten(10.0f);
03694         IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
03695       }
03696     }
03697   }
03698 
03699   if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
03700     SDValue Op = getValue(I.getOperand(2));
03701 
03702     // Put the exponent in the right bit position for later addition to the
03703     // final result:
03704     //
03705     //   #define LOG2OF10 3.3219281f
03706     //   IntegerPartOfX = (int32_t)(x * LOG2OF10);
03707     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
03708                              getF32Constant(DAG, 0x40549a78));
03709     SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
03710 
03711     //   FractionalPartOfX = x - (float)IntegerPartOfX;
03712     SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
03713     SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
03714 
03715     //   IntegerPartOfX <<= 23;
03716     IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
03717                                  DAG.getConstant(23, TLI.getPointerTy()));
03718 
03719     if (LimitFloatPrecision <= 6) {
03720       // For floating-point precision of 6:
03721       //
03722       //   twoToFractionalPartOfX =
03723       //     0.997535578f +
03724       //       (0.735607626f + 0.252464424f * x) * x;
03725       //
03726       // error 0.0144103317, which is 6 bits
03727       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
03728                                getF32Constant(DAG, 0x3e814304));
03729       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
03730                                getF32Constant(DAG, 0x3f3c50c8));
03731       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
03732       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
03733                                getF32Constant(DAG, 0x3f7f5e7e));
03734       SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
03735       SDValue TwoToFractionalPartOfX =
03736         DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
03737 
03738       result = DAG.getNode(ISD::BIT_CONVERT, dl,
03739                            MVT::f32, TwoToFractionalPartOfX);
03740     } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
03741       // For floating-point precision of 12:
03742       //
03743       //   TwoToFractionalPartOfX =
03744       //     0.999892986f +
03745       //       (0.696457318f +
03746       //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
03747       //
03748       // error 0.000107046256, which is 13 to 14 bits
03749       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
03750                                getF32Constant(DAG, 0x3da235e3));
03751       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
03752                                getF32Constant(DAG, 0x3e65b8f3));
03753       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
03754       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
03755                                getF32Constant(DAG, 0x3f324b07));
03756       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
03757       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
03758                                getF32Constant(DAG, 0x3f7ff8fd));
03759       SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
03760       SDValue TwoToFractionalPartOfX =
03761         DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
03762 
03763       result = DAG.getNode(ISD::BIT_CONVERT, dl, 
03764                            MVT::f32, TwoToFractionalPartOfX);
03765     } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
03766       // For floating-point precision of 18:
03767       //
03768       //   TwoToFractionalPartOfX =
03769       //     0.999999982f +
03770       //       (0.693148872f +
03771       //         (0.240227044f +
03772       //           (0.554906021e-1f +
03773       //             (0.961591928e-2f +
03774       //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
03775       // error 2.47208000*10^(-7), which is better than 18 bits
03776       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
03777                                getF32Constant(DAG, 0x3924b03e));
03778       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
03779                                getF32Constant(DAG, 0x3ab24b87));
03780       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
03781       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
03782                                getF32Constant(DAG, 0x3c1d8c17));
03783       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
03784       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
03785                                getF32Constant(DAG, 0x3d634a1d));
03786       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
03787       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
03788                                getF32Constant(DAG, 0x3e75fe14));
03789       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
03790       SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
03791                                 getF32Constant(DAG, 0x3f317234));
03792       SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
03793       SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
03794                                 getF32Constant(DAG, 0x3f800000));
03795       SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
03796       SDValue TwoToFractionalPartOfX =
03797         DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
03798 
03799       result = DAG.getNode(ISD::BIT_CONVERT, dl, 
03800                            MVT::f32, TwoToFractionalPartOfX);
03801     }
03802   } else {
03803     // No special expansion.
03804     result = DAG.getNode(ISD::FPOW, dl,
03805                          getValue(I.getOperand(1)).getValueType(),
03806                          getValue(I.getOperand(1)),
03807                          getValue(I.getOperand(2)));
03808   }
03809 
03810   setValue(&I, result);
03811 }
03812 
03813 /// visitIntrinsicCall - Lower the call to the specified intrinsic function.  If
03814 /// we want to emit this as a call to a named external function, return the name
03815 /// otherwise lower it and return null.
03816 const char *
03817 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
03818   DebugLoc dl = getCurDebugLoc();
03819   switch (Intrinsic) {
03820   default:
03821     // By default, turn this into a target intrinsic node.
03822     visitTargetIntrinsic(I, Intrinsic);
03823     return 0;
03824   case Intrinsic::vastart:  visitVAStart(I); return 0;
03825   case Intrinsic::vaend:    visitVAEnd(I); return 0;
03826   case Intrinsic::vacopy:   visitVACopy(I); return 0;
03827   case Intrinsic::returnaddress:
03828     setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
03829                              getValue(I.getOperand(1))));
03830     return 0;
03831   case Intrinsic::frameaddress:
03832     setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
03833                              getValue(I.getOperand(1))));
03834     return 0;
03835   case Intrinsic::setjmp:
03836     return "_setjmp"+!TLI.usesUnderscoreSetJmp();
03837     break;
03838   case Intrinsic::longjmp:
03839     return "_longjmp"+!TLI.usesUnderscoreLongJmp();
03840     break;
03841   case Intrinsic::memcpy: {
03842     SDValue Op1 = getValue(I.getOperand(1));
03843     SDValue Op2 = getValue(I.getOperand(2));
03844     SDValue Op3 = getValue(I.getOperand(3));
03845     unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
03846     DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
03847                               I.getOperand(1), 0, I.getOperand(2), 0));
03848     return 0;
03849   }
03850   case Intrinsic::memset: {
03851     SDValue Op1 = getValue(I.getOperand(1));
03852     SDValue Op2 = getValue(I.getOperand(2));
03853     SDValue Op3 = getValue(I.getOperand(3));
03854     unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
03855     DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
03856                               I.getOperand(1), 0));
03857     return 0;
03858   }
03859   case Intrinsic::memmove: {
03860     SDValue Op1 = getValue(I.getOperand(1));
03861     SDValue Op2 = getValue(I.getOperand(2));
03862     SDValue Op3 = getValue(I.getOperand(3));
03863     unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
03864 
03865     // If the source and destination are known to not be aliases, we can
03866     // lower memmove as memcpy.
03867     uint64_t Size = -1ULL;
03868     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
03869       Size = C->getZExtValue();
03870     if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
03871         AliasAnalysis::NoAlias) {
03872       DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
03873                                 I.getOperand(1), 0, I.getOperand(2), 0));
03874       return 0;
03875     }
03876 
03877     DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
03878                                I.getOperand(1), 0, I.getOperand(2), 0));
03879     return 0;
03880   }
03881   case Intrinsic::dbg_stoppoint: {
03882     DwarfWriter *DW = DAG.getDwarfWriter();
03883     DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
03884     if (DW && DW->ValidDebugInfo(SPI.getContext())) {
03885       DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
03886                                       SPI.getLine(),
03887                                       SPI.getColumn(),
03888                                       SPI.getContext()));
03889       DICompileUnit CU(cast<GlobalVariable>(SPI.getContext()));
03890       unsigned SrcFile = DW->RecordSource(CU.getDirectory(), CU.getFilename());
03891       unsigned idx = DAG.getMachineFunction().
03892                          getOrCreateDebugLocID(SrcFile,
03893                                                SPI.getLine(), 
03894                                                SPI.getColumn());
03895       setCurDebugLoc(DebugLoc::get(idx));
03896     }
03897     return 0;
03898   }
03899   case Intrinsic::dbg_region_start: {
03900     DwarfWriter *DW = DAG.getDwarfWriter();
03901     DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
03902     if (DW && DW->ValidDebugInfo(RSI.getContext())) {
03903       unsigned LabelID =
03904         DW->RecordRegionStart(cast<GlobalVariable>(RSI.getContext()));
03905       DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
03906     }
03907 
03908     return 0;
03909   }
03910   case Intrinsic::dbg_region_end: {
03911     DwarfWriter *DW = DAG.getDwarfWriter();
03912     DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
03913     if (DW && DW->ValidDebugInfo(REI.getContext())) {
03914       unsigned LabelID =
03915         DW->RecordRegionEnd(cast<GlobalVariable>(REI.getContext()));
03916       DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
03917     }
03918 
03919     return 0;
03920   }
03921   case Intrinsic::dbg_func_start: {
03922     DwarfWriter *DW = DAG.getDwarfWriter();
03923     if (!DW) return 0;
03924     DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
03925     Value *SP = FSI.getSubprogram();
03926     if (SP && DW->ValidDebugInfo(SP)) {
03927       // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
03928       // what (most?) gdb expects.
03929       DISubprogram Subprogram(cast<GlobalVariable>(SP));
03930       DICompileUnit CompileUnit = Subprogram.getCompileUnit();
03931       unsigned SrcFile = DW->RecordSource(CompileUnit.getDirectory(),
03932                                           CompileUnit.getFilename());
03933 
03934       // Record the source line but does not create a label for the normal
03935       // function start. It will be emitted at asm emission time. However,
03936       // create a label if this is a beginning of inlined function.
03937       unsigned Line = Subprogram.getLineNumber();
03938       unsigned LabelID = DW->RecordSourceLine(Line, 0, SrcFile);
03939 
03940       if (DW->getRecordSourceLineCount() != 1)
03941         DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
03942 
03943       setCurDebugLoc(DebugLoc::get(DAG.getMachineFunction().
03944                          getOrCreateDebugLocID(SrcFile, Line, 0)));
03945     }
03946 
03947     return 0;
03948   }
03949   case Intrinsic::dbg_declare: {
03950     DwarfWriter *DW = DAG.getDwarfWriter();
03951     DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
03952     Value *Variable = DI.getVariable();
03953     if (DW && DW->ValidDebugInfo(Variable))
03954       DAG.setRoot(DAG.getNode(ISD::DECLARE, dl, MVT::Other, getRoot(),
03955                               getValue(DI.getAddress()), getValue(Variable)));
03956     return 0;
03957   }
03958 
03959   case Intrinsic::eh_exception: {
03960     if (!CurMBB->isLandingPad()) {
03961       // FIXME: Mark exception register as live in.  Hack for PR1508.
03962       unsigned Reg = TLI.getExceptionAddressRegister();
03963       if (Reg) CurMBB->addLiveIn(Reg);
03964     }
03965     // Insert the EXCEPTIONADDR instruction.
03966     SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
03967     SDValue Ops[1];
03968     Ops[0] = DAG.getRoot();
03969     SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
03970     setValue(&I, Op);
03971     DAG.setRoot(Op.getValue(1));
03972     return 0;
03973   }
03974 
03975   case Intrinsic::eh_selector_i32:
03976   case Intrinsic::eh_selector_i64: {
03977     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
03978     MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
03979                          MVT::i32 : MVT::i64);
03980 
03981     if (MMI) {
03982       if (CurMBB->isLandingPad())
03983         AddCatchInfo(I, MMI, CurMBB);
03984       else {
03985 #ifndef NDEBUG
03986         FuncInfo.CatchInfoLost.insert(&I);
03987 #endif
03988         // FIXME: Mark exception selector register as live in.  Hack for PR1508.
03989         unsigned Reg = TLI.getExceptionSelectorRegister();
03990         if (Reg) CurMBB->addLiveIn(Reg);
03991       }
03992 
03993       // Insert the EHSELECTION instruction.
03994       SDVTList VTs = DAG.getVTList(VT, MVT::Other);
03995       SDValue Ops[2];
03996       Ops[0] = getValue(I.getOperand(1));
03997       Ops[1] = getRoot();
03998       SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
03999       setValue(&I, Op);
04000       DAG.setRoot(Op.getValue(1));
04001     } else {
04002       setValue(&I, DAG.getConstant(0, VT));
04003     }
04004 
04005     return 0;
04006   }
04007 
04008   case Intrinsic::eh_typeid_for_i32:
04009   case Intrinsic::eh_typeid_for_i64: {
04010     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
04011     MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
04012                          MVT::i32 : MVT::i64);
04013 
04014     if (MMI) {
04015       // Find the type id for the given typeinfo.
04016       GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
04017 
04018       unsigned TypeID = MMI->getTypeIDFor(GV);
04019       setValue(&I, DAG.getConstant(TypeID, VT));
04020     } else {
04021       // Return something different to eh_selector.
04022       setValue(&I, DAG.getConstant(1, VT));
04023     }
04024 
04025     return 0;
04026   }
04027 
04028   case Intrinsic::eh_return_i32:
04029   case Intrinsic::eh_return_i64:
04030     if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
04031       MMI->setCallsEHReturn(true);
04032       DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
04033                               MVT::Other,
04034                               getControlRoot(),
04035                               getValue(I.getOperand(1)),
04036                               getValue(I.getOperand(2))));
04037     } else {
04038       setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
04039     }
04040 
04041     return 0;
04042   case Intrinsic::eh_unwind_init:
04043     if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
04044       MMI->setCallsUnwindInit(true);
04045     }
04046 
04047     return 0;
04048 
04049   case Intrinsic::eh_dwarf_cfa: {
04050     MVT VT = getValue(I.getOperand(1)).getValueType();
04051     SDValue CfaArg;
04052     if (VT.bitsGT(TLI.getPointerTy()))
04053       CfaArg = DAG.getNode(ISD::TRUNCATE, dl,
04054                            TLI.getPointerTy(), getValue(I.getOperand(1)));
04055     else
04056       CfaArg = DAG.getNode(ISD::SIGN_EXTEND, dl,
04057                            TLI.getPointerTy(), getValue(I.getOperand(1)));
04058 
04059     SDValue Offset = DAG.getNode(ISD::ADD, dl,
04060                                  TLI.getPointerTy(),
04061                                  DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
04062                                              TLI.getPointerTy()),
04063                                  CfaArg);
04064     setValue(&I, DAG.getNode(ISD::ADD, dl,
04065                              TLI.getPointerTy(),
04066                              DAG.getNode(ISD::FRAMEADDR, dl,
04067                                          TLI.getPointerTy(),
04068                                          DAG.getConstant(0,
04069                                                          TLI.getPointerTy())),
04070                              Offset));
04071     return 0;
04072   }
04073 
04074   case Intrinsic::convertff:
04075   case Intrinsic::convertfsi:
04076   case Intrinsic::convertfui:
04077   case Intrinsic::convertsif:
04078   case Intrinsic::convertuif:
04079   case Intrinsic::convertss:
04080   case Intrinsic::convertsu:
04081   case Intrinsic::convertus:
04082   case Intrinsic::convertuu: {
04083     ISD::CvtCode Code = ISD::CVT_INVALID;
04084     switch (Intrinsic) {
04085     case Intrinsic::convertff:  Code = ISD::CVT_FF; break;
04086     case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
04087     case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
04088     case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
04089     case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
04090     case Intrinsic::convertss:  Code = ISD::CVT_SS; break;
04091     case Intrinsic::convertsu:  Code = ISD::CVT_SU; break;
04092     case Intrinsic::convertus:  Code = ISD::CVT_US; break;
04093     case Intrinsic::convertuu:  Code = ISD::CVT_UU; break;
04094     }
04095     MVT DestVT = TLI.getValueType(I.getType());
04096     Value* Op1 = I.getOperand(1);
04097     setValue(&I, DAG.getConvertRndSat(DestVT, getValue(Op1),
04098                                 DAG.getValueType(DestVT),
04099                                 DAG.getValueType(getValue(Op1).getValueType()),
04100                                 getValue(I.getOperand(2)),
04101                                 getValue(I.getOperand(3)),
04102                                 Code));
04103     return 0;
04104   }
04105 
04106   case Intrinsic::sqrt:
04107     setValue(&I, DAG.getNode(ISD::FSQRT, dl,
04108                              getValue(I.getOperand(1)).getValueType(),
04109                              getValue(I.getOperand(1))));
04110     return 0;
04111   case Intrinsic::powi:
04112     setValue(&I, DAG.getNode(ISD::FPOWI, dl,
04113                              getValue(I.getOperand(1)).getValueType(),
04114                              getValue(I.getOperand(1)),
04115                              getValue(I.getOperand(2))));
04116     return 0;
04117   case Intrinsic::sin:
04118     setValue(&I, DAG.getNode(ISD::FSIN, dl,
04119                              getValue(I.getOperand(1)).getValueType(),
04120                              getValue(I.getOperand(1))));
04121     return 0;
04122   case Intrinsic::cos:
04123     setValue(&I, DAG.getNode(ISD::FCOS, dl,
04124                              getValue(I.getOperand(1)).getValueType(),
04125                              getValue(I.getOperand(1))));
04126     return 0;
04127   case Intrinsic::log:
04128     visitLog(I);
04129     return 0;
04130   case Intrinsic::log2:
04131     visitLog2(I);
04132     return 0;
04133   case Intrinsic::log10:
04134     visitLog10(I);
04135     return 0;
04136   case Intrinsic::exp:
04137     visitExp(I);
04138     return 0;
04139   case Intrinsic::exp2:
04140     visitExp2(I);
04141     return 0;
04142   case Intrinsic::pow:
04143     visitPow(I);
04144     return 0;
04145   case Intrinsic::pcmarker: {
04146     SDValue Tmp = getValue(I.getOperand(1));
04147     DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
04148     return 0;
04149   }
04150   case Intrinsic::readcyclecounter: {
04151     SDValue Op = getRoot();
04152     SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER, dl,
04153                                 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
04154                                 &Op, 1);
04155     setValue(&I, Tmp);
04156     DAG.setRoot(Tmp.getValue(1));
04157     return 0;
04158   }
04159   case Intrinsic::part_select: {
04160     // Currently not implemented: just abort
04161     assert(0 && "part_select intrinsic not implemented");
04162     abort();
04163   }
04164   case Intrinsic::part_set: {
04165     // Currently not implemented: just abort
04166     assert(0 && "part_set intrinsic not implemented");
04167     abort();
04168   }
04169   case Intrinsic::bswap:
04170     setValue(&I, DAG.getNode(ISD::BSWAP, dl,
04171                              getValue(I.getOperand(1)).getValueType(),
04172                              getValue(I.getOperand(1))));
04173     return 0;
04174   case Intrinsic::cttz: {
04175     SDValue Arg = getValue(I.getOperand(1));
04176     MVT Ty = Arg.getValueType();
04177     SDValue result = DAG.getNode(ISD::CTTZ, dl, Ty, Arg);
04178     setValue(&I, result);
04179     return 0;
04180   }
04181   case Intrinsic::ctlz: {
04182     SDValue Arg = getValue(I.getOperand(1));
04183     MVT Ty = Arg.getValueType();
04184     SDValue result = DAG.getNode(ISD::CTLZ, dl, Ty, Arg);
04185     setValue(&I, result);
04186     return 0;
04187   }
04188   case Intrinsic::ctpop: {
04189     SDValue Arg = getValue(I.getOperand(1));
04190     MVT Ty = Arg.getValueType();
04191     SDValue result = DAG.getNode(ISD::CTPOP, dl, Ty, Arg);
04192     setValue(&I, result);
04193     return 0;
04194   }
04195   case Intrinsic::stacksave: {
04196     SDValue Op = getRoot();
04197     SDValue Tmp = DAG.getNode(ISD::STACKSAVE, dl,
04198               DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
04199     setValue(&I, Tmp);
04200     DAG.setRoot(Tmp.getValue(1));
04201     return 0;
04202   }
04203   case Intrinsic::stackrestore: {
04204     SDValue Tmp = getValue(I.getOperand(1));
04205     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Tmp));
04206     return 0;
04207   }
04208   case Intrinsic::stackprotector: {
04209     // Emit code into the DAG to store the stack guard onto the stack.
04210     MachineFunction &MF = DAG.getMachineFunction();
04211     MachineFrameInfo *MFI = MF.getFrameInfo();
04212     MVT PtrTy = TLI.getPointerTy();
04213 
04214     SDValue Src = getValue(I.getOperand(1));   // The guard's value.
04215     AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
04216 
04217     int FI = FuncInfo.StaticAllocaMap[Slot];
04218     MFI->setStackProtectorIndex(FI);
04219 
04220     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
04221 
04222     // Store the stack protector onto the stack.
04223     SDValue Result = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
04224                                   PseudoSourceValue::getFixedStack(FI),
04225                                   0, true);
04226     setValue(&I, Result);
04227     DAG.setRoot(Result);
04228     return 0;
04229   }
04230   case Intrinsic::var_annotation:
04231     // Discard annotate attributes
04232     return 0;
04233 
04234   case Intrinsic::init_trampoline: {
04235     const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
04236 
04237     SDValue Ops[6];
04238     Ops[0] = getRoot();
04239     Ops[1] = getValue(I.getOperand(1));
04240     Ops[2] = getValue(I.getOperand(2));
04241     Ops[3] = getValue(I.getOperand(3));
04242     Ops[4] = DAG.getSrcValue(I.getOperand(1));
04243     Ops[5] = DAG.getSrcValue(F);
04244 
04245     SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE, dl,
04246                                 DAG.getNodeValueTypes(TLI.getPointerTy(),
04247                                                       MVT::Other), 2,
04248                                 Ops, 6);
04249 
04250     setValue(&I, Tmp);
04251     DAG.setRoot(Tmp.getValue(1));
04252     return 0;
04253   }
04254 
04255   case Intrinsic::gcroot:
04256     if (GFI) {
04257       Value *Alloca = I.getOperand(1);
04258       Constant *TypeMap = cast<Constant>(I.getOperand(2));
04259 
04260       FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
04261       GFI->addStackRoot(FI->getIndex(), TypeMap);
04262     }
04263     return 0;
04264 
04265   case Intrinsic::gcread:
04266   case Intrinsic::gcwrite:
04267     assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
04268     return 0;
04269 
04270   case Intrinsic::flt_rounds: {
04271     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
04272     return 0;
04273   }
04274 
04275   case Intrinsic::trap: {
04276     DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
04277     return 0;
04278   }
04279 
04280   case Intrinsic::uadd_with_overflow:
04281     return implVisitAluOverflow(I, ISD::UADDO);
04282   case Intrinsic::sadd_with_overflow:
04283     return implVisitAluOverflow(I, ISD::SADDO);
04284   case Intrinsic::usub_with_overflow:
04285     return implVisitAluOverflow(I, ISD::USUBO);
04286   case Intrinsic::ssub_with_overflow:
04287     return implVisitAluOverflow(I, ISD::SSUBO);
04288   case Intrinsic::umul_with_overflow:
04289     return implVisitAluOverflow(I, ISD::UMULO);
04290   case Intrinsic::smul_with_overflow:
04291     return implVisitAluOverflow(I, ISD::SMULO);
04292 
04293   case Intrinsic::prefetch: {
04294     SDValue Ops[4];
04295     Ops[0] = getRoot();
04296     Ops[1] = getValue(I.getOperand(1));
04297     Ops[2] = getValue(I.getOperand(2));
04298     Ops[3] = getValue(I.getOperand(3));
04299     DAG.setRoot(DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4));
04300     return 0;
04301   }
04302 
04303   case Intrinsic::memory_barrier: {
04304     SDValue Ops[6];
04305     Ops[0] = getRoot();
04306     for (int x = 1; x < 6; ++x)
04307       Ops[x] = getValue(I.getOperand(x));
04308 
04309     DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6));
04310     return 0;
04311   }
04312   case Intrinsic::atomic_cmp_swap: {
04313     SDValue Root = getRoot();
04314     SDValue L =
04315       DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
04316                     getValue(I.getOperand(2)).getValueType().getSimpleVT(),
04317                     Root,
04318                     getValue(I.getOperand(1)),
04319                     getValue(I.getOperand(2)),
04320                     getValue(I.getOperand(3)),
04321                     I.getOperand(1));
04322     setValue(&I, L);
04323     DAG.setRoot(L.getValue(1));
04324     return 0;
04325   }
04326   case Intrinsic::atomic_load_add:
04327     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
04328   case Intrinsic::atomic_load_sub:
04329     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
04330   case Intrinsic::atomic_load_or:
04331     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
04332   case Intrinsic::atomic_load_xor:
04333     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
04334   case Intrinsic::atomic_load_and:
04335     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
04336   case Intrinsic::atomic_load_nand:
04337     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
04338   case Intrinsic::atomic_load_max:
04339     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
04340   case Intrinsic::atomic_load_min:
04341     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
04342   case Intrinsic::atomic_load_umin:
04343     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
04344   case Intrinsic::atomic_load_umax:
04345     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
04346   case Intrinsic::atomic_swap:
04347     return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
04348   }
04349 }
04350 
04351 
04352 void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
04353                                        bool IsTailCall,
04354                                        MachineBasicBlock *LandingPad) {
04355   const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
04356   const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
04357   MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
04358   unsigned BeginLabel = 0, EndLabel = 0;
04359 
04360   TargetLowering::ArgListTy Args;
04361   TargetLowering::ArgListEntry Entry;
04362   Args.reserve(CS.arg_size());
04363   for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
04364        i != e; ++i) {
04365     SDValue ArgNode = getValue(*i);
04366     Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
04367 
04368     unsigned attrInd = i - CS.arg_begin() + 1;
04369     Entry.isSExt  = CS.paramHasAttr(attrInd, Attribute::SExt);
04370     Entry.isZExt  = CS.paramHasAttr(attrInd, Attribute::ZExt);
04371     Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
04372     Entry.isSRet  = CS.paramHasAttr(attrInd, Attribute::StructRet);
04373     Entry.isNest  = CS.paramHasAttr(attrInd, Attribute::Nest);
04374     Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
04375     Entry.Alignment = CS.getParamAlignment(attrInd);
04376     Args.push_back(Entry);
04377   }
04378 
04379   if (LandingPad && MMI) {
04380     // Insert a label before the invoke call to mark the try range.  This can be
04381     // used to detect deletion of the invoke via the MachineModuleInfo.
04382     BeginLabel = MMI->NextLabelID();
04383     // Both PendingLoads and PendingExports must be flushed here;
04384     // this call might not return.
04385     (void)getRoot();
04386     DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getControlRoot(), BeginLabel));
04387   }
04388 
04389   std::pair<SDValue,SDValue> Result =
04390     TLI.LowerCallTo(getRoot(), CS.getType(),
04391                     CS.paramHasAttr(0, Attribute::SExt),
04392                     CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
04393                     CS.paramHasAttr(0, Attribute::InReg),
04394                     CS.getCallingConv(),
04395                     IsTailCall && PerformTailCallOpt,
04396                     Callee, Args, DAG, getCurDebugLoc());
04397   if (CS.getType() != Type::VoidTy)
04398     setValue(CS.getInstruction(), Result.first);
04399   DAG.setRoot(Result.second);
04400 
04401   if (LandingPad && MMI) {
04402     // Insert a label at the end of the invoke call to mark the try range.  This
04403     // can be used to detect deletion of the invoke via the MachineModuleInfo.
04404     EndLabel = MMI->NextLabelID();
04405     DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getRoot(), EndLabel));
04406 
04407     // Inform MachineModuleInfo of range.
04408     MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
04409   }
04410 }
04411 
04412 
04413 void SelectionDAGLowering::visitCall(CallInst &I) {
04414   const char *RenameFn = 0;
04415   if (Function *F = I.getCalledFunction()) {
04416     if (F->isDeclaration()) {
04417       if (unsigned IID = F->getIntrinsicID()) {
04418         RenameFn = visitIntrinsicCall(I, IID);
04419         if (!RenameFn)
04420           return;
04421       }
04422     }
04423 
04424     // Check for well-known libc/libm calls.  If the function is internal, it
04425     // can't be a library call.
04426     unsigned NameLen = F->getNameLen();
04427     if (!F->hasLocalLinkage() && NameLen) {
04428       const char *NameStr = F->getNameStart();
04429       if (NameStr[0] == 'c' &&
04430           ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
04431            (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
04432         if (I.getNumOperands() == 3 &&   // Basic sanity checks.
04433             I.getOperand(1)->getType()->isFloatingPoint() &&
04434             I.getType() == I.getOperand(1)->getType() &&
04435             I.getType() == I.getOperand(2)->getType()) {
04436           SDValue LHS = getValue(I.getOperand(1));
04437           SDValue RHS = getValue(I.getOperand(2));
04438           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(), 
04439                                    LHS.getValueType(), LHS, RHS));
04440           return;
04441         }
04442       } else if (NameStr[0] == 'f' &&
04443                  ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
04444                   (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
04445                   (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
04446         if (I.getNumOperands() == 2 &&   // Basic sanity checks.
04447             I.getOperand(1)->getType()->isFloatingPoint() &&
04448             I.getType() == I.getOperand(1)->getType()) {
04449           SDValue Tmp = getValue(I.getOperand(1));
04450           setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(), 
04451                                    Tmp.getValueType(), Tmp));
04452           return;
04453         }
04454       } else if (NameStr[0] == 's' &&
04455                  ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
04456                   (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
04457                   (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
04458         if (I.getNumOperands() == 2 &&   // Basic sanity checks.
04459             I.getOperand(1)->getType()->isFloatingPoint() &&
04460             I.getType() == I.getOperand(1)->getType()) {
04461           SDValue Tmp = getValue(I.getOperand(1));
04462           setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(), 
04463                                    Tmp.getValueType(), Tmp));
04464           return;
04465         }
04466       } else if (NameStr[0] == 'c' &&
04467                  ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
04468                   (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
04469                   (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
04470         if (I.getNumOperands() == 2 &&   // Basic sanity checks.
04471             I.getOperand(1)->getType()->isFloatingPoint() &&
04472             I.getType() == I.getOperand(1)->getType()) {
04473           SDValue Tmp = getValue(I.getOperand(1));
04474           setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(), 
04475                                    Tmp.getValueType(), Tmp));
04476           return;
04477         }
04478       }
04479     }
04480   } else if (isa<InlineAsm>(I.getOperand(0))) {
04481     visitInlineAsm(&I);
04482     return;
04483   }
04484 
04485   SDValue Callee;
04486   if (!RenameFn)
04487     Callee = getValue(I.getOperand(0));
04488   else
04489     Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
04490 
04491   LowerCallTo(&I, Callee, I.isTailCall());
04492 }
04493 
04494 
04495 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
04496 /// this value and returns the result as a ValueVT value.  This uses
04497 /// Chain/Flag as the input and updates them for the output Chain/Flag.
04498 /// If the Flag pointer is NULL, no flag is used.
04499 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
04500                                       SDValue &Chain,
04501                                       SDValue *Flag) const {
04502   // Assemble the legal parts into the final values.
04503   SmallVector<SDValue, 4> Values(ValueVTs.size());
04504   SmallVector<SDValue, 8> Parts;
04505   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
04506     // Copy the legal parts from the registers.
04507     MVT ValueVT = ValueVTs[Value];
04508     unsigned NumRegs = TLI->getNumRegisters(ValueVT);
04509     MVT RegisterVT = RegVTs[Value];
04510 
04511     Parts.resize(NumRegs);
04512     for (unsigned i = 0; i != NumRegs; ++i) {
04513       SDValue P;
04514       if (Flag == 0)
04515         P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
04516       else {
04517         P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
04518         *Flag = P.getValue(2);
04519       }
04520       Chain = P.getValue(1);
04521 
04522       // If the source register was virtual and if we know something about it,
04523       // add an assert node.
04524       if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
04525           RegisterVT.isInteger() && !RegisterVT.isVector()) {
04526         unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
04527         FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
04528         if (FLI.LiveOutRegInfo.size() > SlotNo) {
04529           FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
04530 
04531           unsigned RegSize = RegisterVT.getSizeInBits();
04532           unsigned NumSignBits = LOI.NumSignBits;
04533           unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
04534 
04535           // FIXME: We capture more information than the dag can represent.  For
04536           // now, just use the tightest assertzext/assertsext possible.
04537           bool isSExt = true;
04538           MVT FromVT(MVT::Other);
04539           if (NumSignBits == RegSize)
04540             isSExt = true, FromVT = MVT::i1;   // ASSERT SEXT 1
04541           else if (NumZeroBits >= RegSize-1)
04542             isSExt = false, FromVT = MVT::i1;  // ASSERT ZEXT 1
04543           else if (NumSignBits > RegSize-8)
04544             isSExt = true, FromVT = MVT::i8;   // ASSERT SEXT 8
04545           else if (NumZeroBits >= RegSize-9)
04546             isSExt = false, FromVT = MVT::i8;  // ASSERT ZEXT 8
04547           else if (NumSignBits > RegSize-16)
04548             isSExt = true, FromVT = MVT::i16;  // ASSERT SEXT 16
04549           else if (NumZeroBits >= RegSize-17)
04550             isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
04551           else if (NumSignBits > RegSize-32)
04552             isSExt = true, FromVT = MVT::i32;  // ASSERT SEXT 32
04553           else if (NumZeroBits >= RegSize-33)
04554             isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
04555 
04556           if (FromVT != MVT::Other) {
04557             P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
04558                             RegisterVT, P, DAG.getValueType(FromVT));
04559 
04560           }
04561         }
04562       }
04563 
04564       Parts[i] = P;
04565     }
04566 
04567     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), 
04568                                      NumRegs, RegisterVT, ValueVT);
04569     Part += NumRegs;
04570     Parts.clear();
04571   }
04572 
04573   return DAG.getNode(ISD::MERGE_VALUES, dl,
04574                      DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
04575                      &Values[0], ValueVTs.size());
04576 }
04577 
04578 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
04579 /// specified value into the registers specified by this object.  This uses
04580 /// Chain/Flag as the input and updates them for the output Chain/Flag.
04581 /// If the Flag pointer is NULL, no flag is used.
04582 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
04583                                  SDValue &Chain, SDValue *Flag) const {
04584   // Get the list of the values's legal parts.
04585   unsigned NumRegs = Regs.size();
04586   SmallVector<SDValue, 8> Parts(NumRegs);
04587   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
04588     MVT ValueVT = ValueVTs[Value];
04589     unsigned NumParts = TLI->getNumRegisters(ValueVT);
04590     MVT RegisterVT = RegVTs[Value];
04591 
04592     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
04593                    &Parts[Part], NumParts, RegisterVT);
04594     Part += NumParts;
04595   }
04596 
04597   // Copy the parts into the registers.
04598   SmallVector<SDValue, 8> Chains(NumRegs);
04599   for (unsigned i = 0; i != NumRegs; ++i) {
04600     SDValue Part;
04601     if (Flag == 0)
04602       Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
04603     else {
04604       Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
04605       *Flag = Part.getValue(1);
04606     }
04607     Chains[i] = Part.getValue(0);
04608   }
04609 
04610   if (NumRegs == 1 || Flag)
04611     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
04612     // flagged to it. That is the CopyToReg nodes and the user are considered
04613     // a single scheduling unit. If we create a TokenFactor and return it as
04614     // chain, then the TokenFactor is both a predecessor (operand) of the
04615     // user as well as a successor (the TF operands are flagged to the user).
04616     // c1, f1 = CopyToReg
04617     // c2, f2 = CopyToReg
04618     // c3     = TokenFactor c1, c2
04619     // ...
04620     //        = op c3, ..., f2
04621     Chain = Chains[NumRegs-1];
04622   else
04623     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
04624 }
04625 
04626 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
04627 /// operand list.  This adds the code marker and includes the number of
04628 /// values added into it.
04629 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
04630                                         std::vector<SDValue> &Ops) const {
04631   MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
04632   Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
04633   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
04634     unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
04635     MVT RegisterVT = RegVTs[Value];
04636     for (unsigned i = 0; i != NumRegs; ++i) {
04637       assert(Reg < Regs.size() && "Mismatch in # registers expected");
04638       Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
04639     }
04640   }
04641 }
04642 
04643 /// isAllocatableRegister - If the specified register is safe to allocate,
04644 /// i.e. it isn't a stack pointer or some other special register, return the
04645 /// register class for the register.  Otherwise, return null.
04646 static const TargetRegisterClass *
04647 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
04648                       const TargetLowering &TLI,
04649                       const TargetRegisterInfo *TRI) {
04650   MVT FoundVT = MVT::Other;
04651   const TargetRegisterClass *FoundRC = 0;
04652   for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
04653        E = TRI->regclass_end(); RCI != E; ++RCI) {
04654     MVT ThisVT = MVT::Other;
04655 
04656     const TargetRegisterClass *RC = *RCI;
04657     // If none of the the value types for this register class are valid, we
04658     // can't use it.  For example, 64-bit reg classes on 32-bit targets.
04659     for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
04660          I != E; ++I) {
04661       if (TLI.isTypeLegal(*I)) {
04662         // If we have already found this register in a different register class,
04663         // choose the one with the largest VT specified.  For example, on
04664         // PowerPC, we favor f64 register classes over f32.
04665         if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
04666           ThisVT = *I;
04667           break;
04668         }
04669       }
04670     }
04671 
04672     if (ThisVT == MVT::Other) continue;
04673 
04674     // NOTE: This isn't ideal.  In particular, this might allocate the
04675     // frame pointer in functions that need it (due to them not being taken
04676     // out of allocation, because a variable sized allocation hasn't been seen
04677     // yet).  This is a slight code pessimization, but should still work.
04678     for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
04679          E = RC->allocation_order_end(MF); I != E; ++I)
04680       if (*I == Reg) {
04681         // We found a matching register class.  Keep looking at others in case
04682         // we find one with larger registers that this physreg is also in.
04683         FoundRC = RC;
04684         FoundVT = ThisVT;
04685         break;
04686       }
04687   }
04688   return FoundRC;
04689 }
04690 
04691 
04692 namespace llvm {
04693 /// AsmOperandInfo - This contains information for each constraint that we are
04694 /// lowering.
04695 struct VISIBILITY_HIDDEN SDISelAsmOperandInfo :
04696     public TargetLowering::AsmOperandInfo {
04697   /// CallOperand - If this is the result output operand or a clobber
04698   /// this is null, otherwise it is the incoming operand to the CallInst.
04699   /// This gets modified as the asm is processed.
04700   SDValue CallOperand;
04701 
04702   /// AssignedRegs - If this is a register or register class operand, this
04703   /// contains the set of register corresponding to the operand.
04704   RegsForValue AssignedRegs;
04705 
04706   explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
04707     : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
04708   }
04709 
04710   /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
04711   /// busy in OutputRegs/InputRegs.
04712   void MarkAllocatedRegs(bool isOutReg, bool isInReg,
04713                          std::set<unsigned> &OutputRegs,
04714                          std::set<unsigned> &InputRegs,
04715                          const TargetRegisterInfo &TRI) const {
04716     if (isOutReg) {
04717       for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
04718         MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
04719     }
04720     if (isInReg) {
04721       for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
04722         MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
04723     }
04724   }
04725 
04726   /// getCallOperandValMVT - Return the MVT of the Value* that this operand
04727   /// corresponds to.  If there is no Value* for this operand, it returns
04728   /// MVT::Other.
04729   MVT getCallOperandValMVT(const TargetLowering &TLI,
04730                            const TargetData *TD) const {
04731     if (CallOperandVal == 0) return MVT::Other;
04732 
04733     if (isa<BasicBlock>(CallOperandVal))
04734       return TLI.getPointerTy();
04735 
04736     const llvm::Type *OpTy = CallOperandVal->getType();
04737 
04738     // If this is an indirect operand, the operand is a pointer to the
04739     // accessed type.
04740     if (isIndirect)
04741       OpTy = cast<PointerType>(OpTy)->getElementType();
04742 
04743     // If OpTy is not a single value, it may be a struct/union that we
04744     // can tile with integers.
04745     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
04746       unsigned BitSize = TD->getTypeSizeInBits(OpTy);
04747       switch (BitSize) {
04748       default: break;
04749       case 1:
04750       case 8:
04751       case 16:
04752       case 32:
04753       case 64:
04754       case 128:
04755         OpTy = IntegerType::get(BitSize);
04756         break;
04757       }
04758     }
04759 
04760     return TLI.getValueType(OpTy, true);
04761   }
04762 
04763 private:
04764   /// MarkRegAndAliases - Mark the specified register and all aliases in the
04765   /// specified set.
04766   static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
04767                                 const TargetRegisterInfo &TRI) {
04768     assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
04769     Regs.insert(Reg);
04770     if (const unsigned *Aliases = TRI.getAliasSet(Reg))
04771       for (; *Aliases; ++Aliases)
04772         Regs.insert(*Aliases);
04773   }
04774 };
04775 } // end llvm namespace.
04776 
04777 
04778 /// GetRegistersForValue - Assign registers (virtual or physical) for the
04779 /// specified operand.  We prefer to assign virtual registers, to allow the
04780 /// register allocator handle the assignment process.  However, if the asm uses
04781 /// features that we can't model on machineinstrs, we have SDISel do the
04782 /// allocation.  This produces generally horrible, but correct, code.
04783 ///
04784 ///   OpInfo describes the operand.
04785 ///   Input and OutputRegs are the set of already allocated physical registers.
04786 ///
04787 void SelectionDAGLowering::
04788 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
04789                      std::set<unsigned> &OutputRegs,
04790                      std::set<unsigned> &InputRegs) {
04791   // Compute whether this value requires an input register, an output register,
04792   // or both.
04793   bool isOutReg = false;
04794   bool isInReg = false;
04795   switch (OpInfo.Type) {
04796   case InlineAsm::isOutput:
04797     isOutReg = true;
04798 
04799     // If there is an input constraint that matches this, we need to reserve
04800     // the input register so no other inputs allocate to it.
04801     isInReg = OpInfo.hasMatchingInput();
04802     break;
04803   case InlineAsm::isInput:
04804     isInReg = true;
04805     isOutReg = false;
04806     break;
04807   case InlineAsm::isClobber:
04808     isOutReg = true;
04809     isInReg = true;
04810     break;
04811   }
04812 
04813 
04814   MachineFunction &MF = DAG.getMachineFunction();
04815   SmallVector<unsigned, 4> Regs;
04816 
04817   // If this is a constraint for a single physreg, or a constraint for a
04818   // register class, find it.
04819   std::pair<unsigned, const TargetRegisterClass*> PhysReg =
04820     TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
04821                                      OpInfo.ConstraintVT);
04822 
04823   unsigned NumRegs = 1;
04824   if (OpInfo.ConstraintVT != MVT::Other) {
04825     // If this is a FP input in an integer register (or visa versa) insert a bit
04826     // cast of the input value.  More generally, handle any case where the input
04827     // value disagrees with the register class we plan to stick this in.
04828     if (OpInfo.Type == InlineAsm::isInput &&
04829         PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
04830       // Try to convert to the first MVT that the reg class contains.  If the
04831       // types are identical size, use a bitcast to convert (e.g. two differing
04832       // vector types).
04833       MVT RegVT = *PhysReg.second->vt_begin();
04834       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
04835         OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
04836                                          RegVT, OpInfo.CallOperand);
04837         OpInfo.ConstraintVT = RegVT;
04838       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
04839         // If the input is a FP value and we want it in FP registers, do a
04840         // bitcast to the corresponding integer type.  This turns an f64 value
04841         // into i64, which can be passed with two i32 values on a 32-bit
04842         // machine.
04843         RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
04844         OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
04845                                          RegVT, OpInfo.CallOperand);
04846         OpInfo.ConstraintVT = RegVT;
04847       }
04848     }
04849 
04850     NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
04851   }
04852 
04853   MVT RegVT;
04854   MVT ValueVT = OpInfo.ConstraintVT;
04855 
04856   // If this is a constraint for a specific physical register, like {r17},
04857   // assign it now.
04858   if (PhysReg.first) {
04859     if (OpInfo.ConstraintVT == MVT::Other)
04860       ValueVT = *PhysReg.second->vt_begin();
04861 
04862     // Get the actual register value type.  This is important, because the user
04863     // may have asked for (e.g.) the AX register in i32 type.  We need to
04864     // remember that AX is actually i16 to get the right extension.
04865     RegVT = *PhysReg.second->vt_begin();
04866 
04867     // This is a explicit reference to a physical register.
04868     Regs.push_back(PhysReg.first);
04869 
04870     // If this is an expanded reference, add the rest of the regs to Regs.
04871     if (NumRegs != 1) {
04872       TargetRegisterClass::iterator I = PhysReg.second->begin();
04873       for (; *I != PhysReg.first; ++I)
04874         assert(I != PhysReg.second->end() && "Didn't find reg!");
04875 
04876       // Already added the first reg.
04877       --NumRegs; ++I;
04878       for (; NumRegs; --NumRegs, ++I) {
04879         assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
04880         Regs.push_back(*I);
04881       }
04882     }
04883     OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
04884     const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
04885     OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
04886     return;
04887   }
04888 
04889   // Otherwise, if this was a reference to an LLVM register class, create vregs
04890   // for this reference.
04891   std::vector<unsigned> RegClassRegs;
04892   const TargetRegisterClass *RC = PhysReg.second;
04893   if (RC) {
04894     // If this is a tied register, our regalloc doesn't know how to maintain
04895     // the constraint, so we have to pick a register to pin the input/output to.
04896     // If it isn't a matched constraint, go ahead and create vreg and let the
04897     // regalloc do its thing.
04898     if (!OpInfo.hasMatchingInput()) {
04899       RegVT = *PhysReg.second->vt_begin();
04900       if (OpInfo.ConstraintVT == MVT::Other)
04901         ValueVT = RegVT;
04902 
04903       // Create the appropriate number of virtual registers.
04904       MachineRegisterInfo &RegInfo = MF.getRegInfo();
04905       for (; NumRegs; --NumRegs)
04906         Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
04907 
04908       OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
04909       return;
04910     }
04911 
04912     // Otherwise, we can't allocate it.  Let the code below figure out how to
04913     // maintain these constraints.
04914     RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
04915 
04916   } else {
04917     // This is a reference to a register class that doesn't directly correspond
04918     // to an LLVM register class.  Allocate NumRegs consecutive, available,
04919     // registers from the class.
04920     RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
04921                                                          OpInfo.ConstraintVT);
04922   }
04923 
04924   const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
04925   unsigned NumAllocated = 0;
04926   for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
04927     unsigned Reg = RegClassRegs[i];
04928     // See if this register is available.
04929     if ((isOutReg && OutputRegs.count(Reg)) ||   // Already used.
04930         (isInReg  && InputRegs.count(Reg))) {    // Already used.
04931       // Make sure we find consecutive registers.
04932       NumAllocated = 0;
04933       continue;
04934     }
04935 
04936     // Check to see if this register is allocatable (i.e. don't give out the
04937     // stack pointer).
04938     if (RC == 0) {
04939       RC = isAllocatableRegister(Reg, MF, TLI, TRI);
04940       if (!RC) {        // Couldn't allocate this register.
04941         // Reset NumAllocated to make sure we return consecutive registers.
04942         NumAllocated = 0;
04943         continue;
04944       }
04945     }
04946 
04947     // Okay, this register is good, we can use it.
04948     ++NumAllocated;
04949 
04950     // If we allocated enough consecutive registers, succeed.
04951     if (NumAllocated == NumRegs) {
04952       unsigned RegStart = (i-NumAllocated)+1;
04953       unsigned RegEnd   = i+1;
04954       // Mark all of the allocated registers used.
04955       for (unsigned i = RegStart; i != RegEnd; ++i)
04956         Regs.push_back(RegClassRegs[i]);
04957 
04958       OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
04959                                          OpInfo.ConstraintVT);
04960       OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
04961       return;
04962     }
04963   }
04964 
04965   // Otherwise, we couldn't allocate enough registers for this.
04966 }
04967 
04968 /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
04969 /// processed uses a memory 'm' constraint.
04970 static bool
04971 hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
04972                           const TargetLowering &TLI) {
04973   for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
04974     InlineAsm::ConstraintInfo &CI = CInfos[i];
04975     for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
04976       TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
04977       if (CType == TargetLowering::C_Memory)
04978         return true;
04979     }
04980   }
04981 
04982   return false;
04983 }
04984 
04985 /// visitInlineAsm - Handle a call to an InlineAsm object.
04986 ///
04987 void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
04988   InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
04989 
04990   /// ConstraintOperands - Information about all of the constraints.
04991   std::vector<SDISelAsmOperandInfo> ConstraintOperands;
04992 
04993   SDValue Chain = getRoot();
04994   SDValue Flag;
04995 
04996   std::set<unsigned> OutputRegs, InputRegs;
04997 
04998   // Do a prepass over the constraints, canonicalizing them, and building up the
04999   // ConstraintOperands list.
05000   std::vector<InlineAsm::ConstraintInfo>
05001     ConstraintInfos = IA->ParseConstraints();
05002 
05003   bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
05004 
05005   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
05006   unsigned ResNo = 0;   // ResNo - The result number of the next output.
05007   for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
05008     ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
05009     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
05010 
05011     MVT OpVT = MVT::Other;
05012 
05013     // Compute the value type for each operand.
05014     switch (OpInfo.Type) {
05015     case InlineAsm::isOutput:
05016       // Indirect outputs just consume an argument.
05017       if (OpInfo.isIndirect) {
05018         OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
05019         break;
05020       }
05021 
05022       // The return value of the call is this value.  As such, there is no
05023       // corresponding argument.
05024       assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
05025       if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
05026         OpVT = TLI.getValueType(STy->getElementType(ResNo));
05027       } else {
05028         assert(ResNo == 0 && "Asm only has one result!");
05029         OpVT = TLI.getValueType(CS.getType());
05030       }
05031       ++ResNo;
05032       break;
05033     case InlineAsm::isInput:
05034       OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
05035       break;
05036     case InlineAsm::isClobber:
05037       // Nothing to do.
05038       break;
05039     }
05040 
05041     // If this is an input or an indirect output, process the call argument.
05042     // BasicBlocks are labels, currently appearing only in asm's.
05043     if (OpInfo.CallOperandVal) {
05044       if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
05045         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
05046       } else {
05047         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
05048       }
05049 
05050       OpVT = OpInfo.getCallOperandValMVT(TLI, TD);
05051     }
05052 
05053     OpInfo.ConstraintVT = OpVT;
05054   }
05055 
05056   // Second pass over the constraints: compute which constraint option to use
05057   // and assign registers to constraints that want a specific physreg.
05058   for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
05059     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
05060 
05061     // If this is an output operand with a matching input operand, look up the
05062     // matching input. If their types mismatch, e.g. one is an integer, the
05063     // other is floating point, or their sizes are different, flag it as an
05064     // error.
05065     if (OpInfo.hasMatchingInput()) {
05066       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
05067       if (OpInfo.ConstraintVT != Input.ConstraintVT) {
05068         if ((OpInfo.ConstraintVT.isInteger() !=
05069              Input.ConstraintVT.isInteger()) ||
05070             (OpInfo.ConstraintVT.getSizeInBits() !=
05071              Input.ConstraintVT.getSizeInBits())) {
05072           cerr << "Unsupported asm: input constraint with a matching output "
05073                << "constraint of incompatible type!\n";
05074           exit(1);
05075         }
05076         Input.ConstraintVT = OpInfo.ConstraintVT;
05077       }
05078     }
05079 
05080     // Compute the constraint code and ConstraintType to use.
05081     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
05082 
05083     // If this is a memory input, and if the operand is not indirect, do what we
05084     // need to to provide an address for the memory input.
05085     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
05086         !OpInfo.isIndirect) {
05087       assert(OpInfo.Type == InlineAsm::isInput &&
05088              "Can only indirectify direct input operands!");
05089 
05090       // Memory operands really want the address of the value.  If we don't have
05091       // an indirect input, put it in the constpool if we can, otherwise spill
05092       // it to a stack slot.
05093 
05094       // If the operand is a float, integer, or vector constant, spill to a
05095       // constant pool entry to get its address.
05096       Value *OpVal = OpInfo.CallOperandVal;
05097       if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
05098           isa<ConstantVector>(OpVal)) {
05099         OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
05100                                                  TLI.getPointerTy());
05101       } else {
05102         // Otherwise, create a stack slot and emit a store to it before the
05103         // asm.
05104         const Type *Ty = OpVal->getType();
05105         uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
05106         unsigned Align  = TLI.getTargetData()->getPrefTypeAlignment(Ty);
05107         MachineFunction &MF = DAG.getMachineFunction();
05108         int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
05109         SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
05110         Chain = DAG.getStore(Chain, getCurDebugLoc(),
05111                              OpInfo.CallOperand, StackSlot, NULL, 0);
05112         OpInfo.CallOperand = StackSlot;
05113       }
05114 
05115       // There is no longer a Value* corresponding to this operand.
05116       OpInfo.CallOperandVal = 0;
05117       // It is now an indirect operand.
05118       OpInfo.isIndirect = true;
05119     }
05120 
05121     // If this constraint is for a specific register, allocate it before
05122     // anything else.
05123     if (OpInfo.ConstraintType == TargetLowering::C_Register)
05124       GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
05125   }
05126   ConstraintInfos.clear();
05127 
05128 
05129   // Second pass - Loop over all of the operands, assigning virtual or physregs
05130   // to register class operands.
05131   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
05132     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
05133 
05134     // C_Register operands have already been allocated, Other/Memory don't need
05135     // to be.
05136     if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
05137       GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
05138   }
05139 
05140   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
05141   std::vector<SDValue> AsmNodeOperands;
05142   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
05143   AsmNodeOperands.push_back(
05144           DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
05145 
05146 
05147   // Loop over all of the inputs, copying the operand values into the
05148   // appropriate registers and processing the output regs.
05149   RegsForValue RetValRegs;
05150 
05151   // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
05152   std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
05153 
05154   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
05155     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
05156 
05157     switch (OpInfo.Type) {
05158     case InlineAsm::isOutput: {
05159       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
05160           OpInfo.ConstraintType != TargetLowering::C_Register) {
05161         // Memory output, or 'other' output (e.g. 'X' constraint).
05162         assert(OpInfo.isIndirect && "Memory output must be indirect operand");
05163 
05164         // Add information to the INLINEASM node to know about this output.
05165         unsigned ResOpType = 4/*MEM*/ | (1<<3);
05166         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
05167                                                         TLI.getPointerTy()));
05168         AsmNodeOperands.push_back(OpInfo.CallOperand);
05169         break;
05170       }
05171 
05172       // Otherwise, this is a register or register class output.
05173 
05174       // Copy the output from the appropriate register.  Find a register that
05175       // we can use.
05176       if (OpInfo.AssignedRegs.Regs.empty()) {
05177         cerr << "Couldn't allocate output reg for constraint '"
05178              << OpInfo.ConstraintCode << "'!\n";
05179         exit(1);
05180       }
05181 
05182       // If this is an indirect operand, store through the pointer after the
05183       // asm.
05184       if (OpInfo.isIndirect) {
05185         IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
05186                                                       OpInfo.CallOperandVal));
05187       } else {
05188         // This is the result value of the call.
05189         assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
05190         // Concatenate this output onto the outputs list.
05191         RetValRegs.append(OpInfo.AssignedRegs);
05192       }
05193 
05194       // Add information to the INLINEASM node to know that this register is
05195       // set.
05196       OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
05197                                                6 /* EARLYCLOBBER REGDEF */ :
05198                                                2 /* REGDEF */ ,
05199                                                DAG, AsmNodeOperands);
05200       break;
05201     }
05202     case InlineAsm::isInput: {
05203       SDValue InOperandVal = OpInfo.CallOperand;
05204 
05205       if (OpInfo.isMatchingInputConstraint()) {   // Matching constraint?
05206         // If this is required to match an output register we have already set,
05207         // just use its register.
05208         unsigned OperandNo = OpInfo.getMatchedOperand();
05209 
05210         // Scan until we find the definition we already emitted of this operand.
05211         // When we find it, create a RegsForValue operand.
05212         unsigned CurOp = 2;  // The first operand.
05213         for (; OperandNo; --OperandNo) {
05214           // Advance to the next operand.
05215           unsigned NumOps =
05216             cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
05217           assert(((NumOps & 7) == 2 /*REGDEF*/ ||
05218                   (NumOps & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
05219                   (NumOps & 7) == 4 /*MEM*/) &&
05220                  "Skipped past definitions?");
05221           CurOp += (NumOps>>3)+1;
05222         }
05223 
05224         unsigned NumOps =
05225           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
05226         if ((NumOps & 7) == 2 /*REGDEF*/
05227             || (NumOps & 7) == 6 /* EARLYCLOBBER REGDEF */) {
05228           // Add NumOps>>3 registers to MatchedRegs.
05229           RegsForValue MatchedRegs;
05230           MatchedRegs.TLI = &TLI;
05231           MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
05232           MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
05233           for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
05234             unsigned Reg =
05235               cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
05236             MatchedRegs.Regs.push_back(Reg);
05237           }
05238 
05239           // Use the produced MatchedRegs object to
05240           MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
05241                                     Chain, &Flag);
05242           MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
05243           break;
05244         } else {
05245           assert(((NumOps & 7) == 4) && "Unknown matching constraint!");
05246           assert((NumOps >> 3) == 1 && "Unexpected number of operands");
05247           // Add information to the INLINEASM node to know about this input.
05248           AsmNodeOperands.push_back(DAG.getTargetConstant(NumOps,
05249                                                           TLI.getPointerTy()));
05250           AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
05251           break;
05252         }
05253       }
05254 
05255       if (OpInfo.ConstraintType == TargetLowering::C_Other) {
05256         assert(!OpInfo.isIndirect &&
05257                "Don't know how to handle indirect other inputs yet!");
05258 
05259         std::vector<SDValue> Ops;
05260         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
05261                                          hasMemory, Ops, DAG);
05262         if (Ops.empty()) {
05263           cerr << "Invalid operand for inline asm constraint '"
05264                << OpInfo.ConstraintCode << "'!\n";
05265           exit(1);
05266         }
05267 
05268         // Add information to the INLINEASM node to know about this input.
05269         unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
05270         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
05271                                                         TLI.getPointerTy()));
05272         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
05273         break;
05274       } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
05275         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
05276         assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
05277                "Memory operands expect pointer values");
05278 
05279         // Add information to the INLINEASM node to know about this input.
05280         unsigned ResOpType = 4/*MEM*/ | (1<<3);
05281         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
05282                                                         TLI.getPointerTy()));
05283         AsmNodeOperands.push_back(InOperandVal);
05284         break;
05285       }
05286 
05287       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
05288               OpInfo.ConstraintType == TargetLowering::C_Register) &&
05289              "Unknown constraint type!");
05290       assert(!OpInfo.isIndirect &&
05291              "Don't know how to handle indirect register inputs yet!");
05292 
05293       // Copy the input into the appropriate registers.
05294       if (OpInfo.AssignedRegs.Regs.empty()) {
05295         cerr << "Couldn't allocate output reg for constraint '"
05296              << OpInfo.ConstraintCode << "'!\n";
05297         exit(1);
05298       }
05299 
05300       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
05301                                         Chain, &Flag);
05302 
05303       OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/,
05304                                                DAG, AsmNodeOperands);
05305       break;
05306     }
05307     case InlineAsm::isClobber: {
05308       // Add the clobbered value to the operand list, so that the register
05309       // allocator is aware that the physreg got clobbered.
05310       if (!OpInfo.AssignedRegs.Regs.empty())
05311         OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
05312                                                  DAG, AsmNodeOperands);
05313       break;
05314     }
05315     }
05316   }
05317 
05318   // Finish up input operands.
05319   AsmNodeOperands[0] = Chain;
05320   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
05321 
05322   Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
05323                       DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
05324                       &AsmNodeOperands[0], AsmNodeOperands.size());
05325   Flag = Chain.getValue(1);
05326 
05327   // If this asm returns a register value, copy the result from that register
05328   // and set it as the value of the call.
05329   if (!RetValRegs.Regs.empty()) {
05330     SDValue Val = RetValRegs.getCopyFromRegs(DAG, getCurDebugLoc(), 
05331                                              Chain, &Flag);
05332 
05333     // FIXME: Why don't we do this for inline asms with MRVs?
05334     if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
05335       MVT ResultType = TLI.getValueType(CS.getType());
05336 
05337       // If any of the results of the inline asm is a vector, it may have the
05338       // wrong width/num elts.  This can happen for register classes that can
05339       // contain multiple different value types.  The preg or vreg allocated may
05340       // not have the same VT as was expected.  Convert it to the right type
05341       // with bit_convert.
05342       if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
05343         Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
05344                           ResultType, Val);
05345 
05346       } else if (ResultType != Val.getValueType() &&
05347                  ResultType.isInteger() && Val.getValueType().isInteger()) {
05348         // If a result value was tied to an input value, the computed result may
05349         // have a wider width than the expected result.  Extract the relevant
05350         // portion.
05351         Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
05352       }
05353 
05354       assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
05355     }
05356 
05357     setValue(CS.getInstruction(), Val);
05358   }
05359 
05360   std::vector<std::pair<SDValue, Value*> > StoresToEmit;
05361 
05362   // Process indirect outputs, first output all of the flagged copies out of
05363   // physregs.
05364   for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
05365     RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
05366     Value *Ptr = IndirectStoresToEmit[i].second;
05367     SDValue OutVal = OutRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
05368                                              Chain, &Flag);
05369     StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
05370   }
05371 
05372   // Emit the non-flagged stores from the physregs.
05373   SmallVector<SDValue, 8> OutChains;
05374   for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
05375     OutChains.push_back(DAG.getStore(Chain, getCurDebugLoc(),
05376                                     StoresToEmit[i].first,
05377                                     getValue(StoresToEmit[i].second),
05378                                     StoresToEmit[i].second, 0));
05379   if (!OutChains.empty())
05380     Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
05381                         &OutChains[0], OutChains.size());
05382   DAG.setRoot(Chain);
05383 }
05384 
05385 
05386 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
05387   SDValue Src = getValue(I.getOperand(0));
05388 
05389   MVT IntPtr = TLI.getPointerTy();
05390 
05391   if (IntPtr.bitsLT(Src.getValueType()))
05392     Src = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), IntPtr, Src);
05393   else if (IntPtr.bitsGT(Src.getValueType()))
05394     Src = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), IntPtr, Src);
05395 
05396   // Scale the source by the type size.
05397   uint64_t ElementSize = TD->getTypePaddedSize(I.getType()->getElementType());
05398   Src = DAG.getNode(ISD::MUL, getCurDebugLoc(), Src.getValueType(),
05399                     Src, DAG.getIntPtrConstant(ElementSize));
05400 
05401   TargetLowering::ArgListTy Args;
05402   TargetLowering::ArgListEntry Entry;
05403   Entry.Node = Src;
05404   Entry.Ty = TLI.getTargetData()->getIntPtrType();
05405   Args.push_back(Entry);
05406 
05407   std::pair<SDValue,SDValue> Result =
05408     TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, false,
05409                     CallingConv::C, PerformTailCallOpt,
05410                     DAG.getExternalSymbol("malloc", IntPtr),
05411                     Args, DAG, getCurDebugLoc());
05412   setValue(&I, Result.first);  // Pointers always fit in registers
05413   DAG.setRoot(Result.second);
05414 }
05415 
05416 void SelectionDAGLowering::visitFree(FreeInst &I) {
05417   TargetLowering::ArgListTy Args;
05418   TargetLowering::ArgListEntry Entry;
05419   Entry.Node = getValue(I.getOperand(0));
05420   Entry.Ty = TLI.getTargetData()->getIntPtrType();
05421   Args.push_back(Entry);
05422   MVT IntPtr = TLI.getPointerTy();
05423   std::pair<SDValue,SDValue> Result =
05424     TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false, false,
05425                     CallingConv::C, PerformTailCallOpt,
05426                     DAG.getExternalSymbol("free", IntPtr), Args, DAG,
05427                     getCurDebugLoc());
05428   DAG.setRoot(Result.second);
05429 }
05430 
05431 void SelectionDAGLowering::visitVAStart(CallInst &I) {
05432   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
05433                           MVT::Other, getRoot(),
05434                           getValue(I.getOperand(1)),
05435                           DAG.getSrcValue(I.getOperand(1))));
05436 }
05437 
05438 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
05439   SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
05440                              getValue(I.getOperand(0)),
05441                              DAG.getSrcValue(I.getOperand(0)));
05442   setValue(&I, V);
05443   DAG.setRoot(V.getValue(1));
05444 }
05445 
05446 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
05447   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
05448                           MVT::Other, getRoot(),
05449                           getValue(I.getOperand(1)),
05450                           DAG.getSrcValue(I.getOperand(1))));
05451 }
05452 
05453 void SelectionDAGLowering::visitVACopy(CallInst &I) {
05454   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
05455                           MVT::Other, getRoot(),
05456                           getValue(I.getOperand(1)),
05457                           getValue(I.getOperand(2)),
05458                           DAG.getSrcValue(I.getOperand(1)),
05459                           DAG.getSrcValue(I.getOperand(2))));
05460 }
05461 
05462 /// TargetLowering::LowerArguments - This is the default LowerArguments
05463 /// implementation, which just inserts a FORMAL_ARGUMENTS node.  FIXME: When all
05464 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
05465 /// integrated into SDISel.
05466 void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
05467                                     SmallVectorImpl<SDValue> &ArgValues,
05468                                     DebugLoc dl) {
05469   // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
05470   SmallVector<SDValue, 3+16> Ops;
05471   Ops.push_back(DAG.getRoot());
05472   Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
05473   Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
05474 
05475   // Add one result value for each formal argument.
05476   SmallVector<MVT, 16> RetVals;
05477   unsigned j = 1;
05478   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
05479        I != E; ++I, ++j) {
05480     SmallVector<MVT, 4> ValueVTs;
05481     ComputeValueVTs(*this, I->getType(), ValueVTs);
05482     for (unsigned Value = 0, NumValues = ValueVTs.size();
05483          Value != NumValues; ++Value) {
05484       MVT VT = ValueVTs[Value];
05485       const Type *ArgTy = VT.getTypeForMVT();
05486       ISD::ArgFlagsTy Flags;
05487       unsigned OriginalAlignment =
05488         getTargetData()->getABITypeAlignment(ArgTy);
05489 
05490       if (F.paramHasAttr(j, Attribute::ZExt))
05491         Flags.setZExt();
05492       if (F.paramHasAttr(j, Attribute::SExt))
05493         Flags.setSExt();
05494       if (F.paramHasAttr(j, Attribute::InReg))
05495         Flags.setInReg();
05496       if (F.paramHasAttr(j, Attribute::StructRet))
05497         Flags.setSRet();
05498       if (F.paramHasAttr(j, Attribute::ByVal)) {
05499         Flags.setByVal();
05500         const PointerType *Ty = cast<PointerType>(I->getType());
05501         const Type *ElementTy = Ty->getElementType();
05502         unsigned FrameAlign = getByValTypeAlignment(ElementTy);
05503         unsigned FrameSize  = getTargetData()->getTypePaddedSize(ElementTy);
05504         // For ByVal, alignment should be passed from FE.  BE will guess if
05505         // this info is not there but there are cases it cannot get right.
05506         if (F.getParamAlignment(j))
05507           FrameAlign = F.getParamAlignment(j);
05508         Flags.setByValAlign(FrameAlign);
05509         Flags.setByValSize(FrameSize);
05510       }
05511       if (F.paramHasAttr(j, Attribute::Nest))
05512         Flags.setNest();
05513       Flags.setOrigAlign(OriginalAlignment);
05514 
05515       MVT RegisterVT = getRegisterType(VT);
05516       unsigned NumRegs = getNumRegisters(VT);
05517       for (unsigned i = 0; i != NumRegs; ++i) {
05518         RetVals.push_back(RegisterVT);
05519         ISD::ArgFlagsTy MyFlags = Flags;
05520         if (NumRegs > 1 && i == 0)
05521           MyFlags.setSplit();
05522         // if it isn't first piece, alignment must be 1
05523         else if (i > 0)
05524           MyFlags.setOrigAlign(1);
05525         Ops.push_back(DAG.getArgFlags(MyFlags));
05526       }
05527     }
05528   }
05529 
05530   RetVals.push_back(MVT::Other);
05531 
05532   // Create the node.
05533   SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS, dl,
05534                                DAG.getVTList(&RetVals[0], RetVals.size()),
05535                                &Ops[0], Ops.size()).getNode();
05536 
05537   // Prelower FORMAL_ARGUMENTS.  This isn't required for functionality, but
05538   // allows exposing the loads that may be part of the argument access to the
05539   // first DAGCombiner pass.
05540   SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
05541 
05542   // The number of results should match up, except that the lowered one may have
05543   // an extra flag result.
05544   assert((Result->getNumValues() == TmpRes.getNode()->getNumValues() ||
05545           (Result->getNumValues()+1 == TmpRes.getNode()->getNumValues() &&
05546            TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
05547          && "Lowering produced unexpected number of results!");
05548 
05549   // The FORMAL_ARGUMENTS node itself is likely no longer needed.
05550   if (Result != TmpRes.getNode() && Result->use_empty()) {
05551     HandleSDNode Dummy(DAG.getRoot());
05552     DAG.RemoveDeadNode(Result);
05553   }
05554 
05555   Result = TmpRes.getNode();
05556 
05557   unsigned NumArgRegs = Result->getNumValues() - 1;
05558   DAG.setRoot(SDValue(Result, NumArgRegs));
05559 
05560   // Set up the return result vector.
05561   unsigned i = 0;
05562   unsigned Idx = 1;
05563   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
05564       ++I, ++Idx) {
05565     SmallVector<MVT, 4> ValueVTs;
05566     ComputeValueVTs(*this, I->getType(), ValueVTs);
05567     for (unsigned Value = 0, NumValues = ValueVTs.size();
05568          Value != NumValues; ++Value) {
05569       MVT VT = ValueVTs[Value];
05570       MVT PartVT = getRegisterType(VT);
05571 
05572       unsigned NumParts = getNumRegisters(VT);
05573       SmallVector<SDValue, 4> Parts(NumParts);
05574       for (unsigned j = 0; j != NumParts; ++j)
05575         Parts[j] = SDValue(Result, i++);
05576 
05577       ISD::NodeType AssertOp = ISD::DELETED_NODE;
05578       if (F.paramHasAttr(Idx, Attribute::SExt))
05579         AssertOp = ISD::AssertSext;
05580       else if (F.paramHasAttr(Idx, Attribute::ZExt))
05581         AssertOp = ISD::AssertZext;
05582 
05583       ArgValues.push_back(getCopyFromParts(DAG, dl, &Parts[0], NumParts,
05584                                            PartVT, VT, AssertOp));
05585     }
05586   }
05587   assert(i == NumArgRegs && "Argument register count mismatch!");
05588 }
05589 
05590 
05591 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
05592 /// implementation, which just inserts an ISD::CALL node, which is later custom
05593 /// lowered by the target to something concrete.  FIXME: When all targets are
05594 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
05595 std::pair<SDValue, SDValue>
05596 TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
05597                             bool RetSExt, bool RetZExt, bool isVarArg,
05598                             bool isInreg,
05599                             unsigned CallingConv, bool isTailCall,
05600                             SDValue Callee,
05601                             ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl) {
05602   assert((!isTailCall || PerformTailCallOpt) &&
05603          "isTailCall set when tail-call optimizations are disabled!");
05604 
05605   SmallVector<SDValue, 32> Ops;
05606   Ops.push_back(Chain);   // Op#0 - Chain
05607   Ops.push_back(Callee);
05608 
05609   // Handle all of the outgoing arguments.
05610   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
05611     SmallVector<MVT, 4> ValueVTs;
05612     ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
05613     for (unsigned Value = 0, NumValues = ValueVTs.size();
05614          Value != NumValues; ++Value) {
05615       MVT VT = ValueVTs[Value];
05616       const Type *ArgTy = VT.getTypeForMVT();
05617       SDValue Op = SDValue(Args[i].Node.getNode(),
05618                            Args[i].Node.getResNo() + Value);
05619       ISD::ArgFlagsTy Flags;
05620       unsigned OriginalAlignment =
05621         getTargetData()->getABITypeAlignment(ArgTy);
05622 
05623       if (Args[i].isZExt)
05624         Flags.setZExt();
05625       if (Args[i].isSExt)
05626         Flags.setSExt();
05627       if (Args[i].isInReg)
05628         Flags.setInReg();
05629       if (Args[i].isSRet)
05630         Flags.setSRet();
05631       if (Args[i].isByVal) {
05632         Flags.setByVal();
05633         const PointerType *Ty = cast<PointerType>(Args[i].Ty);
05634         const Type *ElementTy = Ty->getElementType();
05635         unsigned FrameAlign = getByValTypeAlignment(ElementTy);
05636         unsigned FrameSize  = getTargetData()->getTypePaddedSize(ElementTy);
05637         // For ByVal, alignment should come from FE.  BE will guess if this
05638         // info is not there but there are cases it cannot get right.
05639         if (Args[i].Alignment)
05640           FrameAlign = Args[i].Alignment;
05641         Flags.setByValAlign(FrameAlign);
05642         Flags.setByValSize(FrameSize);
05643       }
05644       if (Args[i].isNest)
05645         Flags.setNest();
05646       Flags.setOrigAlign(OriginalAlignment);
05647 
05648       MVT PartVT = getRegisterType(VT);
05649       unsigned NumParts = getNumRegisters(VT);
05650       SmallVector<SDValue, 4> Parts(NumParts);
05651       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
05652 
05653       if (Args[i].isSExt)
05654         ExtendKind = ISD::SIGN_EXTEND;
05655       else if (Args[i].isZExt)
05656         ExtendKind = ISD::ZERO_EXTEND;
05657 
05658       getCopyToParts(DAG, dl, Op, &Parts[0], NumParts, PartVT, ExtendKind);
05659 
05660       for (unsigned i = 0; i != NumParts; ++i) {
05661         // if it isn't first piece, alignment must be 1
05662         ISD::ArgFlagsTy MyFlags = Flags;
05663         if (NumParts > 1 && i == 0)
05664           MyFlags.setSplit();
05665         else if (i != 0)
05666           MyFlags.setOrigAlign(1);
05667 
05668         Ops.push_back(Parts[i]);
05669         Ops.push_back(DAG.getArgFlags(MyFlags));
05670       }
05671     }
05672   }
05673 
05674   // Figure out the result value types. We start by making a list of
05675   // the potentially illegal return value types.
05676   SmallVector<MVT, 4> LoweredRetTys;
05677   SmallVector<MVT, 4> RetTys;
05678   ComputeValueVTs(*this, RetTy, RetTys);
05679 
05680   // Then we translate that to a list of legal types.
05681   for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
05682     MVT VT = RetTys[I];
05683     MVT RegisterVT = getRegisterType(VT);
05684     unsigned NumRegs = getNumRegisters(VT);
05685     for (unsigned i = 0; i != NumRegs; ++i)
05686       LoweredRetTys.push_back(RegisterVT);
05687   }
05688 
05689   LoweredRetTys.push_back(MVT::Other);  // Always has a chain.
05690 
05691   // Create the CALL node.
05692   SDValue Res = DAG.getCall(CallingConv, dl,
05693                             isVarArg, isTailCall, isInreg,
05694                             DAG.getVTList(&LoweredRetTys[0],
05695                                           LoweredRetTys.size()),
05696                             &Ops[0], Ops.size()
05697                             );
05698   Chain = Res.getValue(LoweredRetTys.size() - 1);
05699 
05700   // Gather up the call result into a single value.
05701   if (RetTy != Type::VoidTy && !RetTys.empty()) {
05702     ISD::NodeType AssertOp = ISD::DELETED_NODE;
05703 
05704     if (RetSExt)
05705       AssertOp = ISD::AssertSext;
05706     else if (RetZExt)
05707       AssertOp = ISD::AssertZext;
05708 
05709     SmallVector<SDValue, 4> ReturnValues;
05710     unsigned RegNo = 0;
05711     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
05712       MVT VT = RetTys[I];
05713       MVT RegisterVT = getRegisterType(VT);
05714       unsigned NumRegs = getNumRegisters(VT);
05715       unsigned RegNoEnd = NumRegs + RegNo;
05716       SmallVector<SDValue, 4> Results;
05717       for (; RegNo != RegNoEnd; ++RegNo)
05718         Results.push_back(Res.getValue(RegNo));
05719       SDValue ReturnValue =
05720         getCopyFromParts(DAG, dl, &Results[0], NumRegs, RegisterVT, VT,
05721                          AssertOp);
05722       ReturnValues.push_back(ReturnValue);
05723     }
05724     Res = DAG.getNode(ISD::MERGE_VALUES, dl,
05725                       DAG.getVTList(&RetTys[0], RetTys.size()),
05726                       &ReturnValues[0], ReturnValues.size());
05727   }
05728 
05729   return std::make_pair(Res, Chain);
05730 }
05731 
05732 void TargetLowering::LowerOperationWrapper(SDNode *N,
05733                                            SmallVectorImpl<SDValue> &Results,
05734                                            SelectionDAG &DAG) {
05735   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
05736   if (Res.getNode())
05737     Results.push_back(Res);
05738 }
05739 
05740 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
05741   assert(0 && "LowerOperation not implemented for this target!");
05742   abort();
05743   return SDValue();
05744 }
05745 
05746 
05747 void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
05748   SDValue Op = getValue(V);
05749   assert((Op.getOpcode() != ISD::CopyFromReg ||
05750           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
05751          "Copy from a reg to the same reg!");
05752   assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
05753 
05754   RegsForValue RFV(TLI, Reg, V->getType());
05755   SDValue Chain = DAG.getEntryNode();
05756   RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0);
05757   PendingExports.push_back(Chain);
05758 }
05759 
05760 #include "llvm/CodeGen/SelectionDAGISel.h"
05761 
05762 void SelectionDAGISel::
05763 LowerArguments(BasicBlock *LLVMBB) {
05764   // If this is the entry block, emit arguments.
05765   Function &F = *LLVMBB->getParent();
05766   SDValue OldRoot = SDL->DAG.getRoot();
05767   SmallVector<SDValue, 16> Args;
05768   TLI.LowerArguments(F, SDL->DAG, Args, SDL->getCurDebugLoc());
05769 
05770   unsigned a = 0;
05771   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
05772        AI != E; ++AI) {
05773     SmallVector<MVT, 4> ValueVTs;
05774     ComputeValueVTs(TLI, AI->getType(), ValueVTs);
05775     unsigned NumValues = ValueVTs.size();
05776     if (!AI->use_empty()) {
05777       SDL->setValue(AI, SDL->DAG.getMergeValues(&Args[a], NumValues));
05778       // If this argument is live outside of the entry block, insert a copy from
05779       // whereever we got it to the vreg that other BB's will reference it as.
05780       DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo->ValueMap.find(AI);
05781       if (VMI != FuncInfo->ValueMap.end()) {
05782         SDL->CopyValueToVirtualRegister(AI, VMI->second);
05783       }
05784     }
05785     a += NumValues;
05786   }
05787 
05788   // Finally, if the target has anything special to do, allow it to do so.
05789   // FIXME: this should insert code into the DAG!
05790   EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
05791 }
05792 
05793 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
05794 /// ensure constants are generated when needed.  Remember the virtual registers
05795 /// that need to be added to the Machine PHI nodes as input.  We cannot just
05796 /// directly add them, because expansion might result in multiple MBB's for one
05797 /// BB.  As such, the start of the BB might correspond to a different MBB than
05798 /// the end.
05799 ///
05800 void
05801 SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
05802   TerminatorInst *TI = LLVMBB->getTerminator();
05803 
05804   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
05805 
05806   // Check successor nodes' PHI nodes that expect a constant to be available
05807   // from this block.
05808   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
05809     BasicBlock *SuccBB = TI->getSuccessor(succ);
05810     if (!isa<PHINode>(SuccBB->begin())) continue;
05811     MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
05812 
05813     // If this terminator has multiple identical successors (common for
05814     // switches), only handle each succ once.
05815     if (!SuccsHandled.insert(SuccMBB)) continue;
05816 
05817     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
05818     PHINode *PN;
05819 
05820     // At this point we know that there is a 1-1 correspondence between LLVM PHI
05821     // nodes and Machine PHI nodes, but the incoming operands have not been
05822     // emitted yet.
05823     for (BasicBlock::iterator I = SuccBB->begin();
05824          (PN = dyn_cast<PHINode>(I)); ++I) {
05825       // Ignore dead phi's.
05826       if (PN->use_empty()) continue;
05827 
05828       unsigned Reg;
05829       Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
05830 
05831       if (Constant *C = dyn_cast<Constant>(PHIOp)) {
05832         unsigned &RegOut = SDL->ConstantsOut[C];
05833         if (RegOut == 0) {
05834           RegOut = FuncInfo->CreateRegForValue(C);
05835           SDL->CopyValueToVirtualRegister(C, RegOut);
05836         }
05837         Reg = RegOut;
05838       } else {
05839         Reg = FuncInfo->ValueMap[PHIOp];
05840         if (Reg == 0) {
05841           assert(isa<AllocaInst>(PHIOp) &&
05842                  FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
05843                  "Didn't codegen value into a register!??");
05844           Reg = FuncInfo->CreateRegForValue(PHIOp);
05845           SDL->CopyValueToVirtualRegister(PHIOp, Reg);
05846         }
05847       }
05848 
05849       // Remember that this register needs to added to the machine PHI node as
05850       // the input for this MBB.
05851       SmallVector<MVT, 4> ValueVTs;
05852       ComputeValueVTs(TLI, PN->getType(), ValueVTs);
05853       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
05854         MVT VT = ValueVTs[vti];
05855         unsigned NumRegisters = TLI.getNumRegisters(VT);
05856         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
05857           SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
05858         Reg += NumRegisters;
05859       }
05860     }
05861   }
05862   SDL->ConstantsOut.clear();
05863 }
05864 
05865 /// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
05866 /// supports legal types, and it emits MachineInstrs directly instead of
05867 /// creating SelectionDAG nodes.
05868 ///
05869 bool
05870 SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
05871                                                       FastISel *F) {
05872   TerminatorInst *TI = LLVMBB->getTerminator();
05873 
05874   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
05875   unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
05876 
05877   // Check successor nodes' PHI nodes that expect a constant to be available
05878   // from this block.
05879   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
05880     BasicBlock *SuccBB = TI->getSuccessor(succ);
05881     if (!isa<PHINode>(SuccBB->begin())) continue;
05882     MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
05883 
05884     // If this terminator has multiple identical successors (common for
05885     // switches), only handle each succ once.
05886     if (!SuccsHandled.insert(SuccMBB)) continue;
05887 
05888     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
05889     PHINode *PN;
05890 
05891     // At this point we know that there is a 1-1 correspondence between LLVM PHI
05892     // nodes and Machine PHI nodes, but the incoming operands have not been
05893     // emitted yet.
05894     for (BasicBlock::iterator I = SuccBB->begin();
05895          (PN = dyn_cast<PHINode>(I)); ++I) {
05896       // Ignore dead phi's.
05897       if (PN->use_empty()) continue;
05898 
05899       // Only handle legal types. Two interesting things to note here. First,
05900       // by bailing out early, we may leave behind some dead instructions,
05901       // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
05902       // own moves. Second, this check is necessary becuase FastISel doesn't
05903       // use CreateRegForValue to create registers, so it always creates
05904       // exactly one register for each non-void instruction.
05905       MVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
05906       if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
05907         // Promote MVT::i1.
05908         if (VT == MVT::i1)
05909           VT = TLI.getTypeToTransformTo(VT);
05910         else {
05911           SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
05912           return false;
05913         }
05914       }
05915 
05916       Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
05917 
05918       unsigned Reg = F->getRegForValue(PHIOp);
05919       if (Reg == 0) {
05920         SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
05921         return false;
05922       }
05923       SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
05924     }
05925   }
05926 
05927   return true;
05928 }