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