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