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