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