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