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