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