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