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