1eb87e888c0b84c4bd39c1cc537f46bdd3ae042b
[oota-llvm.git] / lib / CodeGen / SelectionDAG / SelectionDAGBuild.cpp
1 //===-- SelectionDAGBuild.cpp - Selection-DAG building --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements routines for translating from LLVM IR into SelectionDAG IR.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "isel"
15 #include "SelectionDAGBuild.h"
16 #include "llvm/ADT/BitVector.h"
17 #include "llvm/ADT/SmallSet.h"
18 #include "llvm/Analysis/AliasAnalysis.h"
19 #include "llvm/Constants.h"
20 #include "llvm/Constants.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Function.h"
24 #include "llvm/GlobalVariable.h"
25 #include "llvm/InlineAsm.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Intrinsics.h"
28 #include "llvm/IntrinsicInst.h"
29 #include "llvm/Module.h"
30 #include "llvm/CodeGen/FastISel.h"
31 #include "llvm/CodeGen/GCStrategy.h"
32 #include "llvm/CodeGen/GCMetadata.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineFrameInfo.h"
35 #include "llvm/CodeGen/MachineInstrBuilder.h"
36 #include "llvm/CodeGen/MachineJumpTableInfo.h"
37 #include "llvm/CodeGen/MachineModuleInfo.h"
38 #include "llvm/CodeGen/MachineRegisterInfo.h"
39 #include "llvm/CodeGen/PseudoSourceValue.h"
40 #include "llvm/CodeGen/SelectionDAG.h"
41 #include "llvm/CodeGen/DwarfWriter.h"
42 #include "llvm/Analysis/DebugInfo.h"
43 #include "llvm/Target/TargetRegisterInfo.h"
44 #include "llvm/Target/TargetData.h"
45 #include "llvm/Target/TargetFrameInfo.h"
46 #include "llvm/Target/TargetInstrInfo.h"
47 #include "llvm/Target/TargetIntrinsicInfo.h"
48 #include "llvm/Target/TargetLowering.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include "llvm/Support/Compiler.h"
51 #include "llvm/Support/CommandLine.h"
52 #include "llvm/Support/Debug.h"
53 #include "llvm/Support/ErrorHandling.h"
54 #include "llvm/Support/MathExtras.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include <algorithm>
57 using namespace llvm;
58
59 /// LimitFloatPrecision - Generate low-precision inline sequences for
60 /// some float libcalls (6, 8 or 12 bits).
61 static unsigned LimitFloatPrecision;
62
63 static cl::opt<unsigned, true>
64 LimitFPPrecision("limit-float-precision",
65                  cl::desc("Generate low-precision inline sequences "
66                           "for some float libcalls"),
67                  cl::location(LimitFloatPrecision),
68                  cl::init(0));
69
70 /// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
71 /// of insertvalue or extractvalue indices that identify a member, return
72 /// the linearized index of the start of the member.
73 ///
74 static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
75                                    const unsigned *Indices,
76                                    const unsigned *IndicesEnd,
77                                    unsigned CurIndex = 0) {
78   // Base case: We're done.
79   if (Indices && Indices == IndicesEnd)
80     return CurIndex;
81
82   // Given a struct type, recursively traverse the elements.
83   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
84     for (StructType::element_iterator EB = STy->element_begin(),
85                                       EI = EB,
86                                       EE = STy->element_end();
87         EI != EE; ++EI) {
88       if (Indices && *Indices == unsigned(EI - EB))
89         return ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd, CurIndex);
90       CurIndex = ComputeLinearIndex(TLI, *EI, 0, 0, CurIndex);
91     }
92     return CurIndex;
93   }
94   // Given an array type, recursively traverse the elements.
95   else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
96     const Type *EltTy = ATy->getElementType();
97     for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
98       if (Indices && *Indices == i)
99         return ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd, CurIndex);
100       CurIndex = ComputeLinearIndex(TLI, EltTy, 0, 0, CurIndex);
101     }
102     return CurIndex;
103   }
104   // We haven't found the type we're looking for, so keep searching.
105   return CurIndex + 1;
106 }
107
108 /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
109 /// MVTs that represent all the individual underlying
110 /// non-aggregate types that comprise it.
111 ///
112 /// If Offsets is non-null, it points to a vector to be filled in
113 /// with the in-memory offsets of each of the individual values.
114 ///
115 static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
116                             SmallVectorImpl<MVT> &ValueVTs,
117                             SmallVectorImpl<uint64_t> *Offsets = 0,
118                             uint64_t StartingOffset = 0) {
119   // Given a struct type, recursively traverse the elements.
120   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
121     const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
122     for (StructType::element_iterator EB = STy->element_begin(),
123                                       EI = EB,
124                                       EE = STy->element_end();
125          EI != EE; ++EI)
126       ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
127                       StartingOffset + SL->getElementOffset(EI - EB));
128     return;
129   }
130   // Given an array type, recursively traverse the elements.
131   if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
132     const Type *EltTy = ATy->getElementType();
133     uint64_t EltSize = TLI.getTargetData()->getTypeAllocSize(EltTy);
134     for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
135       ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
136                       StartingOffset + i * EltSize);
137     return;
138   }
139   // Interpret void as zero return values.
140   if (Ty == Type::VoidTy)
141     return;
142   // Base case: we can get an MVT for this LLVM IR type.
143   ValueVTs.push_back(TLI.getValueType(Ty));
144   if (Offsets)
145     Offsets->push_back(StartingOffset);
146 }
147
148 namespace llvm {
149   /// RegsForValue - This struct represents the registers (physical or virtual)
150   /// that a particular set of values is assigned, and the type information about
151   /// the value. The most common situation is to represent one value at a time,
152   /// but struct or array values are handled element-wise as multiple values.
153   /// The splitting of aggregates is performed recursively, so that we never
154   /// have aggregate-typed registers. The values at this point do not necessarily
155   /// have legal types, so each value may require one or more registers of some
156   /// legal type.
157   ///
158   struct VISIBILITY_HIDDEN RegsForValue {
159     /// TLI - The TargetLowering object.
160     ///
161     const TargetLowering *TLI;
162
163     /// ValueVTs - The value types of the values, which may not be legal, and
164     /// may need be promoted or synthesized from one or more registers.
165     ///
166     SmallVector<MVT, 4> ValueVTs;
167
168     /// RegVTs - The value types of the registers. This is the same size as
169     /// ValueVTs and it records, for each value, what the type of the assigned
170     /// register or registers are. (Individual values are never synthesized
171     /// from more than one type of register.)
172     ///
173     /// With virtual registers, the contents of RegVTs is redundant with TLI's
174     /// getRegisterType member function, however when with physical registers
175     /// it is necessary to have a separate record of the types.
176     ///
177     SmallVector<MVT, 4> RegVTs;
178
179     /// Regs - This list holds the registers assigned to the values.
180     /// Each legal or promoted value requires one register, and each
181     /// expanded value requires multiple registers.
182     ///
183     SmallVector<unsigned, 4> Regs;
184
185     RegsForValue() : TLI(0) {}
186
187     RegsForValue(const TargetLowering &tli,
188                  const SmallVector<unsigned, 4> &regs,
189                  MVT regvt, MVT valuevt)
190       : TLI(&tli),  ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
191     RegsForValue(const TargetLowering &tli,
192                  const SmallVector<unsigned, 4> &regs,
193                  const SmallVector<MVT, 4> &regvts,
194                  const SmallVector<MVT, 4> &valuevts)
195       : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
196     RegsForValue(const TargetLowering &tli,
197                  unsigned Reg, const Type *Ty) : TLI(&tli) {
198       ComputeValueVTs(tli, Ty, ValueVTs);
199
200       for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
201         MVT ValueVT = ValueVTs[Value];
202         unsigned NumRegs = TLI->getNumRegisters(ValueVT);
203         MVT RegisterVT = TLI->getRegisterType(ValueVT);
204         for (unsigned i = 0; i != NumRegs; ++i)
205           Regs.push_back(Reg + i);
206         RegVTs.push_back(RegisterVT);
207         Reg += NumRegs;
208       }
209     }
210
211     /// append - Add the specified values to this one.
212     void append(const RegsForValue &RHS) {
213       TLI = RHS.TLI;
214       ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
215       RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
216       Regs.append(RHS.Regs.begin(), RHS.Regs.end());
217     }
218
219
220     /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
221     /// this value and returns the result as a ValueVTs value.  This uses
222     /// Chain/Flag as the input and updates them for the output Chain/Flag.
223     /// If the Flag pointer is NULL, no flag is used.
224     SDValue getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
225                               SDValue &Chain, SDValue *Flag) const;
226
227     /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
228     /// specified value into the registers specified by this object.  This uses
229     /// Chain/Flag as the input and updates them for the output Chain/Flag.
230     /// If the Flag pointer is NULL, no flag is used.
231     void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
232                        SDValue &Chain, SDValue *Flag) const;
233
234     /// AddInlineAsmOperands - Add this value to the specified inlineasm node
235     /// operand list.  This adds the code marker, matching input operand index
236     /// (if applicable), and includes the number of values added into it.
237     void AddInlineAsmOperands(unsigned Code,
238                               bool HasMatching, unsigned MatchingIdx,
239                               SelectionDAG &DAG, std::vector<SDValue> &Ops) const;
240   };
241 }
242
243 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
244 /// PHI nodes or outside of the basic block that defines it, or used by a
245 /// switch or atomic instruction, which may expand to multiple basic blocks.
246 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
247   if (isa<PHINode>(I)) return true;
248   BasicBlock *BB = I->getParent();
249   for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
250     if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
251       return true;
252   return false;
253 }
254
255 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
256 /// entry block, return true.  This includes arguments used by switches, since
257 /// the switch may expand into multiple basic blocks.
258 static bool isOnlyUsedInEntryBlock(Argument *A, bool EnableFastISel) {
259   // With FastISel active, we may be splitting blocks, so force creation
260   // of virtual registers for all non-dead arguments.
261   // Don't force virtual registers for byval arguments though, because
262   // fast-isel can't handle those in all cases.
263   if (EnableFastISel && !A->hasByValAttr())
264     return A->use_empty();
265
266   BasicBlock *Entry = A->getParent()->begin();
267   for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
268     if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
269       return false;  // Use not in entry block.
270   return true;
271 }
272
273 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli)
274   : TLI(tli) {
275 }
276
277 void FunctionLoweringInfo::set(Function &fn, MachineFunction &mf,
278                                SelectionDAG &DAG,
279                                bool EnableFastISel) {
280   Fn = &fn;
281   MF = &mf;
282   RegInfo = &MF->getRegInfo();
283
284   // Create a vreg for each argument register that is not dead and is used
285   // outside of the entry block for the function.
286   for (Function::arg_iterator AI = Fn->arg_begin(), E = Fn->arg_end();
287        AI != E; ++AI)
288     if (!isOnlyUsedInEntryBlock(AI, EnableFastISel))
289       InitializeRegForValue(AI);
290
291   // Initialize the mapping of values to registers.  This is only set up for
292   // instruction values that are used outside of the block that defines
293   // them.
294   Function::iterator BB = Fn->begin(), EB = Fn->end();
295   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
296     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
297       if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
298         const Type *Ty = AI->getAllocatedType();
299         uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
300         unsigned Align =
301           std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
302                    AI->getAlignment());
303
304         TySize *= CUI->getZExtValue();   // Get total allocated size.
305         if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
306         StaticAllocaMap[AI] =
307           MF->getFrameInfo()->CreateStackObject(TySize, Align);
308       }
309
310   for (; BB != EB; ++BB)
311     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
312       if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
313         if (!isa<AllocaInst>(I) ||
314             !StaticAllocaMap.count(cast<AllocaInst>(I)))
315           InitializeRegForValue(I);
316
317   // Create an initial MachineBasicBlock for each LLVM BasicBlock in F.  This
318   // also creates the initial PHI MachineInstrs, though none of the input
319   // operands are populated.
320   for (BB = Fn->begin(), EB = Fn->end(); BB != EB; ++BB) {
321     MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
322     MBBMap[BB] = MBB;
323     MF->push_back(MBB);
324
325     // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
326     // appropriate.
327     PHINode *PN;
328     DebugLoc DL;
329     for (BasicBlock::iterator
330            I = BB->begin(), E = BB->end(); I != E; ++I) {
331       if (CallInst *CI = dyn_cast<CallInst>(I)) {
332         if (Function *F = CI->getCalledFunction()) {
333           switch (F->getIntrinsicID()) {
334           default: break;
335           case Intrinsic::dbg_stoppoint: {
336             DbgStopPointInst *SPI = cast<DbgStopPointInst>(I);
337             if (isValidDebugInfoIntrinsic(*SPI, CodeGenOpt::Default)) 
338               DL = ExtractDebugLocation(*SPI, MF->getDebugLocInfo());
339             break;
340           }
341           case Intrinsic::dbg_func_start: {
342             DbgFuncStartInst *FSI = cast<DbgFuncStartInst>(I);
343             if (isValidDebugInfoIntrinsic(*FSI, CodeGenOpt::Default)) 
344               DL = ExtractDebugLocation(*FSI, MF->getDebugLocInfo());
345             break;
346           }
347           }
348         }
349       }
350
351       PN = dyn_cast<PHINode>(I);
352       if (!PN || PN->use_empty()) continue;
353
354       unsigned PHIReg = ValueMap[PN];
355       assert(PHIReg && "PHI node does not have an assigned virtual register!");
356
357       SmallVector<MVT, 4> ValueVTs;
358       ComputeValueVTs(TLI, PN->getType(), ValueVTs);
359       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
360         MVT VT = ValueVTs[vti];
361         unsigned NumRegisters = TLI.getNumRegisters(VT);
362         const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
363         for (unsigned i = 0; i != NumRegisters; ++i)
364           BuildMI(MBB, DL, TII->get(TargetInstrInfo::PHI), PHIReg + i);
365         PHIReg += NumRegisters;
366       }
367     }
368   }
369 }
370
371 unsigned FunctionLoweringInfo::MakeReg(MVT VT) {
372   return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
373 }
374
375 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
376 /// the correctly promoted or expanded types.  Assign these registers
377 /// consecutive vreg numbers and return the first assigned number.
378 ///
379 /// In the case that the given value has struct or array type, this function
380 /// will assign registers for each member or element.
381 ///
382 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
383   SmallVector<MVT, 4> ValueVTs;
384   ComputeValueVTs(TLI, V->getType(), ValueVTs);
385
386   unsigned FirstReg = 0;
387   for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
388     MVT ValueVT = ValueVTs[Value];
389     MVT RegisterVT = TLI.getRegisterType(ValueVT);
390
391     unsigned NumRegs = TLI.getNumRegisters(ValueVT);
392     for (unsigned i = 0; i != NumRegs; ++i) {
393       unsigned R = MakeReg(RegisterVT);
394       if (!FirstReg) FirstReg = R;
395     }
396   }
397   return FirstReg;
398 }
399
400 /// getCopyFromParts - Create a value that contains the specified legal parts
401 /// combined into the value they represent.  If the parts combine to a type
402 /// larger then ValueVT then AssertOp can be used to specify whether the extra
403 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
404 /// (ISD::AssertSext).
405 static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc dl,
406                                 const SDValue *Parts,
407                                 unsigned NumParts, MVT PartVT, MVT ValueVT,
408                                 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
409   assert(NumParts > 0 && "No parts to assemble!");
410   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
411   SDValue Val = Parts[0];
412
413   if (NumParts > 1) {
414     // Assemble the value from multiple parts.
415     if (!ValueVT.isVector() && ValueVT.isInteger()) {
416       unsigned PartBits = PartVT.getSizeInBits();
417       unsigned ValueBits = ValueVT.getSizeInBits();
418
419       // Assemble the power of 2 part.
420       unsigned RoundParts = NumParts & (NumParts - 1) ?
421         1 << Log2_32(NumParts) : NumParts;
422       unsigned RoundBits = PartBits * RoundParts;
423       MVT RoundVT = RoundBits == ValueBits ?
424         ValueVT : MVT::getIntegerVT(RoundBits);
425       SDValue Lo, Hi;
426
427       MVT HalfVT = MVT::getIntegerVT(RoundBits/2);
428
429       if (RoundParts > 2) {
430         Lo = getCopyFromParts(DAG, dl, Parts, RoundParts/2, PartVT, HalfVT);
431         Hi = getCopyFromParts(DAG, dl, Parts+RoundParts/2, RoundParts/2,
432                               PartVT, HalfVT);
433       } else {
434         Lo = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[0]);
435         Hi = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[1]);
436       }
437       if (TLI.isBigEndian())
438         std::swap(Lo, Hi);
439       Val = DAG.getNode(ISD::BUILD_PAIR, dl, RoundVT, Lo, Hi);
440
441       if (RoundParts < NumParts) {
442         // Assemble the trailing non-power-of-2 part.
443         unsigned OddParts = NumParts - RoundParts;
444         MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
445         Hi = getCopyFromParts(DAG, dl,
446                               Parts+RoundParts, OddParts, PartVT, OddVT);
447
448         // Combine the round and odd parts.
449         Lo = Val;
450         if (TLI.isBigEndian())
451           std::swap(Lo, Hi);
452         MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
453         Hi = DAG.getNode(ISD::ANY_EXTEND, dl, TotalVT, Hi);
454         Hi = DAG.getNode(ISD::SHL, dl, TotalVT, Hi,
455                          DAG.getConstant(Lo.getValueType().getSizeInBits(),
456                                          TLI.getPointerTy()));
457         Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, TotalVT, Lo);
458         Val = DAG.getNode(ISD::OR, dl, TotalVT, Lo, Hi);
459       }
460     } else if (ValueVT.isVector()) {
461       // Handle a multi-element vector.
462       MVT IntermediateVT, RegisterVT;
463       unsigned NumIntermediates;
464       unsigned NumRegs =
465         TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
466                                    RegisterVT);
467       assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
468       NumParts = NumRegs; // Silence a compiler warning.
469       assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
470       assert(RegisterVT == Parts[0].getValueType() &&
471              "Part type doesn't match part!");
472
473       // Assemble the parts into intermediate operands.
474       SmallVector<SDValue, 8> Ops(NumIntermediates);
475       if (NumIntermediates == NumParts) {
476         // If the register was not expanded, truncate or copy the value,
477         // as appropriate.
478         for (unsigned i = 0; i != NumParts; ++i)
479           Ops[i] = getCopyFromParts(DAG, dl, &Parts[i], 1,
480                                     PartVT, IntermediateVT);
481       } else if (NumParts > 0) {
482         // If the intermediate type was expanded, build the intermediate operands
483         // from the parts.
484         assert(NumParts % NumIntermediates == 0 &&
485                "Must expand into a divisible number of parts!");
486         unsigned Factor = NumParts / NumIntermediates;
487         for (unsigned i = 0; i != NumIntermediates; ++i)
488           Ops[i] = getCopyFromParts(DAG, dl, &Parts[i * Factor], Factor,
489                                     PartVT, IntermediateVT);
490       }
491
492       // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
493       // operands.
494       Val = DAG.getNode(IntermediateVT.isVector() ?
495                         ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, dl,
496                         ValueVT, &Ops[0], NumIntermediates);
497     } else if (PartVT.isFloatingPoint()) {
498       // FP split into multiple FP parts (for ppcf128)
499       assert(ValueVT == MVT(MVT::ppcf128) && PartVT == MVT(MVT::f64) &&
500              "Unexpected split");
501       SDValue Lo, Hi;
502       Lo = DAG.getNode(ISD::BIT_CONVERT, dl, MVT(MVT::f64), Parts[0]);
503       Hi = DAG.getNode(ISD::BIT_CONVERT, dl, MVT(MVT::f64), Parts[1]);
504       if (TLI.isBigEndian())
505         std::swap(Lo, Hi);
506       Val = DAG.getNode(ISD::BUILD_PAIR, dl, ValueVT, Lo, Hi);
507     } else {
508       // FP split into integer parts (soft fp)
509       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
510              !PartVT.isVector() && "Unexpected split");
511       MVT IntVT = MVT::getIntegerVT(ValueVT.getSizeInBits());
512       Val = getCopyFromParts(DAG, dl, Parts, NumParts, PartVT, IntVT);
513     }
514   }
515
516   // There is now one part, held in Val.  Correct it to match ValueVT.
517   PartVT = Val.getValueType();
518
519   if (PartVT == ValueVT)
520     return Val;
521
522   if (PartVT.isVector()) {
523     assert(ValueVT.isVector() && "Unknown vector conversion!");
524     return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
525   }
526
527   if (ValueVT.isVector()) {
528     assert(ValueVT.getVectorElementType() == PartVT &&
529            ValueVT.getVectorNumElements() == 1 &&
530            "Only trivial scalar-to-vector conversions should get here!");
531     return DAG.getNode(ISD::BUILD_VECTOR, dl, ValueVT, Val);
532   }
533
534   if (PartVT.isInteger() &&
535       ValueVT.isInteger()) {
536     if (ValueVT.bitsLT(PartVT)) {
537       // For a truncate, see if we have any information to
538       // indicate whether the truncated bits will always be
539       // zero or sign-extension.
540       if (AssertOp != ISD::DELETED_NODE)
541         Val = DAG.getNode(AssertOp, dl, PartVT, Val,
542                           DAG.getValueType(ValueVT));
543       return DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
544     } else {
545       return DAG.getNode(ISD::ANY_EXTEND, dl, ValueVT, Val);
546     }
547   }
548
549   if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
550     if (ValueVT.bitsLT(Val.getValueType()))
551       // FP_ROUND's are always exact here.
552       return DAG.getNode(ISD::FP_ROUND, dl, ValueVT, Val,
553                          DAG.getIntPtrConstant(1));
554     return DAG.getNode(ISD::FP_EXTEND, dl, ValueVT, Val);
555   }
556
557   if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
558     return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
559
560   llvm_unreachable("Unknown mismatch!");
561   return SDValue();
562 }
563
564 /// getCopyToParts - Create a series of nodes that contain the specified value
565 /// split into legal parts.  If the parts contain more bits than Val, then, for
566 /// integers, ExtendKind can be used to specify how to generate the extra bits.
567 static void getCopyToParts(SelectionDAG &DAG, DebugLoc dl, SDValue Val,
568                            SDValue *Parts, unsigned NumParts, MVT PartVT,
569                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
570   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
571   MVT PtrVT = TLI.getPointerTy();
572   MVT ValueVT = Val.getValueType();
573   unsigned PartBits = PartVT.getSizeInBits();
574   unsigned OrigNumParts = NumParts;
575   assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
576
577   if (!NumParts)
578     return;
579
580   if (!ValueVT.isVector()) {
581     if (PartVT == ValueVT) {
582       assert(NumParts == 1 && "No-op copy with multiple parts!");
583       Parts[0] = Val;
584       return;
585     }
586
587     if (NumParts * PartBits > ValueVT.getSizeInBits()) {
588       // If the parts cover more bits than the value has, promote the value.
589       if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
590         assert(NumParts == 1 && "Do not know what to promote to!");
591         Val = DAG.getNode(ISD::FP_EXTEND, dl, PartVT, Val);
592       } else if (PartVT.isInteger() && ValueVT.isInteger()) {
593         ValueVT = MVT::getIntegerVT(NumParts * PartBits);
594         Val = DAG.getNode(ExtendKind, dl, ValueVT, Val);
595       } else {
596         llvm_unreachable("Unknown mismatch!");
597       }
598     } else if (PartBits == ValueVT.getSizeInBits()) {
599       // Different types of the same size.
600       assert(NumParts == 1 && PartVT != ValueVT);
601       Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
602     } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
603       // If the parts cover less bits than value has, truncate the value.
604       if (PartVT.isInteger() && ValueVT.isInteger()) {
605         ValueVT = MVT::getIntegerVT(NumParts * PartBits);
606         Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
607       } else {
608         llvm_unreachable("Unknown mismatch!");
609       }
610     }
611
612     // The value may have changed - recompute ValueVT.
613     ValueVT = Val.getValueType();
614     assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
615            "Failed to tile the value with PartVT!");
616
617     if (NumParts == 1) {
618       assert(PartVT == ValueVT && "Type conversion failed!");
619       Parts[0] = Val;
620       return;
621     }
622
623     // Expand the value into multiple parts.
624     if (NumParts & (NumParts - 1)) {
625       // The number of parts is not a power of 2.  Split off and copy the tail.
626       assert(PartVT.isInteger() && ValueVT.isInteger() &&
627              "Do not know what to expand to!");
628       unsigned RoundParts = 1 << Log2_32(NumParts);
629       unsigned RoundBits = RoundParts * PartBits;
630       unsigned OddParts = NumParts - RoundParts;
631       SDValue OddVal = DAG.getNode(ISD::SRL, dl, ValueVT, Val,
632                                    DAG.getConstant(RoundBits,
633                                                    TLI.getPointerTy()));
634       getCopyToParts(DAG, dl, OddVal, Parts + RoundParts, OddParts, PartVT);
635       if (TLI.isBigEndian())
636         // The odd parts were reversed by getCopyToParts - unreverse them.
637         std::reverse(Parts + RoundParts, Parts + NumParts);
638       NumParts = RoundParts;
639       ValueVT = MVT::getIntegerVT(NumParts * PartBits);
640       Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
641     }
642
643     // The number of parts is a power of 2.  Repeatedly bisect the value using
644     // EXTRACT_ELEMENT.
645     Parts[0] = DAG.getNode(ISD::BIT_CONVERT, dl,
646                            MVT::getIntegerVT(ValueVT.getSizeInBits()),
647                            Val);
648     for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
649       for (unsigned i = 0; i < NumParts; i += StepSize) {
650         unsigned ThisBits = StepSize * PartBits / 2;
651         MVT ThisVT = MVT::getIntegerVT (ThisBits);
652         SDValue &Part0 = Parts[i];
653         SDValue &Part1 = Parts[i+StepSize/2];
654
655         Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
656                             ThisVT, Part0,
657                             DAG.getConstant(1, PtrVT));
658         Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
659                             ThisVT, Part0,
660                             DAG.getConstant(0, PtrVT));
661
662         if (ThisBits == PartBits && ThisVT != PartVT) {
663           Part0 = DAG.getNode(ISD::BIT_CONVERT, dl,
664                                                 PartVT, Part0);
665           Part1 = DAG.getNode(ISD::BIT_CONVERT, dl,
666                                                 PartVT, Part1);
667         }
668       }
669     }
670
671     if (TLI.isBigEndian())
672       std::reverse(Parts, Parts + OrigNumParts);
673
674     return;
675   }
676
677   // Vector ValueVT.
678   if (NumParts == 1) {
679     if (PartVT != ValueVT) {
680       if (PartVT.isVector()) {
681         Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
682       } else {
683         assert(ValueVT.getVectorElementType() == PartVT &&
684                ValueVT.getVectorNumElements() == 1 &&
685                "Only trivial vector-to-scalar conversions should get here!");
686         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
687                           PartVT, Val,
688                           DAG.getConstant(0, PtrVT));
689       }
690     }
691
692     Parts[0] = Val;
693     return;
694   }
695
696   // Handle a multi-element vector.
697   MVT IntermediateVT, RegisterVT;
698   unsigned NumIntermediates;
699   unsigned NumRegs = TLI
700       .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
701                               RegisterVT);
702   unsigned NumElements = ValueVT.getVectorNumElements();
703
704   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
705   NumParts = NumRegs; // Silence a compiler warning.
706   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
707
708   // Split the vector into intermediate operands.
709   SmallVector<SDValue, 8> Ops(NumIntermediates);
710   for (unsigned i = 0; i != NumIntermediates; ++i)
711     if (IntermediateVT.isVector())
712       Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl,
713                            IntermediateVT, Val,
714                            DAG.getConstant(i * (NumElements / NumIntermediates),
715                                            PtrVT));
716     else
717       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
718                            IntermediateVT, Val,
719                            DAG.getConstant(i, PtrVT));
720
721   // Split the intermediate operands into legal parts.
722   if (NumParts == NumIntermediates) {
723     // If the register was not expanded, promote or copy the value,
724     // as appropriate.
725     for (unsigned i = 0; i != NumParts; ++i)
726       getCopyToParts(DAG, dl, Ops[i], &Parts[i], 1, PartVT);
727   } else if (NumParts > 0) {
728     // If the intermediate type was expanded, split each the value into
729     // legal parts.
730     assert(NumParts % NumIntermediates == 0 &&
731            "Must expand into a divisible number of parts!");
732     unsigned Factor = NumParts / NumIntermediates;
733     for (unsigned i = 0; i != NumIntermediates; ++i)
734       getCopyToParts(DAG, dl, Ops[i], &Parts[i * Factor], Factor, PartVT);
735   }
736 }
737
738
739 void SelectionDAGLowering::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
740   AA = &aa;
741   GFI = gfi;
742   TD = DAG.getTarget().getTargetData();
743 }
744
745 /// clear - Clear out the curret SelectionDAG and the associated
746 /// state and prepare this SelectionDAGLowering object to be used
747 /// for a new block. This doesn't clear out information about
748 /// additional blocks that are needed to complete switch lowering
749 /// or PHI node updating; that information is cleared out as it is
750 /// consumed.
751 void SelectionDAGLowering::clear() {
752   NodeMap.clear();
753   PendingLoads.clear();
754   PendingExports.clear();
755   DAG.clear();
756   CurDebugLoc = DebugLoc::getUnknownLoc();
757   HasTailCall = false;
758 }
759
760 /// getRoot - Return the current virtual root of the Selection DAG,
761 /// flushing any PendingLoad items. This must be done before emitting
762 /// a store or any other node that may need to be ordered after any
763 /// prior load instructions.
764 ///
765 SDValue SelectionDAGLowering::getRoot() {
766   if (PendingLoads.empty())
767     return DAG.getRoot();
768
769   if (PendingLoads.size() == 1) {
770     SDValue Root = PendingLoads[0];
771     DAG.setRoot(Root);
772     PendingLoads.clear();
773     return Root;
774   }
775
776   // Otherwise, we have to make a token factor node.
777   SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
778                                &PendingLoads[0], PendingLoads.size());
779   PendingLoads.clear();
780   DAG.setRoot(Root);
781   return Root;
782 }
783
784 /// getControlRoot - Similar to getRoot, but instead of flushing all the
785 /// PendingLoad items, flush all the PendingExports items. It is necessary
786 /// to do this before emitting a terminator instruction.
787 ///
788 SDValue SelectionDAGLowering::getControlRoot() {
789   SDValue Root = DAG.getRoot();
790
791   if (PendingExports.empty())
792     return Root;
793
794   // Turn all of the CopyToReg chains into one factored node.
795   if (Root.getOpcode() != ISD::EntryToken) {
796     unsigned i = 0, e = PendingExports.size();
797     for (; i != e; ++i) {
798       assert(PendingExports[i].getNode()->getNumOperands() > 1);
799       if (PendingExports[i].getNode()->getOperand(0) == Root)
800         break;  // Don't add the root if we already indirectly depend on it.
801     }
802
803     if (i == e)
804       PendingExports.push_back(Root);
805   }
806
807   Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
808                      &PendingExports[0],
809                      PendingExports.size());
810   PendingExports.clear();
811   DAG.setRoot(Root);
812   return Root;
813 }
814
815 void SelectionDAGLowering::visit(Instruction &I) {
816   visit(I.getOpcode(), I);
817 }
818
819 void SelectionDAGLowering::visit(unsigned Opcode, User &I) {
820   // Note: this doesn't use InstVisitor, because it has to work with
821   // ConstantExpr's in addition to instructions.
822   switch (Opcode) {
823   default: llvm_unreachable("Unknown instruction type encountered!");
824     // Build the switch statement using the Instruction.def file.
825 #define HANDLE_INST(NUM, OPCODE, CLASS) \
826   case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
827 #include "llvm/Instruction.def"
828   }
829 }
830
831 SDValue SelectionDAGLowering::getValue(const Value *V) {
832   SDValue &N = NodeMap[V];
833   if (N.getNode()) return N;
834
835   if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
836     MVT VT = TLI.getValueType(V->getType(), true);
837
838     if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
839       return N = DAG.getConstant(*CI, VT);
840
841     if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
842       return N = DAG.getGlobalAddress(GV, VT);
843
844     if (isa<ConstantPointerNull>(C))
845       return N = DAG.getConstant(0, TLI.getPointerTy());
846
847     if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
848       return N = DAG.getConstantFP(*CFP, VT);
849
850     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
851       return N = DAG.getUNDEF(VT);
852
853     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
854       visit(CE->getOpcode(), *CE);
855       SDValue N1 = NodeMap[V];
856       assert(N1.getNode() && "visit didn't populate the ValueMap!");
857       return N1;
858     }
859
860     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
861       SmallVector<SDValue, 4> Constants;
862       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
863            OI != OE; ++OI) {
864         SDNode *Val = getValue(*OI).getNode();
865         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
866           Constants.push_back(SDValue(Val, i));
867       }
868       return DAG.getMergeValues(&Constants[0], Constants.size(),
869                                 getCurDebugLoc());
870     }
871
872     if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
873       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
874              "Unknown struct or array constant!");
875
876       SmallVector<MVT, 4> ValueVTs;
877       ComputeValueVTs(TLI, C->getType(), ValueVTs);
878       unsigned NumElts = ValueVTs.size();
879       if (NumElts == 0)
880         return SDValue(); // empty struct
881       SmallVector<SDValue, 4> Constants(NumElts);
882       for (unsigned i = 0; i != NumElts; ++i) {
883         MVT EltVT = ValueVTs[i];
884         if (isa<UndefValue>(C))
885           Constants[i] = DAG.getUNDEF(EltVT);
886         else if (EltVT.isFloatingPoint())
887           Constants[i] = DAG.getConstantFP(0, EltVT);
888         else
889           Constants[i] = DAG.getConstant(0, EltVT);
890       }
891       return DAG.getMergeValues(&Constants[0], NumElts, getCurDebugLoc());
892     }
893
894     const VectorType *VecTy = cast<VectorType>(V->getType());
895     unsigned NumElements = VecTy->getNumElements();
896
897     // Now that we know the number and type of the elements, get that number of
898     // elements into the Ops array based on what kind of constant it is.
899     SmallVector<SDValue, 16> Ops;
900     if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
901       for (unsigned i = 0; i != NumElements; ++i)
902         Ops.push_back(getValue(CP->getOperand(i)));
903     } else {
904       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
905       MVT EltVT = TLI.getValueType(VecTy->getElementType());
906
907       SDValue Op;
908       if (EltVT.isFloatingPoint())
909         Op = DAG.getConstantFP(0, EltVT);
910       else
911         Op = DAG.getConstant(0, EltVT);
912       Ops.assign(NumElements, Op);
913     }
914
915     // Create a BUILD_VECTOR node.
916     return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
917                                     VT, &Ops[0], Ops.size());
918   }
919
920   // If this is a static alloca, generate it as the frameindex instead of
921   // computation.
922   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
923     DenseMap<const AllocaInst*, int>::iterator SI =
924       FuncInfo.StaticAllocaMap.find(AI);
925     if (SI != FuncInfo.StaticAllocaMap.end())
926       return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
927   }
928
929   unsigned InReg = FuncInfo.ValueMap[V];
930   assert(InReg && "Value not in map!");
931
932   RegsForValue RFV(TLI, InReg, V->getType());
933   SDValue Chain = DAG.getEntryNode();
934   return RFV.getCopyFromRegs(DAG, getCurDebugLoc(), Chain, NULL);
935 }
936
937
938 void SelectionDAGLowering::visitRet(ReturnInst &I) {
939   SDValue Chain = getControlRoot();
940   SmallVector<ISD::OutputArg, 8> Outs;
941   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
942     SmallVector<MVT, 4> ValueVTs;
943     ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
944     unsigned NumValues = ValueVTs.size();
945     if (NumValues == 0) continue;
946
947     SDValue RetOp = getValue(I.getOperand(i));
948     for (unsigned j = 0, f = NumValues; j != f; ++j) {
949       MVT VT = ValueVTs[j];
950
951       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
952
953       const Function *F = I.getParent()->getParent();
954       if (F->paramHasAttr(0, Attribute::SExt))
955         ExtendKind = ISD::SIGN_EXTEND;
956       else if (F->paramHasAttr(0, Attribute::ZExt))
957         ExtendKind = ISD::ZERO_EXTEND;
958
959       // FIXME: C calling convention requires the return type to be promoted to
960       // at least 32-bit. But this is not necessary for non-C calling
961       // conventions. The frontend should mark functions whose return values
962       // require promoting with signext or zeroext attributes.
963       if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
964         MVT MinVT = TLI.getRegisterType(MVT::i32);
965         if (VT.bitsLT(MinVT))
966           VT = MinVT;
967       }
968
969       unsigned NumParts = TLI.getNumRegisters(VT);
970       MVT PartVT = TLI.getRegisterType(VT);
971       SmallVector<SDValue, 4> Parts(NumParts);
972       getCopyToParts(DAG, getCurDebugLoc(),
973                      SDValue(RetOp.getNode(), RetOp.getResNo() + j),
974                      &Parts[0], NumParts, PartVT, ExtendKind);
975
976       // 'inreg' on function refers to return value
977       ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
978       if (F->paramHasAttr(0, Attribute::InReg))
979         Flags.setInReg();
980
981       // Propagate extension type if any
982       if (F->paramHasAttr(0, Attribute::SExt))
983         Flags.setSExt();
984       else if (F->paramHasAttr(0, Attribute::ZExt))
985         Flags.setZExt();
986
987       for (unsigned i = 0; i < NumParts; ++i)
988         Outs.push_back(ISD::OutputArg(Flags, Parts[i], /*isfixed=*/true));
989     }
990   }
991
992   bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
993   unsigned CallConv = DAG.getMachineFunction().getFunction()->getCallingConv();
994   Chain = TLI.LowerReturn(Chain, CallConv, isVarArg,
995                           Outs, getCurDebugLoc(), DAG);
996   DAG.setRoot(Chain);
997 }
998
999 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1000 /// created for it, emit nodes to copy the value into the virtual
1001 /// registers.
1002 void SelectionDAGLowering::CopyToExportRegsIfNeeded(Value *V) {
1003   if (!V->use_empty()) {
1004     DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1005     if (VMI != FuncInfo.ValueMap.end())
1006       CopyValueToVirtualRegister(V, VMI->second);
1007   }
1008 }
1009
1010 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1011 /// the current basic block, add it to ValueMap now so that we'll get a
1012 /// CopyTo/FromReg.
1013 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1014   // No need to export constants.
1015   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1016
1017   // Already exported?
1018   if (FuncInfo.isExportedInst(V)) return;
1019
1020   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1021   CopyValueToVirtualRegister(V, Reg);
1022 }
1023
1024 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1025                                                     const BasicBlock *FromBB) {
1026   // The operands of the setcc have to be in this block.  We don't know
1027   // how to export them from some other block.
1028   if (Instruction *VI = dyn_cast<Instruction>(V)) {
1029     // Can export from current BB.
1030     if (VI->getParent() == FromBB)
1031       return true;
1032
1033     // Is already exported, noop.
1034     return FuncInfo.isExportedInst(V);
1035   }
1036
1037   // If this is an argument, we can export it if the BB is the entry block or
1038   // if it is already exported.
1039   if (isa<Argument>(V)) {
1040     if (FromBB == &FromBB->getParent()->getEntryBlock())
1041       return true;
1042
1043     // Otherwise, can only export this if it is already exported.
1044     return FuncInfo.isExportedInst(V);
1045   }
1046
1047   // Otherwise, constants can always be exported.
1048   return true;
1049 }
1050
1051 static bool InBlock(const Value *V, const BasicBlock *BB) {
1052   if (const Instruction *I = dyn_cast<Instruction>(V))
1053     return I->getParent() == BB;
1054   return true;
1055 }
1056
1057 /// getFCmpCondCode - Return the ISD condition code corresponding to
1058 /// the given LLVM IR floating-point condition code.  This includes
1059 /// consideration of global floating-point math flags.
1060 ///
1061 static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
1062   ISD::CondCode FPC, FOC;
1063   switch (Pred) {
1064   case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1065   case FCmpInst::FCMP_OEQ:   FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1066   case FCmpInst::FCMP_OGT:   FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1067   case FCmpInst::FCMP_OGE:   FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1068   case FCmpInst::FCMP_OLT:   FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1069   case FCmpInst::FCMP_OLE:   FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1070   case FCmpInst::FCMP_ONE:   FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1071   case FCmpInst::FCMP_ORD:   FOC = FPC = ISD::SETO;   break;
1072   case FCmpInst::FCMP_UNO:   FOC = FPC = ISD::SETUO;  break;
1073   case FCmpInst::FCMP_UEQ:   FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1074   case FCmpInst::FCMP_UGT:   FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1075   case FCmpInst::FCMP_UGE:   FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1076   case FCmpInst::FCMP_ULT:   FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1077   case FCmpInst::FCMP_ULE:   FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1078   case FCmpInst::FCMP_UNE:   FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1079   case FCmpInst::FCMP_TRUE:  FOC = FPC = ISD::SETTRUE; break;
1080   default:
1081     llvm_unreachable("Invalid FCmp predicate opcode!");
1082     FOC = FPC = ISD::SETFALSE;
1083     break;
1084   }
1085   if (FiniteOnlyFPMath())
1086     return FOC;
1087   else
1088     return FPC;
1089 }
1090
1091 /// getICmpCondCode - Return the ISD condition code corresponding to
1092 /// the given LLVM IR integer condition code.
1093 ///
1094 static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
1095   switch (Pred) {
1096   case ICmpInst::ICMP_EQ:  return ISD::SETEQ;
1097   case ICmpInst::ICMP_NE:  return ISD::SETNE;
1098   case ICmpInst::ICMP_SLE: return ISD::SETLE;
1099   case ICmpInst::ICMP_ULE: return ISD::SETULE;
1100   case ICmpInst::ICMP_SGE: return ISD::SETGE;
1101   case ICmpInst::ICMP_UGE: return ISD::SETUGE;
1102   case ICmpInst::ICMP_SLT: return ISD::SETLT;
1103   case ICmpInst::ICMP_ULT: return ISD::SETULT;
1104   case ICmpInst::ICMP_SGT: return ISD::SETGT;
1105   case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1106   default:
1107     llvm_unreachable("Invalid ICmp predicate opcode!");
1108     return ISD::SETNE;
1109   }
1110 }
1111
1112 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1113 /// This function emits a branch and is used at the leaves of an OR or an
1114 /// AND operator tree.
1115 ///
1116 void
1117 SelectionDAGLowering::EmitBranchForMergedCondition(Value *Cond,
1118                                                    MachineBasicBlock *TBB,
1119                                                    MachineBasicBlock *FBB,
1120                                                    MachineBasicBlock *CurBB) {
1121   const BasicBlock *BB = CurBB->getBasicBlock();
1122
1123   // If the leaf of the tree is a comparison, merge the condition into
1124   // the caseblock.
1125   if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1126     // The operands of the cmp have to be in this block.  We don't know
1127     // how to export them from some other block.  If this is the first block
1128     // of the sequence, no exporting is needed.
1129     if (CurBB == CurMBB ||
1130         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1131          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1132       ISD::CondCode Condition;
1133       if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1134         Condition = getICmpCondCode(IC->getPredicate());
1135       } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1136         Condition = getFCmpCondCode(FC->getPredicate());
1137       } else {
1138         Condition = ISD::SETEQ; // silence warning.
1139         llvm_unreachable("Unknown compare instruction");
1140       }
1141
1142       CaseBlock CB(Condition, BOp->getOperand(0),
1143                    BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1144       SwitchCases.push_back(CB);
1145       return;
1146     }
1147   }
1148
1149   // Create a CaseBlock record representing this branch.
1150   CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
1151                NULL, TBB, FBB, CurBB);
1152   SwitchCases.push_back(CB);
1153 }
1154
1155 /// FindMergedConditions - If Cond is an expression like
1156 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1157                                                 MachineBasicBlock *TBB,
1158                                                 MachineBasicBlock *FBB,
1159                                                 MachineBasicBlock *CurBB,
1160                                                 unsigned Opc) {
1161   // If this node is not part of the or/and tree, emit it as a branch.
1162   Instruction *BOp = dyn_cast<Instruction>(Cond);
1163   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1164       (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1165       BOp->getParent() != CurBB->getBasicBlock() ||
1166       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1167       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1168     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
1169     return;
1170   }
1171
1172   //  Create TmpBB after CurBB.
1173   MachineFunction::iterator BBI = CurBB;
1174   MachineFunction &MF = DAG.getMachineFunction();
1175   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1176   CurBB->getParent()->insert(++BBI, TmpBB);
1177
1178   if (Opc == Instruction::Or) {
1179     // Codegen X | Y as:
1180     //   jmp_if_X TBB
1181     //   jmp TmpBB
1182     // TmpBB:
1183     //   jmp_if_Y TBB
1184     //   jmp FBB
1185     //
1186
1187     // Emit the LHS condition.
1188     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1189
1190     // Emit the RHS condition into TmpBB.
1191     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1192   } else {
1193     assert(Opc == Instruction::And && "Unknown merge op!");
1194     // Codegen X & Y as:
1195     //   jmp_if_X TmpBB
1196     //   jmp FBB
1197     // TmpBB:
1198     //   jmp_if_Y TBB
1199     //   jmp FBB
1200     //
1201     //  This requires creation of TmpBB after CurBB.
1202
1203     // Emit the LHS condition.
1204     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1205
1206     // Emit the RHS condition into TmpBB.
1207     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1208   }
1209 }
1210
1211 /// If the set of cases should be emitted as a series of branches, return true.
1212 /// If we should emit this as a bunch of and/or'd together conditions, return
1213 /// false.
1214 bool
1215 SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1216   if (Cases.size() != 2) return true;
1217
1218   // If this is two comparisons of the same values or'd or and'd together, they
1219   // will get folded into a single comparison, so don't emit two blocks.
1220   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1221        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1222       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1223        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1224     return false;
1225   }
1226
1227   return true;
1228 }
1229
1230 void SelectionDAGLowering::visitBr(BranchInst &I) {
1231   // Update machine-CFG edges.
1232   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1233
1234   // Figure out which block is immediately after the current one.
1235   MachineBasicBlock *NextBlock = 0;
1236   MachineFunction::iterator BBI = CurMBB;
1237   if (++BBI != CurMBB->getParent()->end())
1238     NextBlock = BBI;
1239
1240   if (I.isUnconditional()) {
1241     // Update machine-CFG edges.
1242     CurMBB->addSuccessor(Succ0MBB);
1243
1244     // If this is not a fall-through branch, emit the branch.
1245     if (Succ0MBB != NextBlock)
1246       DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1247                               MVT::Other, getControlRoot(),
1248                               DAG.getBasicBlock(Succ0MBB)));
1249     return;
1250   }
1251
1252   // If this condition is one of the special cases we handle, do special stuff
1253   // now.
1254   Value *CondVal = I.getCondition();
1255   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1256
1257   // If this is a series of conditions that are or'd or and'd together, emit
1258   // this as a sequence of branches instead of setcc's with and/or operations.
1259   // For example, instead of something like:
1260   //     cmp A, B
1261   //     C = seteq
1262   //     cmp D, E
1263   //     F = setle
1264   //     or C, F
1265   //     jnz foo
1266   // Emit:
1267   //     cmp A, B
1268   //     je foo
1269   //     cmp D, E
1270   //     jle foo
1271   //
1272   if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1273     if (BOp->hasOneUse() &&
1274         (BOp->getOpcode() == Instruction::And ||
1275          BOp->getOpcode() == Instruction::Or)) {
1276       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1277       // If the compares in later blocks need to use values not currently
1278       // exported from this block, export them now.  This block should always
1279       // be the first entry.
1280       assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1281
1282       // Allow some cases to be rejected.
1283       if (ShouldEmitAsBranches(SwitchCases)) {
1284         for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1285           ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1286           ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1287         }
1288
1289         // Emit the branch for this block.
1290         visitSwitchCase(SwitchCases[0]);
1291         SwitchCases.erase(SwitchCases.begin());
1292         return;
1293       }
1294
1295       // Okay, we decided not to do this, remove any inserted MBB's and clear
1296       // SwitchCases.
1297       for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1298         CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
1299
1300       SwitchCases.clear();
1301     }
1302   }
1303
1304   // Create a CaseBlock record representing this branch.
1305   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1306                NULL, Succ0MBB, Succ1MBB, CurMBB);
1307   // Use visitSwitchCase to actually insert the fast branch sequence for this
1308   // cond branch.
1309   visitSwitchCase(CB);
1310 }
1311
1312 /// visitSwitchCase - Emits the necessary code to represent a single node in
1313 /// the binary search tree resulting from lowering a switch instruction.
1314 void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
1315   SDValue Cond;
1316   SDValue CondLHS = getValue(CB.CmpLHS);
1317   DebugLoc dl = getCurDebugLoc();
1318
1319   // Build the setcc now.
1320   if (CB.CmpMHS == NULL) {
1321     // Fold "(X == true)" to X and "(X == false)" to !X to
1322     // handle common cases produced by branch lowering.
1323     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1324         CB.CC == ISD::SETEQ)
1325       Cond = CondLHS;
1326     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1327              CB.CC == ISD::SETEQ) {
1328       SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1329       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1330     } else
1331       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1332   } else {
1333     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1334
1335     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1336     const APInt& High  = cast<ConstantInt>(CB.CmpRHS)->getValue();
1337
1338     SDValue CmpOp = getValue(CB.CmpMHS);
1339     MVT VT = CmpOp.getValueType();
1340
1341     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1342       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
1343                           ISD::SETLE);
1344     } else {
1345       SDValue SUB = DAG.getNode(ISD::SUB, dl,
1346                                 VT, CmpOp, DAG.getConstant(Low, VT));
1347       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1348                           DAG.getConstant(High-Low, VT), ISD::SETULE);
1349     }
1350   }
1351
1352   // Update successor info
1353   CurMBB->addSuccessor(CB.TrueBB);
1354   CurMBB->addSuccessor(CB.FalseBB);
1355
1356   // Set NextBlock to be the MBB immediately after the current one, if any.
1357   // This is used to avoid emitting unnecessary branches to the next block.
1358   MachineBasicBlock *NextBlock = 0;
1359   MachineFunction::iterator BBI = CurMBB;
1360   if (++BBI != CurMBB->getParent()->end())
1361     NextBlock = BBI;
1362
1363   // If the lhs block is the next block, invert the condition so that we can
1364   // fall through to the lhs instead of the rhs block.
1365   if (CB.TrueBB == NextBlock) {
1366     std::swap(CB.TrueBB, CB.FalseBB);
1367     SDValue True = DAG.getConstant(1, Cond.getValueType());
1368     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1369   }
1370   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1371                                MVT::Other, getControlRoot(), Cond,
1372                                DAG.getBasicBlock(CB.TrueBB));
1373
1374   // If the branch was constant folded, fix up the CFG.
1375   if (BrCond.getOpcode() == ISD::BR) {
1376     CurMBB->removeSuccessor(CB.FalseBB);
1377     DAG.setRoot(BrCond);
1378   } else {
1379     // Otherwise, go ahead and insert the false branch.
1380     if (BrCond == getControlRoot())
1381       CurMBB->removeSuccessor(CB.TrueBB);
1382
1383     if (CB.FalseBB == NextBlock)
1384       DAG.setRoot(BrCond);
1385     else
1386       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1387                               DAG.getBasicBlock(CB.FalseBB)));
1388   }
1389 }
1390
1391 /// visitJumpTable - Emit JumpTable node in the current MBB
1392 void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
1393   // Emit the code for the jump table
1394   assert(JT.Reg != -1U && "Should lower JT Header first!");
1395   MVT PTy = TLI.getPointerTy();
1396   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1397                                      JT.Reg, PTy);
1398   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1399   DAG.setRoot(DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
1400                           MVT::Other, Index.getValue(1),
1401                           Table, Index));
1402 }
1403
1404 /// visitJumpTableHeader - This function emits necessary code to produce index
1405 /// in the JumpTable from switch case.
1406 void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
1407                                                 JumpTableHeader &JTH) {
1408   // Subtract the lowest switch case value from the value being switched on and
1409   // conditional branch to default mbb if the result is greater than the
1410   // difference between smallest and largest cases.
1411   SDValue SwitchOp = getValue(JTH.SValue);
1412   MVT VT = SwitchOp.getValueType();
1413   SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1414                             DAG.getConstant(JTH.First, VT));
1415
1416   // The SDNode we just created, which holds the value being switched on minus
1417   // the the smallest case value, needs to be copied to a virtual register so it
1418   // can be used as an index into the jump table in a subsequent basic block.
1419   // This value may be smaller or larger than the target's pointer type, and
1420   // therefore require extension or truncating.
1421   if (VT.bitsGT(TLI.getPointerTy()))
1422     SwitchOp = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
1423                            TLI.getPointerTy(), SUB);
1424   else
1425     SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
1426                            TLI.getPointerTy(), SUB);
1427
1428   unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1429   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1430                                     JumpTableReg, SwitchOp);
1431   JT.Reg = JumpTableReg;
1432
1433   // Emit the range check for the jump table, and branch to the default block
1434   // for the switch statement if the value being switched on exceeds the largest
1435   // case in the switch.
1436   SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
1437                              TLI.getSetCCResultType(SUB.getValueType()), SUB,
1438                              DAG.getConstant(JTH.Last-JTH.First,VT),
1439                              ISD::SETUGT);
1440
1441   // Set NextBlock to be the MBB immediately after the current one, if any.
1442   // This is used to avoid emitting unnecessary branches to the next block.
1443   MachineBasicBlock *NextBlock = 0;
1444   MachineFunction::iterator BBI = CurMBB;
1445   if (++BBI != CurMBB->getParent()->end())
1446     NextBlock = BBI;
1447
1448   SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1449                                MVT::Other, CopyTo, CMP,
1450                                DAG.getBasicBlock(JT.Default));
1451
1452   if (JT.MBB == NextBlock)
1453     DAG.setRoot(BrCond);
1454   else
1455     DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
1456                             DAG.getBasicBlock(JT.MBB)));
1457 }
1458
1459 /// visitBitTestHeader - This function emits necessary code to produce value
1460 /// suitable for "bit tests"
1461 void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
1462   // Subtract the minimum value
1463   SDValue SwitchOp = getValue(B.SValue);
1464   MVT VT = SwitchOp.getValueType();
1465   SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1466                             DAG.getConstant(B.First, VT));
1467
1468   // Check range
1469   SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
1470                                   TLI.getSetCCResultType(SUB.getValueType()),
1471                                   SUB, DAG.getConstant(B.Range, VT),
1472                                   ISD::SETUGT);
1473
1474   SDValue ShiftOp;
1475   if (VT.bitsGT(TLI.getPointerTy()))
1476     ShiftOp = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
1477                           TLI.getPointerTy(), SUB);
1478   else
1479     ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
1480                           TLI.getPointerTy(), SUB);
1481
1482   B.Reg = FuncInfo.MakeReg(TLI.getPointerTy());
1483   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1484                                     B.Reg, ShiftOp);
1485
1486   // Set NextBlock to be the MBB immediately after the current one, if any.
1487   // This is used to avoid emitting unnecessary branches to the next block.
1488   MachineBasicBlock *NextBlock = 0;
1489   MachineFunction::iterator BBI = CurMBB;
1490   if (++BBI != CurMBB->getParent()->end())
1491     NextBlock = BBI;
1492
1493   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1494
1495   CurMBB->addSuccessor(B.Default);
1496   CurMBB->addSuccessor(MBB);
1497
1498   SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1499                                 MVT::Other, CopyTo, RangeCmp,
1500                                 DAG.getBasicBlock(B.Default));
1501
1502   if (MBB == NextBlock)
1503     DAG.setRoot(BrRange);
1504   else
1505     DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
1506                             DAG.getBasicBlock(MBB)));
1507 }
1508
1509 /// visitBitTestCase - this function produces one "bit test"
1510 void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1511                                             unsigned Reg,
1512                                             BitTestCase &B) {
1513   // Make desired shift
1514   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), Reg,
1515                                        TLI.getPointerTy());
1516   SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(),
1517                                   TLI.getPointerTy(),
1518                                   DAG.getConstant(1, TLI.getPointerTy()),
1519                                   ShiftOp);
1520
1521   // Emit bit tests and jumps
1522   SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
1523                               TLI.getPointerTy(), SwitchVal,
1524                               DAG.getConstant(B.Mask, TLI.getPointerTy()));
1525   SDValue AndCmp = DAG.getSetCC(getCurDebugLoc(),
1526                                 TLI.getSetCCResultType(AndOp.getValueType()),
1527                                 AndOp, DAG.getConstant(0, TLI.getPointerTy()),
1528                                 ISD::SETNE);
1529
1530   CurMBB->addSuccessor(B.TargetBB);
1531   CurMBB->addSuccessor(NextMBB);
1532
1533   SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1534                               MVT::Other, getControlRoot(),
1535                               AndCmp, DAG.getBasicBlock(B.TargetBB));
1536
1537   // Set NextBlock to be the MBB immediately after the current one, if any.
1538   // This is used to avoid emitting unnecessary branches to the next block.
1539   MachineBasicBlock *NextBlock = 0;
1540   MachineFunction::iterator BBI = CurMBB;
1541   if (++BBI != CurMBB->getParent()->end())
1542     NextBlock = BBI;
1543
1544   if (NextMBB == NextBlock)
1545     DAG.setRoot(BrAnd);
1546   else
1547     DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
1548                             DAG.getBasicBlock(NextMBB)));
1549 }
1550
1551 void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1552   // Retrieve successors.
1553   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1554   MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1555
1556   const Value *Callee(I.getCalledValue());
1557   if (isa<InlineAsm>(Callee))
1558     visitInlineAsm(&I);
1559   else
1560     LowerCallTo(&I, getValue(Callee), false, LandingPad);
1561
1562   // If the value of the invoke is used outside of its defining block, make it
1563   // available as a virtual register.
1564   CopyToExportRegsIfNeeded(&I);
1565
1566   // Update successor info
1567   CurMBB->addSuccessor(Return);
1568   CurMBB->addSuccessor(LandingPad);
1569
1570   // Drop into normal successor.
1571   DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1572                           MVT::Other, getControlRoot(),
1573                           DAG.getBasicBlock(Return)));
1574 }
1575
1576 void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1577 }
1578
1579 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1580 /// small case ranges).
1581 bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1582                                                   CaseRecVector& WorkList,
1583                                                   Value* SV,
1584                                                   MachineBasicBlock* Default) {
1585   Case& BackCase  = *(CR.Range.second-1);
1586
1587   // Size is the number of Cases represented by this range.
1588   size_t Size = CR.Range.second - CR.Range.first;
1589   if (Size > 3)
1590     return false;
1591
1592   // Get the MachineFunction which holds the current MBB.  This is used when
1593   // inserting any additional MBBs necessary to represent the switch.
1594   MachineFunction *CurMF = CurMBB->getParent();
1595
1596   // Figure out which block is immediately after the current one.
1597   MachineBasicBlock *NextBlock = 0;
1598   MachineFunction::iterator BBI = CR.CaseBB;
1599
1600   if (++BBI != CurMBB->getParent()->end())
1601     NextBlock = BBI;
1602
1603   // TODO: If any two of the cases has the same destination, and if one value
1604   // is the same as the other, but has one bit unset that the other has set,
1605   // use bit manipulation to do two compares at once.  For example:
1606   // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1607
1608   // Rearrange the case blocks so that the last one falls through if possible.
1609   if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1610     // The last case block won't fall through into 'NextBlock' if we emit the
1611     // branches in this order.  See if rearranging a case value would help.
1612     for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1613       if (I->BB == NextBlock) {
1614         std::swap(*I, BackCase);
1615         break;
1616       }
1617     }
1618   }
1619
1620   // Create a CaseBlock record representing a conditional branch to
1621   // the Case's target mbb if the value being switched on SV is equal
1622   // to C.
1623   MachineBasicBlock *CurBlock = CR.CaseBB;
1624   for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1625     MachineBasicBlock *FallThrough;
1626     if (I != E-1) {
1627       FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1628       CurMF->insert(BBI, FallThrough);
1629
1630       // Put SV in a virtual register to make it available from the new blocks.
1631       ExportFromCurrentBlock(SV);
1632     } else {
1633       // If the last case doesn't match, go to the default block.
1634       FallThrough = Default;
1635     }
1636
1637     Value *RHS, *LHS, *MHS;
1638     ISD::CondCode CC;
1639     if (I->High == I->Low) {
1640       // This is just small small case range :) containing exactly 1 case
1641       CC = ISD::SETEQ;
1642       LHS = SV; RHS = I->High; MHS = NULL;
1643     } else {
1644       CC = ISD::SETLE;
1645       LHS = I->Low; MHS = SV; RHS = I->High;
1646     }
1647     CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
1648
1649     // If emitting the first comparison, just call visitSwitchCase to emit the
1650     // code into the current block.  Otherwise, push the CaseBlock onto the
1651     // vector to be later processed by SDISel, and insert the node's MBB
1652     // before the next MBB.
1653     if (CurBlock == CurMBB)
1654       visitSwitchCase(CB);
1655     else
1656       SwitchCases.push_back(CB);
1657
1658     CurBlock = FallThrough;
1659   }
1660
1661   return true;
1662 }
1663
1664 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1665   return !DisableJumpTables &&
1666           (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1667            TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
1668 }
1669
1670 static APInt ComputeRange(const APInt &First, const APInt &Last) {
1671   APInt LastExt(Last), FirstExt(First);
1672   uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1673   LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1674   return (LastExt - FirstExt + 1ULL);
1675 }
1676
1677 /// handleJTSwitchCase - Emit jumptable for current switch case range
1678 bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1679                                               CaseRecVector& WorkList,
1680                                               Value* SV,
1681                                               MachineBasicBlock* Default) {
1682   Case& FrontCase = *CR.Range.first;
1683   Case& BackCase  = *(CR.Range.second-1);
1684
1685   const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1686   const APInt& Last  = cast<ConstantInt>(BackCase.High)->getValue();
1687
1688   size_t TSize = 0;
1689   for (CaseItr I = CR.Range.first, E = CR.Range.second;
1690        I!=E; ++I)
1691     TSize += I->size();
1692
1693   if (!areJTsAllowed(TLI) || TSize <= 3)
1694     return false;
1695
1696   APInt Range = ComputeRange(First, Last);
1697   double Density = (double)TSize / Range.roundToDouble();
1698   if (Density < 0.4)
1699     return false;
1700
1701   DEBUG(errs() << "Lowering jump table\n"
1702                << "First entry: " << First << ". Last entry: " << Last << '\n'
1703                << "Range: " << Range
1704                << "Size: " << TSize << ". Density: " << Density << "\n\n");
1705
1706   // Get the MachineFunction which holds the current MBB.  This is used when
1707   // inserting any additional MBBs necessary to represent the switch.
1708   MachineFunction *CurMF = CurMBB->getParent();
1709
1710   // Figure out which block is immediately after the current one.
1711   MachineBasicBlock *NextBlock = 0;
1712   MachineFunction::iterator BBI = CR.CaseBB;
1713
1714   if (++BBI != CurMBB->getParent()->end())
1715     NextBlock = BBI;
1716
1717   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1718
1719   // Create a new basic block to hold the code for loading the address
1720   // of the jump table, and jumping to it.  Update successor information;
1721   // we will either branch to the default case for the switch, or the jump
1722   // table.
1723   MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1724   CurMF->insert(BBI, JumpTableBB);
1725   CR.CaseBB->addSuccessor(Default);
1726   CR.CaseBB->addSuccessor(JumpTableBB);
1727
1728   // Build a vector of destination BBs, corresponding to each target
1729   // of the jump table. If the value of the jump table slot corresponds to
1730   // a case statement, push the case's BB onto the vector, otherwise, push
1731   // the default BB.
1732   std::vector<MachineBasicBlock*> DestBBs;
1733   APInt TEI = First;
1734   for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1735     const APInt& Low = cast<ConstantInt>(I->Low)->getValue();
1736     const APInt& High = cast<ConstantInt>(I->High)->getValue();
1737
1738     if (Low.sle(TEI) && TEI.sle(High)) {
1739       DestBBs.push_back(I->BB);
1740       if (TEI==High)
1741         ++I;
1742     } else {
1743       DestBBs.push_back(Default);
1744     }
1745   }
1746
1747   // Update successor info. Add one edge to each unique successor.
1748   BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1749   for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1750          E = DestBBs.end(); I != E; ++I) {
1751     if (!SuccsHandled[(*I)->getNumber()]) {
1752       SuccsHandled[(*I)->getNumber()] = true;
1753       JumpTableBB->addSuccessor(*I);
1754     }
1755   }
1756
1757   // Create a jump table index for this jump table, or return an existing
1758   // one.
1759   unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1760
1761   // Set the jump table information so that we can codegen it as a second
1762   // MachineBasicBlock
1763   JumpTable JT(-1U, JTI, JumpTableBB, Default);
1764   JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1765   if (CR.CaseBB == CurMBB)
1766     visitJumpTableHeader(JT, JTH);
1767
1768   JTCases.push_back(JumpTableBlock(JTH, JT));
1769
1770   return true;
1771 }
1772
1773 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1774 /// 2 subtrees.
1775 bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1776                                                    CaseRecVector& WorkList,
1777                                                    Value* SV,
1778                                                    MachineBasicBlock* Default) {
1779   // Get the MachineFunction which holds the current MBB.  This is used when
1780   // inserting any additional MBBs necessary to represent the switch.
1781   MachineFunction *CurMF = CurMBB->getParent();
1782
1783   // Figure out which block is immediately after the current one.
1784   MachineBasicBlock *NextBlock = 0;
1785   MachineFunction::iterator BBI = CR.CaseBB;
1786
1787   if (++BBI != CurMBB->getParent()->end())
1788     NextBlock = BBI;
1789
1790   Case& FrontCase = *CR.Range.first;
1791   Case& BackCase  = *(CR.Range.second-1);
1792   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1793
1794   // Size is the number of Cases represented by this range.
1795   unsigned Size = CR.Range.second - CR.Range.first;
1796
1797   const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1798   const APInt& Last  = cast<ConstantInt>(BackCase.High)->getValue();
1799   double FMetric = 0;
1800   CaseItr Pivot = CR.Range.first + Size/2;
1801
1802   // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1803   // (heuristically) allow us to emit JumpTable's later.
1804   size_t TSize = 0;
1805   for (CaseItr I = CR.Range.first, E = CR.Range.second;
1806        I!=E; ++I)
1807     TSize += I->size();
1808
1809   size_t LSize = FrontCase.size();
1810   size_t RSize = TSize-LSize;
1811   DEBUG(errs() << "Selecting best pivot: \n"
1812                << "First: " << First << ", Last: " << Last <<'\n'
1813                << "LSize: " << LSize << ", RSize: " << RSize << '\n');
1814   for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1815        J!=E; ++I, ++J) {
1816     const APInt& LEnd = cast<ConstantInt>(I->High)->getValue();
1817     const APInt& RBegin = cast<ConstantInt>(J->Low)->getValue();
1818     APInt Range = ComputeRange(LEnd, RBegin);
1819     assert((Range - 2ULL).isNonNegative() &&
1820            "Invalid case distance");
1821     double LDensity = (double)LSize / (LEnd - First + 1ULL).roundToDouble();
1822     double RDensity = (double)RSize / (Last - RBegin + 1ULL).roundToDouble();
1823     double Metric = Range.logBase2()*(LDensity+RDensity);
1824     // Should always split in some non-trivial place
1825     DEBUG(errs() <<"=>Step\n"
1826                  << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1827                  << "LDensity: " << LDensity
1828                  << ", RDensity: " << RDensity << '\n'
1829                  << "Metric: " << Metric << '\n');
1830     if (FMetric < Metric) {
1831       Pivot = J;
1832       FMetric = Metric;
1833       DEBUG(errs() << "Current metric set to: " << FMetric << '\n');
1834     }
1835
1836     LSize += J->size();
1837     RSize -= J->size();
1838   }
1839   if (areJTsAllowed(TLI)) {
1840     // If our case is dense we *really* should handle it earlier!
1841     assert((FMetric > 0) && "Should handle dense range earlier!");
1842   } else {
1843     Pivot = CR.Range.first + Size/2;
1844   }
1845
1846   CaseRange LHSR(CR.Range.first, Pivot);
1847   CaseRange RHSR(Pivot, CR.Range.second);
1848   Constant *C = Pivot->Low;
1849   MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1850
1851   // We know that we branch to the LHS if the Value being switched on is
1852   // less than the Pivot value, C.  We use this to optimize our binary
1853   // tree a bit, by recognizing that if SV is greater than or equal to the
1854   // LHS's Case Value, and that Case Value is exactly one less than the
1855   // Pivot's Value, then we can branch directly to the LHS's Target,
1856   // rather than creating a leaf node for it.
1857   if ((LHSR.second - LHSR.first) == 1 &&
1858       LHSR.first->High == CR.GE &&
1859       cast<ConstantInt>(C)->getValue() ==
1860       (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
1861     TrueBB = LHSR.first->BB;
1862   } else {
1863     TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1864     CurMF->insert(BBI, TrueBB);
1865     WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1866
1867     // Put SV in a virtual register to make it available from the new blocks.
1868     ExportFromCurrentBlock(SV);
1869   }
1870
1871   // Similar to the optimization above, if the Value being switched on is
1872   // known to be less than the Constant CR.LT, and the current Case Value
1873   // is CR.LT - 1, then we can branch directly to the target block for
1874   // the current Case Value, rather than emitting a RHS leaf node for it.
1875   if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1876       cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1877       (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
1878     FalseBB = RHSR.first->BB;
1879   } else {
1880     FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1881     CurMF->insert(BBI, FalseBB);
1882     WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1883
1884     // Put SV in a virtual register to make it available from the new blocks.
1885     ExportFromCurrentBlock(SV);
1886   }
1887
1888   // Create a CaseBlock record representing a conditional branch to
1889   // the LHS node if the value being switched on SV is less than C.
1890   // Otherwise, branch to LHS.
1891   CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1892
1893   if (CR.CaseBB == CurMBB)
1894     visitSwitchCase(CB);
1895   else
1896     SwitchCases.push_back(CB);
1897
1898   return true;
1899 }
1900
1901 /// handleBitTestsSwitchCase - if current case range has few destination and
1902 /// range span less, than machine word bitwidth, encode case range into series
1903 /// of masks and emit bit tests with these masks.
1904 bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1905                                                     CaseRecVector& WorkList,
1906                                                     Value* SV,
1907                                                     MachineBasicBlock* Default){
1908   unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
1909
1910   Case& FrontCase = *CR.Range.first;
1911   Case& BackCase  = *(CR.Range.second-1);
1912
1913   // Get the MachineFunction which holds the current MBB.  This is used when
1914   // inserting any additional MBBs necessary to represent the switch.
1915   MachineFunction *CurMF = CurMBB->getParent();
1916
1917   // If target does not have legal shift left, do not emit bit tests at all.
1918   if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy()))
1919     return false;
1920
1921   size_t numCmps = 0;
1922   for (CaseItr I = CR.Range.first, E = CR.Range.second;
1923        I!=E; ++I) {
1924     // Single case counts one, case range - two.
1925     numCmps += (I->Low == I->High ? 1 : 2);
1926   }
1927
1928   // Count unique destinations
1929   SmallSet<MachineBasicBlock*, 4> Dests;
1930   for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1931     Dests.insert(I->BB);
1932     if (Dests.size() > 3)
1933       // Don't bother the code below, if there are too much unique destinations
1934       return false;
1935   }
1936   DEBUG(errs() << "Total number of unique destinations: " << Dests.size() << '\n'
1937                << "Total number of comparisons: " << numCmps << '\n');
1938
1939   // Compute span of values.
1940   const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
1941   const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
1942   APInt cmpRange = maxValue - minValue;
1943
1944   DEBUG(errs() << "Compare range: " << cmpRange << '\n'
1945                << "Low bound: " << minValue << '\n'
1946                << "High bound: " << maxValue << '\n');
1947
1948   if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
1949       (!(Dests.size() == 1 && numCmps >= 3) &&
1950        !(Dests.size() == 2 && numCmps >= 5) &&
1951        !(Dests.size() >= 3 && numCmps >= 6)))
1952     return false;
1953
1954   DEBUG(errs() << "Emitting bit tests\n");
1955   APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
1956
1957   // Optimize the case where all the case values fit in a
1958   // word without having to subtract minValue. In this case,
1959   // we can optimize away the subtraction.
1960   if (minValue.isNonNegative() &&
1961       maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
1962     cmpRange = maxValue;
1963   } else {
1964     lowBound = minValue;
1965   }
1966
1967   CaseBitsVector CasesBits;
1968   unsigned i, count = 0;
1969
1970   for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1971     MachineBasicBlock* Dest = I->BB;
1972     for (i = 0; i < count; ++i)
1973       if (Dest == CasesBits[i].BB)
1974         break;
1975
1976     if (i == count) {
1977       assert((count < 3) && "Too much destinations to test!");
1978       CasesBits.push_back(CaseBits(0, Dest, 0));
1979       count++;
1980     }
1981
1982     const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
1983     const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
1984
1985     uint64_t lo = (lowValue - lowBound).getZExtValue();
1986     uint64_t hi = (highValue - lowBound).getZExtValue();
1987
1988     for (uint64_t j = lo; j <= hi; j++) {
1989       CasesBits[i].Mask |=  1ULL << j;
1990       CasesBits[i].Bits++;
1991     }
1992
1993   }
1994   std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1995
1996   BitTestInfo BTC;
1997
1998   // Figure out which block is immediately after the current one.
1999   MachineFunction::iterator BBI = CR.CaseBB;
2000   ++BBI;
2001
2002   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2003
2004   DEBUG(errs() << "Cases:\n");
2005   for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2006     DEBUG(errs() << "Mask: " << CasesBits[i].Mask
2007                  << ", Bits: " << CasesBits[i].Bits
2008                  << ", BB: " << CasesBits[i].BB << '\n');
2009
2010     MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2011     CurMF->insert(BBI, CaseBB);
2012     BTC.push_back(BitTestCase(CasesBits[i].Mask,
2013                               CaseBB,
2014                               CasesBits[i].BB));
2015
2016     // Put SV in a virtual register to make it available from the new blocks.
2017     ExportFromCurrentBlock(SV);
2018   }
2019
2020   BitTestBlock BTB(lowBound, cmpRange, SV,
2021                    -1U, (CR.CaseBB == CurMBB),
2022                    CR.CaseBB, Default, BTC);
2023
2024   if (CR.CaseBB == CurMBB)
2025     visitBitTestHeader(BTB);
2026
2027   BitTestCases.push_back(BTB);
2028
2029   return true;
2030 }
2031
2032
2033 /// Clusterify - Transform simple list of Cases into list of CaseRange's
2034 size_t SelectionDAGLowering::Clusterify(CaseVector& Cases,
2035                                           const SwitchInst& SI) {
2036   size_t numCmps = 0;
2037
2038   // Start with "simple" cases
2039   for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
2040     MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2041     Cases.push_back(Case(SI.getSuccessorValue(i),
2042                          SI.getSuccessorValue(i),
2043                          SMBB));
2044   }
2045   std::sort(Cases.begin(), Cases.end(), CaseCmp());
2046
2047   // Merge case into clusters
2048   if (Cases.size() >= 2)
2049     // Must recompute end() each iteration because it may be
2050     // invalidated by erase if we hold on to it
2051     for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
2052       const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2053       const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
2054       MachineBasicBlock* nextBB = J->BB;
2055       MachineBasicBlock* currentBB = I->BB;
2056
2057       // If the two neighboring cases go to the same destination, merge them
2058       // into a single case.
2059       if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
2060         I->High = J->High;
2061         J = Cases.erase(J);
2062       } else {
2063         I = J++;
2064       }
2065     }
2066
2067   for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2068     if (I->Low != I->High)
2069       // A range counts double, since it requires two compares.
2070       ++numCmps;
2071   }
2072
2073   return numCmps;
2074 }
2075
2076 void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
2077   // Figure out which block is immediately after the current one.
2078   MachineBasicBlock *NextBlock = 0;
2079   MachineFunction::iterator BBI = CurMBB;
2080
2081   MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2082
2083   // If there is only the default destination, branch to it if it is not the
2084   // next basic block.  Otherwise, just fall through.
2085   if (SI.getNumOperands() == 2) {
2086     // Update machine-CFG edges.
2087
2088     // If this is not a fall-through branch, emit the branch.
2089     CurMBB->addSuccessor(Default);
2090     if (Default != NextBlock)
2091       DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
2092                               MVT::Other, getControlRoot(),
2093                               DAG.getBasicBlock(Default)));
2094     return;
2095   }
2096
2097   // If there are any non-default case statements, create a vector of Cases
2098   // representing each one, and sort the vector so that we can efficiently
2099   // create a binary search tree from them.
2100   CaseVector Cases;
2101   size_t numCmps = Clusterify(Cases, SI);
2102   DEBUG(errs() << "Clusterify finished. Total clusters: " << Cases.size()
2103                << ". Total compares: " << numCmps << '\n');
2104   numCmps = 0;
2105
2106   // Get the Value to be switched on and default basic blocks, which will be
2107   // inserted into CaseBlock records, representing basic blocks in the binary
2108   // search tree.
2109   Value *SV = SI.getOperand(0);
2110
2111   // Push the initial CaseRec onto the worklist
2112   CaseRecVector WorkList;
2113   WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2114
2115   while (!WorkList.empty()) {
2116     // Grab a record representing a case range to process off the worklist
2117     CaseRec CR = WorkList.back();
2118     WorkList.pop_back();
2119
2120     if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2121       continue;
2122
2123     // If the range has few cases (two or less) emit a series of specific
2124     // tests.
2125     if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2126       continue;
2127
2128     // If the switch has more than 5 blocks, and at least 40% dense, and the
2129     // target supports indirect branches, then emit a jump table rather than
2130     // lowering the switch to a binary tree of conditional branches.
2131     if (handleJTSwitchCase(CR, WorkList, SV, Default))
2132       continue;
2133
2134     // Emit binary tree. We need to pick a pivot, and push left and right ranges
2135     // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2136     handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2137   }
2138 }
2139
2140
2141 void SelectionDAGLowering::visitFSub(User &I) {
2142   // -0.0 - X --> fneg
2143   const Type *Ty = I.getType();
2144   if (isa<VectorType>(Ty)) {
2145     if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2146       const VectorType *DestTy = cast<VectorType>(I.getType());
2147       const Type *ElTy = DestTy->getElementType();
2148       unsigned VL = DestTy->getNumElements();
2149       std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2150       Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2151       if (CV == CNZ) {
2152         SDValue Op2 = getValue(I.getOperand(1));
2153         setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2154                                  Op2.getValueType(), Op2));
2155         return;
2156       }
2157     }
2158   }
2159   if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2160     if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2161       SDValue Op2 = getValue(I.getOperand(1));
2162       setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2163                                Op2.getValueType(), Op2));
2164       return;
2165     }
2166
2167   visitBinary(I, ISD::FSUB);
2168 }
2169
2170 void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2171   SDValue Op1 = getValue(I.getOperand(0));
2172   SDValue Op2 = getValue(I.getOperand(1));
2173
2174   setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
2175                            Op1.getValueType(), Op1, Op2));
2176 }
2177
2178 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2179   SDValue Op1 = getValue(I.getOperand(0));
2180   SDValue Op2 = getValue(I.getOperand(1));
2181   if (!isa<VectorType>(I.getType()) &&
2182       Op2.getValueType() != TLI.getShiftAmountTy()) {
2183     // If the operand is smaller than the shift count type, promote it.
2184     if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
2185       Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2186                         TLI.getShiftAmountTy(), Op2);
2187     // If the operand is larger than the shift count type but the shift
2188     // count type has enough bits to represent any shift value, truncate
2189     // it now. This is a common case and it exposes the truncate to
2190     // optimization early.
2191     else if (TLI.getShiftAmountTy().getSizeInBits() >=
2192              Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2193       Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2194                         TLI.getShiftAmountTy(), Op2);
2195     // Otherwise we'll need to temporarily settle for some other
2196     // convenient type; type legalization will make adjustments as
2197     // needed.
2198     else if (TLI.getPointerTy().bitsLT(Op2.getValueType()))
2199       Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2200                         TLI.getPointerTy(), Op2);
2201     else if (TLI.getPointerTy().bitsGT(Op2.getValueType()))
2202       Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2203                         TLI.getPointerTy(), Op2);
2204   }
2205
2206   setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
2207                            Op1.getValueType(), Op1, Op2));
2208 }
2209
2210 void SelectionDAGLowering::visitICmp(User &I) {
2211   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2212   if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2213     predicate = IC->getPredicate();
2214   else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2215     predicate = ICmpInst::Predicate(IC->getPredicate());
2216   SDValue Op1 = getValue(I.getOperand(0));
2217   SDValue Op2 = getValue(I.getOperand(1));
2218   ISD::CondCode Opcode = getICmpCondCode(predicate);
2219   
2220   MVT DestVT = TLI.getValueType(I.getType());
2221   setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Opcode));
2222 }
2223
2224 void SelectionDAGLowering::visitFCmp(User &I) {
2225   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2226   if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2227     predicate = FC->getPredicate();
2228   else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2229     predicate = FCmpInst::Predicate(FC->getPredicate());
2230   SDValue Op1 = getValue(I.getOperand(0));
2231   SDValue Op2 = getValue(I.getOperand(1));
2232   ISD::CondCode Condition = getFCmpCondCode(predicate);
2233   MVT DestVT = TLI.getValueType(I.getType());
2234   setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
2235 }
2236
2237 void SelectionDAGLowering::visitSelect(User &I) {
2238   SmallVector<MVT, 4> ValueVTs;
2239   ComputeValueVTs(TLI, I.getType(), ValueVTs);
2240   unsigned NumValues = ValueVTs.size();
2241   if (NumValues != 0) {
2242     SmallVector<SDValue, 4> Values(NumValues);
2243     SDValue Cond     = getValue(I.getOperand(0));
2244     SDValue TrueVal  = getValue(I.getOperand(1));
2245     SDValue FalseVal = getValue(I.getOperand(2));
2246
2247     for (unsigned i = 0; i != NumValues; ++i)
2248       Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
2249                               TrueVal.getValueType(), Cond,
2250                               SDValue(TrueVal.getNode(), TrueVal.getResNo() + i),
2251                               SDValue(FalseVal.getNode(), FalseVal.getResNo() + i));
2252
2253     setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2254                              DAG.getVTList(&ValueVTs[0], NumValues),
2255                              &Values[0], NumValues));
2256   }
2257 }
2258
2259
2260 void SelectionDAGLowering::visitTrunc(User &I) {
2261   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2262   SDValue N = getValue(I.getOperand(0));
2263   MVT DestVT = TLI.getValueType(I.getType());
2264   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
2265 }
2266
2267 void SelectionDAGLowering::visitZExt(User &I) {
2268   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2269   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2270   SDValue N = getValue(I.getOperand(0));
2271   MVT DestVT = TLI.getValueType(I.getType());
2272   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
2273 }
2274
2275 void SelectionDAGLowering::visitSExt(User &I) {
2276   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2277   // SExt also can't be a cast to bool for same reason. So, nothing much to do
2278   SDValue N = getValue(I.getOperand(0));
2279   MVT DestVT = TLI.getValueType(I.getType());
2280   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
2281 }
2282
2283 void SelectionDAGLowering::visitFPTrunc(User &I) {
2284   // FPTrunc is never a no-op cast, no need to check
2285   SDValue N = getValue(I.getOperand(0));
2286   MVT DestVT = TLI.getValueType(I.getType());
2287   setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
2288                            DestVT, N, DAG.getIntPtrConstant(0)));
2289 }
2290
2291 void SelectionDAGLowering::visitFPExt(User &I){
2292   // FPTrunc is never a no-op cast, no need to check
2293   SDValue N = getValue(I.getOperand(0));
2294   MVT DestVT = TLI.getValueType(I.getType());
2295   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
2296 }
2297
2298 void SelectionDAGLowering::visitFPToUI(User &I) {
2299   // FPToUI is never a no-op cast, no need to check
2300   SDValue N = getValue(I.getOperand(0));
2301   MVT DestVT = TLI.getValueType(I.getType());
2302   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
2303 }
2304
2305 void SelectionDAGLowering::visitFPToSI(User &I) {
2306   // FPToSI is never a no-op cast, no need to check
2307   SDValue N = getValue(I.getOperand(0));
2308   MVT DestVT = TLI.getValueType(I.getType());
2309   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
2310 }
2311
2312 void SelectionDAGLowering::visitUIToFP(User &I) {
2313   // UIToFP is never a no-op cast, no need to check
2314   SDValue N = getValue(I.getOperand(0));
2315   MVT DestVT = TLI.getValueType(I.getType());
2316   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
2317 }
2318
2319 void SelectionDAGLowering::visitSIToFP(User &I){
2320   // SIToFP is never a no-op cast, no need to check
2321   SDValue N = getValue(I.getOperand(0));
2322   MVT DestVT = TLI.getValueType(I.getType());
2323   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
2324 }
2325
2326 void SelectionDAGLowering::visitPtrToInt(User &I) {
2327   // What to do depends on the size of the integer and the size of the pointer.
2328   // We can either truncate, zero extend, or no-op, accordingly.
2329   SDValue N = getValue(I.getOperand(0));
2330   MVT SrcVT = N.getValueType();
2331   MVT DestVT = TLI.getValueType(I.getType());
2332   SDValue Result;
2333   if (DestVT.bitsLT(SrcVT))
2334     Result = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N);
2335   else
2336     // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2337     Result = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N);
2338   setValue(&I, Result);
2339 }
2340
2341 void SelectionDAGLowering::visitIntToPtr(User &I) {
2342   // What to do depends on the size of the integer and the size of the pointer.
2343   // We can either truncate, zero extend, or no-op, accordingly.
2344   SDValue N = getValue(I.getOperand(0));
2345   MVT SrcVT = N.getValueType();
2346   MVT DestVT = TLI.getValueType(I.getType());
2347   if (DestVT.bitsLT(SrcVT))
2348     setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
2349   else
2350     // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2351     setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2352                              DestVT, N));
2353 }
2354
2355 void SelectionDAGLowering::visitBitCast(User &I) {
2356   SDValue N = getValue(I.getOperand(0));
2357   MVT DestVT = TLI.getValueType(I.getType());
2358
2359   // BitCast assures us that source and destination are the same size so this
2360   // is either a BIT_CONVERT or a no-op.
2361   if (DestVT != N.getValueType())
2362     setValue(&I, DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
2363                              DestVT, N)); // convert types
2364   else
2365     setValue(&I, N); // noop cast.
2366 }
2367
2368 void SelectionDAGLowering::visitInsertElement(User &I) {
2369   SDValue InVec = getValue(I.getOperand(0));
2370   SDValue InVal = getValue(I.getOperand(1));
2371   SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2372                                 TLI.getPointerTy(),
2373                                 getValue(I.getOperand(2)));
2374
2375   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
2376                            TLI.getValueType(I.getType()),
2377                            InVec, InVal, InIdx));
2378 }
2379
2380 void SelectionDAGLowering::visitExtractElement(User &I) {
2381   SDValue InVec = getValue(I.getOperand(0));
2382   SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2383                                 TLI.getPointerTy(),
2384                                 getValue(I.getOperand(1)));
2385   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2386                            TLI.getValueType(I.getType()), InVec, InIdx));
2387 }
2388
2389
2390 // Utility for visitShuffleVector - Returns true if the mask is mask starting
2391 // from SIndx and increasing to the element length (undefs are allowed).
2392 static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) {
2393   unsigned MaskNumElts = Mask.size();
2394   for (unsigned i = 0; i != MaskNumElts; ++i)
2395     if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx)))
2396       return false;
2397   return true;
2398 }
2399
2400 void SelectionDAGLowering::visitShuffleVector(User &I) {
2401   SmallVector<int, 8> Mask;
2402   SDValue Src1 = getValue(I.getOperand(0));
2403   SDValue Src2 = getValue(I.getOperand(1));
2404
2405   // Convert the ConstantVector mask operand into an array of ints, with -1
2406   // representing undef values.
2407   SmallVector<Constant*, 8> MaskElts;
2408   cast<Constant>(I.getOperand(2))->getVectorElements(*DAG.getContext(), 
2409                                                      MaskElts);
2410   unsigned MaskNumElts = MaskElts.size();
2411   for (unsigned i = 0; i != MaskNumElts; ++i) {
2412     if (isa<UndefValue>(MaskElts[i]))
2413       Mask.push_back(-1);
2414     else
2415       Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue());
2416   }
2417   
2418   MVT VT = TLI.getValueType(I.getType());
2419   MVT SrcVT = Src1.getValueType();
2420   unsigned SrcNumElts = SrcVT.getVectorNumElements();
2421
2422   if (SrcNumElts == MaskNumElts) {
2423     setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2424                                       &Mask[0]));
2425     return;
2426   }
2427
2428   // Normalize the shuffle vector since mask and vector length don't match.
2429   if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2430     // Mask is longer than the source vectors and is a multiple of the source
2431     // vectors.  We can use concatenate vector to make the mask and vectors
2432     // lengths match.
2433     if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2434       // The shuffle is concatenating two vectors together.
2435       setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
2436                                VT, Src1, Src2));
2437       return;
2438     }
2439
2440     // Pad both vectors with undefs to make them the same length as the mask.
2441     unsigned NumConcat = MaskNumElts / SrcNumElts;
2442     bool Src1U = Src1.getOpcode() == ISD::UNDEF;
2443     bool Src2U = Src2.getOpcode() == ISD::UNDEF;
2444     SDValue UndefVal = DAG.getUNDEF(SrcVT);
2445
2446     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2447     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
2448     MOps1[0] = Src1;
2449     MOps2[0] = Src2;
2450     
2451     Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS, 
2452                                                   getCurDebugLoc(), VT, 
2453                                                   &MOps1[0], NumConcat);
2454     Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2455                                                   getCurDebugLoc(), VT, 
2456                                                   &MOps2[0], NumConcat);
2457
2458     // Readjust mask for new input vector length.
2459     SmallVector<int, 8> MappedOps;
2460     for (unsigned i = 0; i != MaskNumElts; ++i) {
2461       int Idx = Mask[i];
2462       if (Idx < (int)SrcNumElts)
2463         MappedOps.push_back(Idx);
2464       else
2465         MappedOps.push_back(Idx + MaskNumElts - SrcNumElts);
2466     }
2467     setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2, 
2468                                       &MappedOps[0]));
2469     return;
2470   }
2471
2472   if (SrcNumElts > MaskNumElts) {
2473     // Analyze the access pattern of the vector to see if we can extract
2474     // two subvectors and do the shuffle. The analysis is done by calculating
2475     // the range of elements the mask access on both vectors.
2476     int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2477     int MaxRange[2] = {-1, -1};
2478
2479     for (unsigned i = 0; i != MaskNumElts; ++i) {
2480       int Idx = Mask[i];
2481       int Input = 0;
2482       if (Idx < 0)
2483         continue;
2484       
2485       if (Idx >= (int)SrcNumElts) {
2486         Input = 1;
2487         Idx -= SrcNumElts;
2488       }
2489       if (Idx > MaxRange[Input])
2490         MaxRange[Input] = Idx;
2491       if (Idx < MinRange[Input])
2492         MinRange[Input] = Idx;
2493     }
2494
2495     // Check if the access is smaller than the vector size and can we find
2496     // a reasonable extract index.
2497     int RangeUse[2] = { 2, 2 };  // 0 = Unused, 1 = Extract, 2 = Can not Extract.
2498     int StartIdx[2];  // StartIdx to extract from
2499     for (int Input=0; Input < 2; ++Input) {
2500       if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) {
2501         RangeUse[Input] = 0; // Unused
2502         StartIdx[Input] = 0;
2503       } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) {
2504         // Fits within range but we should see if we can find a good
2505         // start index that is a multiple of the mask length.
2506         if (MaxRange[Input] < (int)MaskNumElts) {
2507           RangeUse[Input] = 1; // Extract from beginning of the vector
2508           StartIdx[Input] = 0;
2509         } else {
2510           StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
2511           if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
2512               StartIdx[Input] + MaskNumElts < SrcNumElts)
2513             RangeUse[Input] = 1; // Extract from a multiple of the mask length.
2514         }
2515       }
2516     }
2517
2518     if (RangeUse[0] == 0 && RangeUse[0] == 0) {
2519       setValue(&I, DAG.getUNDEF(VT));  // Vectors are not used.
2520       return;
2521     }
2522     else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2523       // Extract appropriate subvector and generate a vector shuffle
2524       for (int Input=0; Input < 2; ++Input) {
2525         SDValue& Src = Input == 0 ? Src1 : Src2;
2526         if (RangeUse[Input] == 0) {
2527           Src = DAG.getUNDEF(VT);
2528         } else {
2529           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
2530                             Src, DAG.getIntPtrConstant(StartIdx[Input]));
2531         }
2532       }
2533       // Calculate new mask.
2534       SmallVector<int, 8> MappedOps;
2535       for (unsigned i = 0; i != MaskNumElts; ++i) {
2536         int Idx = Mask[i];
2537         if (Idx < 0)
2538           MappedOps.push_back(Idx);
2539         else if (Idx < (int)SrcNumElts)
2540           MappedOps.push_back(Idx - StartIdx[0]);
2541         else
2542           MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts);
2543       }
2544       setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2545                                         &MappedOps[0]));
2546       return;
2547     }
2548   }
2549
2550   // We can't use either concat vectors or extract subvectors so fall back to
2551   // replacing the shuffle with extract and build vector.
2552   // to insert and build vector.
2553   MVT EltVT = VT.getVectorElementType();
2554   MVT PtrVT = TLI.getPointerTy();
2555   SmallVector<SDValue,8> Ops;
2556   for (unsigned i = 0; i != MaskNumElts; ++i) {
2557     if (Mask[i] < 0) {
2558       Ops.push_back(DAG.getUNDEF(EltVT));
2559     } else {
2560       int Idx = Mask[i];
2561       if (Idx < (int)SrcNumElts)
2562         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2563                                   EltVT, Src1, DAG.getConstant(Idx, PtrVT)));
2564       else
2565         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2566                                   EltVT, Src2,
2567                                   DAG.getConstant(Idx - SrcNumElts, PtrVT)));
2568     }
2569   }
2570   setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2571                            VT, &Ops[0], Ops.size()));
2572 }
2573
2574 void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2575   const Value *Op0 = I.getOperand(0);
2576   const Value *Op1 = I.getOperand(1);
2577   const Type *AggTy = I.getType();
2578   const Type *ValTy = Op1->getType();
2579   bool IntoUndef = isa<UndefValue>(Op0);
2580   bool FromUndef = isa<UndefValue>(Op1);
2581
2582   unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2583                                             I.idx_begin(), I.idx_end());
2584
2585   SmallVector<MVT, 4> AggValueVTs;
2586   ComputeValueVTs(TLI, AggTy, AggValueVTs);
2587   SmallVector<MVT, 4> ValValueVTs;
2588   ComputeValueVTs(TLI, ValTy, ValValueVTs);
2589
2590   unsigned NumAggValues = AggValueVTs.size();
2591   unsigned NumValValues = ValValueVTs.size();
2592   SmallVector<SDValue, 4> Values(NumAggValues);
2593
2594   SDValue Agg = getValue(Op0);
2595   SDValue Val = getValue(Op1);
2596   unsigned i = 0;
2597   // Copy the beginning value(s) from the original aggregate.
2598   for (; i != LinearIndex; ++i)
2599     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2600                 SDValue(Agg.getNode(), Agg.getResNo() + i);
2601   // Copy values from the inserted value(s).
2602   for (; i != LinearIndex + NumValValues; ++i)
2603     Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2604                 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2605   // Copy remaining value(s) from the original aggregate.
2606   for (; i != NumAggValues; ++i)
2607     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2608                 SDValue(Agg.getNode(), Agg.getResNo() + i);
2609
2610   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2611                            DAG.getVTList(&AggValueVTs[0], NumAggValues),
2612                            &Values[0], NumAggValues));
2613 }
2614
2615 void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2616   const Value *Op0 = I.getOperand(0);
2617   const Type *AggTy = Op0->getType();
2618   const Type *ValTy = I.getType();
2619   bool OutOfUndef = isa<UndefValue>(Op0);
2620
2621   unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2622                                             I.idx_begin(), I.idx_end());
2623
2624   SmallVector<MVT, 4> ValValueVTs;
2625   ComputeValueVTs(TLI, ValTy, ValValueVTs);
2626
2627   unsigned NumValValues = ValValueVTs.size();
2628   SmallVector<SDValue, 4> Values(NumValValues);
2629
2630   SDValue Agg = getValue(Op0);
2631   // Copy out the selected value(s).
2632   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2633     Values[i - LinearIndex] =
2634       OutOfUndef ?
2635         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2636         SDValue(Agg.getNode(), Agg.getResNo() + i);
2637
2638   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2639                            DAG.getVTList(&ValValueVTs[0], NumValValues),
2640                            &Values[0], NumValValues));
2641 }
2642
2643
2644 void SelectionDAGLowering::visitGetElementPtr(User &I) {
2645   SDValue N = getValue(I.getOperand(0));
2646   const Type *Ty = I.getOperand(0)->getType();
2647
2648   for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2649        OI != E; ++OI) {
2650     Value *Idx = *OI;
2651     if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2652       unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2653       if (Field) {
2654         // N = N + Offset
2655         uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2656         N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2657                         DAG.getIntPtrConstant(Offset));
2658       }
2659       Ty = StTy->getElementType(Field);
2660     } else {
2661       Ty = cast<SequentialType>(Ty)->getElementType();
2662
2663       // If this is a constant subscript, handle it quickly.
2664       if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2665         if (CI->getZExtValue() == 0) continue;
2666         uint64_t Offs =
2667             TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2668         SDValue OffsVal;
2669         unsigned PtrBits = TLI.getPointerTy().getSizeInBits();
2670         if (PtrBits < 64) {
2671           OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2672                                 TLI.getPointerTy(),
2673                                 DAG.getConstant(Offs, MVT::i64));
2674         } else
2675           OffsVal = DAG.getIntPtrConstant(Offs);
2676         N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2677                         OffsVal);
2678         continue;
2679       }
2680
2681       // N = N + Idx * ElementSize;
2682       uint64_t ElementSize = TD->getTypeAllocSize(Ty);
2683       SDValue IdxN = getValue(Idx);
2684
2685       // If the index is smaller or larger than intptr_t, truncate or extend
2686       // it.
2687       if (IdxN.getValueType().bitsLT(N.getValueType()))
2688         IdxN = DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(),
2689                            N.getValueType(), IdxN);
2690       else if (IdxN.getValueType().bitsGT(N.getValueType()))
2691         IdxN = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2692                            N.getValueType(), IdxN);
2693
2694       // If this is a multiply by a power of two, turn it into a shl
2695       // immediately.  This is a very common case.
2696       if (ElementSize != 1) {
2697         if (isPowerOf2_64(ElementSize)) {
2698           unsigned Amt = Log2_64(ElementSize);
2699           IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
2700                              N.getValueType(), IdxN,
2701                              DAG.getConstant(Amt, TLI.getPointerTy()));
2702         } else {
2703           SDValue Scale = DAG.getIntPtrConstant(ElementSize);
2704           IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
2705                              N.getValueType(), IdxN, Scale);
2706         }
2707       }
2708
2709       N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2710                       N.getValueType(), N, IdxN);
2711     }
2712   }
2713   setValue(&I, N);
2714 }
2715
2716 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2717   // If this is a fixed sized alloca in the entry block of the function,
2718   // allocate it statically on the stack.
2719   if (FuncInfo.StaticAllocaMap.count(&I))
2720     return;   // getValue will auto-populate this.
2721
2722   const Type *Ty = I.getAllocatedType();
2723   uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
2724   unsigned Align =
2725     std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2726              I.getAlignment());
2727
2728   SDValue AllocSize = getValue(I.getArraySize());
2729   
2730   AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), AllocSize.getValueType(),
2731                           AllocSize,
2732                           DAG.getConstant(TySize, AllocSize.getValueType()));
2733   
2734   
2735   
2736   MVT IntPtr = TLI.getPointerTy();
2737   if (IntPtr.bitsLT(AllocSize.getValueType()))
2738     AllocSize = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2739                             IntPtr, AllocSize);
2740   else if (IntPtr.bitsGT(AllocSize.getValueType()))
2741     AllocSize = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2742                             IntPtr, AllocSize);
2743
2744   // Handle alignment.  If the requested alignment is less than or equal to
2745   // the stack alignment, ignore it.  If the size is greater than or equal to
2746   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2747   unsigned StackAlign =
2748     TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2749   if (Align <= StackAlign)
2750     Align = 0;
2751
2752   // Round the size of the allocation up to the stack alignment size
2753   // by add SA-1 to the size.
2754   AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2755                           AllocSize.getValueType(), AllocSize,
2756                           DAG.getIntPtrConstant(StackAlign-1));
2757   // Mask out the low bits for alignment purposes.
2758   AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
2759                           AllocSize.getValueType(), AllocSize,
2760                           DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2761
2762   SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2763   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
2764   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
2765                             VTs, Ops, 3);
2766   setValue(&I, DSA);
2767   DAG.setRoot(DSA.getValue(1));
2768
2769   // Inform the Frame Information that we have just allocated a variable-sized
2770   // object.
2771   CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2772 }
2773
2774 void SelectionDAGLowering::visitLoad(LoadInst &I) {
2775   const Value *SV = I.getOperand(0);
2776   SDValue Ptr = getValue(SV);
2777
2778   const Type *Ty = I.getType();
2779   bool isVolatile = I.isVolatile();
2780   unsigned Alignment = I.getAlignment();
2781
2782   SmallVector<MVT, 4> ValueVTs;
2783   SmallVector<uint64_t, 4> Offsets;
2784   ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2785   unsigned NumValues = ValueVTs.size();
2786   if (NumValues == 0)
2787     return;
2788
2789   SDValue Root;
2790   bool ConstantMemory = false;
2791   if (I.isVolatile())
2792     // Serialize volatile loads with other side effects.
2793     Root = getRoot();
2794   else if (AA->pointsToConstantMemory(SV)) {
2795     // Do not serialize (non-volatile) loads of constant memory with anything.
2796     Root = DAG.getEntryNode();
2797     ConstantMemory = true;
2798   } else {
2799     // Do not serialize non-volatile loads against each other.
2800     Root = DAG.getRoot();
2801   }
2802
2803   SmallVector<SDValue, 4> Values(NumValues);
2804   SmallVector<SDValue, 4> Chains(NumValues);
2805   MVT PtrVT = Ptr.getValueType();
2806   for (unsigned i = 0; i != NumValues; ++i) {
2807     SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
2808                               DAG.getNode(ISD::ADD, getCurDebugLoc(),
2809                                           PtrVT, Ptr,
2810                                           DAG.getConstant(Offsets[i], PtrVT)),
2811                               SV, Offsets[i],
2812                               isVolatile, Alignment);
2813     Values[i] = L;
2814     Chains[i] = L.getValue(1);
2815   }
2816
2817   if (!ConstantMemory) {
2818     SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
2819                                   MVT::Other,
2820                                   &Chains[0], NumValues);
2821     if (isVolatile)
2822       DAG.setRoot(Chain);
2823     else
2824       PendingLoads.push_back(Chain);
2825   }
2826
2827   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2828                            DAG.getVTList(&ValueVTs[0], NumValues),
2829                            &Values[0], NumValues));
2830 }
2831
2832
2833 void SelectionDAGLowering::visitStore(StoreInst &I) {
2834   Value *SrcV = I.getOperand(0);
2835   Value *PtrV = I.getOperand(1);
2836
2837   SmallVector<MVT, 4> ValueVTs;
2838   SmallVector<uint64_t, 4> Offsets;
2839   ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2840   unsigned NumValues = ValueVTs.size();
2841   if (NumValues == 0)
2842     return;
2843
2844   // Get the lowered operands. Note that we do this after
2845   // checking if NumResults is zero, because with zero results
2846   // the operands won't have values in the map.
2847   SDValue Src = getValue(SrcV);
2848   SDValue Ptr = getValue(PtrV);
2849
2850   SDValue Root = getRoot();
2851   SmallVector<SDValue, 4> Chains(NumValues);
2852   MVT PtrVT = Ptr.getValueType();
2853   bool isVolatile = I.isVolatile();
2854   unsigned Alignment = I.getAlignment();
2855   for (unsigned i = 0; i != NumValues; ++i)
2856     Chains[i] = DAG.getStore(Root, getCurDebugLoc(),
2857                              SDValue(Src.getNode(), Src.getResNo() + i),
2858                              DAG.getNode(ISD::ADD, getCurDebugLoc(),
2859                                          PtrVT, Ptr,
2860                                          DAG.getConstant(Offsets[i], PtrVT)),
2861                              PtrV, Offsets[i],
2862                              isVolatile, Alignment);
2863
2864   DAG.setRoot(DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
2865                           MVT::Other, &Chains[0], NumValues));
2866 }
2867
2868 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2869 /// node.
2870 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2871                                                 unsigned Intrinsic) {
2872   bool HasChain = !I.doesNotAccessMemory();
2873   bool OnlyLoad = HasChain && I.onlyReadsMemory();
2874
2875   // Build the operand list.
2876   SmallVector<SDValue, 8> Ops;
2877   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
2878     if (OnlyLoad) {
2879       // We don't need to serialize loads against other loads.
2880       Ops.push_back(DAG.getRoot());
2881     } else {
2882       Ops.push_back(getRoot());
2883     }
2884   }
2885
2886   // Info is set by getTgtMemInstrinsic
2887   TargetLowering::IntrinsicInfo Info;
2888   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2889
2890   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
2891   if (!IsTgtIntrinsic)
2892     Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2893
2894   // Add all operands of the call to the operand list.
2895   for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2896     SDValue Op = getValue(I.getOperand(i));
2897     assert(TLI.isTypeLegal(Op.getValueType()) &&
2898            "Intrinsic uses a non-legal type?");
2899     Ops.push_back(Op);
2900   }
2901
2902   SmallVector<MVT, 4> ValueVTs;
2903   ComputeValueVTs(TLI, I.getType(), ValueVTs);
2904 #ifndef NDEBUG
2905   for (unsigned Val = 0, E = ValueVTs.size(); Val != E; ++Val) {
2906     assert(TLI.isTypeLegal(ValueVTs[Val]) &&
2907            "Intrinsic uses a non-legal type?");
2908   }
2909 #endif // NDEBUG
2910   if (HasChain)
2911     ValueVTs.push_back(MVT::Other);
2912
2913   SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
2914
2915   // Create the node.
2916   SDValue Result;
2917   if (IsTgtIntrinsic) {
2918     // This is target intrinsic that touches memory
2919     Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
2920                                      VTs, &Ops[0], Ops.size(),
2921                                      Info.memVT, Info.ptrVal, Info.offset,
2922                                      Info.align, Info.vol,
2923                                      Info.readMem, Info.writeMem);
2924   }
2925   else if (!HasChain)
2926     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
2927                          VTs, &Ops[0], Ops.size());
2928   else if (I.getType() != Type::VoidTy)
2929     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
2930                          VTs, &Ops[0], Ops.size());
2931   else
2932     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
2933                          VTs, &Ops[0], Ops.size());
2934
2935   if (HasChain) {
2936     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2937     if (OnlyLoad)
2938       PendingLoads.push_back(Chain);
2939     else
2940       DAG.setRoot(Chain);
2941   }
2942   if (I.getType() != Type::VoidTy) {
2943     if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2944       MVT VT = TLI.getValueType(PTy);
2945       Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result);
2946     }
2947     setValue(&I, Result);
2948   }
2949 }
2950
2951 /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
2952 static GlobalVariable *ExtractTypeInfo(Value *V) {
2953   V = V->stripPointerCasts();
2954   GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2955   assert ((GV || isa<ConstantPointerNull>(V)) &&
2956           "TypeInfo must be a global variable or NULL");
2957   return GV;
2958 }
2959
2960 namespace llvm {
2961
2962 /// AddCatchInfo - Extract the personality and type infos from an eh.selector
2963 /// call, and add them to the specified machine basic block.
2964 void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2965                   MachineBasicBlock *MBB) {
2966   // Inform the MachineModuleInfo of the personality for this landing pad.
2967   ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2968   assert(CE->getOpcode() == Instruction::BitCast &&
2969          isa<Function>(CE->getOperand(0)) &&
2970          "Personality should be a function");
2971   MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2972
2973   // Gather all the type infos for this landing pad and pass them along to
2974   // MachineModuleInfo.
2975   std::vector<GlobalVariable *> TyInfo;
2976   unsigned N = I.getNumOperands();
2977
2978   for (unsigned i = N - 1; i > 2; --i) {
2979     if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2980       unsigned FilterLength = CI->getZExtValue();
2981       unsigned FirstCatch = i + FilterLength + !FilterLength;
2982       assert (FirstCatch <= N && "Invalid filter length");
2983
2984       if (FirstCatch < N) {
2985         TyInfo.reserve(N - FirstCatch);
2986         for (unsigned j = FirstCatch; j < N; ++j)
2987           TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2988         MMI->addCatchTypeInfo(MBB, TyInfo);
2989         TyInfo.clear();
2990       }
2991
2992       if (!FilterLength) {
2993         // Cleanup.
2994         MMI->addCleanup(MBB);
2995       } else {
2996         // Filter.
2997         TyInfo.reserve(FilterLength - 1);
2998         for (unsigned j = i + 1; j < FirstCatch; ++j)
2999           TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3000         MMI->addFilterTypeInfo(MBB, TyInfo);
3001         TyInfo.clear();
3002       }
3003
3004       N = i;
3005     }
3006   }
3007
3008   if (N > 3) {
3009     TyInfo.reserve(N - 3);
3010     for (unsigned j = 3; j < N; ++j)
3011       TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3012     MMI->addCatchTypeInfo(MBB, TyInfo);
3013   }
3014 }
3015
3016 }
3017
3018 /// GetSignificand - Get the significand and build it into a floating-point
3019 /// number with exponent of 1:
3020 ///
3021 ///   Op = (Op & 0x007fffff) | 0x3f800000;
3022 ///
3023 /// where Op is the hexidecimal representation of floating point value.
3024 static SDValue
3025 GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) {
3026   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3027                            DAG.getConstant(0x007fffff, MVT::i32));
3028   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3029                            DAG.getConstant(0x3f800000, MVT::i32));
3030   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2);
3031 }
3032
3033 /// GetExponent - Get the exponent:
3034 ///
3035 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
3036 ///
3037 /// where Op is the hexidecimal representation of floating point value.
3038 static SDValue
3039 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3040             DebugLoc dl) {
3041   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3042                            DAG.getConstant(0x7f800000, MVT::i32));
3043   SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
3044                            DAG.getConstant(23, TLI.getPointerTy()));
3045   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3046                            DAG.getConstant(127, MVT::i32));
3047   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
3048 }
3049
3050 /// getF32Constant - Get 32-bit floating point constant.
3051 static SDValue
3052 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
3053   return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
3054 }
3055
3056 /// Inlined utility function to implement binary input atomic intrinsics for
3057 /// visitIntrinsicCall: I is a call instruction
3058 ///                     Op is the associated NodeType for I
3059 const char *
3060 SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
3061   SDValue Root = getRoot();
3062   SDValue L =
3063     DAG.getAtomic(Op, getCurDebugLoc(),
3064                   getValue(I.getOperand(2)).getValueType().getSimpleVT(),
3065                   Root,
3066                   getValue(I.getOperand(1)),
3067                   getValue(I.getOperand(2)),
3068                   I.getOperand(1));
3069   setValue(&I, L);
3070   DAG.setRoot(L.getValue(1));
3071   return 0;
3072 }
3073
3074 // implVisitAluOverflow - Lower arithmetic overflow instrinsics.
3075 const char *
3076 SelectionDAGLowering::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
3077   SDValue Op1 = getValue(I.getOperand(1));
3078   SDValue Op2 = getValue(I.getOperand(2));
3079
3080   SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
3081   SDValue Result = DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2);
3082
3083   setValue(&I, Result);
3084   return 0;
3085 }
3086
3087 /// visitExp - Lower an exp intrinsic. Handles the special sequences for
3088 /// limited-precision mode.
3089 void
3090 SelectionDAGLowering::visitExp(CallInst &I) {
3091   SDValue result;
3092   DebugLoc dl = getCurDebugLoc();
3093
3094   if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3095       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3096     SDValue Op = getValue(I.getOperand(1));
3097
3098     // Put the exponent in the right bit position for later addition to the
3099     // final result:
3100     //
3101     //   #define LOG2OFe 1.4426950f
3102     //   IntegerPartOfX = ((int32_t)(X * LOG2OFe));
3103     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3104                              getF32Constant(DAG, 0x3fb8aa3b));
3105     SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3106
3107     //   FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
3108     SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3109     SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3110
3111     //   IntegerPartOfX <<= 23;
3112     IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3113                                  DAG.getConstant(23, TLI.getPointerTy()));
3114
3115     if (LimitFloatPrecision <= 6) {
3116       // For floating-point precision of 6:
3117       //
3118       //   TwoToFractionalPartOfX =
3119       //     0.997535578f +
3120       //       (0.735607626f + 0.252464424f * x) * x;
3121       //
3122       // error 0.0144103317, which is 6 bits
3123       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3124                                getF32Constant(DAG, 0x3e814304));
3125       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3126                                getF32Constant(DAG, 0x3f3c50c8));
3127       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3128       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3129                                getF32Constant(DAG, 0x3f7f5e7e));
3130       SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5);
3131
3132       // Add the exponent into the result in integer domain.
3133       SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3134                                TwoToFracPartOfX, IntegerPartOfX);
3135
3136       result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6);
3137     } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3138       // For floating-point precision of 12:
3139       //
3140       //   TwoToFractionalPartOfX =
3141       //     0.999892986f +
3142       //       (0.696457318f +
3143       //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
3144       //
3145       // 0.000107046256 error, which is 13 to 14 bits
3146       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3147                                getF32Constant(DAG, 0x3da235e3));
3148       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3149                                getF32Constant(DAG, 0x3e65b8f3));
3150       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3151       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3152                                getF32Constant(DAG, 0x3f324b07));
3153       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3154       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3155                                getF32Constant(DAG, 0x3f7ff8fd));
3156       SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7);
3157
3158       // Add the exponent into the result in integer domain.
3159       SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3160                                TwoToFracPartOfX, IntegerPartOfX);
3161
3162       result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8);
3163     } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3164       // For floating-point precision of 18:
3165       //
3166       //   TwoToFractionalPartOfX =
3167       //     0.999999982f +
3168       //       (0.693148872f +
3169       //         (0.240227044f +
3170       //           (0.554906021e-1f +
3171       //             (0.961591928e-2f +
3172       //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3173       //
3174       // error 2.47208000*10^(-7), which is better than 18 bits
3175       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3176                                getF32Constant(DAG, 0x3924b03e));
3177       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3178                                getF32Constant(DAG, 0x3ab24b87));
3179       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3180       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3181                                getF32Constant(DAG, 0x3c1d8c17));
3182       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3183       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3184                                getF32Constant(DAG, 0x3d634a1d));
3185       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3186       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3187                                getF32Constant(DAG, 0x3e75fe14));
3188       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3189       SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3190                                 getF32Constant(DAG, 0x3f317234));
3191       SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3192       SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3193                                 getF32Constant(DAG, 0x3f800000));
3194       SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,
3195                                              MVT::i32, t13);
3196
3197       // Add the exponent into the result in integer domain.
3198       SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3199                                 TwoToFracPartOfX, IntegerPartOfX);
3200
3201       result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14);
3202     }
3203   } else {
3204     // No special expansion.
3205     result = DAG.getNode(ISD::FEXP, dl,
3206                          getValue(I.getOperand(1)).getValueType(),
3207                          getValue(I.getOperand(1)));
3208   }
3209
3210   setValue(&I, result);
3211 }
3212
3213 /// visitLog - Lower a log intrinsic. Handles the special sequences for
3214 /// limited-precision mode.
3215 void
3216 SelectionDAGLowering::visitLog(CallInst &I) {
3217   SDValue result;
3218   DebugLoc dl = getCurDebugLoc();
3219
3220   if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3221       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3222     SDValue Op = getValue(I.getOperand(1));
3223     SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3224
3225     // Scale the exponent by log(2) [0.69314718f].
3226     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3227     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3228                                         getF32Constant(DAG, 0x3f317218));
3229
3230     // Get the significand and build it into a floating-point number with
3231     // exponent of 1.
3232     SDValue X = GetSignificand(DAG, Op1, dl);
3233
3234     if (LimitFloatPrecision <= 6) {
3235       // For floating-point precision of 6:
3236       //
3237       //   LogofMantissa =
3238       //     -1.1609546f +
3239       //       (1.4034025f - 0.23903021f * x) * x;
3240       //
3241       // error 0.0034276066, which is better than 8 bits
3242       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3243                                getF32Constant(DAG, 0xbe74c456));
3244       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3245                                getF32Constant(DAG, 0x3fb3a2b1));
3246       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3247       SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3248                                           getF32Constant(DAG, 0x3f949a29));
3249
3250       result = DAG.getNode(ISD::FADD, dl,
3251                            MVT::f32, LogOfExponent, LogOfMantissa);
3252     } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3253       // For floating-point precision of 12:
3254       //
3255       //   LogOfMantissa =
3256       //     -1.7417939f +
3257       //       (2.8212026f +
3258       //         (-1.4699568f +
3259       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3260       //
3261       // error 0.000061011436, which is 14 bits
3262       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3263                                getF32Constant(DAG, 0xbd67b6d6));
3264       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3265                                getF32Constant(DAG, 0x3ee4f4b8));
3266       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3267       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3268                                getF32Constant(DAG, 0x3fbc278b));
3269       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3270       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3271                                getF32Constant(DAG, 0x40348e95));
3272       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3273       SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3274                                           getF32Constant(DAG, 0x3fdef31a));
3275
3276       result = DAG.getNode(ISD::FADD, dl,
3277                            MVT::f32, LogOfExponent, LogOfMantissa);
3278     } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3279       // For floating-point precision of 18:
3280       //
3281       //   LogOfMantissa =
3282       //     -2.1072184f +
3283       //       (4.2372794f +
3284       //         (-3.7029485f +
3285       //           (2.2781945f +
3286       //             (-0.87823314f +
3287       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3288       //
3289       // error 0.0000023660568, which is better than 18 bits
3290       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3291                                getF32Constant(DAG, 0xbc91e5ac));
3292       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3293                                getF32Constant(DAG, 0x3e4350aa));
3294       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3295       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3296                                getF32Constant(DAG, 0x3f60d3e3));
3297       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3298       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3299                                getF32Constant(DAG, 0x4011cdf0));
3300       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3301       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3302                                getF32Constant(DAG, 0x406cfd1c));
3303       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3304       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3305                                getF32Constant(DAG, 0x408797cb));
3306       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3307       SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3308                                           getF32Constant(DAG, 0x4006dcab));
3309
3310       result = DAG.getNode(ISD::FADD, dl,
3311                            MVT::f32, LogOfExponent, LogOfMantissa);
3312     }
3313   } else {
3314     // No special expansion.
3315     result = DAG.getNode(ISD::FLOG, dl,
3316                          getValue(I.getOperand(1)).getValueType(),
3317                          getValue(I.getOperand(1)));
3318   }
3319
3320   setValue(&I, result);
3321 }
3322
3323 /// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3324 /// limited-precision mode.
3325 void
3326 SelectionDAGLowering::visitLog2(CallInst &I) {
3327   SDValue result;
3328   DebugLoc dl = getCurDebugLoc();
3329
3330   if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3331       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3332     SDValue Op = getValue(I.getOperand(1));
3333     SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3334
3335     // Get the exponent.
3336     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
3337
3338     // Get the significand and build it into a floating-point number with
3339     // exponent of 1.
3340     SDValue X = GetSignificand(DAG, Op1, dl);
3341
3342     // Different possible minimax approximations of significand in
3343     // floating-point for various degrees of accuracy over [1,2].
3344     if (LimitFloatPrecision <= 6) {
3345       // For floating-point precision of 6:
3346       //
3347       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3348       //
3349       // error 0.0049451742, which is more than 7 bits
3350       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3351                                getF32Constant(DAG, 0xbeb08fe0));
3352       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3353                                getF32Constant(DAG, 0x40019463));
3354       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3355       SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3356                                            getF32Constant(DAG, 0x3fd6633d));
3357
3358       result = DAG.getNode(ISD::FADD, dl,
3359                            MVT::f32, LogOfExponent, Log2ofMantissa);
3360     } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3361       // For floating-point precision of 12:
3362       //
3363       //   Log2ofMantissa =
3364       //     -2.51285454f +
3365       //       (4.07009056f +
3366       //         (-2.12067489f +
3367       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3368       //
3369       // error 0.0000876136000, which is better than 13 bits
3370       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3371                                getF32Constant(DAG, 0xbda7262e));
3372       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3373                                getF32Constant(DAG, 0x3f25280b));
3374       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3375       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3376                                getF32Constant(DAG, 0x4007b923));
3377       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3378       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3379                                getF32Constant(DAG, 0x40823e2f));
3380       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3381       SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3382                                            getF32Constant(DAG, 0x4020d29c));
3383
3384       result = DAG.getNode(ISD::FADD, dl,
3385                            MVT::f32, LogOfExponent, Log2ofMantissa);
3386     } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3387       // For floating-point precision of 18:
3388       //
3389       //   Log2ofMantissa =
3390       //     -3.0400495f +
3391       //       (6.1129976f +
3392       //         (-5.3420409f +
3393       //           (3.2865683f +
3394       //             (-1.2669343f +
3395       //               (0.27515199f -
3396       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3397       //
3398       // error 0.0000018516, which is better than 18 bits
3399       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3400                                getF32Constant(DAG, 0xbcd2769e));
3401       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3402                                getF32Constant(DAG, 0x3e8ce0b9));
3403       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3404       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3405                                getF32Constant(DAG, 0x3fa22ae7));
3406       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3407       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3408                                getF32Constant(DAG, 0x40525723));
3409       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3410       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3411                                getF32Constant(DAG, 0x40aaf200));
3412       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3413       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3414                                getF32Constant(DAG, 0x40c39dad));
3415       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3416       SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3417                                            getF32Constant(DAG, 0x4042902c));
3418
3419       result = DAG.getNode(ISD::FADD, dl,
3420                            MVT::f32, LogOfExponent, Log2ofMantissa);
3421     }
3422   } else {
3423     // No special expansion.
3424     result = DAG.getNode(ISD::FLOG2, dl,
3425                          getValue(I.getOperand(1)).getValueType(),
3426                          getValue(I.getOperand(1)));
3427   }
3428
3429   setValue(&I, result);
3430 }
3431
3432 /// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3433 /// limited-precision mode.
3434 void
3435 SelectionDAGLowering::visitLog10(CallInst &I) {
3436   SDValue result;
3437   DebugLoc dl = getCurDebugLoc();
3438
3439   if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3440       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3441     SDValue Op = getValue(I.getOperand(1));
3442     SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3443
3444     // Scale the exponent by log10(2) [0.30102999f].
3445     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3446     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3447                                         getF32Constant(DAG, 0x3e9a209a));
3448
3449     // Get the significand and build it into a floating-point number with
3450     // exponent of 1.
3451     SDValue X = GetSignificand(DAG, Op1, dl);
3452
3453     if (LimitFloatPrecision <= 6) {
3454       // For floating-point precision of 6:
3455       //
3456       //   Log10ofMantissa =
3457       //     -0.50419619f +
3458       //       (0.60948995f - 0.10380950f * x) * x;
3459       //
3460       // error 0.0014886165, which is 6 bits
3461       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3462                                getF32Constant(DAG, 0xbdd49a13));
3463       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3464                                getF32Constant(DAG, 0x3f1c0789));
3465       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3466       SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3467                                             getF32Constant(DAG, 0x3f011300));
3468
3469       result = DAG.getNode(ISD::FADD, dl,
3470                            MVT::f32, LogOfExponent, Log10ofMantissa);
3471     } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3472       // For floating-point precision of 12:
3473       //
3474       //   Log10ofMantissa =
3475       //     -0.64831180f +
3476       //       (0.91751397f +
3477       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3478       //
3479       // error 0.00019228036, which is better than 12 bits
3480       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3481                                getF32Constant(DAG, 0x3d431f31));
3482       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3483                                getF32Constant(DAG, 0x3ea21fb2));
3484       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3485       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3486                                getF32Constant(DAG, 0x3f6ae232));
3487       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3488       SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3489                                             getF32Constant(DAG, 0x3f25f7c3));
3490
3491       result = DAG.getNode(ISD::FADD, dl,
3492                            MVT::f32, LogOfExponent, Log10ofMantissa);
3493     } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3494       // For floating-point precision of 18:
3495       //
3496       //   Log10ofMantissa =
3497       //     -0.84299375f +
3498       //       (1.5327582f +
3499       //         (-1.0688956f +
3500       //           (0.49102474f +
3501       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3502       //
3503       // error 0.0000037995730, which is better than 18 bits
3504       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3505                                getF32Constant(DAG, 0x3c5d51ce));
3506       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3507                                getF32Constant(DAG, 0x3e00685a));
3508       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3509       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3510                                getF32Constant(DAG, 0x3efb6798));
3511       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3512       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3513                                getF32Constant(DAG, 0x3f88d192));
3514       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3515       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3516                                getF32Constant(DAG, 0x3fc4316c));
3517       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3518       SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
3519                                             getF32Constant(DAG, 0x3f57ce70));
3520
3521       result = DAG.getNode(ISD::FADD, dl,
3522                            MVT::f32, LogOfExponent, Log10ofMantissa);
3523     }
3524   } else {
3525     // No special expansion.
3526     result = DAG.getNode(ISD::FLOG10, dl,
3527                          getValue(I.getOperand(1)).getValueType(),
3528                          getValue(I.getOperand(1)));
3529   }
3530
3531   setValue(&I, result);
3532 }
3533
3534 /// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3535 /// limited-precision mode.
3536 void
3537 SelectionDAGLowering::visitExp2(CallInst &I) {
3538   SDValue result;
3539   DebugLoc dl = getCurDebugLoc();
3540
3541   if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3542       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3543     SDValue Op = getValue(I.getOperand(1));
3544
3545     SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
3546
3547     //   FractionalPartOfX = x - (float)IntegerPartOfX;
3548     SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3549     SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
3550
3551     //   IntegerPartOfX <<= 23;
3552     IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3553                                  DAG.getConstant(23, TLI.getPointerTy()));
3554
3555     if (LimitFloatPrecision <= 6) {
3556       // For floating-point precision of 6:
3557       //
3558       //   TwoToFractionalPartOfX =
3559       //     0.997535578f +
3560       //       (0.735607626f + 0.252464424f * x) * x;
3561       //
3562       // error 0.0144103317, which is 6 bits
3563       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3564                                getF32Constant(DAG, 0x3e814304));
3565       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3566                                getF32Constant(DAG, 0x3f3c50c8));
3567       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3568       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3569                                getF32Constant(DAG, 0x3f7f5e7e));
3570       SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
3571       SDValue TwoToFractionalPartOfX =
3572         DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3573
3574       result = DAG.getNode(ISD::BIT_CONVERT, dl,
3575                            MVT::f32, TwoToFractionalPartOfX);
3576     } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3577       // For floating-point precision of 12:
3578       //
3579       //   TwoToFractionalPartOfX =
3580       //     0.999892986f +
3581       //       (0.696457318f +
3582       //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
3583       //
3584       // error 0.000107046256, which is 13 to 14 bits
3585       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3586                                getF32Constant(DAG, 0x3da235e3));
3587       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3588                                getF32Constant(DAG, 0x3e65b8f3));
3589       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3590       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3591                                getF32Constant(DAG, 0x3f324b07));
3592       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3593       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3594                                getF32Constant(DAG, 0x3f7ff8fd));
3595       SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
3596       SDValue TwoToFractionalPartOfX =
3597         DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
3598
3599       result = DAG.getNode(ISD::BIT_CONVERT, dl,
3600                            MVT::f32, TwoToFractionalPartOfX);
3601     } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3602       // For floating-point precision of 18:
3603       //
3604       //   TwoToFractionalPartOfX =
3605       //     0.999999982f +
3606       //       (0.693148872f +
3607       //         (0.240227044f +
3608       //           (0.554906021e-1f +
3609       //             (0.961591928e-2f +
3610       //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3611       // error 2.47208000*10^(-7), which is better than 18 bits
3612       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3613                                getF32Constant(DAG, 0x3924b03e));
3614       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3615                                getF32Constant(DAG, 0x3ab24b87));
3616       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3617       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3618                                getF32Constant(DAG, 0x3c1d8c17));
3619       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3620       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3621                                getF32Constant(DAG, 0x3d634a1d));
3622       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3623       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3624                                getF32Constant(DAG, 0x3e75fe14));
3625       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3626       SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3627                                 getF32Constant(DAG, 0x3f317234));
3628       SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3629       SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3630                                 getF32Constant(DAG, 0x3f800000));
3631       SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
3632       SDValue TwoToFractionalPartOfX =
3633         DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
3634
3635       result = DAG.getNode(ISD::BIT_CONVERT, dl,
3636                            MVT::f32, TwoToFractionalPartOfX);
3637     }
3638   } else {
3639     // No special expansion.
3640     result = DAG.getNode(ISD::FEXP2, dl,
3641                          getValue(I.getOperand(1)).getValueType(),
3642                          getValue(I.getOperand(1)));
3643   }
3644
3645   setValue(&I, result);
3646 }
3647
3648 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
3649 /// limited-precision mode with x == 10.0f.
3650 void
3651 SelectionDAGLowering::visitPow(CallInst &I) {
3652   SDValue result;
3653   Value *Val = I.getOperand(1);
3654   DebugLoc dl = getCurDebugLoc();
3655   bool IsExp10 = false;
3656
3657   if (getValue(Val).getValueType() == MVT::f32 &&
3658       getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
3659       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3660     if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3661       if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3662         APFloat Ten(10.0f);
3663         IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3664       }
3665     }
3666   }
3667
3668   if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3669     SDValue Op = getValue(I.getOperand(2));
3670
3671     // Put the exponent in the right bit position for later addition to the
3672     // final result:
3673     //
3674     //   #define LOG2OF10 3.3219281f
3675     //   IntegerPartOfX = (int32_t)(x * LOG2OF10);
3676     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3677                              getF32Constant(DAG, 0x40549a78));
3678     SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3679
3680     //   FractionalPartOfX = x - (float)IntegerPartOfX;
3681     SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3682     SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3683
3684     //   IntegerPartOfX <<= 23;
3685     IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3686                                  DAG.getConstant(23, TLI.getPointerTy()));
3687
3688     if (LimitFloatPrecision <= 6) {
3689       // For floating-point precision of 6:
3690       //
3691       //   twoToFractionalPartOfX =
3692       //     0.997535578f +
3693       //       (0.735607626f + 0.252464424f * x) * x;
3694       //
3695       // error 0.0144103317, which is 6 bits
3696       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3697                                getF32Constant(DAG, 0x3e814304));
3698       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3699                                getF32Constant(DAG, 0x3f3c50c8));
3700       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3701       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3702                                getF32Constant(DAG, 0x3f7f5e7e));
3703       SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
3704       SDValue TwoToFractionalPartOfX =
3705         DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3706
3707       result = DAG.getNode(ISD::BIT_CONVERT, dl,
3708                            MVT::f32, TwoToFractionalPartOfX);
3709     } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3710       // For floating-point precision of 12:
3711       //
3712       //   TwoToFractionalPartOfX =
3713       //     0.999892986f +
3714       //       (0.696457318f +
3715       //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
3716       //
3717       // error 0.000107046256, which is 13 to 14 bits
3718       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3719                                getF32Constant(DAG, 0x3da235e3));
3720       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3721                                getF32Constant(DAG, 0x3e65b8f3));
3722       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3723       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3724                                getF32Constant(DAG, 0x3f324b07));
3725       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3726       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3727                                getF32Constant(DAG, 0x3f7ff8fd));
3728       SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
3729       SDValue TwoToFractionalPartOfX =
3730         DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
3731
3732       result = DAG.getNode(ISD::BIT_CONVERT, dl,
3733                            MVT::f32, TwoToFractionalPartOfX);
3734     } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3735       // For floating-point precision of 18:
3736       //
3737       //   TwoToFractionalPartOfX =
3738       //     0.999999982f +
3739       //       (0.693148872f +
3740       //         (0.240227044f +
3741       //           (0.554906021e-1f +
3742       //             (0.961591928e-2f +
3743       //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3744       // error 2.47208000*10^(-7), which is better than 18 bits
3745       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3746                                getF32Constant(DAG, 0x3924b03e));
3747       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3748                                getF32Constant(DAG, 0x3ab24b87));
3749       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3750       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3751                                getF32Constant(DAG, 0x3c1d8c17));
3752       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3753       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3754                                getF32Constant(DAG, 0x3d634a1d));
3755       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3756       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3757                                getF32Constant(DAG, 0x3e75fe14));
3758       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3759       SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3760                                 getF32Constant(DAG, 0x3f317234));
3761       SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3762       SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3763                                 getF32Constant(DAG, 0x3f800000));
3764       SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
3765       SDValue TwoToFractionalPartOfX =
3766         DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
3767
3768       result = DAG.getNode(ISD::BIT_CONVERT, dl,
3769                            MVT::f32, TwoToFractionalPartOfX);
3770     }
3771   } else {
3772     // No special expansion.
3773     result = DAG.getNode(ISD::FPOW, dl,
3774                          getValue(I.getOperand(1)).getValueType(),
3775                          getValue(I.getOperand(1)),
3776                          getValue(I.getOperand(2)));
3777   }
3778
3779   setValue(&I, result);
3780 }
3781
3782 /// visitIntrinsicCall - Lower the call to the specified intrinsic function.  If
3783 /// we want to emit this as a call to a named external function, return the name
3784 /// otherwise lower it and return null.
3785 const char *
3786 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3787   DebugLoc dl = getCurDebugLoc();
3788   switch (Intrinsic) {
3789   default:
3790     // By default, turn this into a target intrinsic node.
3791     visitTargetIntrinsic(I, Intrinsic);
3792     return 0;
3793   case Intrinsic::vastart:  visitVAStart(I); return 0;
3794   case Intrinsic::vaend:    visitVAEnd(I); return 0;
3795   case Intrinsic::vacopy:   visitVACopy(I); return 0;
3796   case Intrinsic::returnaddress:
3797     setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
3798                              getValue(I.getOperand(1))));
3799     return 0;
3800   case Intrinsic::frameaddress:
3801     setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
3802                              getValue(I.getOperand(1))));
3803     return 0;
3804   case Intrinsic::setjmp:
3805     return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3806     break;
3807   case Intrinsic::longjmp:
3808     return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3809     break;
3810   case Intrinsic::memcpy: {
3811     SDValue Op1 = getValue(I.getOperand(1));
3812     SDValue Op2 = getValue(I.getOperand(2));
3813     SDValue Op3 = getValue(I.getOperand(3));
3814     unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3815     DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
3816                               I.getOperand(1), 0, I.getOperand(2), 0));
3817     return 0;
3818   }
3819   case Intrinsic::memset: {
3820     SDValue Op1 = getValue(I.getOperand(1));
3821     SDValue Op2 = getValue(I.getOperand(2));
3822     SDValue Op3 = getValue(I.getOperand(3));
3823     unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3824     DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align,
3825                               I.getOperand(1), 0));
3826     return 0;
3827   }
3828   case Intrinsic::memmove: {
3829     SDValue Op1 = getValue(I.getOperand(1));
3830     SDValue Op2 = getValue(I.getOperand(2));
3831     SDValue Op3 = getValue(I.getOperand(3));
3832     unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3833
3834     // If the source and destination are known to not be aliases, we can
3835     // lower memmove as memcpy.
3836     uint64_t Size = -1ULL;
3837     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
3838       Size = C->getZExtValue();
3839     if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3840         AliasAnalysis::NoAlias) {
3841       DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
3842                                 I.getOperand(1), 0, I.getOperand(2), 0));
3843       return 0;
3844     }
3845
3846     DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align,
3847                                I.getOperand(1), 0, I.getOperand(2), 0));
3848     return 0;
3849   }
3850   case Intrinsic::dbg_stoppoint: {
3851     DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
3852     if (isValidDebugInfoIntrinsic(SPI, CodeGenOpt::Default)) {
3853       MachineFunction &MF = DAG.getMachineFunction();
3854       DebugLoc Loc = ExtractDebugLocation(SPI, MF.getDebugLocInfo());
3855       setCurDebugLoc(Loc);
3856
3857       if (OptLevel == CodeGenOpt::None)
3858         DAG.setRoot(DAG.getDbgStopPoint(Loc, getRoot(),
3859                                         SPI.getLine(),
3860                                         SPI.getColumn(),
3861                                         SPI.getContext()));
3862     }
3863     return 0;
3864   }
3865   case Intrinsic::dbg_region_start: {
3866     DwarfWriter *DW = DAG.getDwarfWriter();
3867     DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
3868     if (isValidDebugInfoIntrinsic(RSI, OptLevel) && DW
3869         && DW->ShouldEmitDwarfDebug()) {
3870       unsigned LabelID =
3871         DW->RecordRegionStart(cast<GlobalVariable>(RSI.getContext()));
3872       DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3873                                getRoot(), LabelID));
3874     }
3875     return 0;
3876   }
3877   case Intrinsic::dbg_region_end: {
3878     DwarfWriter *DW = DAG.getDwarfWriter();
3879     DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
3880
3881     if (!isValidDebugInfoIntrinsic(REI, OptLevel) || !DW
3882         || !DW->ShouldEmitDwarfDebug()) 
3883       return 0;
3884
3885     MachineFunction &MF = DAG.getMachineFunction();
3886     DISubprogram Subprogram(cast<GlobalVariable>(REI.getContext()));
3887     
3888     if (isInlinedFnEnd(REI, MF.getFunction())) {
3889       // This is end of inlined function. Debugging information for inlined
3890       // function is not handled yet (only supported by FastISel).
3891       if (OptLevel == CodeGenOpt::None) {
3892         unsigned ID = DW->RecordInlinedFnEnd(Subprogram);
3893         if (ID != 0)
3894           // Returned ID is 0 if this is unbalanced "end of inlined
3895           // scope". This could happen if optimizer eats dbg intrinsics or
3896           // "beginning of inlined scope" is not recoginized due to missing
3897           // location info. In such cases, do ignore this region.end.
3898           DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(), 
3899                                    getRoot(), ID));
3900       }
3901       return 0;
3902     } 
3903
3904     unsigned LabelID =
3905       DW->RecordRegionEnd(cast<GlobalVariable>(REI.getContext()));
3906     DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3907                              getRoot(), LabelID));
3908     return 0;
3909   }
3910   case Intrinsic::dbg_func_start: {
3911     DwarfWriter *DW = DAG.getDwarfWriter();
3912     DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
3913     if (!isValidDebugInfoIntrinsic(FSI, CodeGenOpt::None))
3914       return 0;
3915
3916     MachineFunction &MF = DAG.getMachineFunction();
3917     // This is a beginning of an inlined function.
3918     if (isInlinedFnStart(FSI, MF.getFunction())) {
3919       if (OptLevel != CodeGenOpt::None)
3920         // FIXME: Debugging informaation for inlined function is only
3921         // supported at CodeGenOpt::Node.
3922         return 0;
3923       
3924       DebugLoc PrevLoc = CurDebugLoc;
3925       // If llvm.dbg.func.start is seen in a new block before any
3926       // llvm.dbg.stoppoint intrinsic then the location info is unknown.
3927       // FIXME : Why DebugLoc is reset at the beginning of each block ?
3928       if (PrevLoc.isUnknown())
3929         return 0;
3930       
3931       // Record the source line.
3932       setCurDebugLoc(ExtractDebugLocation(FSI, MF.getDebugLocInfo()));
3933       
3934       if (!DW || !DW->ShouldEmitDwarfDebug())
3935         return 0;
3936       DebugLocTuple PrevLocTpl = MF.getDebugLocTuple(PrevLoc);
3937       DISubprogram SP(cast<GlobalVariable>(FSI.getSubprogram()));
3938       DICompileUnit CU(PrevLocTpl.CompileUnit);
3939       unsigned LabelID = DW->RecordInlinedFnStart(SP, CU,
3940                                                   PrevLocTpl.Line,
3941                                                   PrevLocTpl.Col);
3942       DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3943                                getRoot(), LabelID));
3944       return 0;
3945     }
3946
3947     // This is a beginning of a new function.
3948     MF.setDefaultDebugLoc(ExtractDebugLocation(FSI, MF.getDebugLocInfo()));
3949
3950     if (!DW || !DW->ShouldEmitDwarfDebug())
3951       return 0;
3952     // llvm.dbg.func_start also defines beginning of function scope.
3953     DW->RecordRegionStart(cast<GlobalVariable>(FSI.getSubprogram()));
3954     return 0;
3955   }
3956   case Intrinsic::dbg_declare: {
3957     if (OptLevel != CodeGenOpt::None) 
3958       // FIXME: Variable debug info is not supported here.
3959       return 0;
3960
3961     DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3962     if (!isValidDebugInfoIntrinsic(DI, CodeGenOpt::None))
3963       return 0;
3964
3965     Value *Variable = DI.getVariable();
3966     DAG.setRoot(DAG.getNode(ISD::DECLARE, dl, MVT::Other, getRoot(),
3967                             getValue(DI.getAddress()), getValue(Variable)));
3968     return 0;
3969   }
3970   case Intrinsic::eh_exception: {
3971     // Insert the EXCEPTIONADDR instruction.
3972     assert(CurMBB->isLandingPad() &&"Call to eh.exception not in landing pad!");
3973     SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3974     SDValue Ops[1];
3975     Ops[0] = DAG.getRoot();
3976     SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
3977     setValue(&I, Op);
3978     DAG.setRoot(Op.getValue(1));
3979     return 0;
3980   }
3981
3982   case Intrinsic::eh_selector_i32:
3983   case Intrinsic::eh_selector_i64: {
3984     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3985     MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
3986                          MVT::i32 : MVT::i64);
3987
3988     if (MMI) {
3989       if (CurMBB->isLandingPad())
3990         AddCatchInfo(I, MMI, CurMBB);
3991       else {
3992 #ifndef NDEBUG
3993         FuncInfo.CatchInfoLost.insert(&I);
3994 #endif
3995         // FIXME: Mark exception selector register as live in.  Hack for PR1508.
3996         unsigned Reg = TLI.getExceptionSelectorRegister();
3997         if (Reg) CurMBB->addLiveIn(Reg);
3998       }
3999
4000       // Insert the EHSELECTION instruction.
4001       SDVTList VTs = DAG.getVTList(VT, MVT::Other);
4002       SDValue Ops[2];
4003       Ops[0] = getValue(I.getOperand(1));
4004       Ops[1] = getRoot();
4005       SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
4006       setValue(&I, Op);
4007       DAG.setRoot(Op.getValue(1));
4008     } else {
4009       setValue(&I, DAG.getConstant(0, VT));
4010     }
4011
4012     return 0;
4013   }
4014
4015   case Intrinsic::eh_typeid_for_i32:
4016   case Intrinsic::eh_typeid_for_i64: {
4017     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4018     MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
4019                          MVT::i32 : MVT::i64);
4020
4021     if (MMI) {
4022       // Find the type id for the given typeinfo.
4023       GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
4024
4025       unsigned TypeID = MMI->getTypeIDFor(GV);
4026       setValue(&I, DAG.getConstant(TypeID, VT));
4027     } else {
4028       // Return something different to eh_selector.
4029       setValue(&I, DAG.getConstant(1, VT));
4030     }
4031
4032     return 0;
4033   }
4034
4035   case Intrinsic::eh_return_i32:
4036   case Intrinsic::eh_return_i64:
4037     if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
4038       MMI->setCallsEHReturn(true);
4039       DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
4040                               MVT::Other,
4041                               getControlRoot(),
4042                               getValue(I.getOperand(1)),
4043                               getValue(I.getOperand(2))));
4044     } else {
4045       setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
4046     }
4047
4048     return 0;
4049   case Intrinsic::eh_unwind_init:
4050     if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
4051       MMI->setCallsUnwindInit(true);
4052     }
4053
4054     return 0;
4055
4056   case Intrinsic::eh_dwarf_cfa: {
4057     MVT VT = getValue(I.getOperand(1)).getValueType();
4058     SDValue CfaArg;
4059     if (VT.bitsGT(TLI.getPointerTy()))
4060       CfaArg = DAG.getNode(ISD::TRUNCATE, dl,
4061                            TLI.getPointerTy(), getValue(I.getOperand(1)));
4062     else
4063       CfaArg = DAG.getNode(ISD::SIGN_EXTEND, dl,
4064                            TLI.getPointerTy(), getValue(I.getOperand(1)));
4065
4066     SDValue Offset = DAG.getNode(ISD::ADD, dl,
4067                                  TLI.getPointerTy(),
4068                                  DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
4069                                              TLI.getPointerTy()),
4070                                  CfaArg);
4071     setValue(&I, DAG.getNode(ISD::ADD, dl,
4072                              TLI.getPointerTy(),
4073                              DAG.getNode(ISD::FRAMEADDR, dl,
4074                                          TLI.getPointerTy(),
4075                                          DAG.getConstant(0,
4076                                                          TLI.getPointerTy())),
4077                              Offset));
4078     return 0;
4079   }
4080
4081   case Intrinsic::convertff:
4082   case Intrinsic::convertfsi:
4083   case Intrinsic::convertfui:
4084   case Intrinsic::convertsif:
4085   case Intrinsic::convertuif:
4086   case Intrinsic::convertss:
4087   case Intrinsic::convertsu:
4088   case Intrinsic::convertus:
4089   case Intrinsic::convertuu: {
4090     ISD::CvtCode Code = ISD::CVT_INVALID;
4091     switch (Intrinsic) {
4092     case Intrinsic::convertff:  Code = ISD::CVT_FF; break;
4093     case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4094     case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4095     case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4096     case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4097     case Intrinsic::convertss:  Code = ISD::CVT_SS; break;
4098     case Intrinsic::convertsu:  Code = ISD::CVT_SU; break;
4099     case Intrinsic::convertus:  Code = ISD::CVT_US; break;
4100     case Intrinsic::convertuu:  Code = ISD::CVT_UU; break;
4101     }
4102     MVT DestVT = TLI.getValueType(I.getType());
4103     Value* Op1 = I.getOperand(1);
4104     setValue(&I, DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
4105                                 DAG.getValueType(DestVT),
4106                                 DAG.getValueType(getValue(Op1).getValueType()),
4107                                 getValue(I.getOperand(2)),
4108                                 getValue(I.getOperand(3)),
4109                                 Code));
4110     return 0;
4111   }
4112
4113   case Intrinsic::sqrt:
4114     setValue(&I, DAG.getNode(ISD::FSQRT, dl,
4115                              getValue(I.getOperand(1)).getValueType(),
4116                              getValue(I.getOperand(1))));
4117     return 0;
4118   case Intrinsic::powi:
4119     setValue(&I, DAG.getNode(ISD::FPOWI, dl,
4120                              getValue(I.getOperand(1)).getValueType(),
4121                              getValue(I.getOperand(1)),
4122                              getValue(I.getOperand(2))));
4123     return 0;
4124   case Intrinsic::sin:
4125     setValue(&I, DAG.getNode(ISD::FSIN, dl,
4126                              getValue(I.getOperand(1)).getValueType(),
4127                              getValue(I.getOperand(1))));
4128     return 0;
4129   case Intrinsic::cos:
4130     setValue(&I, DAG.getNode(ISD::FCOS, dl,
4131                              getValue(I.getOperand(1)).getValueType(),
4132                              getValue(I.getOperand(1))));
4133     return 0;
4134   case Intrinsic::log:
4135     visitLog(I);
4136     return 0;
4137   case Intrinsic::log2:
4138     visitLog2(I);
4139     return 0;
4140   case Intrinsic::log10:
4141     visitLog10(I);
4142     return 0;
4143   case Intrinsic::exp:
4144     visitExp(I);
4145     return 0;
4146   case Intrinsic::exp2:
4147     visitExp2(I);
4148     return 0;
4149   case Intrinsic::pow:
4150     visitPow(I);
4151     return 0;
4152   case Intrinsic::pcmarker: {
4153     SDValue Tmp = getValue(I.getOperand(1));
4154     DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
4155     return 0;
4156   }
4157   case Intrinsic::readcyclecounter: {
4158     SDValue Op = getRoot();
4159     SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER, dl,
4160                               DAG.getVTList(MVT::i64, MVT::Other),
4161                               &Op, 1);
4162     setValue(&I, Tmp);
4163     DAG.setRoot(Tmp.getValue(1));
4164     return 0;
4165   }
4166   case Intrinsic::bswap:
4167     setValue(&I, DAG.getNode(ISD::BSWAP, dl,
4168                              getValue(I.getOperand(1)).getValueType(),
4169                              getValue(I.getOperand(1))));
4170     return 0;
4171   case Intrinsic::cttz: {
4172     SDValue Arg = getValue(I.getOperand(1));
4173     MVT Ty = Arg.getValueType();
4174     SDValue result = DAG.getNode(ISD::CTTZ, dl, Ty, Arg);
4175     setValue(&I, result);
4176     return 0;
4177   }
4178   case Intrinsic::ctlz: {
4179     SDValue Arg = getValue(I.getOperand(1));
4180     MVT Ty = Arg.getValueType();
4181     SDValue result = DAG.getNode(ISD::CTLZ, dl, Ty, Arg);
4182     setValue(&I, result);
4183     return 0;
4184   }
4185   case Intrinsic::ctpop: {
4186     SDValue Arg = getValue(I.getOperand(1));
4187     MVT Ty = Arg.getValueType();
4188     SDValue result = DAG.getNode(ISD::CTPOP, dl, Ty, Arg);
4189     setValue(&I, result);
4190     return 0;
4191   }
4192   case Intrinsic::stacksave: {
4193     SDValue Op = getRoot();
4194     SDValue Tmp = DAG.getNode(ISD::STACKSAVE, dl,
4195               DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
4196     setValue(&I, Tmp);
4197     DAG.setRoot(Tmp.getValue(1));
4198     return 0;
4199   }
4200   case Intrinsic::stackrestore: {
4201     SDValue Tmp = getValue(I.getOperand(1));
4202     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Tmp));
4203     return 0;
4204   }
4205   case Intrinsic::stackprotector: {
4206     // Emit code into the DAG to store the stack guard onto the stack.
4207     MachineFunction &MF = DAG.getMachineFunction();
4208     MachineFrameInfo *MFI = MF.getFrameInfo();
4209     MVT PtrTy = TLI.getPointerTy();
4210
4211     SDValue Src = getValue(I.getOperand(1));   // The guard's value.
4212     AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
4213
4214     int FI = FuncInfo.StaticAllocaMap[Slot];
4215     MFI->setStackProtectorIndex(FI);
4216
4217     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4218
4219     // Store the stack protector onto the stack.
4220     SDValue Result = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
4221                                   PseudoSourceValue::getFixedStack(FI),
4222                                   0, true);
4223     setValue(&I, Result);
4224     DAG.setRoot(Result);
4225     return 0;
4226   }
4227   case Intrinsic::var_annotation:
4228     // Discard annotate attributes
4229     return 0;
4230
4231   case Intrinsic::init_trampoline: {
4232     const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4233
4234     SDValue Ops[6];
4235     Ops[0] = getRoot();
4236     Ops[1] = getValue(I.getOperand(1));
4237     Ops[2] = getValue(I.getOperand(2));
4238     Ops[3] = getValue(I.getOperand(3));
4239     Ops[4] = DAG.getSrcValue(I.getOperand(1));
4240     Ops[5] = DAG.getSrcValue(F);
4241
4242     SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE, dl,
4243                               DAG.getVTList(TLI.getPointerTy(), MVT::Other),
4244                               Ops, 6);
4245
4246     setValue(&I, Tmp);
4247     DAG.setRoot(Tmp.getValue(1));
4248     return 0;
4249   }
4250
4251   case Intrinsic::gcroot:
4252     if (GFI) {
4253       Value *Alloca = I.getOperand(1);
4254       Constant *TypeMap = cast<Constant>(I.getOperand(2));
4255
4256       FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4257       GFI->addStackRoot(FI->getIndex(), TypeMap);
4258     }
4259     return 0;
4260
4261   case Intrinsic::gcread:
4262   case Intrinsic::gcwrite:
4263     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
4264     return 0;
4265
4266   case Intrinsic::flt_rounds: {
4267     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
4268     return 0;
4269   }
4270
4271   case Intrinsic::trap: {
4272     DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
4273     return 0;
4274   }
4275
4276   case Intrinsic::uadd_with_overflow:
4277     return implVisitAluOverflow(I, ISD::UADDO);
4278   case Intrinsic::sadd_with_overflow:
4279     return implVisitAluOverflow(I, ISD::SADDO);
4280   case Intrinsic::usub_with_overflow:
4281     return implVisitAluOverflow(I, ISD::USUBO);
4282   case Intrinsic::ssub_with_overflow:
4283     return implVisitAluOverflow(I, ISD::SSUBO);
4284   case Intrinsic::umul_with_overflow:
4285     return implVisitAluOverflow(I, ISD::UMULO);
4286   case Intrinsic::smul_with_overflow:
4287     return implVisitAluOverflow(I, ISD::SMULO);
4288
4289   case Intrinsic::prefetch: {
4290     SDValue Ops[4];
4291     Ops[0] = getRoot();
4292     Ops[1] = getValue(I.getOperand(1));
4293     Ops[2] = getValue(I.getOperand(2));
4294     Ops[3] = getValue(I.getOperand(3));
4295     DAG.setRoot(DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4));
4296     return 0;
4297   }
4298
4299   case Intrinsic::memory_barrier: {
4300     SDValue Ops[6];
4301     Ops[0] = getRoot();
4302     for (int x = 1; x < 6; ++x)
4303       Ops[x] = getValue(I.getOperand(x));
4304
4305     DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6));
4306     return 0;
4307   }
4308   case Intrinsic::atomic_cmp_swap: {
4309     SDValue Root = getRoot();
4310     SDValue L =
4311       DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
4312                     getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4313                     Root,
4314                     getValue(I.getOperand(1)),
4315                     getValue(I.getOperand(2)),
4316                     getValue(I.getOperand(3)),
4317                     I.getOperand(1));
4318     setValue(&I, L);
4319     DAG.setRoot(L.getValue(1));
4320     return 0;
4321   }
4322   case Intrinsic::atomic_load_add:
4323     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
4324   case Intrinsic::atomic_load_sub:
4325     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
4326   case Intrinsic::atomic_load_or:
4327     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
4328   case Intrinsic::atomic_load_xor:
4329     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
4330   case Intrinsic::atomic_load_and:
4331     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
4332   case Intrinsic::atomic_load_nand:
4333     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
4334   case Intrinsic::atomic_load_max:
4335     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
4336   case Intrinsic::atomic_load_min:
4337     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
4338   case Intrinsic::atomic_load_umin:
4339     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
4340   case Intrinsic::atomic_load_umax:
4341     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
4342   case Intrinsic::atomic_swap:
4343     return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
4344   }
4345 }
4346
4347 /// Test if the given instruction is in a position to be optimized
4348 /// with a tail-call. This roughly means that it's in a block with
4349 /// a return and there's nothing that needs to be scheduled
4350 /// between it and the return.
4351 ///
4352 /// This function only tests target-independent requirements.
4353 /// For target-dependent requirements, a target should override
4354 /// TargetLowering::IsEligibleForTailCallOptimization.
4355 ///
4356 static bool
4357 isInTailCallPosition(const Instruction *I, Attributes RetAttr,
4358                      const TargetLowering &TLI) {
4359   const BasicBlock *ExitBB = I->getParent();
4360   const TerminatorInst *Term = ExitBB->getTerminator();
4361   const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
4362   const Function *F = ExitBB->getParent();
4363
4364   // The block must end in a return statement or an unreachable.
4365   if (!Ret && !isa<UnreachableInst>(Term)) return false;
4366
4367   // If I will have a chain, make sure no other instruction that will have a
4368   // chain interposes between I and the return.
4369   if (I->mayHaveSideEffects() || I->mayReadFromMemory() ||
4370       !I->isSafeToSpeculativelyExecute())
4371     for (BasicBlock::const_iterator BBI = prior(prior(ExitBB->end())); ;
4372          --BBI) {
4373       if (&*BBI == I)
4374         break;
4375       if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
4376           !BBI->isSafeToSpeculativelyExecute())
4377         return false;
4378     }
4379
4380   // If the block ends with a void return or unreachable, it doesn't matter
4381   // what the call's return type is.
4382   if (!Ret || Ret->getNumOperands() == 0) return true;
4383
4384   // Conservatively require the attributes of the call to match those of
4385   // the return.
4386   if (F->getAttributes().getRetAttributes() != RetAttr)
4387     return false;
4388
4389   // Otherwise, make sure the unmodified return value of I is the return value.
4390   for (const Instruction *U = dyn_cast<Instruction>(Ret->getOperand(0)); ;
4391        U = dyn_cast<Instruction>(U->getOperand(0))) {
4392     if (!U)
4393       return false;
4394     if (!U->hasOneUse())
4395       return false;
4396     if (U == I)
4397       break;
4398     // Check for a truly no-op truncate.
4399     if (isa<TruncInst>(U) &&
4400         TLI.isTruncateFree(U->getOperand(0)->getType(), U->getType()))
4401       continue;
4402     // Check for a truly no-op bitcast.
4403     if (isa<BitCastInst>(U) &&
4404         (U->getOperand(0)->getType() == U->getType() ||
4405          (isa<PointerType>(U->getOperand(0)->getType()) &&
4406           isa<PointerType>(U->getType()))))
4407       continue;
4408     // Otherwise it's not a true no-op.
4409     return false;
4410   }
4411
4412   return true;
4413 }
4414
4415 void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
4416                                        bool isTailCall,
4417                                        MachineBasicBlock *LandingPad) {
4418   const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4419   const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4420   MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4421   unsigned BeginLabel = 0, EndLabel = 0;
4422
4423   TargetLowering::ArgListTy Args;
4424   TargetLowering::ArgListEntry Entry;
4425   Args.reserve(CS.arg_size());
4426   unsigned j = 1;
4427   for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4428        i != e; ++i, ++j) {
4429     SDValue ArgNode = getValue(*i);
4430     Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4431
4432     unsigned attrInd = i - CS.arg_begin() + 1;
4433     Entry.isSExt  = CS.paramHasAttr(attrInd, Attribute::SExt);
4434     Entry.isZExt  = CS.paramHasAttr(attrInd, Attribute::ZExt);
4435     Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4436     Entry.isSRet  = CS.paramHasAttr(attrInd, Attribute::StructRet);
4437     Entry.isNest  = CS.paramHasAttr(attrInd, Attribute::Nest);
4438     Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
4439     Entry.Alignment = CS.getParamAlignment(attrInd);
4440     Args.push_back(Entry);
4441   }
4442
4443   if (LandingPad && MMI) {
4444     // Insert a label before the invoke call to mark the try range.  This can be
4445     // used to detect deletion of the invoke via the MachineModuleInfo.
4446     BeginLabel = MMI->NextLabelID();
4447     // Both PendingLoads and PendingExports must be flushed here;
4448     // this call might not return.
4449     (void)getRoot();
4450     DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4451                              getControlRoot(), BeginLabel));
4452   }
4453
4454   // Check if target-independent constraints permit a tail call here.
4455   // Target-dependent constraints are checked within TLI.LowerCallTo.
4456   if (isTailCall &&
4457       !isInTailCallPosition(CS.getInstruction(),
4458                             CS.getAttributes().getRetAttributes(),
4459                             TLI))
4460     isTailCall = false;
4461
4462   std::pair<SDValue,SDValue> Result =
4463     TLI.LowerCallTo(getRoot(), CS.getType(),
4464                     CS.paramHasAttr(0, Attribute::SExt),
4465                     CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4466                     CS.paramHasAttr(0, Attribute::InReg), FTy->getNumParams(),
4467                     CS.getCallingConv(),
4468                     isTailCall,
4469                     !CS.getInstruction()->use_empty(),
4470                     Callee, Args, DAG, getCurDebugLoc());
4471   assert((isTailCall || CS.getType() == Type::VoidTy ||
4472           Result.first.getNode()) &&
4473          "Non-null value expected with non-void non-tail call!");
4474   assert((isTailCall || Result.second.getNode()) &&
4475          "Non-null chain expected with non-tail call!");
4476   assert((Result.second.getNode() || !Result.first.getNode()) &&
4477          "Null value expected with tail call!");
4478   if (Result.first.getNode())
4479     setValue(CS.getInstruction(), Result.first);
4480   // As a special case, a null chain means that a tail call has
4481   // been emitted and the DAG root is already updated.
4482   if (Result.second.getNode())
4483     DAG.setRoot(Result.second);
4484   else
4485     HasTailCall = true;
4486
4487   if (LandingPad && MMI) {
4488     // Insert a label at the end of the invoke call to mark the try range.  This
4489     // can be used to detect deletion of the invoke via the MachineModuleInfo.
4490     EndLabel = MMI->NextLabelID();
4491     DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4492                              getRoot(), EndLabel));
4493
4494     // Inform MachineModuleInfo of range.
4495     MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4496   }
4497 }
4498
4499
4500 void SelectionDAGLowering::visitCall(CallInst &I) {
4501   const char *RenameFn = 0;
4502   if (Function *F = I.getCalledFunction()) {
4503     if (F->isDeclaration()) {
4504       const TargetIntrinsicInfo *II = TLI.getTargetMachine().getIntrinsicInfo();
4505       if (II) {
4506         if (unsigned IID = II->getIntrinsicID(F)) {
4507           RenameFn = visitIntrinsicCall(I, IID);
4508           if (!RenameFn)
4509             return;
4510         }
4511       }
4512       if (unsigned IID = F->getIntrinsicID()) {
4513         RenameFn = visitIntrinsicCall(I, IID);
4514         if (!RenameFn)
4515           return;
4516       }
4517     }
4518
4519     // Check for well-known libc/libm calls.  If the function is internal, it
4520     // can't be a library call.
4521     if (!F->hasLocalLinkage() && F->hasName()) {
4522       StringRef Name = F->getName();
4523       if (Name == "copysign" || Name == "copysignf") {
4524         if (I.getNumOperands() == 3 &&   // Basic sanity checks.
4525             I.getOperand(1)->getType()->isFloatingPoint() &&
4526             I.getType() == I.getOperand(1)->getType() &&
4527             I.getType() == I.getOperand(2)->getType()) {
4528           SDValue LHS = getValue(I.getOperand(1));
4529           SDValue RHS = getValue(I.getOperand(2));
4530           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
4531                                    LHS.getValueType(), LHS, RHS));
4532           return;
4533         }
4534       } else if (Name == "fabs" || Name == "fabsf" || Name == "fabsl") {
4535         if (I.getNumOperands() == 2 &&   // Basic sanity checks.
4536             I.getOperand(1)->getType()->isFloatingPoint() &&
4537             I.getType() == I.getOperand(1)->getType()) {
4538           SDValue Tmp = getValue(I.getOperand(1));
4539           setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
4540                                    Tmp.getValueType(), Tmp));
4541           return;
4542         }
4543       } else if (Name == "sin" || Name == "sinf" || Name == "sinl") {
4544         if (I.getNumOperands() == 2 &&   // Basic sanity checks.
4545             I.getOperand(1)->getType()->isFloatingPoint() &&
4546             I.getType() == I.getOperand(1)->getType()) {
4547           SDValue Tmp = getValue(I.getOperand(1));
4548           setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
4549                                    Tmp.getValueType(), Tmp));
4550           return;
4551         }
4552       } else if (Name == "cos" || Name == "cosf" || Name == "cosl") {
4553         if (I.getNumOperands() == 2 &&   // Basic sanity checks.
4554             I.getOperand(1)->getType()->isFloatingPoint() &&
4555             I.getType() == I.getOperand(1)->getType()) {
4556           SDValue Tmp = getValue(I.getOperand(1));
4557           setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
4558                                    Tmp.getValueType(), Tmp));
4559           return;
4560         }
4561       }
4562     }
4563   } else if (isa<InlineAsm>(I.getOperand(0))) {
4564     visitInlineAsm(&I);
4565     return;
4566   }
4567
4568   SDValue Callee;
4569   if (!RenameFn)
4570     Callee = getValue(I.getOperand(0));
4571   else
4572     Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
4573
4574   // Check if we can potentially perform a tail call. More detailed
4575   // checking is be done within LowerCallTo, after more information
4576   // about the call is known.
4577   bool isTailCall = PerformTailCallOpt && I.isTailCall();
4578
4579   LowerCallTo(&I, Callee, isTailCall);
4580 }
4581
4582
4583 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
4584 /// this value and returns the result as a ValueVT value.  This uses
4585 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4586 /// If the Flag pointer is NULL, no flag is used.
4587 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
4588                                       SDValue &Chain,
4589                                       SDValue *Flag) const {
4590   // Assemble the legal parts into the final values.
4591   SmallVector<SDValue, 4> Values(ValueVTs.size());
4592   SmallVector<SDValue, 8> Parts;
4593   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4594     // Copy the legal parts from the registers.
4595     MVT ValueVT = ValueVTs[Value];
4596     unsigned NumRegs = TLI->getNumRegisters(ValueVT);
4597     MVT RegisterVT = RegVTs[Value];
4598
4599     Parts.resize(NumRegs);
4600     for (unsigned i = 0; i != NumRegs; ++i) {
4601       SDValue P;
4602       if (Flag == 0)
4603         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
4604       else {
4605         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
4606         *Flag = P.getValue(2);
4607       }
4608       Chain = P.getValue(1);
4609
4610       // If the source register was virtual and if we know something about it,
4611       // add an assert node.
4612       if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4613           RegisterVT.isInteger() && !RegisterVT.isVector()) {
4614         unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4615         FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4616         if (FLI.LiveOutRegInfo.size() > SlotNo) {
4617           FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
4618
4619           unsigned RegSize = RegisterVT.getSizeInBits();
4620           unsigned NumSignBits = LOI.NumSignBits;
4621           unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
4622
4623           // FIXME: We capture more information than the dag can represent.  For
4624           // now, just use the tightest assertzext/assertsext possible.
4625           bool isSExt = true;
4626           MVT FromVT(MVT::Other);
4627           if (NumSignBits == RegSize)
4628             isSExt = true, FromVT = MVT::i1;   // ASSERT SEXT 1
4629           else if (NumZeroBits >= RegSize-1)
4630             isSExt = false, FromVT = MVT::i1;  // ASSERT ZEXT 1
4631           else if (NumSignBits > RegSize-8)
4632             isSExt = true, FromVT = MVT::i8;   // ASSERT SEXT 8
4633           else if (NumZeroBits >= RegSize-8)
4634             isSExt = false, FromVT = MVT::i8;  // ASSERT ZEXT 8
4635           else if (NumSignBits > RegSize-16)
4636             isSExt = true, FromVT = MVT::i16;  // ASSERT SEXT 16
4637           else if (NumZeroBits >= RegSize-16)
4638             isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
4639           else if (NumSignBits > RegSize-32)
4640             isSExt = true, FromVT = MVT::i32;  // ASSERT SEXT 32
4641           else if (NumZeroBits >= RegSize-32)
4642             isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
4643
4644           if (FromVT != MVT::Other) {
4645             P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
4646                             RegisterVT, P, DAG.getValueType(FromVT));
4647
4648           }
4649         }
4650       }
4651
4652       Parts[i] = P;
4653     }
4654
4655     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
4656                                      NumRegs, RegisterVT, ValueVT);
4657     Part += NumRegs;
4658     Parts.clear();
4659   }
4660
4661   return DAG.getNode(ISD::MERGE_VALUES, dl,
4662                      DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4663                      &Values[0], ValueVTs.size());
4664 }
4665
4666 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
4667 /// specified value into the registers specified by this object.  This uses
4668 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4669 /// If the Flag pointer is NULL, no flag is used.
4670 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
4671                                  SDValue &Chain, SDValue *Flag) const {
4672   // Get the list of the values's legal parts.
4673   unsigned NumRegs = Regs.size();
4674   SmallVector<SDValue, 8> Parts(NumRegs);
4675   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4676     MVT ValueVT = ValueVTs[Value];
4677     unsigned NumParts = TLI->getNumRegisters(ValueVT);
4678     MVT RegisterVT = RegVTs[Value];
4679
4680     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
4681                    &Parts[Part], NumParts, RegisterVT);
4682     Part += NumParts;
4683   }
4684
4685   // Copy the parts into the registers.
4686   SmallVector<SDValue, 8> Chains(NumRegs);
4687   for (unsigned i = 0; i != NumRegs; ++i) {
4688     SDValue Part;
4689     if (Flag == 0)
4690       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
4691     else {
4692       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
4693       *Flag = Part.getValue(1);
4694     }
4695     Chains[i] = Part.getValue(0);
4696   }
4697
4698   if (NumRegs == 1 || Flag)
4699     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
4700     // flagged to it. That is the CopyToReg nodes and the user are considered
4701     // a single scheduling unit. If we create a TokenFactor and return it as
4702     // chain, then the TokenFactor is both a predecessor (operand) of the
4703     // user as well as a successor (the TF operands are flagged to the user).
4704     // c1, f1 = CopyToReg
4705     // c2, f2 = CopyToReg
4706     // c3     = TokenFactor c1, c2
4707     // ...
4708     //        = op c3, ..., f2
4709     Chain = Chains[NumRegs-1];
4710   else
4711     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
4712 }
4713
4714 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
4715 /// operand list.  This adds the code marker and includes the number of
4716 /// values added into it.
4717 void RegsForValue::AddInlineAsmOperands(unsigned Code,
4718                                         bool HasMatching,unsigned MatchingIdx,
4719                                         SelectionDAG &DAG,
4720                                         std::vector<SDValue> &Ops) const {
4721   MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
4722   assert(Regs.size() < (1 << 13) && "Too many inline asm outputs!");
4723   unsigned Flag = Code | (Regs.size() << 3);
4724   if (HasMatching)
4725     Flag |= 0x80000000 | (MatchingIdx << 16);
4726   Ops.push_back(DAG.getTargetConstant(Flag, IntPtrTy));
4727   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4728     unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
4729     MVT RegisterVT = RegVTs[Value];
4730     for (unsigned i = 0; i != NumRegs; ++i) {
4731       assert(Reg < Regs.size() && "Mismatch in # registers expected");
4732       Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
4733     }
4734   }
4735 }
4736
4737 /// isAllocatableRegister - If the specified register is safe to allocate,
4738 /// i.e. it isn't a stack pointer or some other special register, return the
4739 /// register class for the register.  Otherwise, return null.
4740 static const TargetRegisterClass *
4741 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4742                       const TargetLowering &TLI,
4743                       const TargetRegisterInfo *TRI) {
4744   MVT FoundVT = MVT::Other;
4745   const TargetRegisterClass *FoundRC = 0;
4746   for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4747        E = TRI->regclass_end(); RCI != E; ++RCI) {
4748     MVT ThisVT = MVT::Other;
4749
4750     const TargetRegisterClass *RC = *RCI;
4751     // If none of the the value types for this register class are valid, we
4752     // can't use it.  For example, 64-bit reg classes on 32-bit targets.
4753     for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4754          I != E; ++I) {
4755       if (TLI.isTypeLegal(*I)) {
4756         // If we have already found this register in a different register class,
4757         // choose the one with the largest VT specified.  For example, on
4758         // PowerPC, we favor f64 register classes over f32.
4759         if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
4760           ThisVT = *I;
4761           break;
4762         }
4763       }
4764     }
4765
4766     if (ThisVT == MVT::Other) continue;
4767
4768     // NOTE: This isn't ideal.  In particular, this might allocate the
4769     // frame pointer in functions that need it (due to them not being taken
4770     // out of allocation, because a variable sized allocation hasn't been seen
4771     // yet).  This is a slight code pessimization, but should still work.
4772     for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4773          E = RC->allocation_order_end(MF); I != E; ++I)
4774       if (*I == Reg) {
4775         // We found a matching register class.  Keep looking at others in case
4776         // we find one with larger registers that this physreg is also in.
4777         FoundRC = RC;
4778         FoundVT = ThisVT;
4779         break;
4780       }
4781   }
4782   return FoundRC;
4783 }
4784
4785
4786 namespace llvm {
4787 /// AsmOperandInfo - This contains information for each constraint that we are
4788 /// lowering.
4789 class VISIBILITY_HIDDEN SDISelAsmOperandInfo :
4790     public TargetLowering::AsmOperandInfo {
4791 public:
4792   /// CallOperand - If this is the result output operand or a clobber
4793   /// this is null, otherwise it is the incoming operand to the CallInst.
4794   /// This gets modified as the asm is processed.
4795   SDValue CallOperand;
4796
4797   /// AssignedRegs - If this is a register or register class operand, this
4798   /// contains the set of register corresponding to the operand.
4799   RegsForValue AssignedRegs;
4800
4801   explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4802     : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4803   }
4804
4805   /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4806   /// busy in OutputRegs/InputRegs.
4807   void MarkAllocatedRegs(bool isOutReg, bool isInReg,
4808                          std::set<unsigned> &OutputRegs,
4809                          std::set<unsigned> &InputRegs,
4810                          const TargetRegisterInfo &TRI) const {
4811     if (isOutReg) {
4812       for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4813         MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4814     }
4815     if (isInReg) {
4816       for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4817         MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4818     }
4819   }
4820
4821   /// getCallOperandValMVT - Return the MVT of the Value* that this operand
4822   /// corresponds to.  If there is no Value* for this operand, it returns
4823   /// MVT::Other.
4824   MVT getCallOperandValMVT(const TargetLowering &TLI,
4825                            const TargetData *TD) const {
4826     if (CallOperandVal == 0) return MVT::Other;
4827
4828     if (isa<BasicBlock>(CallOperandVal))
4829       return TLI.getPointerTy();
4830
4831     const llvm::Type *OpTy = CallOperandVal->getType();
4832
4833     // If this is an indirect operand, the operand is a pointer to the
4834     // accessed type.
4835     if (isIndirect)
4836       OpTy = cast<PointerType>(OpTy)->getElementType();
4837
4838     // If OpTy is not a single value, it may be a struct/union that we
4839     // can tile with integers.
4840     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4841       unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4842       switch (BitSize) {
4843       default: break;
4844       case 1:
4845       case 8:
4846       case 16:
4847       case 32:
4848       case 64:
4849       case 128:
4850         OpTy = IntegerType::get(BitSize);
4851         break;
4852       }
4853     }
4854
4855     return TLI.getValueType(OpTy, true);
4856   }
4857
4858 private:
4859   /// MarkRegAndAliases - Mark the specified register and all aliases in the
4860   /// specified set.
4861   static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
4862                                 const TargetRegisterInfo &TRI) {
4863     assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4864     Regs.insert(Reg);
4865     if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4866       for (; *Aliases; ++Aliases)
4867         Regs.insert(*Aliases);
4868   }
4869 };
4870 } // end llvm namespace.
4871
4872
4873 /// GetRegistersForValue - Assign registers (virtual or physical) for the
4874 /// specified operand.  We prefer to assign virtual registers, to allow the
4875 /// register allocator handle the assignment process.  However, if the asm uses
4876 /// features that we can't model on machineinstrs, we have SDISel do the
4877 /// allocation.  This produces generally horrible, but correct, code.
4878 ///
4879 ///   OpInfo describes the operand.
4880 ///   Input and OutputRegs are the set of already allocated physical registers.
4881 ///
4882 void SelectionDAGLowering::
4883 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
4884                      std::set<unsigned> &OutputRegs,
4885                      std::set<unsigned> &InputRegs) {
4886   // Compute whether this value requires an input register, an output register,
4887   // or both.
4888   bool isOutReg = false;
4889   bool isInReg = false;
4890   switch (OpInfo.Type) {
4891   case InlineAsm::isOutput:
4892     isOutReg = true;
4893
4894     // If there is an input constraint that matches this, we need to reserve
4895     // the input register so no other inputs allocate to it.
4896     isInReg = OpInfo.hasMatchingInput();
4897     break;
4898   case InlineAsm::isInput:
4899     isInReg = true;
4900     isOutReg = false;
4901     break;
4902   case InlineAsm::isClobber:
4903     isOutReg = true;
4904     isInReg = true;
4905     break;
4906   }
4907
4908
4909   MachineFunction &MF = DAG.getMachineFunction();
4910   SmallVector<unsigned, 4> Regs;
4911
4912   // If this is a constraint for a single physreg, or a constraint for a
4913   // register class, find it.
4914   std::pair<unsigned, const TargetRegisterClass*> PhysReg =
4915     TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4916                                      OpInfo.ConstraintVT);
4917
4918   unsigned NumRegs = 1;
4919   if (OpInfo.ConstraintVT != MVT::Other) {
4920     // If this is a FP input in an integer register (or visa versa) insert a bit
4921     // cast of the input value.  More generally, handle any case where the input
4922     // value disagrees with the register class we plan to stick this in.
4923     if (OpInfo.Type == InlineAsm::isInput &&
4924         PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
4925       // Try to convert to the first MVT that the reg class contains.  If the
4926       // types are identical size, use a bitcast to convert (e.g. two differing
4927       // vector types).
4928       MVT RegVT = *PhysReg.second->vt_begin();
4929       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
4930         OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
4931                                          RegVT, OpInfo.CallOperand);
4932         OpInfo.ConstraintVT = RegVT;
4933       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
4934         // If the input is a FP value and we want it in FP registers, do a
4935         // bitcast to the corresponding integer type.  This turns an f64 value
4936         // into i64, which can be passed with two i32 values on a 32-bit
4937         // machine.
4938         RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
4939         OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
4940                                          RegVT, OpInfo.CallOperand);
4941         OpInfo.ConstraintVT = RegVT;
4942       }
4943     }
4944
4945     NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
4946   }
4947
4948   MVT RegVT;
4949   MVT ValueVT = OpInfo.ConstraintVT;
4950
4951   // If this is a constraint for a specific physical register, like {r17},
4952   // assign it now.
4953   if (unsigned AssignedReg = PhysReg.first) {
4954     const TargetRegisterClass *RC = PhysReg.second;
4955     if (OpInfo.ConstraintVT == MVT::Other)
4956       ValueVT = *RC->vt_begin();
4957
4958     // Get the actual register value type.  This is important, because the user
4959     // may have asked for (e.g.) the AX register in i32 type.  We need to
4960     // remember that AX is actually i16 to get the right extension.
4961     RegVT = *RC->vt_begin();
4962
4963     // This is a explicit reference to a physical register.
4964     Regs.push_back(AssignedReg);
4965
4966     // If this is an expanded reference, add the rest of the regs to Regs.
4967     if (NumRegs != 1) {
4968       TargetRegisterClass::iterator I = RC->begin();
4969       for (; *I != AssignedReg; ++I)
4970         assert(I != RC->end() && "Didn't find reg!");
4971
4972       // Already added the first reg.
4973       --NumRegs; ++I;
4974       for (; NumRegs; --NumRegs, ++I) {
4975         assert(I != RC->end() && "Ran out of registers to allocate!");
4976         Regs.push_back(*I);
4977       }
4978     }
4979     OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4980     const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4981     OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4982     return;
4983   }
4984
4985   // Otherwise, if this was a reference to an LLVM register class, create vregs
4986   // for this reference.
4987   if (const TargetRegisterClass *RC = PhysReg.second) {
4988     RegVT = *RC->vt_begin();
4989     if (OpInfo.ConstraintVT == MVT::Other)
4990       ValueVT = RegVT;
4991
4992     // Create the appropriate number of virtual registers.
4993     MachineRegisterInfo &RegInfo = MF.getRegInfo();
4994     for (; NumRegs; --NumRegs)
4995       Regs.push_back(RegInfo.createVirtualRegister(RC));
4996
4997     OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4998     return;
4999   }
5000   
5001   // This is a reference to a register class that doesn't directly correspond
5002   // to an LLVM register class.  Allocate NumRegs consecutive, available,
5003   // registers from the class.
5004   std::vector<unsigned> RegClassRegs
5005     = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
5006                                             OpInfo.ConstraintVT);
5007
5008   const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5009   unsigned NumAllocated = 0;
5010   for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
5011     unsigned Reg = RegClassRegs[i];
5012     // See if this register is available.
5013     if ((isOutReg && OutputRegs.count(Reg)) ||   // Already used.
5014         (isInReg  && InputRegs.count(Reg))) {    // Already used.
5015       // Make sure we find consecutive registers.
5016       NumAllocated = 0;
5017       continue;
5018     }
5019
5020     // Check to see if this register is allocatable (i.e. don't give out the
5021     // stack pointer).
5022     const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI);
5023     if (!RC) {        // Couldn't allocate this register.
5024       // Reset NumAllocated to make sure we return consecutive registers.
5025       NumAllocated = 0;
5026       continue;
5027     }
5028
5029     // Okay, this register is good, we can use it.
5030     ++NumAllocated;
5031
5032     // If we allocated enough consecutive registers, succeed.
5033     if (NumAllocated == NumRegs) {
5034       unsigned RegStart = (i-NumAllocated)+1;
5035       unsigned RegEnd   = i+1;
5036       // Mark all of the allocated registers used.
5037       for (unsigned i = RegStart; i != RegEnd; ++i)
5038         Regs.push_back(RegClassRegs[i]);
5039
5040       OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
5041                                          OpInfo.ConstraintVT);
5042       OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5043       return;
5044     }
5045   }
5046
5047   // Otherwise, we couldn't allocate enough registers for this.
5048 }
5049
5050 /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
5051 /// processed uses a memory 'm' constraint.
5052 static bool
5053 hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
5054                           const TargetLowering &TLI) {
5055   for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
5056     InlineAsm::ConstraintInfo &CI = CInfos[i];
5057     for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
5058       TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
5059       if (CType == TargetLowering::C_Memory)
5060         return true;
5061     }
5062     
5063     // Indirect operand accesses access memory.
5064     if (CI.isIndirect)
5065       return true;
5066   }
5067
5068   return false;
5069 }
5070
5071 /// visitInlineAsm - Handle a call to an InlineAsm object.
5072 ///
5073 void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
5074   InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5075
5076   /// ConstraintOperands - Information about all of the constraints.
5077   std::vector<SDISelAsmOperandInfo> ConstraintOperands;
5078
5079   std::set<unsigned> OutputRegs, InputRegs;
5080
5081   // Do a prepass over the constraints, canonicalizing them, and building up the
5082   // ConstraintOperands list.
5083   std::vector<InlineAsm::ConstraintInfo>
5084     ConstraintInfos = IA->ParseConstraints();
5085
5086   bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
5087   
5088   SDValue Chain, Flag;
5089   
5090   // We won't need to flush pending loads if this asm doesn't touch
5091   // memory and is nonvolatile.
5092   if (hasMemory || IA->hasSideEffects())
5093     Chain = getRoot();
5094   else
5095     Chain = DAG.getRoot();
5096
5097   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
5098   unsigned ResNo = 0;   // ResNo - The result number of the next output.
5099   for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5100     ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
5101     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
5102
5103     MVT OpVT = MVT::Other;
5104
5105     // Compute the value type for each operand.
5106     switch (OpInfo.Type) {
5107     case InlineAsm::isOutput:
5108       // Indirect outputs just consume an argument.
5109       if (OpInfo.isIndirect) {
5110         OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5111         break;
5112       }
5113
5114       // The return value of the call is this value.  As such, there is no
5115       // corresponding argument.
5116       assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
5117       if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
5118         OpVT = TLI.getValueType(STy->getElementType(ResNo));
5119       } else {
5120         assert(ResNo == 0 && "Asm only has one result!");
5121         OpVT = TLI.getValueType(CS.getType());
5122       }
5123       ++ResNo;
5124       break;
5125     case InlineAsm::isInput:
5126       OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5127       break;
5128     case InlineAsm::isClobber:
5129       // Nothing to do.
5130       break;
5131     }
5132
5133     // If this is an input or an indirect output, process the call argument.
5134     // BasicBlocks are labels, currently appearing only in asm's.
5135     if (OpInfo.CallOperandVal) {
5136       // Strip bitcasts, if any.  This mostly comes up for functions.
5137       ConstantExpr* CE = NULL;
5138       while ((CE = dyn_cast<ConstantExpr>(OpInfo.CallOperandVal)) &&
5139              CE->getOpcode()==Instruction::BitCast)
5140         OpInfo.CallOperandVal = CE->getOperand(0);
5141       if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
5142         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
5143       } else {
5144         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
5145       }
5146
5147       OpVT = OpInfo.getCallOperandValMVT(TLI, TD);
5148     }
5149
5150     OpInfo.ConstraintVT = OpVT;
5151   }
5152
5153   // Second pass over the constraints: compute which constraint option to use
5154   // and assign registers to constraints that want a specific physreg.
5155   for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5156     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5157
5158     // If this is an output operand with a matching input operand, look up the
5159     // matching input. If their types mismatch, e.g. one is an integer, the
5160     // other is floating point, or their sizes are different, flag it as an
5161     // error.
5162     if (OpInfo.hasMatchingInput()) {
5163       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5164       if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5165         if ((OpInfo.ConstraintVT.isInteger() !=
5166              Input.ConstraintVT.isInteger()) ||
5167             (OpInfo.ConstraintVT.getSizeInBits() !=
5168              Input.ConstraintVT.getSizeInBits())) {
5169           llvm_report_error("Unsupported asm: input constraint"
5170                             " with a matching output constraint of incompatible"
5171                             " type!");
5172         }
5173         Input.ConstraintVT = OpInfo.ConstraintVT;
5174       }
5175     }
5176
5177     // Compute the constraint code and ConstraintType to use.
5178     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
5179
5180     // If this is a memory input, and if the operand is not indirect, do what we
5181     // need to to provide an address for the memory input.
5182     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5183         !OpInfo.isIndirect) {
5184       assert(OpInfo.Type == InlineAsm::isInput &&
5185              "Can only indirectify direct input operands!");
5186
5187       // Memory operands really want the address of the value.  If we don't have
5188       // an indirect input, put it in the constpool if we can, otherwise spill
5189       // it to a stack slot.
5190
5191       // If the operand is a float, integer, or vector constant, spill to a
5192       // constant pool entry to get its address.
5193       Value *OpVal = OpInfo.CallOperandVal;
5194       if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5195           isa<ConstantVector>(OpVal)) {
5196         OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5197                                                  TLI.getPointerTy());
5198       } else {
5199         // Otherwise, create a stack slot and emit a store to it before the
5200         // asm.
5201         const Type *Ty = OpVal->getType();
5202         uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
5203         unsigned Align  = TLI.getTargetData()->getPrefTypeAlignment(Ty);
5204         MachineFunction &MF = DAG.getMachineFunction();
5205         int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
5206         SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
5207         Chain = DAG.getStore(Chain, getCurDebugLoc(),
5208                              OpInfo.CallOperand, StackSlot, NULL, 0);
5209         OpInfo.CallOperand = StackSlot;
5210       }
5211
5212       // There is no longer a Value* corresponding to this operand.
5213       OpInfo.CallOperandVal = 0;
5214       // It is now an indirect operand.
5215       OpInfo.isIndirect = true;
5216     }
5217
5218     // If this constraint is for a specific register, allocate it before
5219     // anything else.
5220     if (OpInfo.ConstraintType == TargetLowering::C_Register)
5221       GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
5222   }
5223   ConstraintInfos.clear();
5224
5225
5226   // Second pass - Loop over all of the operands, assigning virtual or physregs
5227   // to register class operands.
5228   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5229     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5230
5231     // C_Register operands have already been allocated, Other/Memory don't need
5232     // to be.
5233     if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
5234       GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
5235   }
5236
5237   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
5238   std::vector<SDValue> AsmNodeOperands;
5239   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
5240   AsmNodeOperands.push_back(
5241           DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
5242
5243
5244   // Loop over all of the inputs, copying the operand values into the
5245   // appropriate registers and processing the output regs.
5246   RegsForValue RetValRegs;
5247
5248   // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
5249   std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
5250
5251   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5252     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5253
5254     switch (OpInfo.Type) {
5255     case InlineAsm::isOutput: {
5256       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5257           OpInfo.ConstraintType != TargetLowering::C_Register) {
5258         // Memory output, or 'other' output (e.g. 'X' constraint).
5259         assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5260
5261         // Add information to the INLINEASM node to know about this output.
5262         unsigned ResOpType = 4/*MEM*/ | (1<<3);
5263         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5264                                                         TLI.getPointerTy()));
5265         AsmNodeOperands.push_back(OpInfo.CallOperand);
5266         break;
5267       }
5268
5269       // Otherwise, this is a register or register class output.
5270
5271       // Copy the output from the appropriate register.  Find a register that
5272       // we can use.
5273       if (OpInfo.AssignedRegs.Regs.empty()) {
5274         llvm_report_error("Couldn't allocate output reg for"
5275                           " constraint '" + OpInfo.ConstraintCode + "'!");
5276       }
5277
5278       // If this is an indirect operand, store through the pointer after the
5279       // asm.
5280       if (OpInfo.isIndirect) {
5281         IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5282                                                       OpInfo.CallOperandVal));
5283       } else {
5284         // This is the result value of the call.
5285         assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
5286         // Concatenate this output onto the outputs list.
5287         RetValRegs.append(OpInfo.AssignedRegs);
5288       }
5289
5290       // Add information to the INLINEASM node to know that this register is
5291       // set.
5292       OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5293                                                6 /* EARLYCLOBBER REGDEF */ :
5294                                                2 /* REGDEF */ ,
5295                                                false,
5296                                                0,
5297                                                DAG, AsmNodeOperands);
5298       break;
5299     }
5300     case InlineAsm::isInput: {
5301       SDValue InOperandVal = OpInfo.CallOperand;
5302
5303       if (OpInfo.isMatchingInputConstraint()) {   // Matching constraint?
5304         // If this is required to match an output register we have already set,
5305         // just use its register.
5306         unsigned OperandNo = OpInfo.getMatchedOperand();
5307
5308         // Scan until we find the definition we already emitted of this operand.
5309         // When we find it, create a RegsForValue operand.
5310         unsigned CurOp = 2;  // The first operand.
5311         for (; OperandNo; --OperandNo) {
5312           // Advance to the next operand.
5313           unsigned OpFlag =
5314             cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5315           assert(((OpFlag & 7) == 2 /*REGDEF*/ ||
5316                   (OpFlag & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
5317                   (OpFlag & 7) == 4 /*MEM*/) &&
5318                  "Skipped past definitions?");
5319           CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
5320         }
5321
5322         unsigned OpFlag =
5323           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5324         if ((OpFlag & 7) == 2 /*REGDEF*/
5325             || (OpFlag & 7) == 6 /* EARLYCLOBBER REGDEF */) {
5326           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
5327           if (OpInfo.isIndirect) {
5328             llvm_report_error("Don't know how to handle tied indirect "
5329                               "register inputs yet!");
5330           }
5331           RegsForValue MatchedRegs;
5332           MatchedRegs.TLI = &TLI;
5333           MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
5334           MVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
5335           MatchedRegs.RegVTs.push_back(RegVT);
5336           MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
5337           for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
5338                i != e; ++i)
5339             MatchedRegs.Regs.
5340               push_back(RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
5341
5342           // Use the produced MatchedRegs object to
5343           MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5344                                     Chain, &Flag);
5345           MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/,
5346                                            true, OpInfo.getMatchedOperand(),
5347                                            DAG, AsmNodeOperands);
5348           break;
5349         } else {
5350           assert(((OpFlag & 7) == 4) && "Unknown matching constraint!");
5351           assert((InlineAsm::getNumOperandRegisters(OpFlag)) == 1 &&
5352                  "Unexpected number of operands");
5353           // Add information to the INLINEASM node to know about this input.
5354           // See InlineAsm.h isUseOperandTiedToDef.
5355           OpFlag |= 0x80000000 | (OpInfo.getMatchedOperand() << 16);
5356           AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
5357                                                           TLI.getPointerTy()));
5358           AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5359           break;
5360         }
5361       }
5362
5363       if (OpInfo.ConstraintType == TargetLowering::C_Other) {
5364         assert(!OpInfo.isIndirect &&
5365                "Don't know how to handle indirect other inputs yet!");
5366
5367         std::vector<SDValue> Ops;
5368         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
5369                                          hasMemory, Ops, DAG);
5370         if (Ops.empty()) {
5371           llvm_report_error("Invalid operand for inline asm"
5372                             " constraint '" + OpInfo.ConstraintCode + "'!");
5373         }
5374
5375         // Add information to the INLINEASM node to know about this input.
5376         unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
5377         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5378                                                         TLI.getPointerTy()));
5379         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5380         break;
5381       } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5382         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5383         assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5384                "Memory operands expect pointer values");
5385
5386         // Add information to the INLINEASM node to know about this input.
5387         unsigned ResOpType = 4/*MEM*/ | (1<<3);
5388         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5389                                                         TLI.getPointerTy()));
5390         AsmNodeOperands.push_back(InOperandVal);
5391         break;
5392       }
5393
5394       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5395               OpInfo.ConstraintType == TargetLowering::C_Register) &&
5396              "Unknown constraint type!");
5397       assert(!OpInfo.isIndirect &&
5398              "Don't know how to handle indirect register inputs yet!");
5399
5400       // Copy the input into the appropriate registers.
5401       if (OpInfo.AssignedRegs.Regs.empty()) {
5402         llvm_report_error("Couldn't allocate input reg for"
5403                           " constraint '"+ OpInfo.ConstraintCode +"'!");
5404       }
5405
5406       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5407                                         Chain, &Flag);
5408
5409       OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, false, 0,
5410                                                DAG, AsmNodeOperands);
5411       break;
5412     }
5413     case InlineAsm::isClobber: {
5414       // Add the clobbered value to the operand list, so that the register
5415       // allocator is aware that the physreg got clobbered.
5416       if (!OpInfo.AssignedRegs.Regs.empty())
5417         OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
5418                                                  false, 0, DAG,AsmNodeOperands);
5419       break;
5420     }
5421     }
5422   }
5423
5424   // Finish up input operands.
5425   AsmNodeOperands[0] = Chain;
5426   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
5427
5428   Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
5429                       DAG.getVTList(MVT::Other, MVT::Flag),
5430                       &AsmNodeOperands[0], AsmNodeOperands.size());
5431   Flag = Chain.getValue(1);
5432
5433   // If this asm returns a register value, copy the result from that register
5434   // and set it as the value of the call.
5435   if (!RetValRegs.Regs.empty()) {
5436     SDValue Val = RetValRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
5437                                              Chain, &Flag);
5438
5439     // FIXME: Why don't we do this for inline asms with MRVs?
5440     if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5441       MVT ResultType = TLI.getValueType(CS.getType());
5442
5443       // If any of the results of the inline asm is a vector, it may have the
5444       // wrong width/num elts.  This can happen for register classes that can
5445       // contain multiple different value types.  The preg or vreg allocated may
5446       // not have the same VT as was expected.  Convert it to the right type
5447       // with bit_convert.
5448       if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
5449         Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
5450                           ResultType, Val);
5451
5452       } else if (ResultType != Val.getValueType() &&
5453                  ResultType.isInteger() && Val.getValueType().isInteger()) {
5454         // If a result value was tied to an input value, the computed result may
5455         // have a wider width than the expected result.  Extract the relevant
5456         // portion.
5457         Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
5458       }
5459
5460       assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
5461     }
5462
5463     setValue(CS.getInstruction(), Val);
5464     // Don't need to use this as a chain in this case.
5465     if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
5466       return;
5467   }
5468
5469   std::vector<std::pair<SDValue, Value*> > StoresToEmit;
5470
5471   // Process indirect outputs, first output all of the flagged copies out of
5472   // physregs.
5473   for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5474     RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5475     Value *Ptr = IndirectStoresToEmit[i].second;
5476     SDValue OutVal = OutRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
5477                                              Chain, &Flag);
5478     StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
5479
5480   }
5481
5482   // Emit the non-flagged stores from the physregs.
5483   SmallVector<SDValue, 8> OutChains;
5484   for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
5485     OutChains.push_back(DAG.getStore(Chain, getCurDebugLoc(),
5486                                     StoresToEmit[i].first,
5487                                     getValue(StoresToEmit[i].second),
5488                                     StoresToEmit[i].second, 0));
5489   if (!OutChains.empty())
5490     Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
5491                         &OutChains[0], OutChains.size());
5492   DAG.setRoot(Chain);
5493 }
5494
5495
5496 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
5497   SDValue Src = getValue(I.getOperand(0));
5498
5499   // Scale up by the type size in the original i32 type width.  Various
5500   // mid-level optimizers may make assumptions about demanded bits etc from the
5501   // i32-ness of the optimizer: we do not want to promote to i64 and then
5502   // multiply on 64-bit targets.
5503   // FIXME: Malloc inst should go away: PR715.
5504   uint64_t ElementSize = TD->getTypeAllocSize(I.getType()->getElementType());
5505   if (ElementSize != 1) {
5506     // Src is always 32-bits, make sure the constant fits.
5507     assert(Src.getValueType() == MVT::i32);
5508     ElementSize = (uint32_t)ElementSize;
5509     Src = DAG.getNode(ISD::MUL, getCurDebugLoc(), Src.getValueType(),
5510                       Src, DAG.getConstant(ElementSize, Src.getValueType()));
5511   }
5512   
5513   MVT IntPtr = TLI.getPointerTy();
5514
5515   if (IntPtr.bitsLT(Src.getValueType()))
5516     Src = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), IntPtr, Src);
5517   else if (IntPtr.bitsGT(Src.getValueType()))
5518     Src = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), IntPtr, Src);
5519
5520   TargetLowering::ArgListTy Args;
5521   TargetLowering::ArgListEntry Entry;
5522   Entry.Node = Src;
5523   Entry.Ty = TLI.getTargetData()->getIntPtrType();
5524   Args.push_back(Entry);
5525
5526   bool isTailCall = PerformTailCallOpt &&
5527                     isInTailCallPosition(&I, Attribute::None, TLI);
5528   std::pair<SDValue,SDValue> Result =
5529     TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, false,
5530                     0, CallingConv::C, isTailCall,
5531                     /*isReturnValueUsed=*/true,
5532                     DAG.getExternalSymbol("malloc", IntPtr),
5533                     Args, DAG, getCurDebugLoc());
5534   if (Result.first.getNode())
5535     setValue(&I, Result.first);  // Pointers always fit in registers
5536   if (Result.second.getNode())
5537     DAG.setRoot(Result.second);
5538 }
5539
5540 void SelectionDAGLowering::visitFree(FreeInst &I) {
5541   TargetLowering::ArgListTy Args;
5542   TargetLowering::ArgListEntry Entry;
5543   Entry.Node = getValue(I.getOperand(0));
5544   Entry.Ty = TLI.getTargetData()->getIntPtrType();
5545   Args.push_back(Entry);
5546   MVT IntPtr = TLI.getPointerTy();
5547   bool isTailCall = PerformTailCallOpt &&
5548                     isInTailCallPosition(&I, Attribute::None, TLI);
5549   std::pair<SDValue,SDValue> Result =
5550     TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false, false,
5551                     0, CallingConv::C, isTailCall,
5552                     /*isReturnValueUsed=*/true,
5553                     DAG.getExternalSymbol("free", IntPtr), Args, DAG,
5554                     getCurDebugLoc());
5555   if (Result.second.getNode())
5556     DAG.setRoot(Result.second);
5557 }
5558
5559 void SelectionDAGLowering::visitVAStart(CallInst &I) {
5560   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
5561                           MVT::Other, getRoot(),
5562                           getValue(I.getOperand(1)),
5563                           DAG.getSrcValue(I.getOperand(1))));
5564 }
5565
5566 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
5567   SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
5568                            getRoot(), getValue(I.getOperand(0)),
5569                            DAG.getSrcValue(I.getOperand(0)));
5570   setValue(&I, V);
5571   DAG.setRoot(V.getValue(1));
5572 }
5573
5574 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
5575   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
5576                           MVT::Other, getRoot(),
5577                           getValue(I.getOperand(1)),
5578                           DAG.getSrcValue(I.getOperand(1))));
5579 }
5580
5581 void SelectionDAGLowering::visitVACopy(CallInst &I) {
5582   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
5583                           MVT::Other, getRoot(),
5584                           getValue(I.getOperand(1)),
5585                           getValue(I.getOperand(2)),
5586                           DAG.getSrcValue(I.getOperand(1)),
5587                           DAG.getSrcValue(I.getOperand(2))));
5588 }
5589
5590 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
5591 /// implementation, which just calls LowerCall.
5592 /// FIXME: When all targets are
5593 /// migrated to using LowerCall, this hook should be integrated into SDISel.
5594 std::pair<SDValue, SDValue>
5595 TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5596                             bool RetSExt, bool RetZExt, bool isVarArg,
5597                             bool isInreg, unsigned NumFixedArgs,
5598                             unsigned CallConv, bool isTailCall,
5599                             bool isReturnValueUsed,
5600                             SDValue Callee,
5601                             ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl) {
5602
5603   assert((!isTailCall || PerformTailCallOpt) &&
5604          "isTailCall set when tail-call optimizations are disabled!");
5605
5606   // Handle all of the outgoing arguments.
5607   SmallVector<ISD::OutputArg, 32> Outs;
5608   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5609     SmallVector<MVT, 4> ValueVTs;
5610     ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5611     for (unsigned Value = 0, NumValues = ValueVTs.size();
5612          Value != NumValues; ++Value) {
5613       MVT VT = ValueVTs[Value];
5614       const Type *ArgTy = VT.getTypeForMVT();
5615       SDValue Op = SDValue(Args[i].Node.getNode(),
5616                            Args[i].Node.getResNo() + Value);
5617       ISD::ArgFlagsTy Flags;
5618       unsigned OriginalAlignment =
5619         getTargetData()->getABITypeAlignment(ArgTy);
5620
5621       if (Args[i].isZExt)
5622         Flags.setZExt();
5623       if (Args[i].isSExt)
5624         Flags.setSExt();
5625       if (Args[i].isInReg)
5626         Flags.setInReg();
5627       if (Args[i].isSRet)
5628         Flags.setSRet();
5629       if (Args[i].isByVal) {
5630         Flags.setByVal();
5631         const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5632         const Type *ElementTy = Ty->getElementType();
5633         unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5634         unsigned FrameSize  = getTargetData()->getTypeAllocSize(ElementTy);
5635         // For ByVal, alignment should come from FE.  BE will guess if this
5636         // info is not there but there are cases it cannot get right.
5637         if (Args[i].Alignment)
5638           FrameAlign = Args[i].Alignment;
5639         Flags.setByValAlign(FrameAlign);
5640         Flags.setByValSize(FrameSize);
5641       }
5642       if (Args[i].isNest)
5643         Flags.setNest();
5644       Flags.setOrigAlign(OriginalAlignment);
5645
5646       MVT PartVT = getRegisterType(VT);
5647       unsigned NumParts = getNumRegisters(VT);
5648       SmallVector<SDValue, 4> Parts(NumParts);
5649       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5650
5651       if (Args[i].isSExt)
5652         ExtendKind = ISD::SIGN_EXTEND;
5653       else if (Args[i].isZExt)
5654         ExtendKind = ISD::ZERO_EXTEND;
5655
5656       getCopyToParts(DAG, dl, Op, &Parts[0], NumParts, PartVT, ExtendKind);
5657
5658       for (unsigned j = 0; j != NumParts; ++j) {
5659         // if it isn't first piece, alignment must be 1
5660         ISD::OutputArg MyFlags(Flags, Parts[j], i < NumFixedArgs);
5661         if (NumParts > 1 && j == 0)
5662           MyFlags.Flags.setSplit();
5663         else if (j != 0)
5664           MyFlags.Flags.setOrigAlign(1);
5665
5666         Outs.push_back(MyFlags);
5667       }
5668     }
5669   }
5670
5671   // Handle the incoming return values from the call.
5672   SmallVector<ISD::InputArg, 32> Ins;
5673   SmallVector<MVT, 4> RetTys;
5674   ComputeValueVTs(*this, RetTy, RetTys);
5675   for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5676     MVT VT = RetTys[I];
5677     MVT RegisterVT = getRegisterType(VT);
5678     unsigned NumRegs = getNumRegisters(VT);
5679     for (unsigned i = 0; i != NumRegs; ++i) {
5680       ISD::InputArg MyFlags;
5681       MyFlags.VT = RegisterVT;
5682       MyFlags.Used = isReturnValueUsed;
5683       if (RetSExt)
5684         MyFlags.Flags.setSExt();
5685       if (RetZExt)
5686         MyFlags.Flags.setZExt();
5687       if (isInreg)
5688         MyFlags.Flags.setInReg();
5689       Ins.push_back(MyFlags);
5690     }
5691   }
5692
5693   // Check if target-dependent constraints permit a tail call here.
5694   // Target-independent constraints should be checked by the caller.
5695   if (isTailCall &&
5696       !IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, Ins, DAG))
5697     isTailCall = false;
5698
5699   SmallVector<SDValue, 4> InVals;
5700   Chain = LowerCall(Chain, Callee, CallConv, isVarArg, isTailCall,
5701                     Outs, Ins, dl, DAG, InVals);
5702   assert((!isTailCall || InVals.empty()) && "Tail call had return SDValues!");
5703
5704   // For a tail call, the return value is merely live-out and there aren't
5705   // any nodes in the DAG representing it. Return a special value to
5706   // indicate that a tail call has been emitted and no more Instructions
5707   // should be processed in the current block.
5708   if (isTailCall) {
5709     DAG.setRoot(Chain);
5710     return std::make_pair(SDValue(), SDValue());
5711   }
5712
5713   // Collect the legal value parts into potentially illegal values
5714   // that correspond to the original function's return values.
5715   ISD::NodeType AssertOp = ISD::DELETED_NODE;
5716   if (RetSExt)
5717     AssertOp = ISD::AssertSext;
5718   else if (RetZExt)
5719     AssertOp = ISD::AssertZext;
5720   SmallVector<SDValue, 4> ReturnValues;
5721   unsigned CurReg = 0;
5722   for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5723     MVT VT = RetTys[I];
5724     MVT RegisterVT = getRegisterType(VT);
5725     unsigned NumRegs = getNumRegisters(VT);
5726
5727     SDValue ReturnValue =
5728       getCopyFromParts(DAG, dl, &InVals[CurReg], NumRegs, RegisterVT, VT,
5729                        AssertOp);
5730     ReturnValues.push_back(ReturnValue);
5731     CurReg += NumRegs;
5732   }
5733
5734   // For a function returning void, there is no return value. We can't create
5735   // such a node, so we just return a null return value in that case. In
5736   // that case, nothing will actualy look at the value.
5737   if (ReturnValues.empty())
5738     return std::make_pair(SDValue(), Chain);
5739
5740   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
5741                             DAG.getVTList(&RetTys[0], RetTys.size()),
5742                             &ReturnValues[0], ReturnValues.size());
5743
5744   return std::make_pair(Res, Chain);
5745 }
5746
5747 void TargetLowering::LowerOperationWrapper(SDNode *N,
5748                                            SmallVectorImpl<SDValue> &Results,
5749                                            SelectionDAG &DAG) {
5750   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
5751   if (Res.getNode())
5752     Results.push_back(Res);
5753 }
5754
5755 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5756   llvm_unreachable("LowerOperation not implemented for this target!");
5757   return SDValue();
5758 }
5759
5760
5761 void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5762   SDValue Op = getValue(V);
5763   assert((Op.getOpcode() != ISD::CopyFromReg ||
5764           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5765          "Copy from a reg to the same reg!");
5766   assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5767
5768   RegsForValue RFV(TLI, Reg, V->getType());
5769   SDValue Chain = DAG.getEntryNode();
5770   RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0);
5771   PendingExports.push_back(Chain);
5772 }
5773
5774 #include "llvm/CodeGen/SelectionDAGISel.h"
5775
5776 void SelectionDAGISel::
5777 LowerArguments(BasicBlock *LLVMBB) {
5778   // If this is the entry block, emit arguments.
5779   Function &F = *LLVMBB->getParent();
5780   SelectionDAG &DAG = SDL->DAG;
5781   SDValue OldRoot = DAG.getRoot();
5782   DebugLoc dl = SDL->getCurDebugLoc();
5783   const TargetData *TD = TLI.getTargetData();
5784
5785   // Set up the incoming argument description vector.
5786   SmallVector<ISD::InputArg, 16> Ins;
5787   unsigned Idx = 1;
5788   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5789        I != E; ++I, ++Idx) {
5790     SmallVector<MVT, 4> ValueVTs;
5791     ComputeValueVTs(TLI, I->getType(), ValueVTs);
5792     bool isArgValueUsed = !I->use_empty();
5793     for (unsigned Value = 0, NumValues = ValueVTs.size();
5794          Value != NumValues; ++Value) {
5795       MVT VT = ValueVTs[Value];
5796       const Type *ArgTy = VT.getTypeForMVT();
5797       ISD::ArgFlagsTy Flags;
5798       unsigned OriginalAlignment =
5799         TD->getABITypeAlignment(ArgTy);
5800
5801       if (F.paramHasAttr(Idx, Attribute::ZExt))
5802         Flags.setZExt();
5803       if (F.paramHasAttr(Idx, Attribute::SExt))
5804         Flags.setSExt();
5805       if (F.paramHasAttr(Idx, Attribute::InReg))
5806         Flags.setInReg();
5807       if (F.paramHasAttr(Idx, Attribute::StructRet))
5808         Flags.setSRet();
5809       if (F.paramHasAttr(Idx, Attribute::ByVal)) {
5810         Flags.setByVal();
5811         const PointerType *Ty = cast<PointerType>(I->getType());
5812         const Type *ElementTy = Ty->getElementType();
5813         unsigned FrameAlign = TLI.getByValTypeAlignment(ElementTy);
5814         unsigned FrameSize  = TD->getTypeAllocSize(ElementTy);
5815         // For ByVal, alignment should be passed from FE.  BE will guess if
5816         // this info is not there but there are cases it cannot get right.
5817         if (F.getParamAlignment(Idx))
5818           FrameAlign = F.getParamAlignment(Idx);
5819         Flags.setByValAlign(FrameAlign);
5820         Flags.setByValSize(FrameSize);
5821       }
5822       if (F.paramHasAttr(Idx, Attribute::Nest))
5823         Flags.setNest();
5824       Flags.setOrigAlign(OriginalAlignment);
5825
5826       MVT RegisterVT = TLI.getRegisterType(VT);
5827       unsigned NumRegs = TLI.getNumRegisters(VT);
5828       for (unsigned i = 0; i != NumRegs; ++i) {
5829         ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed);
5830         if (NumRegs > 1 && i == 0)
5831           MyFlags.Flags.setSplit();
5832         // if it isn't first piece, alignment must be 1
5833         else if (i > 0)
5834           MyFlags.Flags.setOrigAlign(1);
5835         Ins.push_back(MyFlags);
5836       }
5837     }
5838   }
5839
5840   // Call the target to set up the argument values.
5841   SmallVector<SDValue, 8> InVals;
5842   SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
5843                                              F.isVarArg(), Ins,
5844                                              dl, DAG, InVals);
5845   DAG.setRoot(NewRoot);
5846
5847   // Set up the argument values.
5848   unsigned i = 0;
5849   Idx = 1;
5850   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
5851       ++I, ++Idx) {
5852     SmallVector<SDValue, 4> ArgValues;
5853     SmallVector<MVT, 4> ValueVTs;
5854     ComputeValueVTs(TLI, I->getType(), ValueVTs);
5855     unsigned NumValues = ValueVTs.size();
5856     for (unsigned Value = 0; Value != NumValues; ++Value) {
5857       MVT VT = ValueVTs[Value];
5858       MVT PartVT = TLI.getRegisterType(VT);
5859       unsigned NumParts = TLI.getNumRegisters(VT);
5860
5861       if (!I->use_empty()) {
5862         ISD::NodeType AssertOp = ISD::DELETED_NODE;
5863         if (F.paramHasAttr(Idx, Attribute::SExt))
5864           AssertOp = ISD::AssertSext;
5865         else if (F.paramHasAttr(Idx, Attribute::ZExt))
5866           AssertOp = ISD::AssertZext;
5867
5868         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
5869                                              PartVT, VT, AssertOp));
5870       }
5871       i += NumParts;
5872     }
5873     if (!I->use_empty()) {
5874       SDL->setValue(I, DAG.getMergeValues(&ArgValues[0], NumValues,
5875                                           SDL->getCurDebugLoc()));
5876       // If this argument is live outside of the entry block, insert a copy from
5877       // whereever we got it to the vreg that other BB's will reference it as.
5878       SDL->CopyToExportRegsIfNeeded(I);
5879     }
5880   }
5881   assert(i == InVals.size() && "Argument register count mismatch!");
5882
5883   // Finally, if the target has anything special to do, allow it to do so.
5884   // FIXME: this should insert code into the DAG!
5885   EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
5886 }
5887
5888 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
5889 /// ensure constants are generated when needed.  Remember the virtual registers
5890 /// that need to be added to the Machine PHI nodes as input.  We cannot just
5891 /// directly add them, because expansion might result in multiple MBB's for one
5892 /// BB.  As such, the start of the BB might correspond to a different MBB than
5893 /// the end.
5894 ///
5895 void
5896 SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
5897   TerminatorInst *TI = LLVMBB->getTerminator();
5898
5899   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5900
5901   // Check successor nodes' PHI nodes that expect a constant to be available
5902   // from this block.
5903   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5904     BasicBlock *SuccBB = TI->getSuccessor(succ);
5905     if (!isa<PHINode>(SuccBB->begin())) continue;
5906     MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5907
5908     // If this terminator has multiple identical successors (common for
5909     // switches), only handle each succ once.
5910     if (!SuccsHandled.insert(SuccMBB)) continue;
5911
5912     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5913     PHINode *PN;
5914
5915     // At this point we know that there is a 1-1 correspondence between LLVM PHI
5916     // nodes and Machine PHI nodes, but the incoming operands have not been
5917     // emitted yet.
5918     for (BasicBlock::iterator I = SuccBB->begin();
5919          (PN = dyn_cast<PHINode>(I)); ++I) {
5920       // Ignore dead phi's.
5921       if (PN->use_empty()) continue;
5922
5923       unsigned Reg;
5924       Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5925
5926       if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5927         unsigned &RegOut = SDL->ConstantsOut[C];
5928         if (RegOut == 0) {
5929           RegOut = FuncInfo->CreateRegForValue(C);
5930           SDL->CopyValueToVirtualRegister(C, RegOut);
5931         }
5932         Reg = RegOut;
5933       } else {
5934         Reg = FuncInfo->ValueMap[PHIOp];
5935         if (Reg == 0) {
5936           assert(isa<AllocaInst>(PHIOp) &&
5937                  FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5938                  "Didn't codegen value into a register!??");
5939           Reg = FuncInfo->CreateRegForValue(PHIOp);
5940           SDL->CopyValueToVirtualRegister(PHIOp, Reg);
5941         }
5942       }
5943
5944       // Remember that this register needs to added to the machine PHI node as
5945       // the input for this MBB.
5946       SmallVector<MVT, 4> ValueVTs;
5947       ComputeValueVTs(TLI, PN->getType(), ValueVTs);
5948       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
5949         MVT VT = ValueVTs[vti];
5950         unsigned NumRegisters = TLI.getNumRegisters(VT);
5951         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5952           SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5953         Reg += NumRegisters;
5954       }
5955     }
5956   }
5957   SDL->ConstantsOut.clear();
5958 }
5959
5960 /// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
5961 /// supports legal types, and it emits MachineInstrs directly instead of
5962 /// creating SelectionDAG nodes.
5963 ///
5964 bool
5965 SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
5966                                                       FastISel *F) {
5967   TerminatorInst *TI = LLVMBB->getTerminator();
5968
5969   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5970   unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
5971
5972   // Check successor nodes' PHI nodes that expect a constant to be available
5973   // from this block.
5974   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5975     BasicBlock *SuccBB = TI->getSuccessor(succ);
5976     if (!isa<PHINode>(SuccBB->begin())) continue;
5977     MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5978
5979     // If this terminator has multiple identical successors (common for
5980     // switches), only handle each succ once.
5981     if (!SuccsHandled.insert(SuccMBB)) continue;
5982
5983     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5984     PHINode *PN;
5985
5986     // At this point we know that there is a 1-1 correspondence between LLVM PHI
5987     // nodes and Machine PHI nodes, but the incoming operands have not been
5988     // emitted yet.
5989     for (BasicBlock::iterator I = SuccBB->begin();
5990          (PN = dyn_cast<PHINode>(I)); ++I) {
5991       // Ignore dead phi's.
5992       if (PN->use_empty()) continue;
5993
5994       // Only handle legal types. Two interesting things to note here. First,
5995       // by bailing out early, we may leave behind some dead instructions,
5996       // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
5997       // own moves. Second, this check is necessary becuase FastISel doesn't
5998       // use CreateRegForValue to create registers, so it always creates
5999       // exactly one register for each non-void instruction.
6000       MVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
6001       if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
6002         // Promote MVT::i1.
6003         if (VT == MVT::i1)
6004           VT = TLI.getTypeToTransformTo(VT);
6005         else {
6006           SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
6007           return false;
6008         }
6009       }
6010
6011       Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6012
6013       unsigned Reg = F->getRegForValue(PHIOp);
6014       if (Reg == 0) {
6015         SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
6016         return false;
6017       }
6018       SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
6019     }
6020   }
6021
6022   return true;
6023 }