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