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