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