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