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