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