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