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