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