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