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