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