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