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