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