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