xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision a617576bb1507c90ecbfa090c237b44f4b42fe74)
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     SDDbgValue *SDV;
1008     if (Val.getNode()) {
1009       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1010         SDV = getDbgValue(Val, Variable, Expr, dl, DbgSDNodeOrder);
1011         DAG.AddDbgValue(SDV, Val.getNode(), false);
1012       }
1013     } else
1014       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1015     DanglingDebugInfoMap[V] = DanglingDebugInfo();
1016   }
1017 }
1018 
1019 /// getCopyFromRegs - If there was virtual register allocated for the value V
1020 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1021 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1022   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1023   SDValue Result;
1024 
1025   if (It != FuncInfo.ValueMap.end()) {
1026     unsigned InReg = It->second;
1027     bool IsABIRegCopy =
1028         V && ((isa<CallInst>(V) &&
1029                !(static_cast<const CallInst *>(V))->isInlineAsm()) ||
1030               isa<ReturnInst>(V));
1031 
1032     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1033                      DAG.getDataLayout(), InReg, Ty, IsABIRegCopy);
1034     SDValue Chain = DAG.getEntryNode();
1035     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1036                                  V);
1037     resolveDanglingDebugInfo(V, Result);
1038   }
1039 
1040   return Result;
1041 }
1042 
1043 /// getValue - Return an SDValue for the given Value.
1044 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1045   // If we already have an SDValue for this value, use it. It's important
1046   // to do this first, so that we don't create a CopyFromReg if we already
1047   // have a regular SDValue.
1048   SDValue &N = NodeMap[V];
1049   if (N.getNode()) return N;
1050 
1051   // If there's a virtual register allocated and initialized for this
1052   // value, use it.
1053   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1054     return copyFromReg;
1055 
1056   // Otherwise create a new SDValue and remember it.
1057   SDValue Val = getValueImpl(V);
1058   NodeMap[V] = Val;
1059   resolveDanglingDebugInfo(V, Val);
1060   return Val;
1061 }
1062 
1063 // Return true if SDValue exists for the given Value
1064 bool SelectionDAGBuilder::findValue(const Value *V) const {
1065   return (NodeMap.find(V) != NodeMap.end()) ||
1066     (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
1067 }
1068 
1069 /// getNonRegisterValue - Return an SDValue for the given Value, but
1070 /// don't look in FuncInfo.ValueMap for a virtual register.
1071 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1072   // If we already have an SDValue for this value, use it.
1073   SDValue &N = NodeMap[V];
1074   if (N.getNode()) {
1075     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1076       // Remove the debug location from the node as the node is about to be used
1077       // in a location which may differ from the original debug location.  This
1078       // is relevant to Constant and ConstantFP nodes because they can appear
1079       // as constant expressions inside PHI nodes.
1080       N->setDebugLoc(DebugLoc());
1081     }
1082     return N;
1083   }
1084 
1085   // Otherwise create a new SDValue and remember it.
1086   SDValue Val = getValueImpl(V);
1087   NodeMap[V] = Val;
1088   resolveDanglingDebugInfo(V, Val);
1089   return Val;
1090 }
1091 
1092 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1093 /// Create an SDValue for the given value.
1094 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1095   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1096 
1097   if (const Constant *C = dyn_cast<Constant>(V)) {
1098     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1099 
1100     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1101       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1102 
1103     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1104       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1105 
1106     if (isa<ConstantPointerNull>(C)) {
1107       unsigned AS = V->getType()->getPointerAddressSpace();
1108       return DAG.getConstant(0, getCurSDLoc(),
1109                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1110     }
1111 
1112     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1113       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1114 
1115     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1116       return DAG.getUNDEF(VT);
1117 
1118     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1119       visit(CE->getOpcode(), *CE);
1120       SDValue N1 = NodeMap[V];
1121       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1122       return N1;
1123     }
1124 
1125     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1126       SmallVector<SDValue, 4> Constants;
1127       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1128            OI != OE; ++OI) {
1129         SDNode *Val = getValue(*OI).getNode();
1130         // If the operand is an empty aggregate, there are no values.
1131         if (!Val) continue;
1132         // Add each leaf value from the operand to the Constants list
1133         // to form a flattened list of all the values.
1134         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1135           Constants.push_back(SDValue(Val, i));
1136       }
1137 
1138       return DAG.getMergeValues(Constants, getCurSDLoc());
1139     }
1140 
1141     if (const ConstantDataSequential *CDS =
1142           dyn_cast<ConstantDataSequential>(C)) {
1143       SmallVector<SDValue, 4> Ops;
1144       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1145         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1146         // Add each leaf value from the operand to the Constants list
1147         // to form a flattened list of all the values.
1148         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1149           Ops.push_back(SDValue(Val, i));
1150       }
1151 
1152       if (isa<ArrayType>(CDS->getType()))
1153         return DAG.getMergeValues(Ops, getCurSDLoc());
1154       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1155     }
1156 
1157     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1158       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1159              "Unknown struct or array constant!");
1160 
1161       SmallVector<EVT, 4> ValueVTs;
1162       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1163       unsigned NumElts = ValueVTs.size();
1164       if (NumElts == 0)
1165         return SDValue(); // empty struct
1166       SmallVector<SDValue, 4> Constants(NumElts);
1167       for (unsigned i = 0; i != NumElts; ++i) {
1168         EVT EltVT = ValueVTs[i];
1169         if (isa<UndefValue>(C))
1170           Constants[i] = DAG.getUNDEF(EltVT);
1171         else if (EltVT.isFloatingPoint())
1172           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1173         else
1174           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1175       }
1176 
1177       return DAG.getMergeValues(Constants, getCurSDLoc());
1178     }
1179 
1180     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1181       return DAG.getBlockAddress(BA, VT);
1182 
1183     VectorType *VecTy = cast<VectorType>(V->getType());
1184     unsigned NumElements = VecTy->getNumElements();
1185 
1186     // Now that we know the number and type of the elements, get that number of
1187     // elements into the Ops array based on what kind of constant it is.
1188     SmallVector<SDValue, 16> Ops;
1189     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1190       for (unsigned i = 0; i != NumElements; ++i)
1191         Ops.push_back(getValue(CV->getOperand(i)));
1192     } else {
1193       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1194       EVT EltVT =
1195           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1196 
1197       SDValue Op;
1198       if (EltVT.isFloatingPoint())
1199         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1200       else
1201         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1202       Ops.assign(NumElements, Op);
1203     }
1204 
1205     // Create a BUILD_VECTOR node.
1206     return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1207   }
1208 
1209   // If this is a static alloca, generate it as the frameindex instead of
1210   // computation.
1211   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1212     DenseMap<const AllocaInst*, int>::iterator SI =
1213       FuncInfo.StaticAllocaMap.find(AI);
1214     if (SI != FuncInfo.StaticAllocaMap.end())
1215       return DAG.getFrameIndex(SI->second,
1216                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1217   }
1218 
1219   // If this is an instruction which fast-isel has deferred, select it now.
1220   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1221     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1222     bool IsABIRegCopy =
1223         V && ((isa<CallInst>(V) &&
1224                !(static_cast<const CallInst *>(V))->isInlineAsm()) ||
1225               isa<ReturnInst>(V));
1226 
1227     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1228                      Inst->getType(), IsABIRegCopy);
1229     SDValue Chain = DAG.getEntryNode();
1230     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1231   }
1232 
1233   llvm_unreachable("Can't get register for value!");
1234 }
1235 
1236 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1237   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1238   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1239   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1240   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1241   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1242   if (IsMSVCCXX || IsCoreCLR)
1243     CatchPadMBB->setIsEHFuncletEntry();
1244 
1245   DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other, getControlRoot()));
1246 }
1247 
1248 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1249   // Update machine-CFG edge.
1250   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1251   FuncInfo.MBB->addSuccessor(TargetMBB);
1252 
1253   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1254   bool IsSEH = isAsynchronousEHPersonality(Pers);
1255   if (IsSEH) {
1256     // If this is not a fall-through branch or optimizations are switched off,
1257     // emit the branch.
1258     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1259         TM.getOptLevel() == CodeGenOpt::None)
1260       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1261                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1262     return;
1263   }
1264 
1265   // Figure out the funclet membership for the catchret's successor.
1266   // This will be used by the FuncletLayout pass to determine how to order the
1267   // BB's.
1268   // A 'catchret' returns to the outer scope's color.
1269   Value *ParentPad = I.getCatchSwitchParentPad();
1270   const BasicBlock *SuccessorColor;
1271   if (isa<ConstantTokenNone>(ParentPad))
1272     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1273   else
1274     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1275   assert(SuccessorColor && "No parent funclet for catchret!");
1276   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1277   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1278 
1279   // Create the terminator node.
1280   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1281                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1282                             DAG.getBasicBlock(SuccessorColorMBB));
1283   DAG.setRoot(Ret);
1284 }
1285 
1286 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1287   // Don't emit any special code for the cleanuppad instruction. It just marks
1288   // the start of a funclet.
1289   FuncInfo.MBB->setIsEHFuncletEntry();
1290   FuncInfo.MBB->setIsCleanupFuncletEntry();
1291 }
1292 
1293 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1294 /// many places it could ultimately go. In the IR, we have a single unwind
1295 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1296 /// This function skips over imaginary basic blocks that hold catchswitch
1297 /// instructions, and finds all the "real" machine
1298 /// basic block destinations. As those destinations may not be successors of
1299 /// EHPadBB, here we also calculate the edge probability to those destinations.
1300 /// The passed-in Prob is the edge probability to EHPadBB.
1301 static void findUnwindDestinations(
1302     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1303     BranchProbability Prob,
1304     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1305         &UnwindDests) {
1306   EHPersonality Personality =
1307     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1308   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1309   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1310 
1311   while (EHPadBB) {
1312     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1313     BasicBlock *NewEHPadBB = nullptr;
1314     if (isa<LandingPadInst>(Pad)) {
1315       // Stop on landingpads. They are not funclets.
1316       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1317       break;
1318     } else if (isa<CleanupPadInst>(Pad)) {
1319       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1320       // personalities.
1321       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1322       UnwindDests.back().first->setIsEHFuncletEntry();
1323       break;
1324     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1325       // Add the catchpad handlers to the possible destinations.
1326       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1327         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1328         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1329         if (IsMSVCCXX || IsCoreCLR)
1330           UnwindDests.back().first->setIsEHFuncletEntry();
1331       }
1332       NewEHPadBB = CatchSwitch->getUnwindDest();
1333     } else {
1334       continue;
1335     }
1336 
1337     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1338     if (BPI && NewEHPadBB)
1339       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1340     EHPadBB = NewEHPadBB;
1341   }
1342 }
1343 
1344 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1345   // Update successor info.
1346   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1347   auto UnwindDest = I.getUnwindDest();
1348   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1349   BranchProbability UnwindDestProb =
1350       (BPI && UnwindDest)
1351           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1352           : BranchProbability::getZero();
1353   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1354   for (auto &UnwindDest : UnwindDests) {
1355     UnwindDest.first->setIsEHPad();
1356     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1357   }
1358   FuncInfo.MBB->normalizeSuccProbs();
1359 
1360   // Create the terminator node.
1361   SDValue Ret =
1362       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1363   DAG.setRoot(Ret);
1364 }
1365 
1366 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1367   report_fatal_error("visitCatchSwitch not yet implemented!");
1368 }
1369 
1370 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1371   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1372   auto &DL = DAG.getDataLayout();
1373   SDValue Chain = getControlRoot();
1374   SmallVector<ISD::OutputArg, 8> Outs;
1375   SmallVector<SDValue, 8> OutVals;
1376 
1377   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1378   // lower
1379   //
1380   //   %val = call <ty> @llvm.experimental.deoptimize()
1381   //   ret <ty> %val
1382   //
1383   // differently.
1384   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1385     LowerDeoptimizingReturn();
1386     return;
1387   }
1388 
1389   if (!FuncInfo.CanLowerReturn) {
1390     unsigned DemoteReg = FuncInfo.DemoteRegister;
1391     const Function *F = I.getParent()->getParent();
1392 
1393     // Emit a store of the return value through the virtual register.
1394     // Leave Outs empty so that LowerReturn won't try to load return
1395     // registers the usual way.
1396     SmallVector<EVT, 1> PtrValueVTs;
1397     ComputeValueVTs(TLI, DL, PointerType::getUnqual(F->getReturnType()),
1398                     PtrValueVTs);
1399 
1400     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1401                                         DemoteReg, PtrValueVTs[0]);
1402     SDValue RetOp = getValue(I.getOperand(0));
1403 
1404     SmallVector<EVT, 4> ValueVTs;
1405     SmallVector<uint64_t, 4> Offsets;
1406     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1407     unsigned NumValues = ValueVTs.size();
1408 
1409     // An aggregate return value cannot wrap around the address space, so
1410     // offsets to its parts don't wrap either.
1411     SDNodeFlags Flags;
1412     Flags.setNoUnsignedWrap(true);
1413 
1414     SmallVector<SDValue, 4> Chains(NumValues);
1415     for (unsigned i = 0; i != NumValues; ++i) {
1416       SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(),
1417                                 RetPtr.getValueType(), RetPtr,
1418                                 DAG.getIntPtrConstant(Offsets[i],
1419                                                       getCurSDLoc()),
1420                                 Flags);
1421       Chains[i] = DAG.getStore(Chain, getCurSDLoc(),
1422                                SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1423                                // FIXME: better loc info would be nice.
1424                                Add, MachinePointerInfo());
1425     }
1426 
1427     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1428                         MVT::Other, Chains);
1429   } else if (I.getNumOperands() != 0) {
1430     SmallVector<EVT, 4> ValueVTs;
1431     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1432     unsigned NumValues = ValueVTs.size();
1433     if (NumValues) {
1434       SDValue RetOp = getValue(I.getOperand(0));
1435 
1436       const Function *F = I.getParent()->getParent();
1437 
1438       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1439       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1440                                           Attribute::SExt))
1441         ExtendKind = ISD::SIGN_EXTEND;
1442       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1443                                                Attribute::ZExt))
1444         ExtendKind = ISD::ZERO_EXTEND;
1445 
1446       LLVMContext &Context = F->getContext();
1447       bool RetInReg = F->getAttributes().hasAttribute(
1448           AttributeList::ReturnIndex, Attribute::InReg);
1449 
1450       for (unsigned j = 0; j != NumValues; ++j) {
1451         EVT VT = ValueVTs[j];
1452 
1453         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1454           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1455 
1456         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, VT);
1457         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, VT);
1458         SmallVector<SDValue, 4> Parts(NumParts);
1459         getCopyToParts(DAG, getCurSDLoc(),
1460                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1461                        &Parts[0], NumParts, PartVT, &I, ExtendKind, true);
1462 
1463         // 'inreg' on function refers to return value
1464         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1465         if (RetInReg)
1466           Flags.setInReg();
1467 
1468         // Propagate extension type if any
1469         if (ExtendKind == ISD::SIGN_EXTEND)
1470           Flags.setSExt();
1471         else if (ExtendKind == ISD::ZERO_EXTEND)
1472           Flags.setZExt();
1473 
1474         for (unsigned i = 0; i < NumParts; ++i) {
1475           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1476                                         VT, /*isfixed=*/true, 0, 0));
1477           OutVals.push_back(Parts[i]);
1478         }
1479       }
1480     }
1481   }
1482 
1483   // Push in swifterror virtual register as the last element of Outs. This makes
1484   // sure swifterror virtual register will be returned in the swifterror
1485   // physical register.
1486   const Function *F = I.getParent()->getParent();
1487   if (TLI.supportSwiftError() &&
1488       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1489     assert(FuncInfo.SwiftErrorArg && "Need a swift error argument");
1490     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1491     Flags.setSwiftError();
1492     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1493                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1494                                   true /*isfixed*/, 1 /*origidx*/,
1495                                   0 /*partOffs*/));
1496     // Create SDNode for the swifterror virtual register.
1497     OutVals.push_back(
1498         DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVRegUseAt(
1499                             &I, FuncInfo.MBB, FuncInfo.SwiftErrorArg).first,
1500                         EVT(TLI.getPointerTy(DL))));
1501   }
1502 
1503   bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
1504   CallingConv::ID CallConv =
1505     DAG.getMachineFunction().getFunction()->getCallingConv();
1506   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1507       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1508 
1509   // Verify that the target's LowerReturn behaved as expected.
1510   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1511          "LowerReturn didn't return a valid chain!");
1512 
1513   // Update the DAG with the new chain value resulting from return lowering.
1514   DAG.setRoot(Chain);
1515 }
1516 
1517 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1518 /// created for it, emit nodes to copy the value into the virtual
1519 /// registers.
1520 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1521   // Skip empty types
1522   if (V->getType()->isEmptyTy())
1523     return;
1524 
1525   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1526   if (VMI != FuncInfo.ValueMap.end()) {
1527     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1528     CopyValueToVirtualRegister(V, VMI->second);
1529   }
1530 }
1531 
1532 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1533 /// the current basic block, add it to ValueMap now so that we'll get a
1534 /// CopyTo/FromReg.
1535 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1536   // No need to export constants.
1537   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1538 
1539   // Already exported?
1540   if (FuncInfo.isExportedInst(V)) return;
1541 
1542   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1543   CopyValueToVirtualRegister(V, Reg);
1544 }
1545 
1546 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1547                                                      const BasicBlock *FromBB) {
1548   // The operands of the setcc have to be in this block.  We don't know
1549   // how to export them from some other block.
1550   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1551     // Can export from current BB.
1552     if (VI->getParent() == FromBB)
1553       return true;
1554 
1555     // Is already exported, noop.
1556     return FuncInfo.isExportedInst(V);
1557   }
1558 
1559   // If this is an argument, we can export it if the BB is the entry block or
1560   // if it is already exported.
1561   if (isa<Argument>(V)) {
1562     if (FromBB == &FromBB->getParent()->getEntryBlock())
1563       return true;
1564 
1565     // Otherwise, can only export this if it is already exported.
1566     return FuncInfo.isExportedInst(V);
1567   }
1568 
1569   // Otherwise, constants can always be exported.
1570   return true;
1571 }
1572 
1573 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1574 BranchProbability
1575 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
1576                                         const MachineBasicBlock *Dst) const {
1577   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1578   const BasicBlock *SrcBB = Src->getBasicBlock();
1579   const BasicBlock *DstBB = Dst->getBasicBlock();
1580   if (!BPI) {
1581     // If BPI is not available, set the default probability as 1 / N, where N is
1582     // the number of successors.
1583     auto SuccSize = std::max<uint32_t>(
1584         std::distance(succ_begin(SrcBB), succ_end(SrcBB)), 1);
1585     return BranchProbability(1, SuccSize);
1586   }
1587   return BPI->getEdgeProbability(SrcBB, DstBB);
1588 }
1589 
1590 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
1591                                                MachineBasicBlock *Dst,
1592                                                BranchProbability Prob) {
1593   if (!FuncInfo.BPI)
1594     Src->addSuccessorWithoutProb(Dst);
1595   else {
1596     if (Prob.isUnknown())
1597       Prob = getEdgeProbability(Src, Dst);
1598     Src->addSuccessor(Dst, Prob);
1599   }
1600 }
1601 
1602 static bool InBlock(const Value *V, const BasicBlock *BB) {
1603   if (const Instruction *I = dyn_cast<Instruction>(V))
1604     return I->getParent() == BB;
1605   return true;
1606 }
1607 
1608 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1609 /// This function emits a branch and is used at the leaves of an OR or an
1610 /// AND operator tree.
1611 ///
1612 void
1613 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1614                                                   MachineBasicBlock *TBB,
1615                                                   MachineBasicBlock *FBB,
1616                                                   MachineBasicBlock *CurBB,
1617                                                   MachineBasicBlock *SwitchBB,
1618                                                   BranchProbability TProb,
1619                                                   BranchProbability FProb,
1620                                                   bool InvertCond) {
1621   const BasicBlock *BB = CurBB->getBasicBlock();
1622 
1623   // If the leaf of the tree is a comparison, merge the condition into
1624   // the caseblock.
1625   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1626     // The operands of the cmp have to be in this block.  We don't know
1627     // how to export them from some other block.  If this is the first block
1628     // of the sequence, no exporting is needed.
1629     if (CurBB == SwitchBB ||
1630         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1631          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1632       ISD::CondCode Condition;
1633       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1634         ICmpInst::Predicate Pred =
1635             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
1636         Condition = getICmpCondCode(Pred);
1637       } else {
1638         const FCmpInst *FC = cast<FCmpInst>(Cond);
1639         FCmpInst::Predicate Pred =
1640             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
1641         Condition = getFCmpCondCode(Pred);
1642         if (TM.Options.NoNaNsFPMath)
1643           Condition = getFCmpCodeWithoutNaN(Condition);
1644       }
1645 
1646       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
1647                    TBB, FBB, CurBB, TProb, FProb);
1648       SwitchCases.push_back(CB);
1649       return;
1650     }
1651   }
1652 
1653   // Create a CaseBlock record representing this branch.
1654   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
1655   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
1656                nullptr, TBB, FBB, CurBB, TProb, FProb);
1657   SwitchCases.push_back(CB);
1658 }
1659 
1660 /// FindMergedConditions - If Cond is an expression like
1661 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1662                                                MachineBasicBlock *TBB,
1663                                                MachineBasicBlock *FBB,
1664                                                MachineBasicBlock *CurBB,
1665                                                MachineBasicBlock *SwitchBB,
1666                                                Instruction::BinaryOps Opc,
1667                                                BranchProbability TProb,
1668                                                BranchProbability FProb,
1669                                                bool InvertCond) {
1670   // Skip over not part of the tree and remember to invert op and operands at
1671   // next level.
1672   if (BinaryOperator::isNot(Cond) && Cond->hasOneUse()) {
1673     const Value *CondOp = BinaryOperator::getNotArgument(Cond);
1674     if (InBlock(CondOp, CurBB->getBasicBlock())) {
1675       FindMergedConditions(CondOp, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
1676                            !InvertCond);
1677       return;
1678     }
1679   }
1680 
1681   const Instruction *BOp = dyn_cast<Instruction>(Cond);
1682   // Compute the effective opcode for Cond, taking into account whether it needs
1683   // to be inverted, e.g.
1684   //   and (not (or A, B)), C
1685   // gets lowered as
1686   //   and (and (not A, not B), C)
1687   unsigned BOpc = 0;
1688   if (BOp) {
1689     BOpc = BOp->getOpcode();
1690     if (InvertCond) {
1691       if (BOpc == Instruction::And)
1692         BOpc = Instruction::Or;
1693       else if (BOpc == Instruction::Or)
1694         BOpc = Instruction::And;
1695     }
1696   }
1697 
1698   // If this node is not part of the or/and tree, emit it as a branch.
1699   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1700       BOpc != Opc || !BOp->hasOneUse() ||
1701       BOp->getParent() != CurBB->getBasicBlock() ||
1702       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1703       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1704     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
1705                                  TProb, FProb, InvertCond);
1706     return;
1707   }
1708 
1709   //  Create TmpBB after CurBB.
1710   MachineFunction::iterator BBI(CurBB);
1711   MachineFunction &MF = DAG.getMachineFunction();
1712   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1713   CurBB->getParent()->insert(++BBI, TmpBB);
1714 
1715   if (Opc == Instruction::Or) {
1716     // Codegen X | Y as:
1717     // BB1:
1718     //   jmp_if_X TBB
1719     //   jmp TmpBB
1720     // TmpBB:
1721     //   jmp_if_Y TBB
1722     //   jmp FBB
1723     //
1724 
1725     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1726     // The requirement is that
1727     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
1728     //     = TrueProb for original BB.
1729     // Assuming the original probabilities are A and B, one choice is to set
1730     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
1731     // A/(1+B) and 2B/(1+B). This choice assumes that
1732     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
1733     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
1734     // TmpBB, but the math is more complicated.
1735 
1736     auto NewTrueProb = TProb / 2;
1737     auto NewFalseProb = TProb / 2 + FProb;
1738     // Emit the LHS condition.
1739     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
1740                          NewTrueProb, NewFalseProb, InvertCond);
1741 
1742     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
1743     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
1744     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
1745     // Emit the RHS condition into TmpBB.
1746     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1747                          Probs[0], Probs[1], InvertCond);
1748   } else {
1749     assert(Opc == Instruction::And && "Unknown merge op!");
1750     // Codegen X & Y as:
1751     // BB1:
1752     //   jmp_if_X TmpBB
1753     //   jmp FBB
1754     // TmpBB:
1755     //   jmp_if_Y TBB
1756     //   jmp FBB
1757     //
1758     //  This requires creation of TmpBB after CurBB.
1759 
1760     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1761     // The requirement is that
1762     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
1763     //     = FalseProb for original BB.
1764     // Assuming the original probabilities are A and B, one choice is to set
1765     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
1766     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
1767     // TrueProb for BB1 * FalseProb for TmpBB.
1768 
1769     auto NewTrueProb = TProb + FProb / 2;
1770     auto NewFalseProb = FProb / 2;
1771     // Emit the LHS condition.
1772     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
1773                          NewTrueProb, NewFalseProb, InvertCond);
1774 
1775     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
1776     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
1777     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
1778     // Emit the RHS condition into TmpBB.
1779     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1780                          Probs[0], Probs[1], InvertCond);
1781   }
1782 }
1783 
1784 /// If the set of cases should be emitted as a series of branches, return true.
1785 /// If we should emit this as a bunch of and/or'd together conditions, return
1786 /// false.
1787 bool
1788 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
1789   if (Cases.size() != 2) return true;
1790 
1791   // If this is two comparisons of the same values or'd or and'd together, they
1792   // will get folded into a single comparison, so don't emit two blocks.
1793   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1794        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1795       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1796        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1797     return false;
1798   }
1799 
1800   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1801   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1802   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1803       Cases[0].CC == Cases[1].CC &&
1804       isa<Constant>(Cases[0].CmpRHS) &&
1805       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1806     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1807       return false;
1808     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1809       return false;
1810   }
1811 
1812   return true;
1813 }
1814 
1815 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
1816   MachineBasicBlock *BrMBB = FuncInfo.MBB;
1817 
1818   // Update machine-CFG edges.
1819   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1820 
1821   if (I.isUnconditional()) {
1822     // Update machine-CFG edges.
1823     BrMBB->addSuccessor(Succ0MBB);
1824 
1825     // If this is not a fall-through branch or optimizations are switched off,
1826     // emit the branch.
1827     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
1828       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
1829                               MVT::Other, getControlRoot(),
1830                               DAG.getBasicBlock(Succ0MBB)));
1831 
1832     return;
1833   }
1834 
1835   // If this condition is one of the special cases we handle, do special stuff
1836   // now.
1837   const Value *CondVal = I.getCondition();
1838   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1839 
1840   // If this is a series of conditions that are or'd or and'd together, emit
1841   // this as a sequence of branches instead of setcc's with and/or operations.
1842   // As long as jumps are not expensive, this should improve performance.
1843   // For example, instead of something like:
1844   //     cmp A, B
1845   //     C = seteq
1846   //     cmp D, E
1847   //     F = setle
1848   //     or C, F
1849   //     jnz foo
1850   // Emit:
1851   //     cmp A, B
1852   //     je foo
1853   //     cmp D, E
1854   //     jle foo
1855   //
1856   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1857     Instruction::BinaryOps Opcode = BOp->getOpcode();
1858     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
1859         !I.getMetadata(LLVMContext::MD_unpredictable) &&
1860         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
1861       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
1862                            Opcode,
1863                            getEdgeProbability(BrMBB, Succ0MBB),
1864                            getEdgeProbability(BrMBB, Succ1MBB),
1865                            /*InvertCond=*/false);
1866       // If the compares in later blocks need to use values not currently
1867       // exported from this block, export them now.  This block should always
1868       // be the first entry.
1869       assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
1870 
1871       // Allow some cases to be rejected.
1872       if (ShouldEmitAsBranches(SwitchCases)) {
1873         for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1874           ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1875           ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1876         }
1877 
1878         // Emit the branch for this block.
1879         visitSwitchCase(SwitchCases[0], BrMBB);
1880         SwitchCases.erase(SwitchCases.begin());
1881         return;
1882       }
1883 
1884       // Okay, we decided not to do this, remove any inserted MBB's and clear
1885       // SwitchCases.
1886       for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1887         FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1888 
1889       SwitchCases.clear();
1890     }
1891   }
1892 
1893   // Create a CaseBlock record representing this branch.
1894   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1895                nullptr, Succ0MBB, Succ1MBB, BrMBB);
1896 
1897   // Use visitSwitchCase to actually insert the fast branch sequence for this
1898   // cond branch.
1899   visitSwitchCase(CB, BrMBB);
1900 }
1901 
1902 /// visitSwitchCase - Emits the necessary code to represent a single node in
1903 /// the binary search tree resulting from lowering a switch instruction.
1904 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
1905                                           MachineBasicBlock *SwitchBB) {
1906   SDValue Cond;
1907   SDValue CondLHS = getValue(CB.CmpLHS);
1908   SDLoc dl = getCurSDLoc();
1909 
1910   // Build the setcc now.
1911   if (!CB.CmpMHS) {
1912     // Fold "(X == true)" to X and "(X == false)" to !X to
1913     // handle common cases produced by branch lowering.
1914     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1915         CB.CC == ISD::SETEQ)
1916       Cond = CondLHS;
1917     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1918              CB.CC == ISD::SETEQ) {
1919       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
1920       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1921     } else
1922       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1923   } else {
1924     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1925 
1926     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1927     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1928 
1929     SDValue CmpOp = getValue(CB.CmpMHS);
1930     EVT VT = CmpOp.getValueType();
1931 
1932     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1933       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
1934                           ISD::SETLE);
1935     } else {
1936       SDValue SUB = DAG.getNode(ISD::SUB, dl,
1937                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
1938       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1939                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
1940     }
1941   }
1942 
1943   // Update successor info
1944   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
1945   // TrueBB and FalseBB are always different unless the incoming IR is
1946   // degenerate. This only happens when running llc on weird IR.
1947   if (CB.TrueBB != CB.FalseBB)
1948     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
1949   SwitchBB->normalizeSuccProbs();
1950 
1951   // If the lhs block is the next block, invert the condition so that we can
1952   // fall through to the lhs instead of the rhs block.
1953   if (CB.TrueBB == NextBlock(SwitchBB)) {
1954     std::swap(CB.TrueBB, CB.FalseBB);
1955     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
1956     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1957   }
1958 
1959   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1960                                MVT::Other, getControlRoot(), Cond,
1961                                DAG.getBasicBlock(CB.TrueBB));
1962 
1963   // Insert the false branch. Do this even if it's a fall through branch,
1964   // this makes it easier to do DAG optimizations which require inverting
1965   // the branch condition.
1966   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1967                        DAG.getBasicBlock(CB.FalseBB));
1968 
1969   DAG.setRoot(BrCond);
1970 }
1971 
1972 /// visitJumpTable - Emit JumpTable node in the current MBB
1973 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
1974   // Emit the code for the jump table
1975   assert(JT.Reg != -1U && "Should lower JT Header first!");
1976   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1977   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
1978                                      JT.Reg, PTy);
1979   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1980   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
1981                                     MVT::Other, Index.getValue(1),
1982                                     Table, Index);
1983   DAG.setRoot(BrJumpTable);
1984 }
1985 
1986 /// visitJumpTableHeader - This function emits necessary code to produce index
1987 /// in the JumpTable from switch case.
1988 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1989                                                JumpTableHeader &JTH,
1990                                                MachineBasicBlock *SwitchBB) {
1991   SDLoc dl = getCurSDLoc();
1992 
1993   // Subtract the lowest switch case value from the value being switched on and
1994   // conditional branch to default mbb if the result is greater than the
1995   // difference between smallest and largest cases.
1996   SDValue SwitchOp = getValue(JTH.SValue);
1997   EVT VT = SwitchOp.getValueType();
1998   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
1999                             DAG.getConstant(JTH.First, dl, VT));
2000 
2001   // The SDNode we just created, which holds the value being switched on minus
2002   // the smallest case value, needs to be copied to a virtual register so it
2003   // can be used as an index into the jump table in a subsequent basic block.
2004   // This value may be smaller or larger than the target's pointer type, and
2005   // therefore require extension or truncating.
2006   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2007   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2008 
2009   unsigned JumpTableReg =
2010       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2011   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2012                                     JumpTableReg, SwitchOp);
2013   JT.Reg = JumpTableReg;
2014 
2015   // Emit the range check for the jump table, and branch to the default block
2016   // for the switch statement if the value being switched on exceeds the largest
2017   // case in the switch.
2018   SDValue CMP = DAG.getSetCC(
2019       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2020                                  Sub.getValueType()),
2021       Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2022 
2023   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2024                                MVT::Other, CopyTo, CMP,
2025                                DAG.getBasicBlock(JT.Default));
2026 
2027   // Avoid emitting unnecessary branches to the next block.
2028   if (JT.MBB != NextBlock(SwitchBB))
2029     BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2030                          DAG.getBasicBlock(JT.MBB));
2031 
2032   DAG.setRoot(BrCond);
2033 }
2034 
2035 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2036 /// variable if there exists one.
2037 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2038                                  SDValue &Chain) {
2039   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2040   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2041   MachineFunction &MF = DAG.getMachineFunction();
2042   Value *Global = TLI.getSDagStackGuard(*MF.getFunction()->getParent());
2043   MachineSDNode *Node =
2044       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2045   if (Global) {
2046     MachinePointerInfo MPInfo(Global);
2047     MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1);
2048     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2049                  MachineMemOperand::MODereferenceable;
2050     *MemRefs = MF.getMachineMemOperand(MPInfo, Flags, PtrTy.getSizeInBits() / 8,
2051                                        DAG.getEVTAlignment(PtrTy));
2052     Node->setMemRefs(MemRefs, MemRefs + 1);
2053   }
2054   return SDValue(Node, 0);
2055 }
2056 
2057 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2058 /// tail spliced into a stack protector check success bb.
2059 ///
2060 /// For a high level explanation of how this fits into the stack protector
2061 /// generation see the comment on the declaration of class
2062 /// StackProtectorDescriptor.
2063 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2064                                                   MachineBasicBlock *ParentBB) {
2065 
2066   // First create the loads to the guard/stack slot for the comparison.
2067   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2068   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2069 
2070   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2071   int FI = MFI.getStackProtectorIndex();
2072 
2073   SDValue Guard;
2074   SDLoc dl = getCurSDLoc();
2075   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2076   const Module &M = *ParentBB->getParent()->getFunction()->getParent();
2077   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2078 
2079   // Generate code to load the content of the guard slot.
2080   SDValue StackSlot = DAG.getLoad(
2081       PtrTy, dl, DAG.getEntryNode(), StackSlotPtr,
2082       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2083       MachineMemOperand::MOVolatile);
2084 
2085   // Retrieve guard check function, nullptr if instrumentation is inlined.
2086   if (const Value *GuardCheck = TLI.getSSPStackGuardCheck(M)) {
2087     // The target provides a guard check function to validate the guard value.
2088     // Generate a call to that function with the content of the guard slot as
2089     // argument.
2090     auto *Fn = cast<Function>(GuardCheck);
2091     FunctionType *FnTy = Fn->getFunctionType();
2092     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2093 
2094     TargetLowering::ArgListTy Args;
2095     TargetLowering::ArgListEntry Entry;
2096     Entry.Node = StackSlot;
2097     Entry.Ty = FnTy->getParamType(0);
2098     if (Fn->hasAttribute(1, Attribute::AttrKind::InReg))
2099       Entry.IsInReg = true;
2100     Args.push_back(Entry);
2101 
2102     TargetLowering::CallLoweringInfo CLI(DAG);
2103     CLI.setDebugLoc(getCurSDLoc())
2104       .setChain(DAG.getEntryNode())
2105       .setCallee(Fn->getCallingConv(), FnTy->getReturnType(),
2106                  getValue(GuardCheck), std::move(Args));
2107 
2108     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2109     DAG.setRoot(Result.second);
2110     return;
2111   }
2112 
2113   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2114   // Otherwise, emit a volatile load to retrieve the stack guard value.
2115   SDValue Chain = DAG.getEntryNode();
2116   if (TLI.useLoadStackGuardNode()) {
2117     Guard = getLoadStackGuard(DAG, dl, Chain);
2118   } else {
2119     const Value *IRGuard = TLI.getSDagStackGuard(M);
2120     SDValue GuardPtr = getValue(IRGuard);
2121 
2122     Guard =
2123         DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0),
2124                     Align, MachineMemOperand::MOVolatile);
2125   }
2126 
2127   // Perform the comparison via a subtract/getsetcc.
2128   EVT VT = Guard.getValueType();
2129   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, StackSlot);
2130 
2131   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2132                                                         *DAG.getContext(),
2133                                                         Sub.getValueType()),
2134                              Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
2135 
2136   // If the sub is not 0, then we know the guard/stackslot do not equal, so
2137   // branch to failure MBB.
2138   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2139                                MVT::Other, StackSlot.getOperand(0),
2140                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2141   // Otherwise branch to success MBB.
2142   SDValue Br = DAG.getNode(ISD::BR, dl,
2143                            MVT::Other, BrCond,
2144                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2145 
2146   DAG.setRoot(Br);
2147 }
2148 
2149 /// Codegen the failure basic block for a stack protector check.
2150 ///
2151 /// A failure stack protector machine basic block consists simply of a call to
2152 /// __stack_chk_fail().
2153 ///
2154 /// For a high level explanation of how this fits into the stack protector
2155 /// generation see the comment on the declaration of class
2156 /// StackProtectorDescriptor.
2157 void
2158 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2159   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2160   SDValue Chain =
2161       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2162                       None, false, getCurSDLoc(), false, false).second;
2163   DAG.setRoot(Chain);
2164 }
2165 
2166 /// visitBitTestHeader - This function emits necessary code to produce value
2167 /// suitable for "bit tests"
2168 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2169                                              MachineBasicBlock *SwitchBB) {
2170   SDLoc dl = getCurSDLoc();
2171 
2172   // Subtract the minimum value
2173   SDValue SwitchOp = getValue(B.SValue);
2174   EVT VT = SwitchOp.getValueType();
2175   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2176                             DAG.getConstant(B.First, dl, VT));
2177 
2178   // Check range
2179   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2180   SDValue RangeCmp = DAG.getSetCC(
2181       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2182                                  Sub.getValueType()),
2183       Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
2184 
2185   // Determine the type of the test operands.
2186   bool UsePtrType = false;
2187   if (!TLI.isTypeLegal(VT))
2188     UsePtrType = true;
2189   else {
2190     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2191       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2192         // Switch table case range are encoded into series of masks.
2193         // Just use pointer type, it's guaranteed to fit.
2194         UsePtrType = true;
2195         break;
2196       }
2197   }
2198   if (UsePtrType) {
2199     VT = TLI.getPointerTy(DAG.getDataLayout());
2200     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2201   }
2202 
2203   B.RegVT = VT.getSimpleVT();
2204   B.Reg = FuncInfo.CreateReg(B.RegVT);
2205   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2206 
2207   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2208 
2209   addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2210   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2211   SwitchBB->normalizeSuccProbs();
2212 
2213   SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
2214                                 MVT::Other, CopyTo, RangeCmp,
2215                                 DAG.getBasicBlock(B.Default));
2216 
2217   // Avoid emitting unnecessary branches to the next block.
2218   if (MBB != NextBlock(SwitchBB))
2219     BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
2220                           DAG.getBasicBlock(MBB));
2221 
2222   DAG.setRoot(BrRange);
2223 }
2224 
2225 /// visitBitTestCase - this function produces one "bit test"
2226 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2227                                            MachineBasicBlock* NextMBB,
2228                                            BranchProbability BranchProbToNext,
2229                                            unsigned Reg,
2230                                            BitTestCase &B,
2231                                            MachineBasicBlock *SwitchBB) {
2232   SDLoc dl = getCurSDLoc();
2233   MVT VT = BB.RegVT;
2234   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2235   SDValue Cmp;
2236   unsigned PopCount = countPopulation(B.Mask);
2237   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2238   if (PopCount == 1) {
2239     // Testing for a single bit; just compare the shift count with what it
2240     // would need to be to shift a 1 bit in that position.
2241     Cmp = DAG.getSetCC(
2242         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2243         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2244         ISD::SETEQ);
2245   } else if (PopCount == BB.Range) {
2246     // There is only one zero bit in the range, test for it directly.
2247     Cmp = DAG.getSetCC(
2248         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2249         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2250         ISD::SETNE);
2251   } else {
2252     // Make desired shift
2253     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2254                                     DAG.getConstant(1, dl, VT), ShiftOp);
2255 
2256     // Emit bit tests and jumps
2257     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2258                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2259     Cmp = DAG.getSetCC(
2260         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2261         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2262   }
2263 
2264   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2265   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2266   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2267   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2268   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2269   // one as they are relative probabilities (and thus work more like weights),
2270   // and hence we need to normalize them to let the sum of them become one.
2271   SwitchBB->normalizeSuccProbs();
2272 
2273   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2274                               MVT::Other, getControlRoot(),
2275                               Cmp, DAG.getBasicBlock(B.TargetBB));
2276 
2277   // Avoid emitting unnecessary branches to the next block.
2278   if (NextMBB != NextBlock(SwitchBB))
2279     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2280                         DAG.getBasicBlock(NextMBB));
2281 
2282   DAG.setRoot(BrAnd);
2283 }
2284 
2285 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2286   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2287 
2288   // Retrieve successors. Look through artificial IR level blocks like
2289   // catchswitch for successors.
2290   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2291   const BasicBlock *EHPadBB = I.getSuccessor(1);
2292 
2293   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2294   // have to do anything here to lower funclet bundles.
2295   assert(!I.hasOperandBundlesOtherThan(
2296              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2297          "Cannot lower invokes with arbitrary operand bundles yet!");
2298 
2299   const Value *Callee(I.getCalledValue());
2300   const Function *Fn = dyn_cast<Function>(Callee);
2301   if (isa<InlineAsm>(Callee))
2302     visitInlineAsm(&I);
2303   else if (Fn && Fn->isIntrinsic()) {
2304     switch (Fn->getIntrinsicID()) {
2305     default:
2306       llvm_unreachable("Cannot invoke this intrinsic");
2307     case Intrinsic::donothing:
2308       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2309       break;
2310     case Intrinsic::experimental_patchpoint_void:
2311     case Intrinsic::experimental_patchpoint_i64:
2312       visitPatchpoint(&I, EHPadBB);
2313       break;
2314     case Intrinsic::experimental_gc_statepoint:
2315       LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2316       break;
2317     }
2318   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2319     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2320     // Eventually we will support lowering the @llvm.experimental.deoptimize
2321     // intrinsic, and right now there are no plans to support other intrinsics
2322     // with deopt state.
2323     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2324   } else {
2325     LowerCallTo(&I, getValue(Callee), false, EHPadBB);
2326   }
2327 
2328   // If the value of the invoke is used outside of its defining block, make it
2329   // available as a virtual register.
2330   // We already took care of the exported value for the statepoint instruction
2331   // during call to the LowerStatepoint.
2332   if (!isStatepoint(I)) {
2333     CopyToExportRegsIfNeeded(&I);
2334   }
2335 
2336   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2337   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2338   BranchProbability EHPadBBProb =
2339       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2340           : BranchProbability::getZero();
2341   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2342 
2343   // Update successor info.
2344   addSuccessorWithProb(InvokeMBB, Return);
2345   for (auto &UnwindDest : UnwindDests) {
2346     UnwindDest.first->setIsEHPad();
2347     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2348   }
2349   InvokeMBB->normalizeSuccProbs();
2350 
2351   // Drop into normal successor.
2352   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2353                           MVT::Other, getControlRoot(),
2354                           DAG.getBasicBlock(Return)));
2355 }
2356 
2357 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2358   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2359 }
2360 
2361 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2362   assert(FuncInfo.MBB->isEHPad() &&
2363          "Call to landingpad not in landing pad!");
2364 
2365   MachineBasicBlock *MBB = FuncInfo.MBB;
2366   addLandingPadInfo(LP, *MBB);
2367 
2368   // If there aren't registers to copy the values into (e.g., during SjLj
2369   // exceptions), then don't bother to create these DAG nodes.
2370   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2371   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2372   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2373       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2374     return;
2375 
2376   // If landingpad's return type is token type, we don't create DAG nodes
2377   // for its exception pointer and selector value. The extraction of exception
2378   // pointer or selector value from token type landingpads is not currently
2379   // supported.
2380   if (LP.getType()->isTokenTy())
2381     return;
2382 
2383   SmallVector<EVT, 2> ValueVTs;
2384   SDLoc dl = getCurSDLoc();
2385   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2386   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2387 
2388   // Get the two live-in registers as SDValues. The physregs have already been
2389   // copied into virtual registers.
2390   SDValue Ops[2];
2391   if (FuncInfo.ExceptionPointerVirtReg) {
2392     Ops[0] = DAG.getZExtOrTrunc(
2393         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2394                            FuncInfo.ExceptionPointerVirtReg,
2395                            TLI.getPointerTy(DAG.getDataLayout())),
2396         dl, ValueVTs[0]);
2397   } else {
2398     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2399   }
2400   Ops[1] = DAG.getZExtOrTrunc(
2401       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2402                          FuncInfo.ExceptionSelectorVirtReg,
2403                          TLI.getPointerTy(DAG.getDataLayout())),
2404       dl, ValueVTs[1]);
2405 
2406   // Merge into one.
2407   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2408                             DAG.getVTList(ValueVTs), Ops);
2409   setValue(&LP, Res);
2410 }
2411 
2412 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) {
2413 #ifndef NDEBUG
2414   for (const CaseCluster &CC : Clusters)
2415     assert(CC.Low == CC.High && "Input clusters must be single-case");
2416 #endif
2417 
2418   std::sort(Clusters.begin(), Clusters.end(),
2419             [](const CaseCluster &a, const CaseCluster &b) {
2420     return a.Low->getValue().slt(b.Low->getValue());
2421   });
2422 
2423   // Merge adjacent clusters with the same destination.
2424   const unsigned N = Clusters.size();
2425   unsigned DstIndex = 0;
2426   for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) {
2427     CaseCluster &CC = Clusters[SrcIndex];
2428     const ConstantInt *CaseVal = CC.Low;
2429     MachineBasicBlock *Succ = CC.MBB;
2430 
2431     if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ &&
2432         (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) {
2433       // If this case has the same successor and is a neighbour, merge it into
2434       // the previous cluster.
2435       Clusters[DstIndex - 1].High = CaseVal;
2436       Clusters[DstIndex - 1].Prob += CC.Prob;
2437     } else {
2438       std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex],
2439                    sizeof(Clusters[SrcIndex]));
2440     }
2441   }
2442   Clusters.resize(DstIndex);
2443 }
2444 
2445 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2446                                            MachineBasicBlock *Last) {
2447   // Update JTCases.
2448   for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2449     if (JTCases[i].first.HeaderBB == First)
2450       JTCases[i].first.HeaderBB = Last;
2451 
2452   // Update BitTestCases.
2453   for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2454     if (BitTestCases[i].Parent == First)
2455       BitTestCases[i].Parent = Last;
2456 }
2457 
2458 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2459   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2460 
2461   // Update machine-CFG edges with unique successors.
2462   SmallSet<BasicBlock*, 32> Done;
2463   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2464     BasicBlock *BB = I.getSuccessor(i);
2465     bool Inserted = Done.insert(BB).second;
2466     if (!Inserted)
2467         continue;
2468 
2469     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2470     addSuccessorWithProb(IndirectBrMBB, Succ);
2471   }
2472   IndirectBrMBB->normalizeSuccProbs();
2473 
2474   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2475                           MVT::Other, getControlRoot(),
2476                           getValue(I.getAddress())));
2477 }
2478 
2479 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2480   if (DAG.getTarget().Options.TrapUnreachable)
2481     DAG.setRoot(
2482         DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2483 }
2484 
2485 void SelectionDAGBuilder::visitFSub(const User &I) {
2486   // -0.0 - X --> fneg
2487   Type *Ty = I.getType();
2488   if (isa<Constant>(I.getOperand(0)) &&
2489       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2490     SDValue Op2 = getValue(I.getOperand(1));
2491     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2492                              Op2.getValueType(), Op2));
2493     return;
2494   }
2495 
2496   visitBinary(I, ISD::FSUB);
2497 }
2498 
2499 /// Checks if the given instruction performs a vector reduction, in which case
2500 /// we have the freedom to alter the elements in the result as long as the
2501 /// reduction of them stays unchanged.
2502 static bool isVectorReductionOp(const User *I) {
2503   const Instruction *Inst = dyn_cast<Instruction>(I);
2504   if (!Inst || !Inst->getType()->isVectorTy())
2505     return false;
2506 
2507   auto OpCode = Inst->getOpcode();
2508   switch (OpCode) {
2509   case Instruction::Add:
2510   case Instruction::Mul:
2511   case Instruction::And:
2512   case Instruction::Or:
2513   case Instruction::Xor:
2514     break;
2515   case Instruction::FAdd:
2516   case Instruction::FMul:
2517     if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2518       if (FPOp->getFastMathFlags().unsafeAlgebra())
2519         break;
2520     LLVM_FALLTHROUGH;
2521   default:
2522     return false;
2523   }
2524 
2525   unsigned ElemNum = Inst->getType()->getVectorNumElements();
2526   unsigned ElemNumToReduce = ElemNum;
2527 
2528   // Do DFS search on the def-use chain from the given instruction. We only
2529   // allow four kinds of operations during the search until we reach the
2530   // instruction that extracts the first element from the vector:
2531   //
2532   //   1. The reduction operation of the same opcode as the given instruction.
2533   //
2534   //   2. PHI node.
2535   //
2536   //   3. ShuffleVector instruction together with a reduction operation that
2537   //      does a partial reduction.
2538   //
2539   //   4. ExtractElement that extracts the first element from the vector, and we
2540   //      stop searching the def-use chain here.
2541   //
2542   // 3 & 4 above perform a reduction on all elements of the vector. We push defs
2543   // from 1-3 to the stack to continue the DFS. The given instruction is not
2544   // a reduction operation if we meet any other instructions other than those
2545   // listed above.
2546 
2547   SmallVector<const User *, 16> UsersToVisit{Inst};
2548   SmallPtrSet<const User *, 16> Visited;
2549   bool ReduxExtracted = false;
2550 
2551   while (!UsersToVisit.empty()) {
2552     auto User = UsersToVisit.back();
2553     UsersToVisit.pop_back();
2554     if (!Visited.insert(User).second)
2555       continue;
2556 
2557     for (const auto &U : User->users()) {
2558       auto Inst = dyn_cast<Instruction>(U);
2559       if (!Inst)
2560         return false;
2561 
2562       if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
2563         if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2564           if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().unsafeAlgebra())
2565             return false;
2566         UsersToVisit.push_back(U);
2567       } else if (const ShuffleVectorInst *ShufInst =
2568                      dyn_cast<ShuffleVectorInst>(U)) {
2569         // Detect the following pattern: A ShuffleVector instruction together
2570         // with a reduction that do partial reduction on the first and second
2571         // ElemNumToReduce / 2 elements, and store the result in
2572         // ElemNumToReduce / 2 elements in another vector.
2573 
2574         unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
2575         if (ResultElements < ElemNum)
2576           return false;
2577 
2578         if (ElemNumToReduce == 1)
2579           return false;
2580         if (!isa<UndefValue>(U->getOperand(1)))
2581           return false;
2582         for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
2583           if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
2584             return false;
2585         for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
2586           if (ShufInst->getMaskValue(i) != -1)
2587             return false;
2588 
2589         // There is only one user of this ShuffleVector instruction, which
2590         // must be a reduction operation.
2591         if (!U->hasOneUse())
2592           return false;
2593 
2594         auto U2 = dyn_cast<Instruction>(*U->user_begin());
2595         if (!U2 || U2->getOpcode() != OpCode)
2596           return false;
2597 
2598         // Check operands of the reduction operation.
2599         if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
2600             (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
2601           UsersToVisit.push_back(U2);
2602           ElemNumToReduce /= 2;
2603         } else
2604           return false;
2605       } else if (isa<ExtractElementInst>(U)) {
2606         // At this moment we should have reduced all elements in the vector.
2607         if (ElemNumToReduce != 1)
2608           return false;
2609 
2610         const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
2611         if (!Val || Val->getZExtValue() != 0)
2612           return false;
2613 
2614         ReduxExtracted = true;
2615       } else
2616         return false;
2617     }
2618   }
2619   return ReduxExtracted;
2620 }
2621 
2622 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
2623   SDValue Op1 = getValue(I.getOperand(0));
2624   SDValue Op2 = getValue(I.getOperand(1));
2625 
2626   bool nuw = false;
2627   bool nsw = false;
2628   bool exact = false;
2629   bool vec_redux = false;
2630   FastMathFlags FMF;
2631 
2632   if (const OverflowingBinaryOperator *OFBinOp =
2633           dyn_cast<const OverflowingBinaryOperator>(&I)) {
2634     nuw = OFBinOp->hasNoUnsignedWrap();
2635     nsw = OFBinOp->hasNoSignedWrap();
2636   }
2637   if (const PossiblyExactOperator *ExactOp =
2638           dyn_cast<const PossiblyExactOperator>(&I))
2639     exact = ExactOp->isExact();
2640   if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(&I))
2641     FMF = FPOp->getFastMathFlags();
2642 
2643   if (isVectorReductionOp(&I)) {
2644     vec_redux = true;
2645     DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
2646   }
2647 
2648   SDNodeFlags Flags;
2649   Flags.setExact(exact);
2650   Flags.setNoSignedWrap(nsw);
2651   Flags.setNoUnsignedWrap(nuw);
2652   Flags.setVectorReduction(vec_redux);
2653   Flags.setAllowReciprocal(FMF.allowReciprocal());
2654   Flags.setAllowContract(FMF.allowContract());
2655   Flags.setNoInfs(FMF.noInfs());
2656   Flags.setNoNaNs(FMF.noNaNs());
2657   Flags.setNoSignedZeros(FMF.noSignedZeros());
2658   Flags.setUnsafeAlgebra(FMF.unsafeAlgebra());
2659 
2660   SDValue BinNodeValue = DAG.getNode(OpCode, getCurSDLoc(), Op1.getValueType(),
2661                                      Op1, Op2, Flags);
2662   setValue(&I, BinNodeValue);
2663 }
2664 
2665 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2666   SDValue Op1 = getValue(I.getOperand(0));
2667   SDValue Op2 = getValue(I.getOperand(1));
2668 
2669   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
2670       Op2.getValueType(), DAG.getDataLayout());
2671 
2672   // Coerce the shift amount to the right type if we can.
2673   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
2674     unsigned ShiftSize = ShiftTy.getSizeInBits();
2675     unsigned Op2Size = Op2.getValueSizeInBits();
2676     SDLoc DL = getCurSDLoc();
2677 
2678     // If the operand is smaller than the shift count type, promote it.
2679     if (ShiftSize > Op2Size)
2680       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
2681 
2682     // If the operand is larger than the shift count type but the shift
2683     // count type has enough bits to represent any shift value, truncate
2684     // it now. This is a common case and it exposes the truncate to
2685     // optimization early.
2686     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
2687       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2688     // Otherwise we'll need to temporarily settle for some other convenient
2689     // type.  Type legalization will make adjustments once the shiftee is split.
2690     else
2691       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
2692   }
2693 
2694   bool nuw = false;
2695   bool nsw = false;
2696   bool exact = false;
2697 
2698   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
2699 
2700     if (const OverflowingBinaryOperator *OFBinOp =
2701             dyn_cast<const OverflowingBinaryOperator>(&I)) {
2702       nuw = OFBinOp->hasNoUnsignedWrap();
2703       nsw = OFBinOp->hasNoSignedWrap();
2704     }
2705     if (const PossiblyExactOperator *ExactOp =
2706             dyn_cast<const PossiblyExactOperator>(&I))
2707       exact = ExactOp->isExact();
2708   }
2709   SDNodeFlags Flags;
2710   Flags.setExact(exact);
2711   Flags.setNoSignedWrap(nsw);
2712   Flags.setNoUnsignedWrap(nuw);
2713   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
2714                             Flags);
2715   setValue(&I, Res);
2716 }
2717 
2718 void SelectionDAGBuilder::visitSDiv(const User &I) {
2719   SDValue Op1 = getValue(I.getOperand(0));
2720   SDValue Op2 = getValue(I.getOperand(1));
2721 
2722   SDNodeFlags Flags;
2723   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
2724                  cast<PossiblyExactOperator>(&I)->isExact());
2725   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
2726                            Op2, Flags));
2727 }
2728 
2729 void SelectionDAGBuilder::visitICmp(const User &I) {
2730   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2731   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2732     predicate = IC->getPredicate();
2733   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2734     predicate = ICmpInst::Predicate(IC->getPredicate());
2735   SDValue Op1 = getValue(I.getOperand(0));
2736   SDValue Op2 = getValue(I.getOperand(1));
2737   ISD::CondCode Opcode = getICmpCondCode(predicate);
2738 
2739   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2740                                                         I.getType());
2741   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
2742 }
2743 
2744 void SelectionDAGBuilder::visitFCmp(const User &I) {
2745   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2746   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2747     predicate = FC->getPredicate();
2748   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2749     predicate = FCmpInst::Predicate(FC->getPredicate());
2750   SDValue Op1 = getValue(I.getOperand(0));
2751   SDValue Op2 = getValue(I.getOperand(1));
2752   ISD::CondCode Condition = getFCmpCondCode(predicate);
2753 
2754   // FIXME: Fcmp instructions have fast-math-flags in IR, so we should use them.
2755   // FIXME: We should propagate the fast-math-flags to the DAG node itself for
2756   // further optimization, but currently FMF is only applicable to binary nodes.
2757   if (TM.Options.NoNaNsFPMath)
2758     Condition = getFCmpCodeWithoutNaN(Condition);
2759   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2760                                                         I.getType());
2761   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
2762 }
2763 
2764 // Check if the condition of the select has one use or two users that are both
2765 // selects with the same condition.
2766 static bool hasOnlySelectUsers(const Value *Cond) {
2767   return all_of(Cond->users(), [](const Value *V) {
2768     return isa<SelectInst>(V);
2769   });
2770 }
2771 
2772 void SelectionDAGBuilder::visitSelect(const User &I) {
2773   SmallVector<EVT, 4> ValueVTs;
2774   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
2775                   ValueVTs);
2776   unsigned NumValues = ValueVTs.size();
2777   if (NumValues == 0) return;
2778 
2779   SmallVector<SDValue, 4> Values(NumValues);
2780   SDValue Cond     = getValue(I.getOperand(0));
2781   SDValue LHSVal   = getValue(I.getOperand(1));
2782   SDValue RHSVal   = getValue(I.getOperand(2));
2783   auto BaseOps = {Cond};
2784   ISD::NodeType OpCode = Cond.getValueType().isVector() ?
2785     ISD::VSELECT : ISD::SELECT;
2786 
2787   // Min/max matching is only viable if all output VTs are the same.
2788   if (std::equal(ValueVTs.begin(), ValueVTs.end(), ValueVTs.begin())) {
2789     EVT VT = ValueVTs[0];
2790     LLVMContext &Ctx = *DAG.getContext();
2791     auto &TLI = DAG.getTargetLoweringInfo();
2792 
2793     // We care about the legality of the operation after it has been type
2794     // legalized.
2795     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal &&
2796            VT != TLI.getTypeToTransformTo(Ctx, VT))
2797       VT = TLI.getTypeToTransformTo(Ctx, VT);
2798 
2799     // If the vselect is legal, assume we want to leave this as a vector setcc +
2800     // vselect. Otherwise, if this is going to be scalarized, we want to see if
2801     // min/max is legal on the scalar type.
2802     bool UseScalarMinMax = VT.isVector() &&
2803       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
2804 
2805     Value *LHS, *RHS;
2806     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
2807     ISD::NodeType Opc = ISD::DELETED_NODE;
2808     switch (SPR.Flavor) {
2809     case SPF_UMAX:    Opc = ISD::UMAX; break;
2810     case SPF_UMIN:    Opc = ISD::UMIN; break;
2811     case SPF_SMAX:    Opc = ISD::SMAX; break;
2812     case SPF_SMIN:    Opc = ISD::SMIN; break;
2813     case SPF_FMINNUM:
2814       switch (SPR.NaNBehavior) {
2815       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
2816       case SPNB_RETURNS_NAN:   Opc = ISD::FMINNAN; break;
2817       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
2818       case SPNB_RETURNS_ANY: {
2819         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
2820           Opc = ISD::FMINNUM;
2821         else if (TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT))
2822           Opc = ISD::FMINNAN;
2823         else if (UseScalarMinMax)
2824           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
2825             ISD::FMINNUM : ISD::FMINNAN;
2826         break;
2827       }
2828       }
2829       break;
2830     case SPF_FMAXNUM:
2831       switch (SPR.NaNBehavior) {
2832       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
2833       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXNAN; break;
2834       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
2835       case SPNB_RETURNS_ANY:
2836 
2837         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
2838           Opc = ISD::FMAXNUM;
2839         else if (TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT))
2840           Opc = ISD::FMAXNAN;
2841         else if (UseScalarMinMax)
2842           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
2843             ISD::FMAXNUM : ISD::FMAXNAN;
2844         break;
2845       }
2846       break;
2847     default: break;
2848     }
2849 
2850     if (Opc != ISD::DELETED_NODE &&
2851         (TLI.isOperationLegalOrCustom(Opc, VT) ||
2852          (UseScalarMinMax &&
2853           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
2854         // If the underlying comparison instruction is used by any other
2855         // instruction, the consumed instructions won't be destroyed, so it is
2856         // not profitable to convert to a min/max.
2857         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
2858       OpCode = Opc;
2859       LHSVal = getValue(LHS);
2860       RHSVal = getValue(RHS);
2861       BaseOps = {};
2862     }
2863   }
2864 
2865   for (unsigned i = 0; i != NumValues; ++i) {
2866     SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
2867     Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
2868     Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
2869     Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
2870                             LHSVal.getNode()->getValueType(LHSVal.getResNo()+i),
2871                             Ops);
2872   }
2873 
2874   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2875                            DAG.getVTList(ValueVTs), Values));
2876 }
2877 
2878 void SelectionDAGBuilder::visitTrunc(const User &I) {
2879   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2880   SDValue N = getValue(I.getOperand(0));
2881   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2882                                                         I.getType());
2883   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
2884 }
2885 
2886 void SelectionDAGBuilder::visitZExt(const User &I) {
2887   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2888   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2889   SDValue N = getValue(I.getOperand(0));
2890   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2891                                                         I.getType());
2892   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
2893 }
2894 
2895 void SelectionDAGBuilder::visitSExt(const User &I) {
2896   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2897   // SExt also can't be a cast to bool for same reason. So, nothing much to do
2898   SDValue N = getValue(I.getOperand(0));
2899   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2900                                                         I.getType());
2901   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
2902 }
2903 
2904 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
2905   // FPTrunc is never a no-op cast, no need to check
2906   SDValue N = getValue(I.getOperand(0));
2907   SDLoc dl = getCurSDLoc();
2908   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2909   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
2910   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
2911                            DAG.getTargetConstant(
2912                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
2913 }
2914 
2915 void SelectionDAGBuilder::visitFPExt(const User &I) {
2916   // FPExt is never a no-op cast, no need to check
2917   SDValue N = getValue(I.getOperand(0));
2918   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2919                                                         I.getType());
2920   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
2921 }
2922 
2923 void SelectionDAGBuilder::visitFPToUI(const User &I) {
2924   // FPToUI is never a no-op cast, no need to check
2925   SDValue N = getValue(I.getOperand(0));
2926   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2927                                                         I.getType());
2928   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
2929 }
2930 
2931 void SelectionDAGBuilder::visitFPToSI(const User &I) {
2932   // FPToSI is never a no-op cast, no need to check
2933   SDValue N = getValue(I.getOperand(0));
2934   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2935                                                         I.getType());
2936   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
2937 }
2938 
2939 void SelectionDAGBuilder::visitUIToFP(const User &I) {
2940   // UIToFP is never a no-op cast, no need to check
2941   SDValue N = getValue(I.getOperand(0));
2942   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2943                                                         I.getType());
2944   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
2945 }
2946 
2947 void SelectionDAGBuilder::visitSIToFP(const User &I) {
2948   // SIToFP is never a no-op cast, no need to check
2949   SDValue N = getValue(I.getOperand(0));
2950   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2951                                                         I.getType());
2952   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
2953 }
2954 
2955 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
2956   // What to do depends on the size of the integer and the size of the pointer.
2957   // We can either truncate, zero extend, or no-op, accordingly.
2958   SDValue N = getValue(I.getOperand(0));
2959   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2960                                                         I.getType());
2961   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
2962 }
2963 
2964 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
2965   // What to do depends on the size of the integer and the size of the pointer.
2966   // We can either truncate, zero extend, or no-op, accordingly.
2967   SDValue N = getValue(I.getOperand(0));
2968   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2969                                                         I.getType());
2970   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
2971 }
2972 
2973 void SelectionDAGBuilder::visitBitCast(const User &I) {
2974   SDValue N = getValue(I.getOperand(0));
2975   SDLoc dl = getCurSDLoc();
2976   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2977                                                         I.getType());
2978 
2979   // BitCast assures us that source and destination are the same size so this is
2980   // either a BITCAST or a no-op.
2981   if (DestVT != N.getValueType())
2982     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
2983                              DestVT, N)); // convert types.
2984   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
2985   // might fold any kind of constant expression to an integer constant and that
2986   // is not what we are looking for. Only recognize a bitcast of a genuine
2987   // constant integer as an opaque constant.
2988   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
2989     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
2990                                  /*isOpaque*/true));
2991   else
2992     setValue(&I, N);            // noop cast.
2993 }
2994 
2995 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
2996   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2997   const Value *SV = I.getOperand(0);
2998   SDValue N = getValue(SV);
2999   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3000 
3001   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3002   unsigned DestAS = I.getType()->getPointerAddressSpace();
3003 
3004   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3005     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3006 
3007   setValue(&I, N);
3008 }
3009 
3010 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3011   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3012   SDValue InVec = getValue(I.getOperand(0));
3013   SDValue InVal = getValue(I.getOperand(1));
3014   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3015                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3016   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3017                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3018                            InVec, InVal, InIdx));
3019 }
3020 
3021 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3022   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3023   SDValue InVec = getValue(I.getOperand(0));
3024   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3025                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3026   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3027                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3028                            InVec, InIdx));
3029 }
3030 
3031 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3032   SDValue Src1 = getValue(I.getOperand(0));
3033   SDValue Src2 = getValue(I.getOperand(1));
3034   SDLoc DL = getCurSDLoc();
3035 
3036   SmallVector<int, 8> Mask;
3037   ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
3038   unsigned MaskNumElts = Mask.size();
3039 
3040   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3041   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3042   EVT SrcVT = Src1.getValueType();
3043   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3044 
3045   if (SrcNumElts == MaskNumElts) {
3046     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3047     return;
3048   }
3049 
3050   // Normalize the shuffle vector since mask and vector length don't match.
3051   if (SrcNumElts < MaskNumElts) {
3052     // Mask is longer than the source vectors. We can use concatenate vector to
3053     // make the mask and vectors lengths match.
3054 
3055     if (MaskNumElts % SrcNumElts == 0) {
3056       // Mask length is a multiple of the source vector length.
3057       // Check if the shuffle is some kind of concatenation of the input
3058       // vectors.
3059       unsigned NumConcat = MaskNumElts / SrcNumElts;
3060       bool IsConcat = true;
3061       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3062       for (unsigned i = 0; i != MaskNumElts; ++i) {
3063         int Idx = Mask[i];
3064         if (Idx < 0)
3065           continue;
3066         // Ensure the indices in each SrcVT sized piece are sequential and that
3067         // the same source is used for the whole piece.
3068         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3069             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3070              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3071           IsConcat = false;
3072           break;
3073         }
3074         // Remember which source this index came from.
3075         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3076       }
3077 
3078       // The shuffle is concatenating multiple vectors together. Just emit
3079       // a CONCAT_VECTORS operation.
3080       if (IsConcat) {
3081         SmallVector<SDValue, 8> ConcatOps;
3082         for (auto Src : ConcatSrcs) {
3083           if (Src < 0)
3084             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3085           else if (Src == 0)
3086             ConcatOps.push_back(Src1);
3087           else
3088             ConcatOps.push_back(Src2);
3089         }
3090         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3091         return;
3092       }
3093     }
3094 
3095     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3096     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3097     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3098                                     PaddedMaskNumElts);
3099 
3100     // Pad both vectors with undefs to make them the same length as the mask.
3101     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3102 
3103     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3104     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3105     MOps1[0] = Src1;
3106     MOps2[0] = Src2;
3107 
3108     Src1 = Src1.isUndef()
3109                ? DAG.getUNDEF(PaddedVT)
3110                : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3111     Src2 = Src2.isUndef()
3112                ? DAG.getUNDEF(PaddedVT)
3113                : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3114 
3115     // Readjust mask for new input vector length.
3116     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3117     for (unsigned i = 0; i != MaskNumElts; ++i) {
3118       int Idx = Mask[i];
3119       if (Idx >= (int)SrcNumElts)
3120         Idx -= SrcNumElts - PaddedMaskNumElts;
3121       MappedOps[i] = Idx;
3122     }
3123 
3124     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3125 
3126     // If the concatenated vector was padded, extract a subvector with the
3127     // correct number of elements.
3128     if (MaskNumElts != PaddedMaskNumElts)
3129       Result = DAG.getNode(
3130           ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3131           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
3132 
3133     setValue(&I, Result);
3134     return;
3135   }
3136 
3137   if (SrcNumElts > MaskNumElts) {
3138     // Analyze the access pattern of the vector to see if we can extract
3139     // two subvectors and do the shuffle.
3140     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3141     bool CanExtract = true;
3142     for (int Idx : Mask) {
3143       unsigned Input = 0;
3144       if (Idx < 0)
3145         continue;
3146 
3147       if (Idx >= (int)SrcNumElts) {
3148         Input = 1;
3149         Idx -= SrcNumElts;
3150       }
3151 
3152       // If all the indices come from the same MaskNumElts sized portion of
3153       // the sources we can use extract. Also make sure the extract wouldn't
3154       // extract past the end of the source.
3155       int NewStartIdx = alignDown(Idx, MaskNumElts);
3156       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3157           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3158         CanExtract = false;
3159       // Make sure we always update StartIdx as we use it to track if all
3160       // elements are undef.
3161       StartIdx[Input] = NewStartIdx;
3162     }
3163 
3164     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3165       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3166       return;
3167     }
3168     if (CanExtract) {
3169       // Extract appropriate subvector and generate a vector shuffle
3170       for (unsigned Input = 0; Input < 2; ++Input) {
3171         SDValue &Src = Input == 0 ? Src1 : Src2;
3172         if (StartIdx[Input] < 0)
3173           Src = DAG.getUNDEF(VT);
3174         else {
3175           Src = DAG.getNode(
3176               ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3177               DAG.getConstant(StartIdx[Input], DL,
3178                               TLI.getVectorIdxTy(DAG.getDataLayout())));
3179         }
3180       }
3181 
3182       // Calculate new mask.
3183       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3184       for (int &Idx : MappedOps) {
3185         if (Idx >= (int)SrcNumElts)
3186           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3187         else if (Idx >= 0)
3188           Idx -= StartIdx[0];
3189       }
3190 
3191       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3192       return;
3193     }
3194   }
3195 
3196   // We can't use either concat vectors or extract subvectors so fall back to
3197   // replacing the shuffle with extract and build vector.
3198   // to insert and build vector.
3199   EVT EltVT = VT.getVectorElementType();
3200   EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
3201   SmallVector<SDValue,8> Ops;
3202   for (int Idx : Mask) {
3203     SDValue Res;
3204 
3205     if (Idx < 0) {
3206       Res = DAG.getUNDEF(EltVT);
3207     } else {
3208       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3209       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3210 
3211       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
3212                         EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
3213     }
3214 
3215     Ops.push_back(Res);
3216   }
3217 
3218   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3219 }
3220 
3221 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3222   ArrayRef<unsigned> Indices;
3223   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3224     Indices = IV->getIndices();
3225   else
3226     Indices = cast<ConstantExpr>(&I)->getIndices();
3227 
3228   const Value *Op0 = I.getOperand(0);
3229   const Value *Op1 = I.getOperand(1);
3230   Type *AggTy = I.getType();
3231   Type *ValTy = Op1->getType();
3232   bool IntoUndef = isa<UndefValue>(Op0);
3233   bool FromUndef = isa<UndefValue>(Op1);
3234 
3235   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3236 
3237   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3238   SmallVector<EVT, 4> AggValueVTs;
3239   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3240   SmallVector<EVT, 4> ValValueVTs;
3241   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3242 
3243   unsigned NumAggValues = AggValueVTs.size();
3244   unsigned NumValValues = ValValueVTs.size();
3245   SmallVector<SDValue, 4> Values(NumAggValues);
3246 
3247   // Ignore an insertvalue that produces an empty object
3248   if (!NumAggValues) {
3249     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3250     return;
3251   }
3252 
3253   SDValue Agg = getValue(Op0);
3254   unsigned i = 0;
3255   // Copy the beginning value(s) from the original aggregate.
3256   for (; i != LinearIndex; ++i)
3257     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3258                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3259   // Copy values from the inserted value(s).
3260   if (NumValValues) {
3261     SDValue Val = getValue(Op1);
3262     for (; i != LinearIndex + NumValValues; ++i)
3263       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3264                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3265   }
3266   // Copy remaining value(s) from the original aggregate.
3267   for (; i != NumAggValues; ++i)
3268     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3269                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3270 
3271   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3272                            DAG.getVTList(AggValueVTs), Values));
3273 }
3274 
3275 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3276   ArrayRef<unsigned> Indices;
3277   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3278     Indices = EV->getIndices();
3279   else
3280     Indices = cast<ConstantExpr>(&I)->getIndices();
3281 
3282   const Value *Op0 = I.getOperand(0);
3283   Type *AggTy = Op0->getType();
3284   Type *ValTy = I.getType();
3285   bool OutOfUndef = isa<UndefValue>(Op0);
3286 
3287   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3288 
3289   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3290   SmallVector<EVT, 4> ValValueVTs;
3291   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3292 
3293   unsigned NumValValues = ValValueVTs.size();
3294 
3295   // Ignore a extractvalue that produces an empty object
3296   if (!NumValValues) {
3297     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3298     return;
3299   }
3300 
3301   SmallVector<SDValue, 4> Values(NumValValues);
3302 
3303   SDValue Agg = getValue(Op0);
3304   // Copy out the selected value(s).
3305   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3306     Values[i - LinearIndex] =
3307       OutOfUndef ?
3308         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3309         SDValue(Agg.getNode(), Agg.getResNo() + i);
3310 
3311   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3312                            DAG.getVTList(ValValueVTs), Values));
3313 }
3314 
3315 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3316   Value *Op0 = I.getOperand(0);
3317   // Note that the pointer operand may be a vector of pointers. Take the scalar
3318   // element which holds a pointer.
3319   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3320   SDValue N = getValue(Op0);
3321   SDLoc dl = getCurSDLoc();
3322 
3323   // Normalize Vector GEP - all scalar operands should be converted to the
3324   // splat vector.
3325   unsigned VectorWidth = I.getType()->isVectorTy() ?
3326     cast<VectorType>(I.getType())->getVectorNumElements() : 0;
3327 
3328   if (VectorWidth && !N.getValueType().isVector()) {
3329     LLVMContext &Context = *DAG.getContext();
3330     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
3331     N = DAG.getSplatBuildVector(VT, dl, N);
3332   }
3333 
3334   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3335        GTI != E; ++GTI) {
3336     const Value *Idx = GTI.getOperand();
3337     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3338       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3339       if (Field) {
3340         // N = N + Offset
3341         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3342 
3343         // In an inbounds GEP with an offset that is nonnegative even when
3344         // interpreted as signed, assume there is no unsigned overflow.
3345         SDNodeFlags Flags;
3346         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3347           Flags.setNoUnsignedWrap(true);
3348 
3349         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3350                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3351       }
3352     } else {
3353       MVT PtrTy =
3354           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout(), AS);
3355       unsigned PtrSize = PtrTy.getSizeInBits();
3356       APInt ElementSize(PtrSize, DL->getTypeAllocSize(GTI.getIndexedType()));
3357 
3358       // If this is a scalar constant or a splat vector of constants,
3359       // handle it quickly.
3360       const auto *CI = dyn_cast<ConstantInt>(Idx);
3361       if (!CI && isa<ConstantDataVector>(Idx) &&
3362           cast<ConstantDataVector>(Idx)->getSplatValue())
3363         CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue());
3364 
3365       if (CI) {
3366         if (CI->isZero())
3367           continue;
3368         APInt Offs = ElementSize * CI->getValue().sextOrTrunc(PtrSize);
3369         LLVMContext &Context = *DAG.getContext();
3370         SDValue OffsVal = VectorWidth ?
3371           DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, PtrTy, VectorWidth)) :
3372           DAG.getConstant(Offs, dl, PtrTy);
3373 
3374         // In an inbouds GEP with an offset that is nonnegative even when
3375         // interpreted as signed, assume there is no unsigned overflow.
3376         SDNodeFlags Flags;
3377         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3378           Flags.setNoUnsignedWrap(true);
3379 
3380         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3381         continue;
3382       }
3383 
3384       // N = N + Idx * ElementSize;
3385       SDValue IdxN = getValue(Idx);
3386 
3387       if (!IdxN.getValueType().isVector() && VectorWidth) {
3388         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
3389         IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3390       }
3391 
3392       // If the index is smaller or larger than intptr_t, truncate or extend
3393       // it.
3394       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3395 
3396       // If this is a multiply by a power of two, turn it into a shl
3397       // immediately.  This is a very common case.
3398       if (ElementSize != 1) {
3399         if (ElementSize.isPowerOf2()) {
3400           unsigned Amt = ElementSize.logBase2();
3401           IdxN = DAG.getNode(ISD::SHL, dl,
3402                              N.getValueType(), IdxN,
3403                              DAG.getConstant(Amt, dl, IdxN.getValueType()));
3404         } else {
3405           SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType());
3406           IdxN = DAG.getNode(ISD::MUL, dl,
3407                              N.getValueType(), IdxN, Scale);
3408         }
3409       }
3410 
3411       N = DAG.getNode(ISD::ADD, dl,
3412                       N.getValueType(), N, IdxN);
3413     }
3414   }
3415 
3416   setValue(&I, N);
3417 }
3418 
3419 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3420   // If this is a fixed sized alloca in the entry block of the function,
3421   // allocate it statically on the stack.
3422   if (FuncInfo.StaticAllocaMap.count(&I))
3423     return;   // getValue will auto-populate this.
3424 
3425   SDLoc dl = getCurSDLoc();
3426   Type *Ty = I.getAllocatedType();
3427   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3428   auto &DL = DAG.getDataLayout();
3429   uint64_t TySize = DL.getTypeAllocSize(Ty);
3430   unsigned Align =
3431       std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
3432 
3433   SDValue AllocSize = getValue(I.getArraySize());
3434 
3435   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout());
3436   if (AllocSize.getValueType() != IntPtr)
3437     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3438 
3439   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3440                           AllocSize,
3441                           DAG.getConstant(TySize, dl, IntPtr));
3442 
3443   // Handle alignment.  If the requested alignment is less than or equal to
3444   // the stack alignment, ignore it.  If the size is greater than or equal to
3445   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3446   unsigned StackAlign =
3447       DAG.getSubtarget().getFrameLowering()->getStackAlignment();
3448   if (Align <= StackAlign)
3449     Align = 0;
3450 
3451   // Round the size of the allocation up to the stack alignment size
3452   // by add SA-1 to the size. This doesn't overflow because we're computing
3453   // an address inside an alloca.
3454   SDNodeFlags Flags;
3455   Flags.setNoUnsignedWrap(true);
3456   AllocSize = DAG.getNode(ISD::ADD, dl,
3457                           AllocSize.getValueType(), AllocSize,
3458                           DAG.getIntPtrConstant(StackAlign - 1, dl), Flags);
3459 
3460   // Mask out the low bits for alignment purposes.
3461   AllocSize = DAG.getNode(ISD::AND, dl,
3462                           AllocSize.getValueType(), AllocSize,
3463                           DAG.getIntPtrConstant(~(uint64_t)(StackAlign - 1),
3464                                                 dl));
3465 
3466   SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align, dl) };
3467   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3468   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3469   setValue(&I, DSA);
3470   DAG.setRoot(DSA.getValue(1));
3471 
3472   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
3473 }
3474 
3475 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3476   if (I.isAtomic())
3477     return visitAtomicLoad(I);
3478 
3479   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3480   const Value *SV = I.getOperand(0);
3481   if (TLI.supportSwiftError()) {
3482     // Swifterror values can come from either a function parameter with
3483     // swifterror attribute or an alloca with swifterror attribute.
3484     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
3485       if (Arg->hasSwiftErrorAttr())
3486         return visitLoadFromSwiftError(I);
3487     }
3488 
3489     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
3490       if (Alloca->isSwiftError())
3491         return visitLoadFromSwiftError(I);
3492     }
3493   }
3494 
3495   SDValue Ptr = getValue(SV);
3496 
3497   Type *Ty = I.getType();
3498 
3499   bool isVolatile = I.isVolatile();
3500   bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
3501   bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
3502   bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout());
3503   unsigned Alignment = I.getAlignment();
3504 
3505   AAMDNodes AAInfo;
3506   I.getAAMetadata(AAInfo);
3507   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3508 
3509   SmallVector<EVT, 4> ValueVTs;
3510   SmallVector<uint64_t, 4> Offsets;
3511   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets);
3512   unsigned NumValues = ValueVTs.size();
3513   if (NumValues == 0)
3514     return;
3515 
3516   SDValue Root;
3517   bool ConstantMemory = false;
3518   if (isVolatile || NumValues > MaxParallelChains)
3519     // Serialize volatile loads with other side effects.
3520     Root = getRoot();
3521   else if (AA && AA->pointsToConstantMemory(MemoryLocation(
3522                SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) {
3523     // Do not serialize (non-volatile) loads of constant memory with anything.
3524     Root = DAG.getEntryNode();
3525     ConstantMemory = true;
3526   } else {
3527     // Do not serialize non-volatile loads against each other.
3528     Root = DAG.getRoot();
3529   }
3530 
3531   SDLoc dl = getCurSDLoc();
3532 
3533   if (isVolatile)
3534     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
3535 
3536   // An aggregate load cannot wrap around the address space, so offsets to its
3537   // parts don't wrap either.
3538   SDNodeFlags Flags;
3539   Flags.setNoUnsignedWrap(true);
3540 
3541   SmallVector<SDValue, 4> Values(NumValues);
3542   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3543   EVT PtrVT = Ptr.getValueType();
3544   unsigned ChainI = 0;
3545   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3546     // Serializing loads here may result in excessive register pressure, and
3547     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3548     // could recover a bit by hoisting nodes upward in the chain by recognizing
3549     // they are side-effect free or do not alias. The optimizer should really
3550     // avoid this case by converting large object/array copies to llvm.memcpy
3551     // (MaxParallelChains should always remain as failsafe).
3552     if (ChainI == MaxParallelChains) {
3553       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
3554       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3555                                   makeArrayRef(Chains.data(), ChainI));
3556       Root = Chain;
3557       ChainI = 0;
3558     }
3559     SDValue A = DAG.getNode(ISD::ADD, dl,
3560                             PtrVT, Ptr,
3561                             DAG.getConstant(Offsets[i], dl, PtrVT),
3562                             Flags);
3563     auto MMOFlags = MachineMemOperand::MONone;
3564     if (isVolatile)
3565       MMOFlags |= MachineMemOperand::MOVolatile;
3566     if (isNonTemporal)
3567       MMOFlags |= MachineMemOperand::MONonTemporal;
3568     if (isInvariant)
3569       MMOFlags |= MachineMemOperand::MOInvariant;
3570     if (isDereferenceable)
3571       MMOFlags |= MachineMemOperand::MODereferenceable;
3572     MMOFlags |= TLI.getMMOFlags(I);
3573 
3574     SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A,
3575                             MachinePointerInfo(SV, Offsets[i]), Alignment,
3576                             MMOFlags, AAInfo, Ranges);
3577 
3578     Values[i] = L;
3579     Chains[ChainI] = L.getValue(1);
3580   }
3581 
3582   if (!ConstantMemory) {
3583     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3584                                 makeArrayRef(Chains.data(), ChainI));
3585     if (isVolatile)
3586       DAG.setRoot(Chain);
3587     else
3588       PendingLoads.push_back(Chain);
3589   }
3590 
3591   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
3592                            DAG.getVTList(ValueVTs), Values));
3593 }
3594 
3595 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
3596   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
3597          "call visitStoreToSwiftError when backend supports swifterror");
3598 
3599   SmallVector<EVT, 4> ValueVTs;
3600   SmallVector<uint64_t, 4> Offsets;
3601   const Value *SrcV = I.getOperand(0);
3602   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
3603                   SrcV->getType(), ValueVTs, &Offsets);
3604   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
3605          "expect a single EVT for swifterror");
3606 
3607   SDValue Src = getValue(SrcV);
3608   // Create a virtual register, then update the virtual register.
3609   unsigned VReg; bool CreatedVReg;
3610   std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I);
3611   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
3612   // Chain can be getRoot or getControlRoot.
3613   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
3614                                       SDValue(Src.getNode(), Src.getResNo()));
3615   DAG.setRoot(CopyNode);
3616   if (CreatedVReg)
3617     FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg);
3618 }
3619 
3620 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
3621   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
3622          "call visitLoadFromSwiftError when backend supports swifterror");
3623 
3624   assert(!I.isVolatile() &&
3625          I.getMetadata(LLVMContext::MD_nontemporal) == nullptr &&
3626          I.getMetadata(LLVMContext::MD_invariant_load) == nullptr &&
3627          "Support volatile, non temporal, invariant for load_from_swift_error");
3628 
3629   const Value *SV = I.getOperand(0);
3630   Type *Ty = I.getType();
3631   AAMDNodes AAInfo;
3632   I.getAAMetadata(AAInfo);
3633   assert((!AA || !AA->pointsToConstantMemory(MemoryLocation(
3634              SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) &&
3635          "load_from_swift_error should not be constant memory");
3636 
3637   SmallVector<EVT, 4> ValueVTs;
3638   SmallVector<uint64_t, 4> Offsets;
3639   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
3640                   ValueVTs, &Offsets);
3641   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
3642          "expect a single EVT for swifterror");
3643 
3644   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
3645   SDValue L = DAG.getCopyFromReg(
3646       getRoot(), getCurSDLoc(),
3647       FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first,
3648       ValueVTs[0]);
3649 
3650   setValue(&I, L);
3651 }
3652 
3653 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
3654   if (I.isAtomic())
3655     return visitAtomicStore(I);
3656 
3657   const Value *SrcV = I.getOperand(0);
3658   const Value *PtrV = I.getOperand(1);
3659 
3660   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3661   if (TLI.supportSwiftError()) {
3662     // Swifterror values can come from either a function parameter with
3663     // swifterror attribute or an alloca with swifterror attribute.
3664     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
3665       if (Arg->hasSwiftErrorAttr())
3666         return visitStoreToSwiftError(I);
3667     }
3668 
3669     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
3670       if (Alloca->isSwiftError())
3671         return visitStoreToSwiftError(I);
3672     }
3673   }
3674 
3675   SmallVector<EVT, 4> ValueVTs;
3676   SmallVector<uint64_t, 4> Offsets;
3677   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
3678                   SrcV->getType(), ValueVTs, &Offsets);
3679   unsigned NumValues = ValueVTs.size();
3680   if (NumValues == 0)
3681     return;
3682 
3683   // Get the lowered operands. Note that we do this after
3684   // checking if NumResults is zero, because with zero results
3685   // the operands won't have values in the map.
3686   SDValue Src = getValue(SrcV);
3687   SDValue Ptr = getValue(PtrV);
3688 
3689   SDValue Root = getRoot();
3690   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3691   SDLoc dl = getCurSDLoc();
3692   EVT PtrVT = Ptr.getValueType();
3693   unsigned Alignment = I.getAlignment();
3694   AAMDNodes AAInfo;
3695   I.getAAMetadata(AAInfo);
3696 
3697   auto MMOFlags = MachineMemOperand::MONone;
3698   if (I.isVolatile())
3699     MMOFlags |= MachineMemOperand::MOVolatile;
3700   if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr)
3701     MMOFlags |= MachineMemOperand::MONonTemporal;
3702   MMOFlags |= TLI.getMMOFlags(I);
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 /// If the DbgValueInst is a dbg_value of a function argument, create the
4755 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
4756 /// 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, 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(), 0, Variable, Expr));
4819   else
4820     FuncInfo.ArgDbgValues.push_back(
4821         BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE))
4822             .add(*Op)
4823             .addImm(0)
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,
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(), dl,
4841                                      DbgSDNodeOrder);
4842   }
4843   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), false, dl,
4844                          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::memmove_element_unordered_atomic: {
4998     auto &MI = cast<ElementUnorderedAtomicMemMoveInst>(I);
4999     SDValue Dst = getValue(MI.getRawDest());
5000     SDValue Src = getValue(MI.getRawSource());
5001     SDValue Length = getValue(MI.getLength());
5002 
5003     // Emit a library call.
5004     TargetLowering::ArgListTy Args;
5005     TargetLowering::ArgListEntry Entry;
5006     Entry.Ty = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
5007     Entry.Node = Dst;
5008     Args.push_back(Entry);
5009 
5010     Entry.Node = Src;
5011     Args.push_back(Entry);
5012 
5013     Entry.Ty = MI.getLength()->getType();
5014     Entry.Node = Length;
5015     Args.push_back(Entry);
5016 
5017     uint64_t ElementSizeConstant = MI.getElementSizeInBytes();
5018     RTLIB::Libcall LibraryCall =
5019         RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElementSizeConstant);
5020     if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
5021       report_fatal_error("Unsupported element size");
5022 
5023     TargetLowering::CallLoweringInfo CLI(DAG);
5024     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
5025         TLI.getLibcallCallingConv(LibraryCall),
5026         Type::getVoidTy(*DAG.getContext()),
5027         DAG.getExternalSymbol(TLI.getLibcallName(LibraryCall),
5028                               TLI.getPointerTy(DAG.getDataLayout())),
5029         std::move(Args));
5030 
5031     std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
5032     DAG.setRoot(CallResult.second);
5033     return nullptr;
5034   }
5035   case Intrinsic::memset_element_unordered_atomic: {
5036     auto &MI = cast<ElementUnorderedAtomicMemSetInst>(I);
5037     SDValue Dst = getValue(MI.getRawDest());
5038     SDValue Val = getValue(MI.getValue());
5039     SDValue Length = getValue(MI.getLength());
5040 
5041     // Emit a library call.
5042     TargetLowering::ArgListTy Args;
5043     TargetLowering::ArgListEntry Entry;
5044     Entry.Ty = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
5045     Entry.Node = Dst;
5046     Args.push_back(Entry);
5047 
5048     Entry.Ty = Type::getInt8Ty(*DAG.getContext());
5049     Entry.Node = Val;
5050     Args.push_back(Entry);
5051 
5052     Entry.Ty = MI.getLength()->getType();
5053     Entry.Node = Length;
5054     Args.push_back(Entry);
5055 
5056     uint64_t ElementSizeConstant = MI.getElementSizeInBytes();
5057     RTLIB::Libcall LibraryCall =
5058         RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElementSizeConstant);
5059     if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
5060       report_fatal_error("Unsupported element size");
5061 
5062     TargetLowering::CallLoweringInfo CLI(DAG);
5063     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
5064         TLI.getLibcallCallingConv(LibraryCall),
5065         Type::getVoidTy(*DAG.getContext()),
5066         DAG.getExternalSymbol(TLI.getLibcallName(LibraryCall),
5067                               TLI.getPointerTy(DAG.getDataLayout())),
5068         std::move(Args));
5069 
5070     std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
5071     DAG.setRoot(CallResult.second);
5072     return nullptr;
5073   }
5074   case Intrinsic::dbg_declare: {
5075     const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
5076     DILocalVariable *Variable = DI.getVariable();
5077     DIExpression *Expression = DI.getExpression();
5078     const Value *Address = DI.getAddress();
5079     assert(Variable && "Missing variable");
5080     if (!Address) {
5081       DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5082       return nullptr;
5083     }
5084 
5085     // Check if address has undef value.
5086     if (isa<UndefValue>(Address) ||
5087         (Address->use_empty() && !isa<Argument>(Address))) {
5088       DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5089       return nullptr;
5090     }
5091 
5092     // Byval arguments with frame indices were already handled after argument
5093     // lowering and before isel.
5094     const auto *Arg =
5095         dyn_cast<Argument>(Address->stripInBoundsConstantOffsets());
5096     if (Arg && FuncInfo.getArgumentFrameIndex(Arg) != INT_MAX)
5097       return nullptr;
5098 
5099     SDValue &N = NodeMap[Address];
5100     if (!N.getNode() && isa<Argument>(Address))
5101       // Check unused arguments map.
5102       N = UnusedArgNodeMap[Address];
5103     SDDbgValue *SDV;
5104     if (N.getNode()) {
5105       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5106         Address = BCI->getOperand(0);
5107       // Parameters are handled specially.
5108       bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5109       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5110       if (isParameter && FINode) {
5111         // Byval parameter. We have a frame index at this point.
5112         SDV = DAG.getFrameIndexDbgValue(Variable, Expression,
5113                                         FINode->getIndex(), dl, SDNodeOrder);
5114       } else if (isa<Argument>(Address)) {
5115         // Address is an argument, so try to emit its dbg value using
5116         // virtual register info from the FuncInfo.ValueMap.
5117         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5118         return nullptr;
5119       } else {
5120         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5121                               true, dl, SDNodeOrder);
5122       }
5123       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5124     } else {
5125       // If Address is an argument then try to emit its dbg value using
5126       // virtual register info from the FuncInfo.ValueMap.
5127       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5128                                     N)) {
5129         DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5130       }
5131     }
5132     return nullptr;
5133   }
5134   case Intrinsic::dbg_value: {
5135     const DbgValueInst &DI = cast<DbgValueInst>(I);
5136     assert(DI.getVariable() && "Missing variable");
5137 
5138     DILocalVariable *Variable = DI.getVariable();
5139     DIExpression *Expression = DI.getExpression();
5140     const Value *V = DI.getValue();
5141     if (!V)
5142       return nullptr;
5143 
5144     SDDbgValue *SDV;
5145     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
5146       SDV = DAG.getConstantDbgValue(Variable, Expression, V, dl, SDNodeOrder);
5147       DAG.AddDbgValue(SDV, nullptr, false);
5148       return nullptr;
5149     }
5150 
5151     // Do not use getValue() in here; we don't want to generate code at
5152     // this point if it hasn't been done yet.
5153     SDValue N = NodeMap[V];
5154     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
5155       N = UnusedArgNodeMap[V];
5156     if (N.getNode()) {
5157       if (EmitFuncArgumentDbgValue(V, Variable, Expression, dl, false, N))
5158         return nullptr;
5159       SDV = getDbgValue(N, Variable, Expression, dl, SDNodeOrder);
5160       DAG.AddDbgValue(SDV, N.getNode(), false);
5161       return nullptr;
5162     }
5163 
5164     if (!V->use_empty() ) {
5165       // Do not call getValue(V) yet, as we don't want to generate code.
5166       // Remember it for later.
5167       DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
5168       DanglingDebugInfoMap[V] = DDI;
5169       return nullptr;
5170     }
5171 
5172     DEBUG(dbgs() << "Dropping debug location info for:\n  " << DI << "\n");
5173     DEBUG(dbgs() << "  Last seen at:\n    " << *V << "\n");
5174     return nullptr;
5175   }
5176 
5177   case Intrinsic::eh_typeid_for: {
5178     // Find the type id for the given typeinfo.
5179     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
5180     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
5181     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
5182     setValue(&I, Res);
5183     return nullptr;
5184   }
5185 
5186   case Intrinsic::eh_return_i32:
5187   case Intrinsic::eh_return_i64:
5188     DAG.getMachineFunction().setCallsEHReturn(true);
5189     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
5190                             MVT::Other,
5191                             getControlRoot(),
5192                             getValue(I.getArgOperand(0)),
5193                             getValue(I.getArgOperand(1))));
5194     return nullptr;
5195   case Intrinsic::eh_unwind_init:
5196     DAG.getMachineFunction().setCallsUnwindInit(true);
5197     return nullptr;
5198   case Intrinsic::eh_dwarf_cfa: {
5199     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
5200                              TLI.getPointerTy(DAG.getDataLayout()),
5201                              getValue(I.getArgOperand(0))));
5202     return nullptr;
5203   }
5204   case Intrinsic::eh_sjlj_callsite: {
5205     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5206     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
5207     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
5208     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
5209 
5210     MMI.setCurrentCallSite(CI->getZExtValue());
5211     return nullptr;
5212   }
5213   case Intrinsic::eh_sjlj_functioncontext: {
5214     // Get and store the index of the function context.
5215     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5216     AllocaInst *FnCtx =
5217       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
5218     int FI = FuncInfo.StaticAllocaMap[FnCtx];
5219     MFI.setFunctionContextIndex(FI);
5220     return nullptr;
5221   }
5222   case Intrinsic::eh_sjlj_setjmp: {
5223     SDValue Ops[2];
5224     Ops[0] = getRoot();
5225     Ops[1] = getValue(I.getArgOperand(0));
5226     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
5227                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
5228     setValue(&I, Op.getValue(0));
5229     DAG.setRoot(Op.getValue(1));
5230     return nullptr;
5231   }
5232   case Intrinsic::eh_sjlj_longjmp: {
5233     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
5234                             getRoot(), getValue(I.getArgOperand(0))));
5235     return nullptr;
5236   }
5237   case Intrinsic::eh_sjlj_setup_dispatch: {
5238     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
5239                             getRoot()));
5240     return nullptr;
5241   }
5242 
5243   case Intrinsic::masked_gather:
5244     visitMaskedGather(I);
5245     return nullptr;
5246   case Intrinsic::masked_load:
5247     visitMaskedLoad(I);
5248     return nullptr;
5249   case Intrinsic::masked_scatter:
5250     visitMaskedScatter(I);
5251     return nullptr;
5252   case Intrinsic::masked_store:
5253     visitMaskedStore(I);
5254     return nullptr;
5255   case Intrinsic::masked_expandload:
5256     visitMaskedLoad(I, true /* IsExpanding */);
5257     return nullptr;
5258   case Intrinsic::masked_compressstore:
5259     visitMaskedStore(I, true /* IsCompressing */);
5260     return nullptr;
5261   case Intrinsic::x86_mmx_pslli_w:
5262   case Intrinsic::x86_mmx_pslli_d:
5263   case Intrinsic::x86_mmx_pslli_q:
5264   case Intrinsic::x86_mmx_psrli_w:
5265   case Intrinsic::x86_mmx_psrli_d:
5266   case Intrinsic::x86_mmx_psrli_q:
5267   case Intrinsic::x86_mmx_psrai_w:
5268   case Intrinsic::x86_mmx_psrai_d: {
5269     SDValue ShAmt = getValue(I.getArgOperand(1));
5270     if (isa<ConstantSDNode>(ShAmt)) {
5271       visitTargetIntrinsic(I, Intrinsic);
5272       return nullptr;
5273     }
5274     unsigned NewIntrinsic = 0;
5275     EVT ShAmtVT = MVT::v2i32;
5276     switch (Intrinsic) {
5277     case Intrinsic::x86_mmx_pslli_w:
5278       NewIntrinsic = Intrinsic::x86_mmx_psll_w;
5279       break;
5280     case Intrinsic::x86_mmx_pslli_d:
5281       NewIntrinsic = Intrinsic::x86_mmx_psll_d;
5282       break;
5283     case Intrinsic::x86_mmx_pslli_q:
5284       NewIntrinsic = Intrinsic::x86_mmx_psll_q;
5285       break;
5286     case Intrinsic::x86_mmx_psrli_w:
5287       NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
5288       break;
5289     case Intrinsic::x86_mmx_psrli_d:
5290       NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
5291       break;
5292     case Intrinsic::x86_mmx_psrli_q:
5293       NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
5294       break;
5295     case Intrinsic::x86_mmx_psrai_w:
5296       NewIntrinsic = Intrinsic::x86_mmx_psra_w;
5297       break;
5298     case Intrinsic::x86_mmx_psrai_d:
5299       NewIntrinsic = Intrinsic::x86_mmx_psra_d;
5300       break;
5301     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5302     }
5303 
5304     // The vector shift intrinsics with scalars uses 32b shift amounts but
5305     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
5306     // to be zero.
5307     // We must do this early because v2i32 is not a legal type.
5308     SDValue ShOps[2];
5309     ShOps[0] = ShAmt;
5310     ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
5311     ShAmt =  DAG.getBuildVector(ShAmtVT, sdl, ShOps);
5312     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5313     ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
5314     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
5315                        DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
5316                        getValue(I.getArgOperand(0)), ShAmt);
5317     setValue(&I, Res);
5318     return nullptr;
5319   }
5320   case Intrinsic::powi:
5321     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
5322                             getValue(I.getArgOperand(1)), DAG));
5323     return nullptr;
5324   case Intrinsic::log:
5325     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5326     return nullptr;
5327   case Intrinsic::log2:
5328     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5329     return nullptr;
5330   case Intrinsic::log10:
5331     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5332     return nullptr;
5333   case Intrinsic::exp:
5334     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5335     return nullptr;
5336   case Intrinsic::exp2:
5337     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5338     return nullptr;
5339   case Intrinsic::pow:
5340     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
5341                            getValue(I.getArgOperand(1)), DAG, TLI));
5342     return nullptr;
5343   case Intrinsic::sqrt:
5344   case Intrinsic::fabs:
5345   case Intrinsic::sin:
5346   case Intrinsic::cos:
5347   case Intrinsic::floor:
5348   case Intrinsic::ceil:
5349   case Intrinsic::trunc:
5350   case Intrinsic::rint:
5351   case Intrinsic::nearbyint:
5352   case Intrinsic::round:
5353   case Intrinsic::canonicalize: {
5354     unsigned Opcode;
5355     switch (Intrinsic) {
5356     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5357     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
5358     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
5359     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
5360     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
5361     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
5362     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
5363     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
5364     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
5365     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
5366     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
5367     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
5368     }
5369 
5370     setValue(&I, DAG.getNode(Opcode, sdl,
5371                              getValue(I.getArgOperand(0)).getValueType(),
5372                              getValue(I.getArgOperand(0))));
5373     return nullptr;
5374   }
5375   case Intrinsic::minnum: {
5376     auto VT = getValue(I.getArgOperand(0)).getValueType();
5377     unsigned Opc =
5378         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT)
5379             ? ISD::FMINNAN
5380             : ISD::FMINNUM;
5381     setValue(&I, DAG.getNode(Opc, sdl, VT,
5382                              getValue(I.getArgOperand(0)),
5383                              getValue(I.getArgOperand(1))));
5384     return nullptr;
5385   }
5386   case Intrinsic::maxnum: {
5387     auto VT = getValue(I.getArgOperand(0)).getValueType();
5388     unsigned Opc =
5389         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT)
5390             ? ISD::FMAXNAN
5391             : ISD::FMAXNUM;
5392     setValue(&I, DAG.getNode(Opc, sdl, VT,
5393                              getValue(I.getArgOperand(0)),
5394                              getValue(I.getArgOperand(1))));
5395     return nullptr;
5396   }
5397   case Intrinsic::copysign:
5398     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
5399                              getValue(I.getArgOperand(0)).getValueType(),
5400                              getValue(I.getArgOperand(0)),
5401                              getValue(I.getArgOperand(1))));
5402     return nullptr;
5403   case Intrinsic::fma:
5404     setValue(&I, DAG.getNode(ISD::FMA, sdl,
5405                              getValue(I.getArgOperand(0)).getValueType(),
5406                              getValue(I.getArgOperand(0)),
5407                              getValue(I.getArgOperand(1)),
5408                              getValue(I.getArgOperand(2))));
5409     return nullptr;
5410   case Intrinsic::experimental_constrained_fadd:
5411   case Intrinsic::experimental_constrained_fsub:
5412   case Intrinsic::experimental_constrained_fmul:
5413   case Intrinsic::experimental_constrained_fdiv:
5414   case Intrinsic::experimental_constrained_frem:
5415   case Intrinsic::experimental_constrained_sqrt:
5416   case Intrinsic::experimental_constrained_pow:
5417   case Intrinsic::experimental_constrained_powi:
5418   case Intrinsic::experimental_constrained_sin:
5419   case Intrinsic::experimental_constrained_cos:
5420   case Intrinsic::experimental_constrained_exp:
5421   case Intrinsic::experimental_constrained_exp2:
5422   case Intrinsic::experimental_constrained_log:
5423   case Intrinsic::experimental_constrained_log10:
5424   case Intrinsic::experimental_constrained_log2:
5425   case Intrinsic::experimental_constrained_rint:
5426   case Intrinsic::experimental_constrained_nearbyint:
5427     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
5428     return nullptr;
5429   case Intrinsic::fmuladd: {
5430     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5431     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
5432         TLI.isFMAFasterThanFMulAndFAdd(VT)) {
5433       setValue(&I, DAG.getNode(ISD::FMA, sdl,
5434                                getValue(I.getArgOperand(0)).getValueType(),
5435                                getValue(I.getArgOperand(0)),
5436                                getValue(I.getArgOperand(1)),
5437                                getValue(I.getArgOperand(2))));
5438     } else {
5439       // TODO: Intrinsic calls should have fast-math-flags.
5440       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
5441                                 getValue(I.getArgOperand(0)).getValueType(),
5442                                 getValue(I.getArgOperand(0)),
5443                                 getValue(I.getArgOperand(1)));
5444       SDValue Add = DAG.getNode(ISD::FADD, sdl,
5445                                 getValue(I.getArgOperand(0)).getValueType(),
5446                                 Mul,
5447                                 getValue(I.getArgOperand(2)));
5448       setValue(&I, Add);
5449     }
5450     return nullptr;
5451   }
5452   case Intrinsic::convert_to_fp16:
5453     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
5454                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
5455                                          getValue(I.getArgOperand(0)),
5456                                          DAG.getTargetConstant(0, sdl,
5457                                                                MVT::i32))));
5458     return nullptr;
5459   case Intrinsic::convert_from_fp16:
5460     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
5461                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
5462                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
5463                                          getValue(I.getArgOperand(0)))));
5464     return nullptr;
5465   case Intrinsic::pcmarker: {
5466     SDValue Tmp = getValue(I.getArgOperand(0));
5467     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
5468     return nullptr;
5469   }
5470   case Intrinsic::readcyclecounter: {
5471     SDValue Op = getRoot();
5472     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
5473                       DAG.getVTList(MVT::i64, MVT::Other), Op);
5474     setValue(&I, Res);
5475     DAG.setRoot(Res.getValue(1));
5476     return nullptr;
5477   }
5478   case Intrinsic::bitreverse:
5479     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
5480                              getValue(I.getArgOperand(0)).getValueType(),
5481                              getValue(I.getArgOperand(0))));
5482     return nullptr;
5483   case Intrinsic::bswap:
5484     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
5485                              getValue(I.getArgOperand(0)).getValueType(),
5486                              getValue(I.getArgOperand(0))));
5487     return nullptr;
5488   case Intrinsic::cttz: {
5489     SDValue Arg = getValue(I.getArgOperand(0));
5490     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5491     EVT Ty = Arg.getValueType();
5492     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
5493                              sdl, Ty, Arg));
5494     return nullptr;
5495   }
5496   case Intrinsic::ctlz: {
5497     SDValue Arg = getValue(I.getArgOperand(0));
5498     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5499     EVT Ty = Arg.getValueType();
5500     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
5501                              sdl, Ty, Arg));
5502     return nullptr;
5503   }
5504   case Intrinsic::ctpop: {
5505     SDValue Arg = getValue(I.getArgOperand(0));
5506     EVT Ty = Arg.getValueType();
5507     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
5508     return nullptr;
5509   }
5510   case Intrinsic::stacksave: {
5511     SDValue Op = getRoot();
5512     Res = DAG.getNode(
5513         ISD::STACKSAVE, sdl,
5514         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
5515     setValue(&I, Res);
5516     DAG.setRoot(Res.getValue(1));
5517     return nullptr;
5518   }
5519   case Intrinsic::stackrestore: {
5520     Res = getValue(I.getArgOperand(0));
5521     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
5522     return nullptr;
5523   }
5524   case Intrinsic::get_dynamic_area_offset: {
5525     SDValue Op = getRoot();
5526     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5527     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
5528     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
5529     // target.
5530     if (PtrTy != ResTy)
5531       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
5532                          " intrinsic!");
5533     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
5534                       Op);
5535     DAG.setRoot(Op);
5536     setValue(&I, Res);
5537     return nullptr;
5538   }
5539   case Intrinsic::stackguard: {
5540     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5541     MachineFunction &MF = DAG.getMachineFunction();
5542     const Module &M = *MF.getFunction()->getParent();
5543     SDValue Chain = getRoot();
5544     if (TLI.useLoadStackGuardNode()) {
5545       Res = getLoadStackGuard(DAG, sdl, Chain);
5546     } else {
5547       const Value *Global = TLI.getSDagStackGuard(M);
5548       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
5549       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
5550                         MachinePointerInfo(Global, 0), Align,
5551                         MachineMemOperand::MOVolatile);
5552     }
5553     DAG.setRoot(Chain);
5554     setValue(&I, Res);
5555     return nullptr;
5556   }
5557   case Intrinsic::stackprotector: {
5558     // Emit code into the DAG to store the stack guard onto the stack.
5559     MachineFunction &MF = DAG.getMachineFunction();
5560     MachineFrameInfo &MFI = MF.getFrameInfo();
5561     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5562     SDValue Src, Chain = getRoot();
5563 
5564     if (TLI.useLoadStackGuardNode())
5565       Src = getLoadStackGuard(DAG, sdl, Chain);
5566     else
5567       Src = getValue(I.getArgOperand(0));   // The guard's value.
5568 
5569     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
5570 
5571     int FI = FuncInfo.StaticAllocaMap[Slot];
5572     MFI.setStackProtectorIndex(FI);
5573 
5574     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
5575 
5576     // Store the stack protector onto the stack.
5577     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
5578                                                  DAG.getMachineFunction(), FI),
5579                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
5580     setValue(&I, Res);
5581     DAG.setRoot(Res);
5582     return nullptr;
5583   }
5584   case Intrinsic::objectsize: {
5585     // If we don't know by now, we're never going to know.
5586     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
5587 
5588     assert(CI && "Non-constant type in __builtin_object_size?");
5589 
5590     SDValue Arg = getValue(I.getCalledValue());
5591     EVT Ty = Arg.getValueType();
5592 
5593     if (CI->isZero())
5594       Res = DAG.getConstant(-1ULL, sdl, Ty);
5595     else
5596       Res = DAG.getConstant(0, sdl, Ty);
5597 
5598     setValue(&I, Res);
5599     return nullptr;
5600   }
5601   case Intrinsic::annotation:
5602   case Intrinsic::ptr_annotation:
5603   case Intrinsic::invariant_group_barrier:
5604     // Drop the intrinsic, but forward the value
5605     setValue(&I, getValue(I.getOperand(0)));
5606     return nullptr;
5607   case Intrinsic::assume:
5608   case Intrinsic::var_annotation:
5609     // Discard annotate attributes and assumptions
5610     return nullptr;
5611 
5612   case Intrinsic::init_trampoline: {
5613     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
5614 
5615     SDValue Ops[6];
5616     Ops[0] = getRoot();
5617     Ops[1] = getValue(I.getArgOperand(0));
5618     Ops[2] = getValue(I.getArgOperand(1));
5619     Ops[3] = getValue(I.getArgOperand(2));
5620     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
5621     Ops[5] = DAG.getSrcValue(F);
5622 
5623     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
5624 
5625     DAG.setRoot(Res);
5626     return nullptr;
5627   }
5628   case Intrinsic::adjust_trampoline: {
5629     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
5630                              TLI.getPointerTy(DAG.getDataLayout()),
5631                              getValue(I.getArgOperand(0))));
5632     return nullptr;
5633   }
5634   case Intrinsic::gcroot: {
5635     MachineFunction &MF = DAG.getMachineFunction();
5636     const Function *F = MF.getFunction();
5637     (void)F;
5638     assert(F->hasGC() &&
5639            "only valid in functions with gc specified, enforced by Verifier");
5640     assert(GFI && "implied by previous");
5641     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
5642     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
5643 
5644     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
5645     GFI->addStackRoot(FI->getIndex(), TypeMap);
5646     return nullptr;
5647   }
5648   case Intrinsic::gcread:
5649   case Intrinsic::gcwrite:
5650     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
5651   case Intrinsic::flt_rounds:
5652     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
5653     return nullptr;
5654 
5655   case Intrinsic::expect: {
5656     // Just replace __builtin_expect(exp, c) with EXP.
5657     setValue(&I, getValue(I.getArgOperand(0)));
5658     return nullptr;
5659   }
5660 
5661   case Intrinsic::debugtrap:
5662   case Intrinsic::trap: {
5663     StringRef TrapFuncName =
5664         I.getAttributes()
5665             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
5666             .getValueAsString();
5667     if (TrapFuncName.empty()) {
5668       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
5669         ISD::TRAP : ISD::DEBUGTRAP;
5670       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
5671       return nullptr;
5672     }
5673     TargetLowering::ArgListTy Args;
5674 
5675     TargetLowering::CallLoweringInfo CLI(DAG);
5676     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
5677         CallingConv::C, I.getType(),
5678         DAG.getExternalSymbol(TrapFuncName.data(),
5679                               TLI.getPointerTy(DAG.getDataLayout())),
5680         std::move(Args));
5681 
5682     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
5683     DAG.setRoot(Result.second);
5684     return nullptr;
5685   }
5686 
5687   case Intrinsic::uadd_with_overflow:
5688   case Intrinsic::sadd_with_overflow:
5689   case Intrinsic::usub_with_overflow:
5690   case Intrinsic::ssub_with_overflow:
5691   case Intrinsic::umul_with_overflow:
5692   case Intrinsic::smul_with_overflow: {
5693     ISD::NodeType Op;
5694     switch (Intrinsic) {
5695     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5696     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
5697     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
5698     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
5699     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
5700     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
5701     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
5702     }
5703     SDValue Op1 = getValue(I.getArgOperand(0));
5704     SDValue Op2 = getValue(I.getArgOperand(1));
5705 
5706     SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
5707     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
5708     return nullptr;
5709   }
5710   case Intrinsic::prefetch: {
5711     SDValue Ops[5];
5712     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
5713     Ops[0] = getRoot();
5714     Ops[1] = getValue(I.getArgOperand(0));
5715     Ops[2] = getValue(I.getArgOperand(1));
5716     Ops[3] = getValue(I.getArgOperand(2));
5717     Ops[4] = getValue(I.getArgOperand(3));
5718     DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
5719                                         DAG.getVTList(MVT::Other), Ops,
5720                                         EVT::getIntegerVT(*Context, 8),
5721                                         MachinePointerInfo(I.getArgOperand(0)),
5722                                         0, /* align */
5723                                         false, /* volatile */
5724                                         rw==0, /* read */
5725                                         rw==1)); /* write */
5726     return nullptr;
5727   }
5728   case Intrinsic::lifetime_start:
5729   case Intrinsic::lifetime_end: {
5730     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
5731     // Stack coloring is not enabled in O0, discard region information.
5732     if (TM.getOptLevel() == CodeGenOpt::None)
5733       return nullptr;
5734 
5735     SmallVector<Value *, 4> Allocas;
5736     GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL);
5737 
5738     for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
5739            E = Allocas.end(); Object != E; ++Object) {
5740       AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
5741 
5742       // Could not find an Alloca.
5743       if (!LifetimeObject)
5744         continue;
5745 
5746       // First check that the Alloca is static, otherwise it won't have a
5747       // valid frame index.
5748       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
5749       if (SI == FuncInfo.StaticAllocaMap.end())
5750         return nullptr;
5751 
5752       int FI = SI->second;
5753 
5754       SDValue Ops[2];
5755       Ops[0] = getRoot();
5756       Ops[1] =
5757           DAG.getFrameIndex(FI, TLI.getFrameIndexTy(DAG.getDataLayout()), true);
5758       unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
5759 
5760       Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
5761       DAG.setRoot(Res);
5762     }
5763     return nullptr;
5764   }
5765   case Intrinsic::invariant_start:
5766     // Discard region information.
5767     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
5768     return nullptr;
5769   case Intrinsic::invariant_end:
5770     // Discard region information.
5771     return nullptr;
5772   case Intrinsic::clear_cache:
5773     return TLI.getClearCacheBuiltinName();
5774   case Intrinsic::donothing:
5775     // ignore
5776     return nullptr;
5777   case Intrinsic::experimental_stackmap: {
5778     visitStackmap(I);
5779     return nullptr;
5780   }
5781   case Intrinsic::experimental_patchpoint_void:
5782   case Intrinsic::experimental_patchpoint_i64: {
5783     visitPatchpoint(&I);
5784     return nullptr;
5785   }
5786   case Intrinsic::experimental_gc_statepoint: {
5787     LowerStatepoint(ImmutableStatepoint(&I));
5788     return nullptr;
5789   }
5790   case Intrinsic::experimental_gc_result: {
5791     visitGCResult(cast<GCResultInst>(I));
5792     return nullptr;
5793   }
5794   case Intrinsic::experimental_gc_relocate: {
5795     visitGCRelocate(cast<GCRelocateInst>(I));
5796     return nullptr;
5797   }
5798   case Intrinsic::instrprof_increment:
5799     llvm_unreachable("instrprof failed to lower an increment");
5800   case Intrinsic::instrprof_value_profile:
5801     llvm_unreachable("instrprof failed to lower a value profiling call");
5802   case Intrinsic::localescape: {
5803     MachineFunction &MF = DAG.getMachineFunction();
5804     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5805 
5806     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
5807     // is the same on all targets.
5808     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
5809       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
5810       if (isa<ConstantPointerNull>(Arg))
5811         continue; // Skip null pointers. They represent a hole in index space.
5812       AllocaInst *Slot = cast<AllocaInst>(Arg);
5813       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
5814              "can only escape static allocas");
5815       int FI = FuncInfo.StaticAllocaMap[Slot];
5816       MCSymbol *FrameAllocSym =
5817           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
5818               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
5819       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
5820               TII->get(TargetOpcode::LOCAL_ESCAPE))
5821           .addSym(FrameAllocSym)
5822           .addFrameIndex(FI);
5823     }
5824 
5825     return nullptr;
5826   }
5827 
5828   case Intrinsic::localrecover: {
5829     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
5830     MachineFunction &MF = DAG.getMachineFunction();
5831     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
5832 
5833     // Get the symbol that defines the frame offset.
5834     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
5835     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
5836     unsigned IdxVal = unsigned(Idx->getLimitedValue(INT_MAX));
5837     MCSymbol *FrameAllocSym =
5838         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
5839             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
5840 
5841     // Create a MCSymbol for the label to avoid any target lowering
5842     // that would make this PC relative.
5843     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
5844     SDValue OffsetVal =
5845         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
5846 
5847     // Add the offset to the FP.
5848     Value *FP = I.getArgOperand(1);
5849     SDValue FPVal = getValue(FP);
5850     SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
5851     setValue(&I, Add);
5852 
5853     return nullptr;
5854   }
5855 
5856   case Intrinsic::eh_exceptionpointer:
5857   case Intrinsic::eh_exceptioncode: {
5858     // Get the exception pointer vreg, copy from it, and resize it to fit.
5859     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
5860     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
5861     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
5862     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
5863     SDValue N =
5864         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
5865     if (Intrinsic == Intrinsic::eh_exceptioncode)
5866       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
5867     setValue(&I, N);
5868     return nullptr;
5869   }
5870   case Intrinsic::xray_customevent: {
5871     // Here we want to make sure that the intrinsic behaves as if it has a
5872     // specific calling convention, and only for x86_64.
5873     // FIXME: Support other platforms later.
5874     const auto &Triple = DAG.getTarget().getTargetTriple();
5875     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
5876       return nullptr;
5877 
5878     SDLoc DL = getCurSDLoc();
5879     SmallVector<SDValue, 8> Ops;
5880 
5881     // We want to say that we always want the arguments in registers.
5882     SDValue LogEntryVal = getValue(I.getArgOperand(0));
5883     SDValue StrSizeVal = getValue(I.getArgOperand(1));
5884     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
5885     SDValue Chain = getRoot();
5886     Ops.push_back(LogEntryVal);
5887     Ops.push_back(StrSizeVal);
5888     Ops.push_back(Chain);
5889 
5890     // We need to enforce the calling convention for the callsite, so that
5891     // argument ordering is enforced correctly, and that register allocation can
5892     // see that some registers may be assumed clobbered and have to preserve
5893     // them across calls to the intrinsic.
5894     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
5895                                            DL, NodeTys, Ops);
5896     SDValue patchableNode = SDValue(MN, 0);
5897     DAG.setRoot(patchableNode);
5898     setValue(&I, patchableNode);
5899     return nullptr;
5900   }
5901   case Intrinsic::experimental_deoptimize:
5902     LowerDeoptimizeCall(&I);
5903     return nullptr;
5904 
5905   case Intrinsic::experimental_vector_reduce_fadd:
5906   case Intrinsic::experimental_vector_reduce_fmul:
5907   case Intrinsic::experimental_vector_reduce_add:
5908   case Intrinsic::experimental_vector_reduce_mul:
5909   case Intrinsic::experimental_vector_reduce_and:
5910   case Intrinsic::experimental_vector_reduce_or:
5911   case Intrinsic::experimental_vector_reduce_xor:
5912   case Intrinsic::experimental_vector_reduce_smax:
5913   case Intrinsic::experimental_vector_reduce_smin:
5914   case Intrinsic::experimental_vector_reduce_umax:
5915   case Intrinsic::experimental_vector_reduce_umin:
5916   case Intrinsic::experimental_vector_reduce_fmax:
5917   case Intrinsic::experimental_vector_reduce_fmin: {
5918     visitVectorReduce(I, Intrinsic);
5919     return nullptr;
5920   }
5921 
5922   }
5923 }
5924 
5925 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
5926     const ConstrainedFPIntrinsic &FPI) {
5927   SDLoc sdl = getCurSDLoc();
5928   unsigned Opcode;
5929   switch (FPI.getIntrinsicID()) {
5930   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5931   case Intrinsic::experimental_constrained_fadd:
5932     Opcode = ISD::STRICT_FADD;
5933     break;
5934   case Intrinsic::experimental_constrained_fsub:
5935     Opcode = ISD::STRICT_FSUB;
5936     break;
5937   case Intrinsic::experimental_constrained_fmul:
5938     Opcode = ISD::STRICT_FMUL;
5939     break;
5940   case Intrinsic::experimental_constrained_fdiv:
5941     Opcode = ISD::STRICT_FDIV;
5942     break;
5943   case Intrinsic::experimental_constrained_frem:
5944     Opcode = ISD::STRICT_FREM;
5945     break;
5946   case Intrinsic::experimental_constrained_sqrt:
5947     Opcode = ISD::STRICT_FSQRT;
5948     break;
5949   case Intrinsic::experimental_constrained_pow:
5950     Opcode = ISD::STRICT_FPOW;
5951     break;
5952   case Intrinsic::experimental_constrained_powi:
5953     Opcode = ISD::STRICT_FPOWI;
5954     break;
5955   case Intrinsic::experimental_constrained_sin:
5956     Opcode = ISD::STRICT_FSIN;
5957     break;
5958   case Intrinsic::experimental_constrained_cos:
5959     Opcode = ISD::STRICT_FCOS;
5960     break;
5961   case Intrinsic::experimental_constrained_exp:
5962     Opcode = ISD::STRICT_FEXP;
5963     break;
5964   case Intrinsic::experimental_constrained_exp2:
5965     Opcode = ISD::STRICT_FEXP2;
5966     break;
5967   case Intrinsic::experimental_constrained_log:
5968     Opcode = ISD::STRICT_FLOG;
5969     break;
5970   case Intrinsic::experimental_constrained_log10:
5971     Opcode = ISD::STRICT_FLOG10;
5972     break;
5973   case Intrinsic::experimental_constrained_log2:
5974     Opcode = ISD::STRICT_FLOG2;
5975     break;
5976   case Intrinsic::experimental_constrained_rint:
5977     Opcode = ISD::STRICT_FRINT;
5978     break;
5979   case Intrinsic::experimental_constrained_nearbyint:
5980     Opcode = ISD::STRICT_FNEARBYINT;
5981     break;
5982   }
5983   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5984   SDValue Chain = getRoot();
5985   SmallVector<EVT, 4> ValueVTs;
5986   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
5987   ValueVTs.push_back(MVT::Other); // Out chain
5988 
5989   SDVTList VTs = DAG.getVTList(ValueVTs);
5990   SDValue Result;
5991   if (FPI.isUnaryOp())
5992     Result = DAG.getNode(Opcode, sdl, VTs,
5993                          { Chain, getValue(FPI.getArgOperand(0)) });
5994   else
5995     Result = DAG.getNode(Opcode, sdl, VTs,
5996                          { Chain, getValue(FPI.getArgOperand(0)),
5997                            getValue(FPI.getArgOperand(1))  });
5998 
5999   assert(Result.getNode()->getNumValues() == 2);
6000   SDValue OutChain = Result.getValue(1);
6001   DAG.setRoot(OutChain);
6002   SDValue FPResult = Result.getValue(0);
6003   setValue(&FPI, FPResult);
6004 }
6005 
6006 std::pair<SDValue, SDValue>
6007 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
6008                                     const BasicBlock *EHPadBB) {
6009   MachineFunction &MF = DAG.getMachineFunction();
6010   MachineModuleInfo &MMI = MF.getMMI();
6011   MCSymbol *BeginLabel = nullptr;
6012 
6013   if (EHPadBB) {
6014     // Insert a label before the invoke call to mark the try range.  This can be
6015     // used to detect deletion of the invoke via the MachineModuleInfo.
6016     BeginLabel = MMI.getContext().createTempSymbol();
6017 
6018     // For SjLj, keep track of which landing pads go with which invokes
6019     // so as to maintain the ordering of pads in the LSDA.
6020     unsigned CallSiteIndex = MMI.getCurrentCallSite();
6021     if (CallSiteIndex) {
6022       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
6023       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
6024 
6025       // Now that the call site is handled, stop tracking it.
6026       MMI.setCurrentCallSite(0);
6027     }
6028 
6029     // Both PendingLoads and PendingExports must be flushed here;
6030     // this call might not return.
6031     (void)getRoot();
6032     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
6033 
6034     CLI.setChain(getRoot());
6035   }
6036   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6037   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6038 
6039   assert((CLI.IsTailCall || Result.second.getNode()) &&
6040          "Non-null chain expected with non-tail call!");
6041   assert((Result.second.getNode() || !Result.first.getNode()) &&
6042          "Null value expected with tail call!");
6043 
6044   if (!Result.second.getNode()) {
6045     // As a special case, a null chain means that a tail call has been emitted
6046     // and the DAG root is already updated.
6047     HasTailCall = true;
6048 
6049     // Since there's no actual continuation from this block, nothing can be
6050     // relying on us setting vregs for them.
6051     PendingExports.clear();
6052   } else {
6053     DAG.setRoot(Result.second);
6054   }
6055 
6056   if (EHPadBB) {
6057     // Insert a label at the end of the invoke call to mark the try range.  This
6058     // can be used to detect deletion of the invoke via the MachineModuleInfo.
6059     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
6060     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
6061 
6062     // Inform MachineModuleInfo of range.
6063     if (MF.hasEHFunclets()) {
6064       assert(CLI.CS);
6065       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
6066       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
6067                                 BeginLabel, EndLabel);
6068     } else {
6069       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
6070     }
6071   }
6072 
6073   return Result;
6074 }
6075 
6076 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
6077                                       bool isTailCall,
6078                                       const BasicBlock *EHPadBB) {
6079   auto &DL = DAG.getDataLayout();
6080   FunctionType *FTy = CS.getFunctionType();
6081   Type *RetTy = CS.getType();
6082 
6083   TargetLowering::ArgListTy Args;
6084   Args.reserve(CS.arg_size());
6085 
6086   const Value *SwiftErrorVal = nullptr;
6087   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6088 
6089   // We can't tail call inside a function with a swifterror argument. Lowering
6090   // does not support this yet. It would have to move into the swifterror
6091   // register before the call.
6092   auto *Caller = CS.getInstruction()->getParent()->getParent();
6093   if (TLI.supportSwiftError() &&
6094       Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
6095     isTailCall = false;
6096 
6097   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
6098        i != e; ++i) {
6099     TargetLowering::ArgListEntry Entry;
6100     const Value *V = *i;
6101 
6102     // Skip empty types
6103     if (V->getType()->isEmptyTy())
6104       continue;
6105 
6106     SDValue ArgNode = getValue(V);
6107     Entry.Node = ArgNode; Entry.Ty = V->getType();
6108 
6109     Entry.setAttributes(&CS, i - CS.arg_begin());
6110 
6111     // Use swifterror virtual register as input to the call.
6112     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
6113       SwiftErrorVal = V;
6114       // We find the virtual register for the actual swifterror argument.
6115       // Instead of using the Value, we use the virtual register instead.
6116       Entry.Node = DAG.getRegister(FuncInfo
6117                                        .getOrCreateSwiftErrorVRegUseAt(
6118                                            CS.getInstruction(), FuncInfo.MBB, V)
6119                                        .first,
6120                                    EVT(TLI.getPointerTy(DL)));
6121     }
6122 
6123     Args.push_back(Entry);
6124 
6125     // If we have an explicit sret argument that is an Instruction, (i.e., it
6126     // might point to function-local memory), we can't meaningfully tail-call.
6127     if (Entry.IsSRet && isa<Instruction>(V))
6128       isTailCall = false;
6129   }
6130 
6131   // Check if target-independent constraints permit a tail call here.
6132   // Target-dependent constraints are checked within TLI->LowerCallTo.
6133   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
6134     isTailCall = false;
6135 
6136   // Disable tail calls if there is an swifterror argument. Targets have not
6137   // been updated to support tail calls.
6138   if (TLI.supportSwiftError() && SwiftErrorVal)
6139     isTailCall = false;
6140 
6141   TargetLowering::CallLoweringInfo CLI(DAG);
6142   CLI.setDebugLoc(getCurSDLoc())
6143       .setChain(getRoot())
6144       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
6145       .setTailCall(isTailCall)
6146       .setConvergent(CS.isConvergent());
6147   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
6148 
6149   if (Result.first.getNode()) {
6150     const Instruction *Inst = CS.getInstruction();
6151     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
6152     setValue(Inst, Result.first);
6153   }
6154 
6155   // The last element of CLI.InVals has the SDValue for swifterror return.
6156   // Here we copy it to a virtual register and update SwiftErrorMap for
6157   // book-keeping.
6158   if (SwiftErrorVal && TLI.supportSwiftError()) {
6159     // Get the last element of InVals.
6160     SDValue Src = CLI.InVals.back();
6161     unsigned VReg; bool CreatedVReg;
6162     std::tie(VReg, CreatedVReg) =
6163         FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction());
6164     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
6165     // We update the virtual register for the actual swifterror argument.
6166     if (CreatedVReg)
6167       FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg);
6168     DAG.setRoot(CopyNode);
6169   }
6170 }
6171 
6172 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
6173                              SelectionDAGBuilder &Builder) {
6174 
6175   // Check to see if this load can be trivially constant folded, e.g. if the
6176   // input is from a string literal.
6177   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
6178     // Cast pointer to the type we really want to load.
6179     Type *LoadTy =
6180         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
6181     if (LoadVT.isVector())
6182       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
6183 
6184     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
6185                                          PointerType::getUnqual(LoadTy));
6186 
6187     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
6188             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
6189       return Builder.getValue(LoadCst);
6190   }
6191 
6192   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
6193   // still constant memory, the input chain can be the entry node.
6194   SDValue Root;
6195   bool ConstantMemory = false;
6196 
6197   // Do not serialize (non-volatile) loads of constant memory with anything.
6198   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
6199     Root = Builder.DAG.getEntryNode();
6200     ConstantMemory = true;
6201   } else {
6202     // Do not serialize non-volatile loads against each other.
6203     Root = Builder.DAG.getRoot();
6204   }
6205 
6206   SDValue Ptr = Builder.getValue(PtrVal);
6207   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
6208                                         Ptr, MachinePointerInfo(PtrVal),
6209                                         /* Alignment = */ 1);
6210 
6211   if (!ConstantMemory)
6212     Builder.PendingLoads.push_back(LoadVal.getValue(1));
6213   return LoadVal;
6214 }
6215 
6216 /// Record the value for an instruction that produces an integer result,
6217 /// converting the type where necessary.
6218 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
6219                                                   SDValue Value,
6220                                                   bool IsSigned) {
6221   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
6222                                                     I.getType(), true);
6223   if (IsSigned)
6224     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
6225   else
6226     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
6227   setValue(&I, Value);
6228 }
6229 
6230 /// See if we can lower a memcmp call into an optimized form. If so, return
6231 /// true and lower it. Otherwise return false, and it will be lowered like a
6232 /// normal call.
6233 /// The caller already checked that \p I calls the appropriate LibFunc with a
6234 /// correct prototype.
6235 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
6236   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
6237   const Value *Size = I.getArgOperand(2);
6238   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
6239   if (CSize && CSize->getZExtValue() == 0) {
6240     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
6241                                                           I.getType(), true);
6242     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
6243     return true;
6244   }
6245 
6246   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6247   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
6248       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
6249       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
6250   if (Res.first.getNode()) {
6251     processIntegerCallValue(I, Res.first, true);
6252     PendingLoads.push_back(Res.second);
6253     return true;
6254   }
6255 
6256   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
6257   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
6258   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
6259     return false;
6260 
6261   // If the target has a fast compare for the given size, it will return a
6262   // preferred load type for that size. Require that the load VT is legal and
6263   // that the target supports unaligned loads of that type. Otherwise, return
6264   // INVALID.
6265   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
6266     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6267     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
6268     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
6269       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
6270       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
6271       // TODO: Check alignment of src and dest ptrs.
6272       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
6273       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
6274       if (!TLI.isTypeLegal(LVT) ||
6275           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
6276           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
6277         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
6278     }
6279 
6280     return LVT;
6281   };
6282 
6283   // This turns into unaligned loads. We only do this if the target natively
6284   // supports the MVT we'll be loading or if it is small enough (<= 4) that
6285   // we'll only produce a small number of byte loads.
6286   MVT LoadVT;
6287   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
6288   switch (NumBitsToCompare) {
6289   default:
6290     return false;
6291   case 16:
6292     LoadVT = MVT::i16;
6293     break;
6294   case 32:
6295     LoadVT = MVT::i32;
6296     break;
6297   case 64:
6298   case 128:
6299   case 256:
6300     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
6301     break;
6302   }
6303 
6304   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
6305     return false;
6306 
6307   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
6308   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
6309 
6310   // Bitcast to a wide integer type if the loads are vectors.
6311   if (LoadVT.isVector()) {
6312     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
6313     LoadL = DAG.getBitcast(CmpVT, LoadL);
6314     LoadR = DAG.getBitcast(CmpVT, LoadR);
6315   }
6316 
6317   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
6318   processIntegerCallValue(I, Cmp, false);
6319   return true;
6320 }
6321 
6322 /// See if we can lower a memchr call into an optimized form. If so, return
6323 /// true and lower it. Otherwise return false, and it will be lowered like a
6324 /// normal call.
6325 /// The caller already checked that \p I calls the appropriate LibFunc with a
6326 /// correct prototype.
6327 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
6328   const Value *Src = I.getArgOperand(0);
6329   const Value *Char = I.getArgOperand(1);
6330   const Value *Length = I.getArgOperand(2);
6331 
6332   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6333   std::pair<SDValue, SDValue> Res =
6334     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
6335                                 getValue(Src), getValue(Char), getValue(Length),
6336                                 MachinePointerInfo(Src));
6337   if (Res.first.getNode()) {
6338     setValue(&I, Res.first);
6339     PendingLoads.push_back(Res.second);
6340     return true;
6341   }
6342 
6343   return false;
6344 }
6345 
6346 /// See if we can lower a mempcpy call into an optimized form. If so, return
6347 /// true and lower it. Otherwise return false, and it will be lowered like a
6348 /// normal call.
6349 /// The caller already checked that \p I calls the appropriate LibFunc with a
6350 /// correct prototype.
6351 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
6352   SDValue Dst = getValue(I.getArgOperand(0));
6353   SDValue Src = getValue(I.getArgOperand(1));
6354   SDValue Size = getValue(I.getArgOperand(2));
6355 
6356   unsigned DstAlign = DAG.InferPtrAlignment(Dst);
6357   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
6358   unsigned Align = std::min(DstAlign, SrcAlign);
6359   if (Align == 0) // Alignment of one or both could not be inferred.
6360     Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
6361 
6362   bool isVol = false;
6363   SDLoc sdl = getCurSDLoc();
6364 
6365   // In the mempcpy context we need to pass in a false value for isTailCall
6366   // because the return pointer needs to be adjusted by the size of
6367   // the copied memory.
6368   SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
6369                              false, /*isTailCall=*/false,
6370                              MachinePointerInfo(I.getArgOperand(0)),
6371                              MachinePointerInfo(I.getArgOperand(1)));
6372   assert(MC.getNode() != nullptr &&
6373          "** memcpy should not be lowered as TailCall in mempcpy context **");
6374   DAG.setRoot(MC);
6375 
6376   // Check if Size needs to be truncated or extended.
6377   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
6378 
6379   // Adjust return pointer to point just past the last dst byte.
6380   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
6381                                     Dst, Size);
6382   setValue(&I, DstPlusSize);
6383   return true;
6384 }
6385 
6386 /// See if we can lower a strcpy call into an optimized form.  If so, return
6387 /// true and lower it, otherwise return false and it will be lowered like a
6388 /// normal call.
6389 /// The caller already checked that \p I calls the appropriate LibFunc with a
6390 /// correct prototype.
6391 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
6392   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6393 
6394   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6395   std::pair<SDValue, SDValue> Res =
6396     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
6397                                 getValue(Arg0), getValue(Arg1),
6398                                 MachinePointerInfo(Arg0),
6399                                 MachinePointerInfo(Arg1), isStpcpy);
6400   if (Res.first.getNode()) {
6401     setValue(&I, Res.first);
6402     DAG.setRoot(Res.second);
6403     return true;
6404   }
6405 
6406   return false;
6407 }
6408 
6409 /// See if we can lower a strcmp call into an optimized form.  If so, return
6410 /// true and lower it, otherwise return false and it will be lowered like a
6411 /// normal call.
6412 /// The caller already checked that \p I calls the appropriate LibFunc with a
6413 /// correct prototype.
6414 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
6415   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6416 
6417   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6418   std::pair<SDValue, SDValue> Res =
6419     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
6420                                 getValue(Arg0), getValue(Arg1),
6421                                 MachinePointerInfo(Arg0),
6422                                 MachinePointerInfo(Arg1));
6423   if (Res.first.getNode()) {
6424     processIntegerCallValue(I, Res.first, true);
6425     PendingLoads.push_back(Res.second);
6426     return true;
6427   }
6428 
6429   return false;
6430 }
6431 
6432 /// See if we can lower a strlen call into an optimized form.  If so, return
6433 /// true and lower it, otherwise return false and it will be lowered like a
6434 /// normal call.
6435 /// The caller already checked that \p I calls the appropriate LibFunc with a
6436 /// correct prototype.
6437 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
6438   const Value *Arg0 = I.getArgOperand(0);
6439 
6440   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6441   std::pair<SDValue, SDValue> Res =
6442     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
6443                                 getValue(Arg0), MachinePointerInfo(Arg0));
6444   if (Res.first.getNode()) {
6445     processIntegerCallValue(I, Res.first, false);
6446     PendingLoads.push_back(Res.second);
6447     return true;
6448   }
6449 
6450   return false;
6451 }
6452 
6453 /// See if we can lower a strnlen call into an optimized form.  If so, return
6454 /// true and lower it, otherwise return false and it will be lowered like a
6455 /// normal call.
6456 /// The caller already checked that \p I calls the appropriate LibFunc with a
6457 /// correct prototype.
6458 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
6459   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6460 
6461   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6462   std::pair<SDValue, SDValue> Res =
6463     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
6464                                  getValue(Arg0), getValue(Arg1),
6465                                  MachinePointerInfo(Arg0));
6466   if (Res.first.getNode()) {
6467     processIntegerCallValue(I, Res.first, false);
6468     PendingLoads.push_back(Res.second);
6469     return true;
6470   }
6471 
6472   return false;
6473 }
6474 
6475 /// See if we can lower a unary floating-point operation into an SDNode with
6476 /// the specified Opcode.  If so, return true and lower it, otherwise return
6477 /// false and it will be lowered like a normal call.
6478 /// The caller already checked that \p I calls the appropriate LibFunc with a
6479 /// correct prototype.
6480 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
6481                                               unsigned Opcode) {
6482   // We already checked this call's prototype; verify it doesn't modify errno.
6483   if (!I.onlyReadsMemory())
6484     return false;
6485 
6486   SDValue Tmp = getValue(I.getArgOperand(0));
6487   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
6488   return true;
6489 }
6490 
6491 /// See if we can lower a binary floating-point operation into an SDNode with
6492 /// the specified Opcode. If so, return true and lower it. Otherwise return
6493 /// false, and it will be lowered like a normal call.
6494 /// The caller already checked that \p I calls the appropriate LibFunc with a
6495 /// correct prototype.
6496 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
6497                                                unsigned Opcode) {
6498   // We already checked this call's prototype; verify it doesn't modify errno.
6499   if (!I.onlyReadsMemory())
6500     return false;
6501 
6502   SDValue Tmp0 = getValue(I.getArgOperand(0));
6503   SDValue Tmp1 = getValue(I.getArgOperand(1));
6504   EVT VT = Tmp0.getValueType();
6505   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
6506   return true;
6507 }
6508 
6509 void SelectionDAGBuilder::visitCall(const CallInst &I) {
6510   // Handle inline assembly differently.
6511   if (isa<InlineAsm>(I.getCalledValue())) {
6512     visitInlineAsm(&I);
6513     return;
6514   }
6515 
6516   MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6517   computeUsesVAFloatArgument(I, MMI);
6518 
6519   const char *RenameFn = nullptr;
6520   if (Function *F = I.getCalledFunction()) {
6521     if (F->isDeclaration()) {
6522       if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
6523         if (unsigned IID = II->getIntrinsicID(F)) {
6524           RenameFn = visitIntrinsicCall(I, IID);
6525           if (!RenameFn)
6526             return;
6527         }
6528       }
6529       if (Intrinsic::ID IID = F->getIntrinsicID()) {
6530         RenameFn = visitIntrinsicCall(I, IID);
6531         if (!RenameFn)
6532           return;
6533       }
6534     }
6535 
6536     // Check for well-known libc/libm calls.  If the function is internal, it
6537     // can't be a library call.  Don't do the check if marked as nobuiltin for
6538     // some reason.
6539     LibFunc Func;
6540     if (!I.isNoBuiltin() && !F->hasLocalLinkage() && F->hasName() &&
6541         LibInfo->getLibFunc(*F, Func) &&
6542         LibInfo->hasOptimizedCodeGen(Func)) {
6543       switch (Func) {
6544       default: break;
6545       case LibFunc_copysign:
6546       case LibFunc_copysignf:
6547       case LibFunc_copysignl:
6548         // We already checked this call's prototype; verify it doesn't modify
6549         // errno.
6550         if (I.onlyReadsMemory()) {
6551           SDValue LHS = getValue(I.getArgOperand(0));
6552           SDValue RHS = getValue(I.getArgOperand(1));
6553           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
6554                                    LHS.getValueType(), LHS, RHS));
6555           return;
6556         }
6557         break;
6558       case LibFunc_fabs:
6559       case LibFunc_fabsf:
6560       case LibFunc_fabsl:
6561         if (visitUnaryFloatCall(I, ISD::FABS))
6562           return;
6563         break;
6564       case LibFunc_fmin:
6565       case LibFunc_fminf:
6566       case LibFunc_fminl:
6567         if (visitBinaryFloatCall(I, ISD::FMINNUM))
6568           return;
6569         break;
6570       case LibFunc_fmax:
6571       case LibFunc_fmaxf:
6572       case LibFunc_fmaxl:
6573         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
6574           return;
6575         break;
6576       case LibFunc_sin:
6577       case LibFunc_sinf:
6578       case LibFunc_sinl:
6579         if (visitUnaryFloatCall(I, ISD::FSIN))
6580           return;
6581         break;
6582       case LibFunc_cos:
6583       case LibFunc_cosf:
6584       case LibFunc_cosl:
6585         if (visitUnaryFloatCall(I, ISD::FCOS))
6586           return;
6587         break;
6588       case LibFunc_sqrt:
6589       case LibFunc_sqrtf:
6590       case LibFunc_sqrtl:
6591       case LibFunc_sqrt_finite:
6592       case LibFunc_sqrtf_finite:
6593       case LibFunc_sqrtl_finite:
6594         if (visitUnaryFloatCall(I, ISD::FSQRT))
6595           return;
6596         break;
6597       case LibFunc_floor:
6598       case LibFunc_floorf:
6599       case LibFunc_floorl:
6600         if (visitUnaryFloatCall(I, ISD::FFLOOR))
6601           return;
6602         break;
6603       case LibFunc_nearbyint:
6604       case LibFunc_nearbyintf:
6605       case LibFunc_nearbyintl:
6606         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
6607           return;
6608         break;
6609       case LibFunc_ceil:
6610       case LibFunc_ceilf:
6611       case LibFunc_ceill:
6612         if (visitUnaryFloatCall(I, ISD::FCEIL))
6613           return;
6614         break;
6615       case LibFunc_rint:
6616       case LibFunc_rintf:
6617       case LibFunc_rintl:
6618         if (visitUnaryFloatCall(I, ISD::FRINT))
6619           return;
6620         break;
6621       case LibFunc_round:
6622       case LibFunc_roundf:
6623       case LibFunc_roundl:
6624         if (visitUnaryFloatCall(I, ISD::FROUND))
6625           return;
6626         break;
6627       case LibFunc_trunc:
6628       case LibFunc_truncf:
6629       case LibFunc_truncl:
6630         if (visitUnaryFloatCall(I, ISD::FTRUNC))
6631           return;
6632         break;
6633       case LibFunc_log2:
6634       case LibFunc_log2f:
6635       case LibFunc_log2l:
6636         if (visitUnaryFloatCall(I, ISD::FLOG2))
6637           return;
6638         break;
6639       case LibFunc_exp2:
6640       case LibFunc_exp2f:
6641       case LibFunc_exp2l:
6642         if (visitUnaryFloatCall(I, ISD::FEXP2))
6643           return;
6644         break;
6645       case LibFunc_memcmp:
6646         if (visitMemCmpCall(I))
6647           return;
6648         break;
6649       case LibFunc_mempcpy:
6650         if (visitMemPCpyCall(I))
6651           return;
6652         break;
6653       case LibFunc_memchr:
6654         if (visitMemChrCall(I))
6655           return;
6656         break;
6657       case LibFunc_strcpy:
6658         if (visitStrCpyCall(I, false))
6659           return;
6660         break;
6661       case LibFunc_stpcpy:
6662         if (visitStrCpyCall(I, true))
6663           return;
6664         break;
6665       case LibFunc_strcmp:
6666         if (visitStrCmpCall(I))
6667           return;
6668         break;
6669       case LibFunc_strlen:
6670         if (visitStrLenCall(I))
6671           return;
6672         break;
6673       case LibFunc_strnlen:
6674         if (visitStrNLenCall(I))
6675           return;
6676         break;
6677       }
6678     }
6679   }
6680 
6681   SDValue Callee;
6682   if (!RenameFn)
6683     Callee = getValue(I.getCalledValue());
6684   else
6685     Callee = DAG.getExternalSymbol(
6686         RenameFn,
6687         DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6688 
6689   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
6690   // have to do anything here to lower funclet bundles.
6691   assert(!I.hasOperandBundlesOtherThan(
6692              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
6693          "Cannot lower calls with arbitrary operand bundles!");
6694 
6695   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
6696     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
6697   else
6698     // Check if we can potentially perform a tail call. More detailed checking
6699     // is be done within LowerCallTo, after more information about the call is
6700     // known.
6701     LowerCallTo(&I, Callee, I.isTailCall());
6702 }
6703 
6704 namespace {
6705 
6706 /// AsmOperandInfo - This contains information for each constraint that we are
6707 /// lowering.
6708 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
6709 public:
6710   /// CallOperand - If this is the result output operand or a clobber
6711   /// this is null, otherwise it is the incoming operand to the CallInst.
6712   /// This gets modified as the asm is processed.
6713   SDValue CallOperand;
6714 
6715   /// AssignedRegs - If this is a register or register class operand, this
6716   /// contains the set of register corresponding to the operand.
6717   RegsForValue AssignedRegs;
6718 
6719   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
6720     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr,0) {
6721   }
6722 
6723   /// Whether or not this operand accesses memory
6724   bool hasMemory(const TargetLowering &TLI) const {
6725     // Indirect operand accesses access memory.
6726     if (isIndirect)
6727       return true;
6728 
6729     for (const auto &Code : Codes)
6730       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
6731         return true;
6732 
6733     return false;
6734   }
6735 
6736   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
6737   /// corresponds to.  If there is no Value* for this operand, it returns
6738   /// MVT::Other.
6739   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
6740                            const DataLayout &DL) const {
6741     if (!CallOperandVal) return MVT::Other;
6742 
6743     if (isa<BasicBlock>(CallOperandVal))
6744       return TLI.getPointerTy(DL);
6745 
6746     llvm::Type *OpTy = CallOperandVal->getType();
6747 
6748     // FIXME: code duplicated from TargetLowering::ParseConstraints().
6749     // If this is an indirect operand, the operand is a pointer to the
6750     // accessed type.
6751     if (isIndirect) {
6752       llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
6753       if (!PtrTy)
6754         report_fatal_error("Indirect operand for inline asm not a pointer!");
6755       OpTy = PtrTy->getElementType();
6756     }
6757 
6758     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
6759     if (StructType *STy = dyn_cast<StructType>(OpTy))
6760       if (STy->getNumElements() == 1)
6761         OpTy = STy->getElementType(0);
6762 
6763     // If OpTy is not a single value, it may be a struct/union that we
6764     // can tile with integers.
6765     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
6766       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
6767       switch (BitSize) {
6768       default: break;
6769       case 1:
6770       case 8:
6771       case 16:
6772       case 32:
6773       case 64:
6774       case 128:
6775         OpTy = IntegerType::get(Context, BitSize);
6776         break;
6777       }
6778     }
6779 
6780     return TLI.getValueType(DL, OpTy, true);
6781   }
6782 };
6783 
6784 typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
6785 
6786 } // end anonymous namespace
6787 
6788 /// Make sure that the output operand \p OpInfo and its corresponding input
6789 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
6790 /// out).
6791 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
6792                                SDISelAsmOperandInfo &MatchingOpInfo,
6793                                SelectionDAG &DAG) {
6794   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
6795     return;
6796 
6797   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
6798   const auto &TLI = DAG.getTargetLoweringInfo();
6799 
6800   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
6801       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
6802                                        OpInfo.ConstraintVT);
6803   std::pair<unsigned, const TargetRegisterClass *> InputRC =
6804       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
6805                                        MatchingOpInfo.ConstraintVT);
6806   if ((OpInfo.ConstraintVT.isInteger() !=
6807        MatchingOpInfo.ConstraintVT.isInteger()) ||
6808       (MatchRC.second != InputRC.second)) {
6809     // FIXME: error out in a more elegant fashion
6810     report_fatal_error("Unsupported asm: input constraint"
6811                        " with a matching output constraint of"
6812                        " incompatible type!");
6813   }
6814   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
6815 }
6816 
6817 /// Get a direct memory input to behave well as an indirect operand.
6818 /// This may introduce stores, hence the need for a \p Chain.
6819 /// \return The (possibly updated) chain.
6820 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
6821                                         SDISelAsmOperandInfo &OpInfo,
6822                                         SelectionDAG &DAG) {
6823   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6824 
6825   // If we don't have an indirect input, put it in the constpool if we can,
6826   // otherwise spill it to a stack slot.
6827   // TODO: This isn't quite right. We need to handle these according to
6828   // the addressing mode that the constraint wants. Also, this may take
6829   // an additional register for the computation and we don't want that
6830   // either.
6831 
6832   // If the operand is a float, integer, or vector constant, spill to a
6833   // constant pool entry to get its address.
6834   const Value *OpVal = OpInfo.CallOperandVal;
6835   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
6836       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
6837     OpInfo.CallOperand = DAG.getConstantPool(
6838         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
6839     return Chain;
6840   }
6841 
6842   // Otherwise, create a stack slot and emit a store to it before the asm.
6843   Type *Ty = OpVal->getType();
6844   auto &DL = DAG.getDataLayout();
6845   uint64_t TySize = DL.getTypeAllocSize(Ty);
6846   unsigned Align = DL.getPrefTypeAlignment(Ty);
6847   MachineFunction &MF = DAG.getMachineFunction();
6848   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
6849   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
6850   Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot,
6851                        MachinePointerInfo::getFixedStack(MF, SSFI));
6852   OpInfo.CallOperand = StackSlot;
6853 
6854   return Chain;
6855 }
6856 
6857 /// GetRegistersForValue - Assign registers (virtual or physical) for the
6858 /// specified operand.  We prefer to assign virtual registers, to allow the
6859 /// register allocator to handle the assignment process.  However, if the asm
6860 /// uses features that we can't model on machineinstrs, we have SDISel do the
6861 /// allocation.  This produces generally horrible, but correct, code.
6862 ///
6863 ///   OpInfo describes the operand.
6864 ///
6865 static void GetRegistersForValue(SelectionDAG &DAG, const TargetLowering &TLI,
6866                                  const SDLoc &DL,
6867                                  SDISelAsmOperandInfo &OpInfo) {
6868   LLVMContext &Context = *DAG.getContext();
6869 
6870   MachineFunction &MF = DAG.getMachineFunction();
6871   SmallVector<unsigned, 4> Regs;
6872   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
6873 
6874   // If this is a constraint for a single physreg, or a constraint for a
6875   // register class, find it.
6876   std::pair<unsigned, const TargetRegisterClass *> PhysReg =
6877       TLI.getRegForInlineAsmConstraint(&TRI, OpInfo.ConstraintCode,
6878                                        OpInfo.ConstraintVT);
6879 
6880   unsigned NumRegs = 1;
6881   if (OpInfo.ConstraintVT != MVT::Other) {
6882     // If this is a FP input in an integer register (or visa versa) insert a bit
6883     // cast of the input value.  More generally, handle any case where the input
6884     // value disagrees with the register class we plan to stick this in.
6885     if (OpInfo.Type == InlineAsm::isInput && PhysReg.second &&
6886         !TRI.isTypeLegalForClass(*PhysReg.second, OpInfo.ConstraintVT)) {
6887       // Try to convert to the first EVT that the reg class contains.  If the
6888       // types are identical size, use a bitcast to convert (e.g. two differing
6889       // vector types).
6890       MVT RegVT = *TRI.legalclasstypes_begin(*PhysReg.second);
6891       if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) {
6892         OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
6893                                          RegVT, OpInfo.CallOperand);
6894         OpInfo.ConstraintVT = RegVT;
6895       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
6896         // If the input is a FP value and we want it in FP registers, do a
6897         // bitcast to the corresponding integer type.  This turns an f64 value
6898         // into i64, which can be passed with two i32 values on a 32-bit
6899         // machine.
6900         RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
6901         OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
6902                                          RegVT, OpInfo.CallOperand);
6903         OpInfo.ConstraintVT = RegVT;
6904       }
6905     }
6906 
6907     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
6908   }
6909 
6910   MVT RegVT;
6911   EVT ValueVT = OpInfo.ConstraintVT;
6912 
6913   // If this is a constraint for a specific physical register, like {r17},
6914   // assign it now.
6915   if (unsigned AssignedReg = PhysReg.first) {
6916     const TargetRegisterClass *RC = PhysReg.second;
6917     if (OpInfo.ConstraintVT == MVT::Other)
6918       ValueVT = *TRI.legalclasstypes_begin(*RC);
6919 
6920     // Get the actual register value type.  This is important, because the user
6921     // may have asked for (e.g.) the AX register in i32 type.  We need to
6922     // remember that AX is actually i16 to get the right extension.
6923     RegVT = *TRI.legalclasstypes_begin(*RC);
6924 
6925     // This is a explicit reference to a physical register.
6926     Regs.push_back(AssignedReg);
6927 
6928     // If this is an expanded reference, add the rest of the regs to Regs.
6929     if (NumRegs != 1) {
6930       TargetRegisterClass::iterator I = RC->begin();
6931       for (; *I != AssignedReg; ++I)
6932         assert(I != RC->end() && "Didn't find reg!");
6933 
6934       // Already added the first reg.
6935       --NumRegs; ++I;
6936       for (; NumRegs; --NumRegs, ++I) {
6937         assert(I != RC->end() && "Ran out of registers to allocate!");
6938         Regs.push_back(*I);
6939       }
6940     }
6941 
6942     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
6943     return;
6944   }
6945 
6946   // Otherwise, if this was a reference to an LLVM register class, create vregs
6947   // for this reference.
6948   if (const TargetRegisterClass *RC = PhysReg.second) {
6949     RegVT = *TRI.legalclasstypes_begin(*RC);
6950     if (OpInfo.ConstraintVT == MVT::Other)
6951       ValueVT = RegVT;
6952 
6953     // Create the appropriate number of virtual registers.
6954     MachineRegisterInfo &RegInfo = MF.getRegInfo();
6955     for (; NumRegs; --NumRegs)
6956       Regs.push_back(RegInfo.createVirtualRegister(RC));
6957 
6958     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
6959     return;
6960   }
6961 
6962   // Otherwise, we couldn't allocate enough registers for this.
6963 }
6964 
6965 static unsigned
6966 findMatchingInlineAsmOperand(unsigned OperandNo,
6967                              const std::vector<SDValue> &AsmNodeOperands) {
6968   // Scan until we find the definition we already emitted of this operand.
6969   unsigned CurOp = InlineAsm::Op_FirstOperand;
6970   for (; OperandNo; --OperandNo) {
6971     // Advance to the next operand.
6972     unsigned OpFlag =
6973         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
6974     assert((InlineAsm::isRegDefKind(OpFlag) ||
6975             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
6976             InlineAsm::isMemKind(OpFlag)) &&
6977            "Skipped past definitions?");
6978     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
6979   }
6980   return CurOp;
6981 }
6982 
6983 /// Fill \p Regs with \p NumRegs new virtual registers of type \p RegVT
6984 /// \return true if it has succeeded, false otherwise
6985 static bool createVirtualRegs(SmallVector<unsigned, 4> &Regs, unsigned NumRegs,
6986                               MVT RegVT, SelectionDAG &DAG) {
6987   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6988   MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
6989   for (unsigned i = 0, e = NumRegs; i != e; ++i) {
6990     if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT))
6991       Regs.push_back(RegInfo.createVirtualRegister(RC));
6992     else
6993       return false;
6994   }
6995   return true;
6996 }
6997 
6998 class ExtraFlags {
6999   unsigned Flags = 0;
7000 
7001 public:
7002   explicit ExtraFlags(ImmutableCallSite CS) {
7003     const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7004     if (IA->hasSideEffects())
7005       Flags |= InlineAsm::Extra_HasSideEffects;
7006     if (IA->isAlignStack())
7007       Flags |= InlineAsm::Extra_IsAlignStack;
7008     if (CS.isConvergent())
7009       Flags |= InlineAsm::Extra_IsConvergent;
7010     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
7011   }
7012 
7013   void update(const llvm::TargetLowering::AsmOperandInfo &OpInfo) {
7014     // Ideally, we would only check against memory constraints.  However, the
7015     // meaning of an Other constraint can be target-specific and we can't easily
7016     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
7017     // for Other constraints as well.
7018     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
7019         OpInfo.ConstraintType == TargetLowering::C_Other) {
7020       if (OpInfo.Type == InlineAsm::isInput)
7021         Flags |= InlineAsm::Extra_MayLoad;
7022       else if (OpInfo.Type == InlineAsm::isOutput)
7023         Flags |= InlineAsm::Extra_MayStore;
7024       else if (OpInfo.Type == InlineAsm::isClobber)
7025         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
7026     }
7027   }
7028 
7029   unsigned get() const { return Flags; }
7030 };
7031 
7032 /// visitInlineAsm - Handle a call to an InlineAsm object.
7033 ///
7034 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
7035   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7036 
7037   /// ConstraintOperands - Information about all of the constraints.
7038   SDISelAsmOperandInfoVector ConstraintOperands;
7039 
7040   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7041   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
7042       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
7043 
7044   bool hasMemory = false;
7045 
7046   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
7047   ExtraFlags ExtraInfo(CS);
7048 
7049   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
7050   unsigned ResNo = 0;   // ResNo - The result number of the next output.
7051   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
7052     ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
7053     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
7054 
7055     MVT OpVT = MVT::Other;
7056 
7057     // Compute the value type for each operand.
7058     if (OpInfo.Type == InlineAsm::isInput ||
7059         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
7060       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
7061 
7062       // Process the call argument. BasicBlocks are labels, currently appearing
7063       // only in asm's.
7064       if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
7065         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
7066       } else {
7067         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
7068       }
7069 
7070       OpVT =
7071           OpInfo
7072               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
7073               .getSimpleVT();
7074     }
7075 
7076     if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
7077       // The return value of the call is this value.  As such, there is no
7078       // corresponding argument.
7079       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
7080       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
7081         OpVT = TLI.getSimpleValueType(DAG.getDataLayout(),
7082                                       STy->getElementType(ResNo));
7083       } else {
7084         assert(ResNo == 0 && "Asm only has one result!");
7085         OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
7086       }
7087       ++ResNo;
7088     }
7089 
7090     OpInfo.ConstraintVT = OpVT;
7091 
7092     if (!hasMemory)
7093       hasMemory = OpInfo.hasMemory(TLI);
7094 
7095     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
7096     // FIXME: Could we compute this on OpInfo rather than TargetConstraints[i]?
7097     auto TargetConstraint = TargetConstraints[i];
7098 
7099     // Compute the constraint code and ConstraintType to use.
7100     TLI.ComputeConstraintToUse(TargetConstraint, SDValue());
7101 
7102     ExtraInfo.update(TargetConstraint);
7103   }
7104 
7105   SDValue Chain, Flag;
7106 
7107   // We won't need to flush pending loads if this asm doesn't touch
7108   // memory and is nonvolatile.
7109   if (hasMemory || IA->hasSideEffects())
7110     Chain = getRoot();
7111   else
7112     Chain = DAG.getRoot();
7113 
7114   // Second pass over the constraints: compute which constraint option to use
7115   // and assign registers to constraints that want a specific physreg.
7116   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
7117     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
7118 
7119     // If this is an output operand with a matching input operand, look up the
7120     // matching input. If their types mismatch, e.g. one is an integer, the
7121     // other is floating point, or their sizes are different, flag it as an
7122     // error.
7123     if (OpInfo.hasMatchingInput()) {
7124       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
7125       patchMatchingInput(OpInfo, Input, DAG);
7126     }
7127 
7128     // Compute the constraint code and ConstraintType to use.
7129     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
7130 
7131     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
7132         OpInfo.Type == InlineAsm::isClobber)
7133       continue;
7134 
7135     // If this is a memory input, and if the operand is not indirect, do what we
7136     // need to to provide an address for the memory input.
7137     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
7138         !OpInfo.isIndirect) {
7139       assert((OpInfo.isMultipleAlternative ||
7140               (OpInfo.Type == InlineAsm::isInput)) &&
7141              "Can only indirectify direct input operands!");
7142 
7143       // Memory operands really want the address of the value.
7144       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
7145 
7146       // There is no longer a Value* corresponding to this operand.
7147       OpInfo.CallOperandVal = nullptr;
7148 
7149       // It is now an indirect operand.
7150       OpInfo.isIndirect = true;
7151     }
7152 
7153     // If this constraint is for a specific register, allocate it before
7154     // anything else.
7155     if (OpInfo.ConstraintType == TargetLowering::C_Register)
7156       GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
7157   }
7158 
7159   // Third pass - Loop over all of the operands, assigning virtual or physregs
7160   // to register class operands.
7161   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
7162     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
7163 
7164     // C_Register operands have already been allocated, Other/Memory don't need
7165     // to be.
7166     if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
7167       GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
7168   }
7169 
7170   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
7171   std::vector<SDValue> AsmNodeOperands;
7172   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
7173   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
7174       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
7175 
7176   // If we have a !srcloc metadata node associated with it, we want to attach
7177   // this to the ultimately generated inline asm machineinstr.  To do this, we
7178   // pass in the third operand as this (potentially null) inline asm MDNode.
7179   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
7180   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
7181 
7182   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
7183   // bits as operand 3.
7184   AsmNodeOperands.push_back(DAG.getTargetConstant(
7185       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7186 
7187   // Loop over all of the inputs, copying the operand values into the
7188   // appropriate registers and processing the output regs.
7189   RegsForValue RetValRegs;
7190 
7191   // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
7192   std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
7193 
7194   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
7195     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
7196 
7197     switch (OpInfo.Type) {
7198     case InlineAsm::isOutput: {
7199       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
7200           OpInfo.ConstraintType != TargetLowering::C_Register) {
7201         // Memory output, or 'other' output (e.g. 'X' constraint).
7202         assert(OpInfo.isIndirect && "Memory output must be indirect operand");
7203 
7204         unsigned ConstraintID =
7205             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
7206         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
7207                "Failed to convert memory constraint code to constraint id.");
7208 
7209         // Add information to the INLINEASM node to know about this output.
7210         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
7211         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
7212         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
7213                                                         MVT::i32));
7214         AsmNodeOperands.push_back(OpInfo.CallOperand);
7215         break;
7216       }
7217 
7218       // Otherwise, this is a register or register class output.
7219 
7220       // Copy the output from the appropriate register.  Find a register that
7221       // we can use.
7222       if (OpInfo.AssignedRegs.Regs.empty()) {
7223         emitInlineAsmError(
7224             CS, "couldn't allocate output register for constraint '" +
7225                     Twine(OpInfo.ConstraintCode) + "'");
7226         return;
7227       }
7228 
7229       // If this is an indirect operand, store through the pointer after the
7230       // asm.
7231       if (OpInfo.isIndirect) {
7232         IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
7233                                                       OpInfo.CallOperandVal));
7234       } else {
7235         // This is the result value of the call.
7236         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
7237         // Concatenate this output onto the outputs list.
7238         RetValRegs.append(OpInfo.AssignedRegs);
7239       }
7240 
7241       // Add information to the INLINEASM node to know that this register is
7242       // set.
7243       OpInfo.AssignedRegs
7244           .AddInlineAsmOperands(OpInfo.isEarlyClobber
7245                                     ? InlineAsm::Kind_RegDefEarlyClobber
7246                                     : InlineAsm::Kind_RegDef,
7247                                 false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
7248       break;
7249     }
7250     case InlineAsm::isInput: {
7251       SDValue InOperandVal = OpInfo.CallOperand;
7252 
7253       if (OpInfo.isMatchingInputConstraint()) {
7254         // If this is required to match an output register we have already set,
7255         // just use its register.
7256         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
7257                                                   AsmNodeOperands);
7258         unsigned OpFlag =
7259           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7260         if (InlineAsm::isRegDefKind(OpFlag) ||
7261             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
7262           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
7263           if (OpInfo.isIndirect) {
7264             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
7265             emitInlineAsmError(CS, "inline asm not supported yet:"
7266                                    " don't know how to handle tied "
7267                                    "indirect register inputs");
7268             return;
7269           }
7270 
7271           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
7272           SmallVector<unsigned, 4> Regs;
7273 
7274           if (!createVirtualRegs(Regs,
7275                                  InlineAsm::getNumOperandRegisters(OpFlag),
7276                                  RegVT, DAG)) {
7277             emitInlineAsmError(CS, "inline asm error: This value type register "
7278                                    "class is not natively supported!");
7279             return;
7280           }
7281 
7282           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
7283 
7284           SDLoc dl = getCurSDLoc();
7285           // Use the produced MatchedRegs object to
7286           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
7287                                     CS.getInstruction());
7288           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
7289                                            true, OpInfo.getMatchedOperand(), dl,
7290                                            DAG, AsmNodeOperands);
7291           break;
7292         }
7293 
7294         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
7295         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
7296                "Unexpected number of operands");
7297         // Add information to the INLINEASM node to know about this input.
7298         // See InlineAsm.h isUseOperandTiedToDef.
7299         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
7300         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
7301                                                     OpInfo.getMatchedOperand());
7302         AsmNodeOperands.push_back(DAG.getTargetConstant(
7303             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7304         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
7305         break;
7306       }
7307 
7308       // Treat indirect 'X' constraint as memory.
7309       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
7310           OpInfo.isIndirect)
7311         OpInfo.ConstraintType = TargetLowering::C_Memory;
7312 
7313       if (OpInfo.ConstraintType == TargetLowering::C_Other) {
7314         std::vector<SDValue> Ops;
7315         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
7316                                           Ops, DAG);
7317         if (Ops.empty()) {
7318           emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
7319                                      Twine(OpInfo.ConstraintCode) + "'");
7320           return;
7321         }
7322 
7323         // Add information to the INLINEASM node to know about this input.
7324         unsigned ResOpType =
7325           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
7326         AsmNodeOperands.push_back(DAG.getTargetConstant(
7327             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7328         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
7329         break;
7330       }
7331 
7332       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
7333         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
7334         assert(InOperandVal.getValueType() ==
7335                    TLI.getPointerTy(DAG.getDataLayout()) &&
7336                "Memory operands expect pointer values");
7337 
7338         unsigned ConstraintID =
7339             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
7340         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
7341                "Failed to convert memory constraint code to constraint id.");
7342 
7343         // Add information to the INLINEASM node to know about this input.
7344         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
7345         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
7346         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
7347                                                         getCurSDLoc(),
7348                                                         MVT::i32));
7349         AsmNodeOperands.push_back(InOperandVal);
7350         break;
7351       }
7352 
7353       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
7354               OpInfo.ConstraintType == TargetLowering::C_Register) &&
7355              "Unknown constraint type!");
7356 
7357       // TODO: Support this.
7358       if (OpInfo.isIndirect) {
7359         emitInlineAsmError(
7360             CS, "Don't know how to handle indirect register inputs yet "
7361                 "for constraint '" +
7362                     Twine(OpInfo.ConstraintCode) + "'");
7363         return;
7364       }
7365 
7366       // Copy the input into the appropriate registers.
7367       if (OpInfo.AssignedRegs.Regs.empty()) {
7368         emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
7369                                    Twine(OpInfo.ConstraintCode) + "'");
7370         return;
7371       }
7372 
7373       SDLoc dl = getCurSDLoc();
7374 
7375       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
7376                                         Chain, &Flag, CS.getInstruction());
7377 
7378       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
7379                                                dl, DAG, AsmNodeOperands);
7380       break;
7381     }
7382     case InlineAsm::isClobber: {
7383       // Add the clobbered value to the operand list, so that the register
7384       // allocator is aware that the physreg got clobbered.
7385       if (!OpInfo.AssignedRegs.Regs.empty())
7386         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
7387                                                  false, 0, getCurSDLoc(), DAG,
7388                                                  AsmNodeOperands);
7389       break;
7390     }
7391     }
7392   }
7393 
7394   // Finish up input operands.  Set the input chain and add the flag last.
7395   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
7396   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
7397 
7398   Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
7399                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
7400   Flag = Chain.getValue(1);
7401 
7402   // If this asm returns a register value, copy the result from that register
7403   // and set it as the value of the call.
7404   if (!RetValRegs.Regs.empty()) {
7405     SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
7406                                              Chain, &Flag, CS.getInstruction());
7407 
7408     // FIXME: Why don't we do this for inline asms with MRVs?
7409     if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
7410       EVT ResultType = TLI.getValueType(DAG.getDataLayout(), CS.getType());
7411 
7412       // If any of the results of the inline asm is a vector, it may have the
7413       // wrong width/num elts.  This can happen for register classes that can
7414       // contain multiple different value types.  The preg or vreg allocated may
7415       // not have the same VT as was expected.  Convert it to the right type
7416       // with bit_convert.
7417       if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
7418         Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(),
7419                           ResultType, Val);
7420 
7421       } else if (ResultType != Val.getValueType() &&
7422                  ResultType.isInteger() && Val.getValueType().isInteger()) {
7423         // If a result value was tied to an input value, the computed result may
7424         // have a wider width than the expected result.  Extract the relevant
7425         // portion.
7426         Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val);
7427       }
7428 
7429       assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
7430     }
7431 
7432     setValue(CS.getInstruction(), Val);
7433     // Don't need to use this as a chain in this case.
7434     if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
7435       return;
7436   }
7437 
7438   std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
7439 
7440   // Process indirect outputs, first output all of the flagged copies out of
7441   // physregs.
7442   for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
7443     RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
7444     const Value *Ptr = IndirectStoresToEmit[i].second;
7445     SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
7446                                              Chain, &Flag, IA);
7447     StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
7448   }
7449 
7450   // Emit the non-flagged stores from the physregs.
7451   SmallVector<SDValue, 8> OutChains;
7452   for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
7453     SDValue Val = DAG.getStore(Chain, getCurSDLoc(), StoresToEmit[i].first,
7454                                getValue(StoresToEmit[i].second),
7455                                MachinePointerInfo(StoresToEmit[i].second));
7456     OutChains.push_back(Val);
7457   }
7458 
7459   if (!OutChains.empty())
7460     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
7461 
7462   DAG.setRoot(Chain);
7463 }
7464 
7465 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
7466                                              const Twine &Message) {
7467   LLVMContext &Ctx = *DAG.getContext();
7468   Ctx.emitError(CS.getInstruction(), Message);
7469 
7470   // Make sure we leave the DAG in a valid state
7471   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7472   auto VT = TLI.getValueType(DAG.getDataLayout(), CS.getType());
7473   setValue(CS.getInstruction(), DAG.getUNDEF(VT));
7474 }
7475 
7476 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
7477   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
7478                           MVT::Other, getRoot(),
7479                           getValue(I.getArgOperand(0)),
7480                           DAG.getSrcValue(I.getArgOperand(0))));
7481 }
7482 
7483 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
7484   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7485   const DataLayout &DL = DAG.getDataLayout();
7486   SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7487                            getCurSDLoc(), getRoot(), getValue(I.getOperand(0)),
7488                            DAG.getSrcValue(I.getOperand(0)),
7489                            DL.getABITypeAlignment(I.getType()));
7490   setValue(&I, V);
7491   DAG.setRoot(V.getValue(1));
7492 }
7493 
7494 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
7495   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
7496                           MVT::Other, getRoot(),
7497                           getValue(I.getArgOperand(0)),
7498                           DAG.getSrcValue(I.getArgOperand(0))));
7499 }
7500 
7501 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
7502   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
7503                           MVT::Other, getRoot(),
7504                           getValue(I.getArgOperand(0)),
7505                           getValue(I.getArgOperand(1)),
7506                           DAG.getSrcValue(I.getArgOperand(0)),
7507                           DAG.getSrcValue(I.getArgOperand(1))));
7508 }
7509 
7510 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
7511                                                     const Instruction &I,
7512                                                     SDValue Op) {
7513   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
7514   if (!Range)
7515     return Op;
7516 
7517   ConstantRange CR = getConstantRangeFromMetadata(*Range);
7518   if (CR.isFullSet() || CR.isEmptySet() || CR.isWrappedSet())
7519     return Op;
7520 
7521   APInt Lo = CR.getUnsignedMin();
7522   if (!Lo.isMinValue())
7523     return Op;
7524 
7525   APInt Hi = CR.getUnsignedMax();
7526   unsigned Bits = Hi.getActiveBits();
7527 
7528   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
7529 
7530   SDLoc SL = getCurSDLoc();
7531 
7532   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
7533                              DAG.getValueType(SmallVT));
7534   unsigned NumVals = Op.getNode()->getNumValues();
7535   if (NumVals == 1)
7536     return ZExt;
7537 
7538   SmallVector<SDValue, 4> Ops;
7539 
7540   Ops.push_back(ZExt);
7541   for (unsigned I = 1; I != NumVals; ++I)
7542     Ops.push_back(Op.getValue(I));
7543 
7544   return DAG.getMergeValues(Ops, SL);
7545 }
7546 
7547 /// \brief Populate a CallLowerinInfo (into \p CLI) based on the properties of
7548 /// the call being lowered.
7549 ///
7550 /// This is a helper for lowering intrinsics that follow a target calling
7551 /// convention or require stack pointer adjustment. Only a subset of the
7552 /// intrinsic's operands need to participate in the calling convention.
7553 void SelectionDAGBuilder::populateCallLoweringInfo(
7554     TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS,
7555     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
7556     bool IsPatchPoint) {
7557   TargetLowering::ArgListTy Args;
7558   Args.reserve(NumArgs);
7559 
7560   // Populate the argument list.
7561   // Attributes for args start at offset 1, after the return attribute.
7562   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
7563        ArgI != ArgE; ++ArgI) {
7564     const Value *V = CS->getOperand(ArgI);
7565 
7566     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
7567 
7568     TargetLowering::ArgListEntry Entry;
7569     Entry.Node = getValue(V);
7570     Entry.Ty = V->getType();
7571     Entry.setAttributes(&CS, ArgIdx);
7572     Args.push_back(Entry);
7573   }
7574 
7575   CLI.setDebugLoc(getCurSDLoc())
7576       .setChain(getRoot())
7577       .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args))
7578       .setDiscardResult(CS->use_empty())
7579       .setIsPatchPoint(IsPatchPoint);
7580 }
7581 
7582 /// \brief Add a stack map intrinsic call's live variable operands to a stackmap
7583 /// or patchpoint target node's operand list.
7584 ///
7585 /// Constants are converted to TargetConstants purely as an optimization to
7586 /// avoid constant materialization and register allocation.
7587 ///
7588 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
7589 /// generate addess computation nodes, and so ExpandISelPseudo can convert the
7590 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
7591 /// address materialization and register allocation, but may also be required
7592 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
7593 /// alloca in the entry block, then the runtime may assume that the alloca's
7594 /// StackMap location can be read immediately after compilation and that the
7595 /// location is valid at any point during execution (this is similar to the
7596 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
7597 /// only available in a register, then the runtime would need to trap when
7598 /// execution reaches the StackMap in order to read the alloca's location.
7599 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
7600                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
7601                                 SelectionDAGBuilder &Builder) {
7602   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
7603     SDValue OpVal = Builder.getValue(CS.getArgument(i));
7604     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
7605       Ops.push_back(
7606         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
7607       Ops.push_back(
7608         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
7609     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
7610       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
7611       Ops.push_back(Builder.DAG.getTargetFrameIndex(
7612           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
7613     } else
7614       Ops.push_back(OpVal);
7615   }
7616 }
7617 
7618 /// \brief Lower llvm.experimental.stackmap directly to its target opcode.
7619 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
7620   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
7621   //                                  [live variables...])
7622 
7623   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
7624 
7625   SDValue Chain, InFlag, Callee, NullPtr;
7626   SmallVector<SDValue, 32> Ops;
7627 
7628   SDLoc DL = getCurSDLoc();
7629   Callee = getValue(CI.getCalledValue());
7630   NullPtr = DAG.getIntPtrConstant(0, DL, true);
7631 
7632   // The stackmap intrinsic only records the live variables (the arguemnts
7633   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
7634   // intrinsic, this won't be lowered to a function call. This means we don't
7635   // have to worry about calling conventions and target specific lowering code.
7636   // Instead we perform the call lowering right here.
7637   //
7638   // chain, flag = CALLSEQ_START(chain, 0, 0)
7639   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
7640   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
7641   //
7642   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
7643   InFlag = Chain.getValue(1);
7644 
7645   // Add the <id> and <numBytes> constants.
7646   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
7647   Ops.push_back(DAG.getTargetConstant(
7648                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
7649   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
7650   Ops.push_back(DAG.getTargetConstant(
7651                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
7652                   MVT::i32));
7653 
7654   // Push live variables for the stack map.
7655   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
7656 
7657   // We are not pushing any register mask info here on the operands list,
7658   // because the stackmap doesn't clobber anything.
7659 
7660   // Push the chain and the glue flag.
7661   Ops.push_back(Chain);
7662   Ops.push_back(InFlag);
7663 
7664   // Create the STACKMAP node.
7665   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7666   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
7667   Chain = SDValue(SM, 0);
7668   InFlag = Chain.getValue(1);
7669 
7670   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
7671 
7672   // Stackmaps don't generate values, so nothing goes into the NodeMap.
7673 
7674   // Set the root to the target-lowered call chain.
7675   DAG.setRoot(Chain);
7676 
7677   // Inform the Frame Information that we have a stackmap in this function.
7678   FuncInfo.MF->getFrameInfo().setHasStackMap();
7679 }
7680 
7681 /// \brief Lower llvm.experimental.patchpoint directly to its target opcode.
7682 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
7683                                           const BasicBlock *EHPadBB) {
7684   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
7685   //                                                 i32 <numBytes>,
7686   //                                                 i8* <target>,
7687   //                                                 i32 <numArgs>,
7688   //                                                 [Args...],
7689   //                                                 [live variables...])
7690 
7691   CallingConv::ID CC = CS.getCallingConv();
7692   bool IsAnyRegCC = CC == CallingConv::AnyReg;
7693   bool HasDef = !CS->getType()->isVoidTy();
7694   SDLoc dl = getCurSDLoc();
7695   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
7696 
7697   // Handle immediate and symbolic callees.
7698   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
7699     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
7700                                    /*isTarget=*/true);
7701   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
7702     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
7703                                          SDLoc(SymbolicCallee),
7704                                          SymbolicCallee->getValueType(0));
7705 
7706   // Get the real number of arguments participating in the call <numArgs>
7707   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
7708   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
7709 
7710   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
7711   // Intrinsics include all meta-operands up to but not including CC.
7712   unsigned NumMetaOpers = PatchPointOpers::CCPos;
7713   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
7714          "Not enough arguments provided to the patchpoint intrinsic");
7715 
7716   // For AnyRegCC the arguments are lowered later on manually.
7717   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
7718   Type *ReturnTy =
7719     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
7720 
7721   TargetLowering::CallLoweringInfo CLI(DAG);
7722   populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy,
7723                            true);
7724   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7725 
7726   SDNode *CallEnd = Result.second.getNode();
7727   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
7728     CallEnd = CallEnd->getOperand(0).getNode();
7729 
7730   /// Get a call instruction from the call sequence chain.
7731   /// Tail calls are not allowed.
7732   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
7733          "Expected a callseq node.");
7734   SDNode *Call = CallEnd->getOperand(0).getNode();
7735   bool HasGlue = Call->getGluedNode();
7736 
7737   // Replace the target specific call node with the patchable intrinsic.
7738   SmallVector<SDValue, 8> Ops;
7739 
7740   // Add the <id> and <numBytes> constants.
7741   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
7742   Ops.push_back(DAG.getTargetConstant(
7743                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
7744   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
7745   Ops.push_back(DAG.getTargetConstant(
7746                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
7747                   MVT::i32));
7748 
7749   // Add the callee.
7750   Ops.push_back(Callee);
7751 
7752   // Adjust <numArgs> to account for any arguments that have been passed on the
7753   // stack instead.
7754   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
7755   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
7756   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
7757   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
7758 
7759   // Add the calling convention
7760   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
7761 
7762   // Add the arguments we omitted previously. The register allocator should
7763   // place these in any free register.
7764   if (IsAnyRegCC)
7765     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
7766       Ops.push_back(getValue(CS.getArgument(i)));
7767 
7768   // Push the arguments from the call instruction up to the register mask.
7769   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
7770   Ops.append(Call->op_begin() + 2, e);
7771 
7772   // Push live variables for the stack map.
7773   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
7774 
7775   // Push the register mask info.
7776   if (HasGlue)
7777     Ops.push_back(*(Call->op_end()-2));
7778   else
7779     Ops.push_back(*(Call->op_end()-1));
7780 
7781   // Push the chain (this is originally the first operand of the call, but
7782   // becomes now the last or second to last operand).
7783   Ops.push_back(*(Call->op_begin()));
7784 
7785   // Push the glue flag (last operand).
7786   if (HasGlue)
7787     Ops.push_back(*(Call->op_end()-1));
7788 
7789   SDVTList NodeTys;
7790   if (IsAnyRegCC && HasDef) {
7791     // Create the return types based on the intrinsic definition
7792     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7793     SmallVector<EVT, 3> ValueVTs;
7794     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
7795     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
7796 
7797     // There is always a chain and a glue type at the end
7798     ValueVTs.push_back(MVT::Other);
7799     ValueVTs.push_back(MVT::Glue);
7800     NodeTys = DAG.getVTList(ValueVTs);
7801   } else
7802     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7803 
7804   // Replace the target specific call node with a PATCHPOINT node.
7805   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
7806                                          dl, NodeTys, Ops);
7807 
7808   // Update the NodeMap.
7809   if (HasDef) {
7810     if (IsAnyRegCC)
7811       setValue(CS.getInstruction(), SDValue(MN, 0));
7812     else
7813       setValue(CS.getInstruction(), Result.first);
7814   }
7815 
7816   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
7817   // call sequence. Furthermore the location of the chain and glue can change
7818   // when the AnyReg calling convention is used and the intrinsic returns a
7819   // value.
7820   if (IsAnyRegCC && HasDef) {
7821     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
7822     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
7823     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
7824   } else
7825     DAG.ReplaceAllUsesWith(Call, MN);
7826   DAG.DeleteNode(Call);
7827 
7828   // Inform the Frame Information that we have a patchpoint in this function.
7829   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
7830 }
7831 
7832 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
7833                                             unsigned Intrinsic) {
7834   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7835   SDValue Op1 = getValue(I.getArgOperand(0));
7836   SDValue Op2;
7837   if (I.getNumArgOperands() > 1)
7838     Op2 = getValue(I.getArgOperand(1));
7839   SDLoc dl = getCurSDLoc();
7840   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7841   SDValue Res;
7842   FastMathFlags FMF;
7843   if (isa<FPMathOperator>(I))
7844     FMF = I.getFastMathFlags();
7845   SDNodeFlags SDFlags;
7846   SDFlags.setNoNaNs(FMF.noNaNs());
7847 
7848   switch (Intrinsic) {
7849   case Intrinsic::experimental_vector_reduce_fadd:
7850     if (FMF.unsafeAlgebra())
7851       Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2);
7852     else
7853       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
7854     break;
7855   case Intrinsic::experimental_vector_reduce_fmul:
7856     if (FMF.unsafeAlgebra())
7857       Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2);
7858     else
7859       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
7860     break;
7861   case Intrinsic::experimental_vector_reduce_add:
7862     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
7863     break;
7864   case Intrinsic::experimental_vector_reduce_mul:
7865     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
7866     break;
7867   case Intrinsic::experimental_vector_reduce_and:
7868     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
7869     break;
7870   case Intrinsic::experimental_vector_reduce_or:
7871     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
7872     break;
7873   case Intrinsic::experimental_vector_reduce_xor:
7874     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
7875     break;
7876   case Intrinsic::experimental_vector_reduce_smax:
7877     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
7878     break;
7879   case Intrinsic::experimental_vector_reduce_smin:
7880     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
7881     break;
7882   case Intrinsic::experimental_vector_reduce_umax:
7883     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
7884     break;
7885   case Intrinsic::experimental_vector_reduce_umin:
7886     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
7887     break;
7888   case Intrinsic::experimental_vector_reduce_fmax: {
7889     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
7890     break;
7891   }
7892   case Intrinsic::experimental_vector_reduce_fmin: {
7893     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
7894     break;
7895   }
7896   default:
7897     llvm_unreachable("Unhandled vector reduce intrinsic");
7898   }
7899   setValue(&I, Res);
7900 }
7901 
7902 /// Returns an AttributeList representing the attributes applied to the return
7903 /// value of the given call.
7904 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
7905   SmallVector<Attribute::AttrKind, 2> Attrs;
7906   if (CLI.RetSExt)
7907     Attrs.push_back(Attribute::SExt);
7908   if (CLI.RetZExt)
7909     Attrs.push_back(Attribute::ZExt);
7910   if (CLI.IsInReg)
7911     Attrs.push_back(Attribute::InReg);
7912 
7913   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
7914                             Attrs);
7915 }
7916 
7917 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
7918 /// implementation, which just calls LowerCall.
7919 /// FIXME: When all targets are
7920 /// migrated to using LowerCall, this hook should be integrated into SDISel.
7921 std::pair<SDValue, SDValue>
7922 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
7923   // Handle the incoming return values from the call.
7924   CLI.Ins.clear();
7925   Type *OrigRetTy = CLI.RetTy;
7926   SmallVector<EVT, 4> RetTys;
7927   SmallVector<uint64_t, 4> Offsets;
7928   auto &DL = CLI.DAG.getDataLayout();
7929   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
7930 
7931   if (CLI.IsPostTypeLegalization) {
7932     // If we are lowering a libcall after legalization, split the return type.
7933     SmallVector<EVT, 4> OldRetTys = std::move(RetTys);
7934     SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets);
7935     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
7936       EVT RetVT = OldRetTys[i];
7937       uint64_t Offset = OldOffsets[i];
7938       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
7939       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
7940       unsigned RegisterVTSize = RegisterVT.getSizeInBits();
7941       RetTys.append(NumRegs, RegisterVT);
7942       for (unsigned j = 0; j != NumRegs; ++j)
7943         Offsets.push_back(Offset + j * RegisterVTSize);
7944     }
7945   }
7946 
7947   SmallVector<ISD::OutputArg, 4> Outs;
7948   GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
7949 
7950   bool CanLowerReturn =
7951       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
7952                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
7953 
7954   SDValue DemoteStackSlot;
7955   int DemoteStackIdx = -100;
7956   if (!CanLowerReturn) {
7957     // FIXME: equivalent assert?
7958     // assert(!CS.hasInAllocaArgument() &&
7959     //        "sret demotion is incompatible with inalloca");
7960     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
7961     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
7962     MachineFunction &MF = CLI.DAG.getMachineFunction();
7963     DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7964     Type *StackSlotPtrType = PointerType::getUnqual(CLI.RetTy);
7965 
7966     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
7967     ArgListEntry Entry;
7968     Entry.Node = DemoteStackSlot;
7969     Entry.Ty = StackSlotPtrType;
7970     Entry.IsSExt = false;
7971     Entry.IsZExt = false;
7972     Entry.IsInReg = false;
7973     Entry.IsSRet = true;
7974     Entry.IsNest = false;
7975     Entry.IsByVal = false;
7976     Entry.IsReturned = false;
7977     Entry.IsSwiftSelf = false;
7978     Entry.IsSwiftError = false;
7979     Entry.Alignment = Align;
7980     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
7981     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
7982 
7983     // sret demotion isn't compatible with tail-calls, since the sret argument
7984     // points into the callers stack frame.
7985     CLI.IsTailCall = false;
7986   } else {
7987     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
7988       EVT VT = RetTys[I];
7989       MVT RegisterVT =
7990           getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT);
7991       unsigned NumRegs =
7992           getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT);
7993       for (unsigned i = 0; i != NumRegs; ++i) {
7994         ISD::InputArg MyFlags;
7995         MyFlags.VT = RegisterVT;
7996         MyFlags.ArgVT = VT;
7997         MyFlags.Used = CLI.IsReturnValueUsed;
7998         if (CLI.RetSExt)
7999           MyFlags.Flags.setSExt();
8000         if (CLI.RetZExt)
8001           MyFlags.Flags.setZExt();
8002         if (CLI.IsInReg)
8003           MyFlags.Flags.setInReg();
8004         CLI.Ins.push_back(MyFlags);
8005       }
8006     }
8007   }
8008 
8009   // We push in swifterror return as the last element of CLI.Ins.
8010   ArgListTy &Args = CLI.getArgs();
8011   if (supportSwiftError()) {
8012     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8013       if (Args[i].IsSwiftError) {
8014         ISD::InputArg MyFlags;
8015         MyFlags.VT = getPointerTy(DL);
8016         MyFlags.ArgVT = EVT(getPointerTy(DL));
8017         MyFlags.Flags.setSwiftError();
8018         CLI.Ins.push_back(MyFlags);
8019       }
8020     }
8021   }
8022 
8023   // Handle all of the outgoing arguments.
8024   CLI.Outs.clear();
8025   CLI.OutVals.clear();
8026   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8027     SmallVector<EVT, 4> ValueVTs;
8028     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
8029     // FIXME: Split arguments if CLI.IsPostTypeLegalization
8030     Type *FinalType = Args[i].Ty;
8031     if (Args[i].IsByVal)
8032       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
8033     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
8034         FinalType, CLI.CallConv, CLI.IsVarArg);
8035     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
8036          ++Value) {
8037       EVT VT = ValueVTs[Value];
8038       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
8039       SDValue Op = SDValue(Args[i].Node.getNode(),
8040                            Args[i].Node.getResNo() + Value);
8041       ISD::ArgFlagsTy Flags;
8042 
8043       // Certain targets (such as MIPS), may have a different ABI alignment
8044       // for a type depending on the context. Give the target a chance to
8045       // specify the alignment it wants.
8046       unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
8047 
8048       if (Args[i].IsZExt)
8049         Flags.setZExt();
8050       if (Args[i].IsSExt)
8051         Flags.setSExt();
8052       if (Args[i].IsInReg) {
8053         // If we are using vectorcall calling convention, a structure that is
8054         // passed InReg - is surely an HVA
8055         if (CLI.CallConv == CallingConv::X86_VectorCall &&
8056             isa<StructType>(FinalType)) {
8057           // The first value of a structure is marked
8058           if (0 == Value)
8059             Flags.setHvaStart();
8060           Flags.setHva();
8061         }
8062         // Set InReg Flag
8063         Flags.setInReg();
8064       }
8065       if (Args[i].IsSRet)
8066         Flags.setSRet();
8067       if (Args[i].IsSwiftSelf)
8068         Flags.setSwiftSelf();
8069       if (Args[i].IsSwiftError)
8070         Flags.setSwiftError();
8071       if (Args[i].IsByVal)
8072         Flags.setByVal();
8073       if (Args[i].IsInAlloca) {
8074         Flags.setInAlloca();
8075         // Set the byval flag for CCAssignFn callbacks that don't know about
8076         // inalloca.  This way we can know how many bytes we should've allocated
8077         // and how many bytes a callee cleanup function will pop.  If we port
8078         // inalloca to more targets, we'll have to add custom inalloca handling
8079         // in the various CC lowering callbacks.
8080         Flags.setByVal();
8081       }
8082       if (Args[i].IsByVal || Args[i].IsInAlloca) {
8083         PointerType *Ty = cast<PointerType>(Args[i].Ty);
8084         Type *ElementTy = Ty->getElementType();
8085         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
8086         // For ByVal, alignment should come from FE.  BE will guess if this
8087         // info is not there but there are cases it cannot get right.
8088         unsigned FrameAlign;
8089         if (Args[i].Alignment)
8090           FrameAlign = Args[i].Alignment;
8091         else
8092           FrameAlign = getByValTypeAlignment(ElementTy, DL);
8093         Flags.setByValAlign(FrameAlign);
8094       }
8095       if (Args[i].IsNest)
8096         Flags.setNest();
8097       if (NeedsRegBlock)
8098         Flags.setInConsecutiveRegs();
8099       Flags.setOrigAlign(OriginalAlignment);
8100 
8101       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT);
8102       unsigned NumParts =
8103           getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT);
8104       SmallVector<SDValue, 4> Parts(NumParts);
8105       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
8106 
8107       if (Args[i].IsSExt)
8108         ExtendKind = ISD::SIGN_EXTEND;
8109       else if (Args[i].IsZExt)
8110         ExtendKind = ISD::ZERO_EXTEND;
8111 
8112       // Conservatively only handle 'returned' on non-vectors for now
8113       if (Args[i].IsReturned && !Op.getValueType().isVector()) {
8114         assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
8115                "unexpected use of 'returned'");
8116         // Before passing 'returned' to the target lowering code, ensure that
8117         // either the register MVT and the actual EVT are the same size or that
8118         // the return value and argument are extended in the same way; in these
8119         // cases it's safe to pass the argument register value unchanged as the
8120         // return register value (although it's at the target's option whether
8121         // to do so)
8122         // TODO: allow code generation to take advantage of partially preserved
8123         // registers rather than clobbering the entire register when the
8124         // parameter extension method is not compatible with the return
8125         // extension method
8126         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
8127             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
8128              CLI.RetZExt == Args[i].IsZExt))
8129           Flags.setReturned();
8130       }
8131 
8132       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
8133                      CLI.CS.getInstruction(), ExtendKind, true);
8134 
8135       for (unsigned j = 0; j != NumParts; ++j) {
8136         // if it isn't first piece, alignment must be 1
8137         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
8138                                i < CLI.NumFixedArgs,
8139                                i, j*Parts[j].getValueType().getStoreSize());
8140         if (NumParts > 1 && j == 0)
8141           MyFlags.Flags.setSplit();
8142         else if (j != 0) {
8143           MyFlags.Flags.setOrigAlign(1);
8144           if (j == NumParts - 1)
8145             MyFlags.Flags.setSplitEnd();
8146         }
8147 
8148         CLI.Outs.push_back(MyFlags);
8149         CLI.OutVals.push_back(Parts[j]);
8150       }
8151 
8152       if (NeedsRegBlock && Value == NumValues - 1)
8153         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
8154     }
8155   }
8156 
8157   SmallVector<SDValue, 4> InVals;
8158   CLI.Chain = LowerCall(CLI, InVals);
8159 
8160   // Update CLI.InVals to use outside of this function.
8161   CLI.InVals = InVals;
8162 
8163   // Verify that the target's LowerCall behaved as expected.
8164   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
8165          "LowerCall didn't return a valid chain!");
8166   assert((!CLI.IsTailCall || InVals.empty()) &&
8167          "LowerCall emitted a return value for a tail call!");
8168   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
8169          "LowerCall didn't emit the correct number of values!");
8170 
8171   // For a tail call, the return value is merely live-out and there aren't
8172   // any nodes in the DAG representing it. Return a special value to
8173   // indicate that a tail call has been emitted and no more Instructions
8174   // should be processed in the current block.
8175   if (CLI.IsTailCall) {
8176     CLI.DAG.setRoot(CLI.Chain);
8177     return std::make_pair(SDValue(), SDValue());
8178   }
8179 
8180 #ifndef NDEBUG
8181   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
8182     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
8183     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
8184            "LowerCall emitted a value with the wrong type!");
8185   }
8186 #endif
8187 
8188   SmallVector<SDValue, 4> ReturnValues;
8189   if (!CanLowerReturn) {
8190     // The instruction result is the result of loading from the
8191     // hidden sret parameter.
8192     SmallVector<EVT, 1> PVTs;
8193     Type *PtrRetTy = PointerType::getUnqual(OrigRetTy);
8194 
8195     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
8196     assert(PVTs.size() == 1 && "Pointers should fit in one register");
8197     EVT PtrVT = PVTs[0];
8198 
8199     unsigned NumValues = RetTys.size();
8200     ReturnValues.resize(NumValues);
8201     SmallVector<SDValue, 4> Chains(NumValues);
8202 
8203     // An aggregate return value cannot wrap around the address space, so
8204     // offsets to its parts don't wrap either.
8205     SDNodeFlags Flags;
8206     Flags.setNoUnsignedWrap(true);
8207 
8208     for (unsigned i = 0; i < NumValues; ++i) {
8209       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
8210                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
8211                                                         PtrVT), Flags);
8212       SDValue L = CLI.DAG.getLoad(
8213           RetTys[i], CLI.DL, CLI.Chain, Add,
8214           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
8215                                             DemoteStackIdx, Offsets[i]),
8216           /* Alignment = */ 1);
8217       ReturnValues[i] = L;
8218       Chains[i] = L.getValue(1);
8219     }
8220 
8221     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
8222   } else {
8223     // Collect the legal value parts into potentially illegal values
8224     // that correspond to the original function's return values.
8225     Optional<ISD::NodeType> AssertOp;
8226     if (CLI.RetSExt)
8227       AssertOp = ISD::AssertSext;
8228     else if (CLI.RetZExt)
8229       AssertOp = ISD::AssertZext;
8230     unsigned CurReg = 0;
8231     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8232       EVT VT = RetTys[I];
8233       MVT RegisterVT =
8234           getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT);
8235       unsigned NumRegs =
8236           getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT);
8237 
8238       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
8239                                               NumRegs, RegisterVT, VT, nullptr,
8240                                               AssertOp, true));
8241       CurReg += NumRegs;
8242     }
8243 
8244     // For a function returning void, there is no return value. We can't create
8245     // such a node, so we just return a null return value in that case. In
8246     // that case, nothing will actually look at the value.
8247     if (ReturnValues.empty())
8248       return std::make_pair(SDValue(), CLI.Chain);
8249   }
8250 
8251   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
8252                                 CLI.DAG.getVTList(RetTys), ReturnValues);
8253   return std::make_pair(Res, CLI.Chain);
8254 }
8255 
8256 void TargetLowering::LowerOperationWrapper(SDNode *N,
8257                                            SmallVectorImpl<SDValue> &Results,
8258                                            SelectionDAG &DAG) const {
8259   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
8260     Results.push_back(Res);
8261 }
8262 
8263 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8264   llvm_unreachable("LowerOperation not implemented for this target!");
8265 }
8266 
8267 void
8268 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
8269   SDValue Op = getNonRegisterValue(V);
8270   assert((Op.getOpcode() != ISD::CopyFromReg ||
8271           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
8272          "Copy from a reg to the same reg!");
8273   assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
8274 
8275   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8276   // If this is an InlineAsm we have to match the registers required, not the
8277   // notional registers required by the type.
8278   bool IsABIRegCopy =
8279     V && ((isa<CallInst>(V) &&
8280            !(static_cast<const CallInst *>(V))->isInlineAsm()) ||
8281           isa<ReturnInst>(V));
8282 
8283   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
8284                    V->getType(), IsABIRegCopy);
8285   SDValue Chain = DAG.getEntryNode();
8286 
8287   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
8288                               FuncInfo.PreferredExtendType.end())
8289                                  ? ISD::ANY_EXTEND
8290                                  : FuncInfo.PreferredExtendType[V];
8291   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
8292   PendingExports.push_back(Chain);
8293 }
8294 
8295 #include "llvm/CodeGen/SelectionDAGISel.h"
8296 
8297 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
8298 /// entry block, return true.  This includes arguments used by switches, since
8299 /// the switch may expand into multiple basic blocks.
8300 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
8301   // With FastISel active, we may be splitting blocks, so force creation
8302   // of virtual registers for all non-dead arguments.
8303   if (FastISel)
8304     return A->use_empty();
8305 
8306   const BasicBlock &Entry = A->getParent()->front();
8307   for (const User *U : A->users())
8308     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
8309       return false;  // Use not in entry block.
8310 
8311   return true;
8312 }
8313 
8314 typedef DenseMap<const Argument *,
8315                  std::pair<const AllocaInst *, const StoreInst *>>
8316     ArgCopyElisionMapTy;
8317 
8318 /// Scan the entry block of the function in FuncInfo for arguments that look
8319 /// like copies into a local alloca. Record any copied arguments in
8320 /// ArgCopyElisionCandidates.
8321 static void
8322 findArgumentCopyElisionCandidates(const DataLayout &DL,
8323                                   FunctionLoweringInfo *FuncInfo,
8324                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
8325   // Record the state of every static alloca used in the entry block. Argument
8326   // allocas are all used in the entry block, so we need approximately as many
8327   // entries as we have arguments.
8328   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
8329   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
8330   unsigned NumArgs = FuncInfo->Fn->arg_size();
8331   StaticAllocas.reserve(NumArgs * 2);
8332 
8333   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
8334     if (!V)
8335       return nullptr;
8336     V = V->stripPointerCasts();
8337     const auto *AI = dyn_cast<AllocaInst>(V);
8338     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
8339       return nullptr;
8340     auto Iter = StaticAllocas.insert({AI, Unknown});
8341     return &Iter.first->second;
8342   };
8343 
8344   // Look for stores of arguments to static allocas. Look through bitcasts and
8345   // GEPs to handle type coercions, as long as the alloca is fully initialized
8346   // by the store. Any non-store use of an alloca escapes it and any subsequent
8347   // unanalyzed store might write it.
8348   // FIXME: Handle structs initialized with multiple stores.
8349   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
8350     // Look for stores, and handle non-store uses conservatively.
8351     const auto *SI = dyn_cast<StoreInst>(&I);
8352     if (!SI) {
8353       // We will look through cast uses, so ignore them completely.
8354       if (I.isCast())
8355         continue;
8356       // Ignore debug info intrinsics, they don't escape or store to allocas.
8357       if (isa<DbgInfoIntrinsic>(I))
8358         continue;
8359       // This is an unknown instruction. Assume it escapes or writes to all
8360       // static alloca operands.
8361       for (const Use &U : I.operands()) {
8362         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
8363           *Info = StaticAllocaInfo::Clobbered;
8364       }
8365       continue;
8366     }
8367 
8368     // If the stored value is a static alloca, mark it as escaped.
8369     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
8370       *Info = StaticAllocaInfo::Clobbered;
8371 
8372     // Check if the destination is a static alloca.
8373     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
8374     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
8375     if (!Info)
8376       continue;
8377     const AllocaInst *AI = cast<AllocaInst>(Dst);
8378 
8379     // Skip allocas that have been initialized or clobbered.
8380     if (*Info != StaticAllocaInfo::Unknown)
8381       continue;
8382 
8383     // Check if the stored value is an argument, and that this store fully
8384     // initializes the alloca. Don't elide copies from the same argument twice.
8385     const Value *Val = SI->getValueOperand()->stripPointerCasts();
8386     const auto *Arg = dyn_cast<Argument>(Val);
8387     if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
8388         Arg->getType()->isEmptyTy() ||
8389         DL.getTypeStoreSize(Arg->getType()) !=
8390             DL.getTypeAllocSize(AI->getAllocatedType()) ||
8391         ArgCopyElisionCandidates.count(Arg)) {
8392       *Info = StaticAllocaInfo::Clobbered;
8393       continue;
8394     }
8395 
8396     DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI << '\n');
8397 
8398     // Mark this alloca and store for argument copy elision.
8399     *Info = StaticAllocaInfo::Elidable;
8400     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
8401 
8402     // Stop scanning if we've seen all arguments. This will happen early in -O0
8403     // builds, which is useful, because -O0 builds have large entry blocks and
8404     // many allocas.
8405     if (ArgCopyElisionCandidates.size() == NumArgs)
8406       break;
8407   }
8408 }
8409 
8410 /// Try to elide argument copies from memory into a local alloca. Succeeds if
8411 /// ArgVal is a load from a suitable fixed stack object.
8412 static void tryToElideArgumentCopy(
8413     FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
8414     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
8415     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
8416     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
8417     SDValue ArgVal, bool &ArgHasUses) {
8418   // Check if this is a load from a fixed stack object.
8419   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
8420   if (!LNode)
8421     return;
8422   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
8423   if (!FINode)
8424     return;
8425 
8426   // Check that the fixed stack object is the right size and alignment.
8427   // Look at the alignment that the user wrote on the alloca instead of looking
8428   // at the stack object.
8429   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
8430   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
8431   const AllocaInst *AI = ArgCopyIter->second.first;
8432   int FixedIndex = FINode->getIndex();
8433   int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
8434   int OldIndex = AllocaIndex;
8435   MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
8436   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
8437     DEBUG(dbgs() << "  argument copy elision failed due to bad fixed stack "
8438                     "object size\n");
8439     return;
8440   }
8441   unsigned RequiredAlignment = AI->getAlignment();
8442   if (!RequiredAlignment) {
8443     RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
8444         AI->getAllocatedType());
8445   }
8446   if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
8447     DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
8448                     "greater than stack argument alignment ("
8449                  << RequiredAlignment << " vs "
8450                  << MFI.getObjectAlignment(FixedIndex) << ")\n");
8451     return;
8452   }
8453 
8454   // Perform the elision. Delete the old stack object and replace its only use
8455   // in the variable info map. Mark the stack object as mutable.
8456   DEBUG({
8457     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
8458            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
8459            << '\n';
8460   });
8461   MFI.RemoveStackObject(OldIndex);
8462   MFI.setIsImmutableObjectIndex(FixedIndex, false);
8463   AllocaIndex = FixedIndex;
8464   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
8465   Chains.push_back(ArgVal.getValue(1));
8466 
8467   // Avoid emitting code for the store implementing the copy.
8468   const StoreInst *SI = ArgCopyIter->second.second;
8469   ElidedArgCopyInstrs.insert(SI);
8470 
8471   // Check for uses of the argument again so that we can avoid exporting ArgVal
8472   // if it is't used by anything other than the store.
8473   for (const Value *U : Arg.users()) {
8474     if (U != SI) {
8475       ArgHasUses = true;
8476       break;
8477     }
8478   }
8479 }
8480 
8481 void SelectionDAGISel::LowerArguments(const Function &F) {
8482   SelectionDAG &DAG = SDB->DAG;
8483   SDLoc dl = SDB->getCurSDLoc();
8484   const DataLayout &DL = DAG.getDataLayout();
8485   SmallVector<ISD::InputArg, 16> Ins;
8486 
8487   if (!FuncInfo->CanLowerReturn) {
8488     // Put in an sret pointer parameter before all the other parameters.
8489     SmallVector<EVT, 1> ValueVTs;
8490     ComputeValueVTs(*TLI, DAG.getDataLayout(),
8491                     PointerType::getUnqual(F.getReturnType()), ValueVTs);
8492 
8493     // NOTE: Assuming that a pointer will never break down to more than one VT
8494     // or one register.
8495     ISD::ArgFlagsTy Flags;
8496     Flags.setSRet();
8497     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
8498     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
8499                          ISD::InputArg::NoArgIndex, 0);
8500     Ins.push_back(RetArg);
8501   }
8502 
8503   // Look for stores of arguments to static allocas. Mark such arguments with a
8504   // flag to ask the target to give us the memory location of that argument if
8505   // available.
8506   ArgCopyElisionMapTy ArgCopyElisionCandidates;
8507   findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
8508 
8509   // Set up the incoming argument description vector.
8510   for (const Argument &Arg : F.args()) {
8511     unsigned ArgNo = Arg.getArgNo();
8512     SmallVector<EVT, 4> ValueVTs;
8513     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
8514     bool isArgValueUsed = !Arg.use_empty();
8515     unsigned PartBase = 0;
8516     Type *FinalType = Arg.getType();
8517     if (Arg.hasAttribute(Attribute::ByVal))
8518       FinalType = cast<PointerType>(FinalType)->getElementType();
8519     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
8520         FinalType, F.getCallingConv(), F.isVarArg());
8521     for (unsigned Value = 0, NumValues = ValueVTs.size();
8522          Value != NumValues; ++Value) {
8523       EVT VT = ValueVTs[Value];
8524       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
8525       ISD::ArgFlagsTy Flags;
8526 
8527       // Certain targets (such as MIPS), may have a different ABI alignment
8528       // for a type depending on the context. Give the target a chance to
8529       // specify the alignment it wants.
8530       unsigned OriginalAlignment =
8531           TLI->getABIAlignmentForCallingConv(ArgTy, DL);
8532 
8533       if (Arg.hasAttribute(Attribute::ZExt))
8534         Flags.setZExt();
8535       if (Arg.hasAttribute(Attribute::SExt))
8536         Flags.setSExt();
8537       if (Arg.hasAttribute(Attribute::InReg)) {
8538         // If we are using vectorcall calling convention, a structure that is
8539         // passed InReg - is surely an HVA
8540         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
8541             isa<StructType>(Arg.getType())) {
8542           // The first value of a structure is marked
8543           if (0 == Value)
8544             Flags.setHvaStart();
8545           Flags.setHva();
8546         }
8547         // Set InReg Flag
8548         Flags.setInReg();
8549       }
8550       if (Arg.hasAttribute(Attribute::StructRet))
8551         Flags.setSRet();
8552       if (Arg.hasAttribute(Attribute::SwiftSelf))
8553         Flags.setSwiftSelf();
8554       if (Arg.hasAttribute(Attribute::SwiftError))
8555         Flags.setSwiftError();
8556       if (Arg.hasAttribute(Attribute::ByVal))
8557         Flags.setByVal();
8558       if (Arg.hasAttribute(Attribute::InAlloca)) {
8559         Flags.setInAlloca();
8560         // Set the byval flag for CCAssignFn callbacks that don't know about
8561         // inalloca.  This way we can know how many bytes we should've allocated
8562         // and how many bytes a callee cleanup function will pop.  If we port
8563         // inalloca to more targets, we'll have to add custom inalloca handling
8564         // in the various CC lowering callbacks.
8565         Flags.setByVal();
8566       }
8567       if (F.getCallingConv() == CallingConv::X86_INTR) {
8568         // IA Interrupt passes frame (1st parameter) by value in the stack.
8569         if (ArgNo == 0)
8570           Flags.setByVal();
8571       }
8572       if (Flags.isByVal() || Flags.isInAlloca()) {
8573         PointerType *Ty = cast<PointerType>(Arg.getType());
8574         Type *ElementTy = Ty->getElementType();
8575         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
8576         // For ByVal, alignment should be passed from FE.  BE will guess if
8577         // this info is not there but there are cases it cannot get right.
8578         unsigned FrameAlign;
8579         if (Arg.getParamAlignment())
8580           FrameAlign = Arg.getParamAlignment();
8581         else
8582           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
8583         Flags.setByValAlign(FrameAlign);
8584       }
8585       if (Arg.hasAttribute(Attribute::Nest))
8586         Flags.setNest();
8587       if (NeedsRegBlock)
8588         Flags.setInConsecutiveRegs();
8589       Flags.setOrigAlign(OriginalAlignment);
8590       if (ArgCopyElisionCandidates.count(&Arg))
8591         Flags.setCopyElisionCandidate();
8592 
8593       MVT RegisterVT =
8594           TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), VT);
8595       unsigned NumRegs =
8596           TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), VT);
8597       for (unsigned i = 0; i != NumRegs; ++i) {
8598         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
8599                               ArgNo, PartBase+i*RegisterVT.getStoreSize());
8600         if (NumRegs > 1 && i == 0)
8601           MyFlags.Flags.setSplit();
8602         // if it isn't first piece, alignment must be 1
8603         else if (i > 0) {
8604           MyFlags.Flags.setOrigAlign(1);
8605           if (i == NumRegs - 1)
8606             MyFlags.Flags.setSplitEnd();
8607         }
8608         Ins.push_back(MyFlags);
8609       }
8610       if (NeedsRegBlock && Value == NumValues - 1)
8611         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
8612       PartBase += VT.getStoreSize();
8613     }
8614   }
8615 
8616   // Call the target to set up the argument values.
8617   SmallVector<SDValue, 8> InVals;
8618   SDValue NewRoot = TLI->LowerFormalArguments(
8619       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
8620 
8621   // Verify that the target's LowerFormalArguments behaved as expected.
8622   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
8623          "LowerFormalArguments didn't return a valid chain!");
8624   assert(InVals.size() == Ins.size() &&
8625          "LowerFormalArguments didn't emit the correct number of values!");
8626   DEBUG({
8627       for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
8628         assert(InVals[i].getNode() &&
8629                "LowerFormalArguments emitted a null value!");
8630         assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
8631                "LowerFormalArguments emitted a value with the wrong type!");
8632       }
8633     });
8634 
8635   // Update the DAG with the new chain value resulting from argument lowering.
8636   DAG.setRoot(NewRoot);
8637 
8638   // Set up the argument values.
8639   unsigned i = 0;
8640   if (!FuncInfo->CanLowerReturn) {
8641     // Create a virtual register for the sret pointer, and put in a copy
8642     // from the sret argument into it.
8643     SmallVector<EVT, 1> ValueVTs;
8644     ComputeValueVTs(*TLI, DAG.getDataLayout(),
8645                     PointerType::getUnqual(F.getReturnType()), ValueVTs);
8646     MVT VT = ValueVTs[0].getSimpleVT();
8647     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
8648     Optional<ISD::NodeType> AssertOp = None;
8649     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
8650                                         RegVT, VT, nullptr, AssertOp);
8651 
8652     MachineFunction& MF = SDB->DAG.getMachineFunction();
8653     MachineRegisterInfo& RegInfo = MF.getRegInfo();
8654     unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
8655     FuncInfo->DemoteRegister = SRetReg;
8656     NewRoot =
8657         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
8658     DAG.setRoot(NewRoot);
8659 
8660     // i indexes lowered arguments.  Bump it past the hidden sret argument.
8661     ++i;
8662   }
8663 
8664   SmallVector<SDValue, 4> Chains;
8665   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
8666   for (const Argument &Arg : F.args()) {
8667     SmallVector<SDValue, 4> ArgValues;
8668     SmallVector<EVT, 4> ValueVTs;
8669     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
8670     unsigned NumValues = ValueVTs.size();
8671     if (NumValues == 0)
8672       continue;
8673 
8674     bool ArgHasUses = !Arg.use_empty();
8675 
8676     // Elide the copying store if the target loaded this argument from a
8677     // suitable fixed stack object.
8678     if (Ins[i].Flags.isCopyElisionCandidate()) {
8679       tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
8680                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
8681                              InVals[i], ArgHasUses);
8682     }
8683 
8684     // If this argument is unused then remember its value. It is used to generate
8685     // debugging information.
8686     bool isSwiftErrorArg =
8687         TLI->supportSwiftError() &&
8688         Arg.hasAttribute(Attribute::SwiftError);
8689     if (!ArgHasUses && !isSwiftErrorArg) {
8690       SDB->setUnusedArgValue(&Arg, InVals[i]);
8691 
8692       // Also remember any frame index for use in FastISel.
8693       if (FrameIndexSDNode *FI =
8694           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
8695         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
8696     }
8697 
8698     for (unsigned Val = 0; Val != NumValues; ++Val) {
8699       EVT VT = ValueVTs[Val];
8700       MVT PartVT =
8701           TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), VT);
8702       unsigned NumParts =
8703           TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), VT);
8704 
8705       // Even an apparant 'unused' swifterror argument needs to be returned. So
8706       // we do generate a copy for it that can be used on return from the
8707       // function.
8708       if (ArgHasUses || isSwiftErrorArg) {
8709         Optional<ISD::NodeType> AssertOp;
8710         if (Arg.hasAttribute(Attribute::SExt))
8711           AssertOp = ISD::AssertSext;
8712         else if (Arg.hasAttribute(Attribute::ZExt))
8713           AssertOp = ISD::AssertZext;
8714 
8715         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
8716                                              PartVT, VT, nullptr, AssertOp,
8717                                              true));
8718       }
8719 
8720       i += NumParts;
8721     }
8722 
8723     // We don't need to do anything else for unused arguments.
8724     if (ArgValues.empty())
8725       continue;
8726 
8727     // Note down frame index.
8728     if (FrameIndexSDNode *FI =
8729         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
8730       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
8731 
8732     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
8733                                      SDB->getCurSDLoc());
8734 
8735     SDB->setValue(&Arg, Res);
8736     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
8737       if (LoadSDNode *LNode =
8738           dyn_cast<LoadSDNode>(Res.getOperand(0).getNode()))
8739         if (FrameIndexSDNode *FI =
8740             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
8741         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
8742     }
8743 
8744     // Update the SwiftErrorVRegDefMap.
8745     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
8746       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
8747       if (TargetRegisterInfo::isVirtualRegister(Reg))
8748         FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB,
8749                                            FuncInfo->SwiftErrorArg, Reg);
8750     }
8751 
8752     // If this argument is live outside of the entry block, insert a copy from
8753     // wherever we got it to the vreg that other BB's will reference it as.
8754     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
8755       // If we can, though, try to skip creating an unnecessary vreg.
8756       // FIXME: This isn't very clean... it would be nice to make this more
8757       // general.  It's also subtly incompatible with the hacks FastISel
8758       // uses with vregs.
8759       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
8760       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
8761         FuncInfo->ValueMap[&Arg] = Reg;
8762         continue;
8763       }
8764     }
8765     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
8766       FuncInfo->InitializeRegForValue(&Arg);
8767       SDB->CopyToExportRegsIfNeeded(&Arg);
8768     }
8769   }
8770 
8771   if (!Chains.empty()) {
8772     Chains.push_back(NewRoot);
8773     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
8774   }
8775 
8776   DAG.setRoot(NewRoot);
8777 
8778   assert(i == InVals.size() && "Argument register count mismatch!");
8779 
8780   // If any argument copy elisions occurred and we have debug info, update the
8781   // stale frame indices used in the dbg.declare variable info table.
8782   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
8783   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
8784     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
8785       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
8786       if (I != ArgCopyElisionFrameIndexMap.end())
8787         VI.Slot = I->second;
8788     }
8789   }
8790 
8791   // Finally, if the target has anything special to do, allow it to do so.
8792   EmitFunctionEntryCode();
8793 }
8794 
8795 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
8796 /// ensure constants are generated when needed.  Remember the virtual registers
8797 /// that need to be added to the Machine PHI nodes as input.  We cannot just
8798 /// directly add them, because expansion might result in multiple MBB's for one
8799 /// BB.  As such, the start of the BB might correspond to a different MBB than
8800 /// the end.
8801 ///
8802 void
8803 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
8804   const TerminatorInst *TI = LLVMBB->getTerminator();
8805 
8806   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
8807 
8808   // Check PHI nodes in successors that expect a value to be available from this
8809   // block.
8810   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
8811     const BasicBlock *SuccBB = TI->getSuccessor(succ);
8812     if (!isa<PHINode>(SuccBB->begin())) continue;
8813     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
8814 
8815     // If this terminator has multiple identical successors (common for
8816     // switches), only handle each succ once.
8817     if (!SuccsHandled.insert(SuccMBB).second)
8818       continue;
8819 
8820     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
8821 
8822     // At this point we know that there is a 1-1 correspondence between LLVM PHI
8823     // nodes and Machine PHI nodes, but the incoming operands have not been
8824     // emitted yet.
8825     for (BasicBlock::const_iterator I = SuccBB->begin();
8826          const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
8827       // Ignore dead phi's.
8828       if (PN->use_empty()) continue;
8829 
8830       // Skip empty types
8831       if (PN->getType()->isEmptyTy())
8832         continue;
8833 
8834       unsigned Reg;
8835       const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
8836 
8837       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
8838         unsigned &RegOut = ConstantsOut[C];
8839         if (RegOut == 0) {
8840           RegOut = FuncInfo.CreateRegs(C->getType());
8841           CopyValueToVirtualRegister(C, RegOut);
8842         }
8843         Reg = RegOut;
8844       } else {
8845         DenseMap<const Value *, unsigned>::iterator I =
8846           FuncInfo.ValueMap.find(PHIOp);
8847         if (I != FuncInfo.ValueMap.end())
8848           Reg = I->second;
8849         else {
8850           assert(isa<AllocaInst>(PHIOp) &&
8851                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
8852                  "Didn't codegen value into a register!??");
8853           Reg = FuncInfo.CreateRegs(PHIOp->getType());
8854           CopyValueToVirtualRegister(PHIOp, Reg);
8855         }
8856       }
8857 
8858       // Remember that this register needs to added to the machine PHI node as
8859       // the input for this MBB.
8860       SmallVector<EVT, 4> ValueVTs;
8861       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8862       ComputeValueVTs(TLI, DAG.getDataLayout(), PN->getType(), ValueVTs);
8863       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
8864         EVT VT = ValueVTs[vti];
8865         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
8866         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
8867           FuncInfo.PHINodesToUpdate.push_back(
8868               std::make_pair(&*MBBI++, Reg + i));
8869         Reg += NumRegisters;
8870       }
8871     }
8872   }
8873 
8874   ConstantsOut.clear();
8875 }
8876 
8877 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
8878 /// is 0.
8879 MachineBasicBlock *
8880 SelectionDAGBuilder::StackProtectorDescriptor::
8881 AddSuccessorMBB(const BasicBlock *BB,
8882                 MachineBasicBlock *ParentMBB,
8883                 bool IsLikely,
8884                 MachineBasicBlock *SuccMBB) {
8885   // If SuccBB has not been created yet, create it.
8886   if (!SuccMBB) {
8887     MachineFunction *MF = ParentMBB->getParent();
8888     MachineFunction::iterator BBI(ParentMBB);
8889     SuccMBB = MF->CreateMachineBasicBlock(BB);
8890     MF->insert(++BBI, SuccMBB);
8891   }
8892   // Add it as a successor of ParentMBB.
8893   ParentMBB->addSuccessor(
8894       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
8895   return SuccMBB;
8896 }
8897 
8898 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
8899   MachineFunction::iterator I(MBB);
8900   if (++I == FuncInfo.MF->end())
8901     return nullptr;
8902   return &*I;
8903 }
8904 
8905 /// During lowering new call nodes can be created (such as memset, etc.).
8906 /// Those will become new roots of the current DAG, but complications arise
8907 /// when they are tail calls. In such cases, the call lowering will update
8908 /// the root, but the builder still needs to know that a tail call has been
8909 /// lowered in order to avoid generating an additional return.
8910 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
8911   // If the node is null, we do have a tail call.
8912   if (MaybeTC.getNode() != nullptr)
8913     DAG.setRoot(MaybeTC);
8914   else
8915     HasTailCall = true;
8916 }
8917 
8918 uint64_t
8919 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters,
8920                                        unsigned First, unsigned Last) const {
8921   assert(Last >= First);
8922   const APInt &LowCase = Clusters[First].Low->getValue();
8923   const APInt &HighCase = Clusters[Last].High->getValue();
8924   assert(LowCase.getBitWidth() == HighCase.getBitWidth());
8925 
8926   // FIXME: A range of consecutive cases has 100% density, but only requires one
8927   // comparison to lower. We should discriminate against such consecutive ranges
8928   // in jump tables.
8929 
8930   return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1;
8931 }
8932 
8933 uint64_t SelectionDAGBuilder::getJumpTableNumCases(
8934     const SmallVectorImpl<unsigned> &TotalCases, unsigned First,
8935     unsigned Last) const {
8936   assert(Last >= First);
8937   assert(TotalCases[Last] >= TotalCases[First]);
8938   uint64_t NumCases =
8939       TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
8940   return NumCases;
8941 }
8942 
8943 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters,
8944                                          unsigned First, unsigned Last,
8945                                          const SwitchInst *SI,
8946                                          MachineBasicBlock *DefaultMBB,
8947                                          CaseCluster &JTCluster) {
8948   assert(First <= Last);
8949 
8950   auto Prob = BranchProbability::getZero();
8951   unsigned NumCmps = 0;
8952   std::vector<MachineBasicBlock*> Table;
8953   DenseMap<MachineBasicBlock*, BranchProbability> JTProbs;
8954 
8955   // Initialize probabilities in JTProbs.
8956   for (unsigned I = First; I <= Last; ++I)
8957     JTProbs[Clusters[I].MBB] = BranchProbability::getZero();
8958 
8959   for (unsigned I = First; I <= Last; ++I) {
8960     assert(Clusters[I].Kind == CC_Range);
8961     Prob += Clusters[I].Prob;
8962     const APInt &Low = Clusters[I].Low->getValue();
8963     const APInt &High = Clusters[I].High->getValue();
8964     NumCmps += (Low == High) ? 1 : 2;
8965     if (I != First) {
8966       // Fill the gap between this and the previous cluster.
8967       const APInt &PreviousHigh = Clusters[I - 1].High->getValue();
8968       assert(PreviousHigh.slt(Low));
8969       uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
8970       for (uint64_t J = 0; J < Gap; J++)
8971         Table.push_back(DefaultMBB);
8972     }
8973     uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
8974     for (uint64_t J = 0; J < ClusterSize; ++J)
8975       Table.push_back(Clusters[I].MBB);
8976     JTProbs[Clusters[I].MBB] += Clusters[I].Prob;
8977   }
8978 
8979   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8980   unsigned NumDests = JTProbs.size();
8981   if (TLI.isSuitableForBitTests(
8982           NumDests, NumCmps, Clusters[First].Low->getValue(),
8983           Clusters[Last].High->getValue(), DAG.getDataLayout())) {
8984     // Clusters[First..Last] should be lowered as bit tests instead.
8985     return false;
8986   }
8987 
8988   // Create the MBB that will load from and jump through the table.
8989   // Note: We create it here, but it's not inserted into the function yet.
8990   MachineFunction *CurMF = FuncInfo.MF;
8991   MachineBasicBlock *JumpTableMBB =
8992       CurMF->CreateMachineBasicBlock(SI->getParent());
8993 
8994   // Add successors. Note: use table order for determinism.
8995   SmallPtrSet<MachineBasicBlock *, 8> Done;
8996   for (MachineBasicBlock *Succ : Table) {
8997     if (Done.count(Succ))
8998       continue;
8999     addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]);
9000     Done.insert(Succ);
9001   }
9002   JumpTableMBB->normalizeSuccProbs();
9003 
9004   unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding())
9005                      ->createJumpTableIndex(Table);
9006 
9007   // Set up the jump table info.
9008   JumpTable JT(-1U, JTI, JumpTableMBB, nullptr);
9009   JumpTableHeader JTH(Clusters[First].Low->getValue(),
9010                       Clusters[Last].High->getValue(), SI->getCondition(),
9011                       nullptr, false);
9012   JTCases.emplace_back(std::move(JTH), std::move(JT));
9013 
9014   JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
9015                                      JTCases.size() - 1, Prob);
9016   return true;
9017 }
9018 
9019 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters,
9020                                          const SwitchInst *SI,
9021                                          MachineBasicBlock *DefaultMBB) {
9022 #ifndef NDEBUG
9023   // Clusters must be non-empty, sorted, and only contain Range clusters.
9024   assert(!Clusters.empty());
9025   for (CaseCluster &C : Clusters)
9026     assert(C.Kind == CC_Range);
9027   for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
9028     assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
9029 #endif
9030 
9031   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9032   if (!TLI.areJTsAllowed(SI->getParent()->getParent()))
9033     return;
9034 
9035   const int64_t N = Clusters.size();
9036   const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries();
9037   const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2;
9038 
9039   if (N < 2 || N < MinJumpTableEntries)
9040     return;
9041 
9042   // TotalCases[i]: Total nbr of cases in Clusters[0..i].
9043   SmallVector<unsigned, 8> TotalCases(N);
9044   for (unsigned i = 0; i < N; ++i) {
9045     const APInt &Hi = Clusters[i].High->getValue();
9046     const APInt &Lo = Clusters[i].Low->getValue();
9047     TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
9048     if (i != 0)
9049       TotalCases[i] += TotalCases[i - 1];
9050   }
9051 
9052   // Cheap case: the whole range may be suitable for jump table.
9053   uint64_t Range = getJumpTableRange(Clusters,0, N - 1);
9054   uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1);
9055   assert(NumCases < UINT64_MAX / 100);
9056   assert(Range >= NumCases);
9057   if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
9058     CaseCluster JTCluster;
9059     if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) {
9060       Clusters[0] = JTCluster;
9061       Clusters.resize(1);
9062       return;
9063     }
9064   }
9065 
9066   // The algorithm below is not suitable for -O0.
9067   if (TM.getOptLevel() == CodeGenOpt::None)
9068     return;
9069 
9070   // Split Clusters into minimum number of dense partitions. The algorithm uses
9071   // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
9072   // for the Case Statement'" (1994), but builds the MinPartitions array in
9073   // reverse order to make it easier to reconstruct the partitions in ascending
9074   // order. In the choice between two optimal partitionings, it picks the one
9075   // which yields more jump tables.
9076 
9077   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
9078   SmallVector<unsigned, 8> MinPartitions(N);
9079   // LastElement[i] is the last element of the partition starting at i.
9080   SmallVector<unsigned, 8> LastElement(N);
9081   // PartitionsScore[i] is used to break ties when choosing between two
9082   // partitionings resulting in the same number of partitions.
9083   SmallVector<unsigned, 8> PartitionsScore(N);
9084   // For PartitionsScore, a small number of comparisons is considered as good as
9085   // a jump table and a single comparison is considered better than a jump
9086   // table.
9087   enum PartitionScores : unsigned {
9088     NoTable = 0,
9089     Table = 1,
9090     FewCases = 1,
9091     SingleCase = 2
9092   };
9093 
9094   // Base case: There is only one way to partition Clusters[N-1].
9095   MinPartitions[N - 1] = 1;
9096   LastElement[N - 1] = N - 1;
9097   PartitionsScore[N - 1] = PartitionScores::SingleCase;
9098 
9099   // Note: loop indexes are signed to avoid underflow.
9100   for (int64_t i = N - 2; i >= 0; i--) {
9101     // Find optimal partitioning of Clusters[i..N-1].
9102     // Baseline: Put Clusters[i] into a partition on its own.
9103     MinPartitions[i] = MinPartitions[i + 1] + 1;
9104     LastElement[i] = i;
9105     PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase;
9106 
9107     // Search for a solution that results in fewer partitions.
9108     for (int64_t j = N - 1; j > i; j--) {
9109       // Try building a partition from Clusters[i..j].
9110       uint64_t Range = getJumpTableRange(Clusters, i, j);
9111       uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j);
9112       assert(NumCases < UINT64_MAX / 100);
9113       assert(Range >= NumCases);
9114       if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
9115         unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
9116         unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1];
9117         int64_t NumEntries = j - i + 1;
9118 
9119         if (NumEntries == 1)
9120           Score += PartitionScores::SingleCase;
9121         else if (NumEntries <= SmallNumberOfEntries)
9122           Score += PartitionScores::FewCases;
9123         else if (NumEntries >= MinJumpTableEntries)
9124           Score += PartitionScores::Table;
9125 
9126         // If this leads to fewer partitions, or to the same number of
9127         // partitions with better score, it is a better partitioning.
9128         if (NumPartitions < MinPartitions[i] ||
9129             (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) {
9130           MinPartitions[i] = NumPartitions;
9131           LastElement[i] = j;
9132           PartitionsScore[i] = Score;
9133         }
9134       }
9135     }
9136   }
9137 
9138   // Iterate over the partitions, replacing some with jump tables in-place.
9139   unsigned DstIndex = 0;
9140   for (unsigned First = 0, Last; First < N; First = Last + 1) {
9141     Last = LastElement[First];
9142     assert(Last >= First);
9143     assert(DstIndex <= First);
9144     unsigned NumClusters = Last - First + 1;
9145 
9146     CaseCluster JTCluster;
9147     if (NumClusters >= MinJumpTableEntries &&
9148         buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) {
9149       Clusters[DstIndex++] = JTCluster;
9150     } else {
9151       for (unsigned I = First; I <= Last; ++I)
9152         std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
9153     }
9154   }
9155   Clusters.resize(DstIndex);
9156 }
9157 
9158 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters,
9159                                         unsigned First, unsigned Last,
9160                                         const SwitchInst *SI,
9161                                         CaseCluster &BTCluster) {
9162   assert(First <= Last);
9163   if (First == Last)
9164     return false;
9165 
9166   BitVector Dests(FuncInfo.MF->getNumBlockIDs());
9167   unsigned NumCmps = 0;
9168   for (int64_t I = First; I <= Last; ++I) {
9169     assert(Clusters[I].Kind == CC_Range);
9170     Dests.set(Clusters[I].MBB->getNumber());
9171     NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
9172   }
9173   unsigned NumDests = Dests.count();
9174 
9175   APInt Low = Clusters[First].Low->getValue();
9176   APInt High = Clusters[Last].High->getValue();
9177   assert(Low.slt(High));
9178 
9179   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9180   const DataLayout &DL = DAG.getDataLayout();
9181   if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL))
9182     return false;
9183 
9184   APInt LowBound;
9185   APInt CmpRange;
9186 
9187   const int BitWidth = TLI.getPointerTy(DL).getSizeInBits();
9188   assert(TLI.rangeFitsInWord(Low, High, DL) &&
9189          "Case range must fit in bit mask!");
9190 
9191   // Check if the clusters cover a contiguous range such that no value in the
9192   // range will jump to the default statement.
9193   bool ContiguousRange = true;
9194   for (int64_t I = First + 1; I <= Last; ++I) {
9195     if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) {
9196       ContiguousRange = false;
9197       break;
9198     }
9199   }
9200 
9201   if (Low.isStrictlyPositive() && High.slt(BitWidth)) {
9202     // Optimize the case where all the case values fit in a word without having
9203     // to subtract minValue. In this case, we can optimize away the subtraction.
9204     LowBound = APInt::getNullValue(Low.getBitWidth());
9205     CmpRange = High;
9206     ContiguousRange = false;
9207   } else {
9208     LowBound = Low;
9209     CmpRange = High - Low;
9210   }
9211 
9212   CaseBitsVector CBV;
9213   auto TotalProb = BranchProbability::getZero();
9214   for (unsigned i = First; i <= Last; ++i) {
9215     // Find the CaseBits for this destination.
9216     unsigned j;
9217     for (j = 0; j < CBV.size(); ++j)
9218       if (CBV[j].BB == Clusters[i].MBB)
9219         break;
9220     if (j == CBV.size())
9221       CBV.push_back(
9222           CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero()));
9223     CaseBits *CB = &CBV[j];
9224 
9225     // Update Mask, Bits and ExtraProb.
9226     uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
9227     uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
9228     assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
9229     CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
9230     CB->Bits += Hi - Lo + 1;
9231     CB->ExtraProb += Clusters[i].Prob;
9232     TotalProb += Clusters[i].Prob;
9233   }
9234 
9235   BitTestInfo BTI;
9236   std::sort(CBV.begin(), CBV.end(), [](const CaseBits &a, const CaseBits &b) {
9237     // Sort by probability first, number of bits second.
9238     if (a.ExtraProb != b.ExtraProb)
9239       return a.ExtraProb > b.ExtraProb;
9240     return a.Bits > b.Bits;
9241   });
9242 
9243   for (auto &CB : CBV) {
9244     MachineBasicBlock *BitTestBB =
9245         FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
9246     BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb));
9247   }
9248   BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
9249                             SI->getCondition(), -1U, MVT::Other, false,
9250                             ContiguousRange, nullptr, nullptr, std::move(BTI),
9251                             TotalProb);
9252 
9253   BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
9254                                     BitTestCases.size() - 1, TotalProb);
9255   return true;
9256 }
9257 
9258 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters,
9259                                               const SwitchInst *SI) {
9260 // Partition Clusters into as few subsets as possible, where each subset has a
9261 // range that fits in a machine word and has <= 3 unique destinations.
9262 
9263 #ifndef NDEBUG
9264   // Clusters must be sorted and contain Range or JumpTable clusters.
9265   assert(!Clusters.empty());
9266   assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
9267   for (const CaseCluster &C : Clusters)
9268     assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
9269   for (unsigned i = 1; i < Clusters.size(); ++i)
9270     assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
9271 #endif
9272 
9273   // The algorithm below is not suitable for -O0.
9274   if (TM.getOptLevel() == CodeGenOpt::None)
9275     return;
9276 
9277   // If target does not have legal shift left, do not emit bit tests at all.
9278   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9279   const DataLayout &DL = DAG.getDataLayout();
9280 
9281   EVT PTy = TLI.getPointerTy(DL);
9282   if (!TLI.isOperationLegal(ISD::SHL, PTy))
9283     return;
9284 
9285   int BitWidth = PTy.getSizeInBits();
9286   const int64_t N = Clusters.size();
9287 
9288   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
9289   SmallVector<unsigned, 8> MinPartitions(N);
9290   // LastElement[i] is the last element of the partition starting at i.
9291   SmallVector<unsigned, 8> LastElement(N);
9292 
9293   // FIXME: This might not be the best algorithm for finding bit test clusters.
9294 
9295   // Base case: There is only one way to partition Clusters[N-1].
9296   MinPartitions[N - 1] = 1;
9297   LastElement[N - 1] = N - 1;
9298 
9299   // Note: loop indexes are signed to avoid underflow.
9300   for (int64_t i = N - 2; i >= 0; --i) {
9301     // Find optimal partitioning of Clusters[i..N-1].
9302     // Baseline: Put Clusters[i] into a partition on its own.
9303     MinPartitions[i] = MinPartitions[i + 1] + 1;
9304     LastElement[i] = i;
9305 
9306     // Search for a solution that results in fewer partitions.
9307     // Note: the search is limited by BitWidth, reducing time complexity.
9308     for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
9309       // Try building a partition from Clusters[i..j].
9310 
9311       // Check the range.
9312       if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(),
9313                                Clusters[j].High->getValue(), DL))
9314         continue;
9315 
9316       // Check nbr of destinations and cluster types.
9317       // FIXME: This works, but doesn't seem very efficient.
9318       bool RangesOnly = true;
9319       BitVector Dests(FuncInfo.MF->getNumBlockIDs());
9320       for (int64_t k = i; k <= j; k++) {
9321         if (Clusters[k].Kind != CC_Range) {
9322           RangesOnly = false;
9323           break;
9324         }
9325         Dests.set(Clusters[k].MBB->getNumber());
9326       }
9327       if (!RangesOnly || Dests.count() > 3)
9328         break;
9329 
9330       // Check if it's a better partition.
9331       unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
9332       if (NumPartitions < MinPartitions[i]) {
9333         // Found a better partition.
9334         MinPartitions[i] = NumPartitions;
9335         LastElement[i] = j;
9336       }
9337     }
9338   }
9339 
9340   // Iterate over the partitions, replacing with bit-test clusters in-place.
9341   unsigned DstIndex = 0;
9342   for (unsigned First = 0, Last; First < N; First = Last + 1) {
9343     Last = LastElement[First];
9344     assert(First <= Last);
9345     assert(DstIndex <= First);
9346 
9347     CaseCluster BitTestCluster;
9348     if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
9349       Clusters[DstIndex++] = BitTestCluster;
9350     } else {
9351       size_t NumClusters = Last - First + 1;
9352       std::memmove(&Clusters[DstIndex], &Clusters[First],
9353                    sizeof(Clusters[0]) * NumClusters);
9354       DstIndex += NumClusters;
9355     }
9356   }
9357   Clusters.resize(DstIndex);
9358 }
9359 
9360 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
9361                                         MachineBasicBlock *SwitchMBB,
9362                                         MachineBasicBlock *DefaultMBB) {
9363   MachineFunction *CurMF = FuncInfo.MF;
9364   MachineBasicBlock *NextMBB = nullptr;
9365   MachineFunction::iterator BBI(W.MBB);
9366   if (++BBI != FuncInfo.MF->end())
9367     NextMBB = &*BBI;
9368 
9369   unsigned Size = W.LastCluster - W.FirstCluster + 1;
9370 
9371   BranchProbabilityInfo *BPI = FuncInfo.BPI;
9372 
9373   if (Size == 2 && W.MBB == SwitchMBB) {
9374     // If any two of the cases has the same destination, and if one value
9375     // is the same as the other, but has one bit unset that the other has set,
9376     // use bit manipulation to do two compares at once.  For example:
9377     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
9378     // TODO: This could be extended to merge any 2 cases in switches with 3
9379     // cases.
9380     // TODO: Handle cases where W.CaseBB != SwitchBB.
9381     CaseCluster &Small = *W.FirstCluster;
9382     CaseCluster &Big = *W.LastCluster;
9383 
9384     if (Small.Low == Small.High && Big.Low == Big.High &&
9385         Small.MBB == Big.MBB) {
9386       const APInt &SmallValue = Small.Low->getValue();
9387       const APInt &BigValue = Big.Low->getValue();
9388 
9389       // Check that there is only one bit different.
9390       APInt CommonBit = BigValue ^ SmallValue;
9391       if (CommonBit.isPowerOf2()) {
9392         SDValue CondLHS = getValue(Cond);
9393         EVT VT = CondLHS.getValueType();
9394         SDLoc DL = getCurSDLoc();
9395 
9396         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
9397                                  DAG.getConstant(CommonBit, DL, VT));
9398         SDValue Cond = DAG.getSetCC(
9399             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
9400             ISD::SETEQ);
9401 
9402         // Update successor info.
9403         // Both Small and Big will jump to Small.BB, so we sum up the
9404         // probabilities.
9405         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
9406         if (BPI)
9407           addSuccessorWithProb(
9408               SwitchMBB, DefaultMBB,
9409               // The default destination is the first successor in IR.
9410               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
9411         else
9412           addSuccessorWithProb(SwitchMBB, DefaultMBB);
9413 
9414         // Insert the true branch.
9415         SDValue BrCond =
9416             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
9417                         DAG.getBasicBlock(Small.MBB));
9418         // Insert the false branch.
9419         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
9420                              DAG.getBasicBlock(DefaultMBB));
9421 
9422         DAG.setRoot(BrCond);
9423         return;
9424       }
9425     }
9426   }
9427 
9428   if (TM.getOptLevel() != CodeGenOpt::None) {
9429     // Order cases by probability so the most likely case will be checked first.
9430     std::sort(W.FirstCluster, W.LastCluster + 1,
9431               [](const CaseCluster &a, const CaseCluster &b) {
9432       return a.Prob > b.Prob;
9433     });
9434 
9435     // Rearrange the case blocks so that the last one falls through if possible
9436     // without without changing the order of probabilities.
9437     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
9438       --I;
9439       if (I->Prob > W.LastCluster->Prob)
9440         break;
9441       if (I->Kind == CC_Range && I->MBB == NextMBB) {
9442         std::swap(*I, *W.LastCluster);
9443         break;
9444       }
9445     }
9446   }
9447 
9448   // Compute total probability.
9449   BranchProbability DefaultProb = W.DefaultProb;
9450   BranchProbability UnhandledProbs = DefaultProb;
9451   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
9452     UnhandledProbs += I->Prob;
9453 
9454   MachineBasicBlock *CurMBB = W.MBB;
9455   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
9456     MachineBasicBlock *Fallthrough;
9457     if (I == W.LastCluster) {
9458       // For the last cluster, fall through to the default destination.
9459       Fallthrough = DefaultMBB;
9460     } else {
9461       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
9462       CurMF->insert(BBI, Fallthrough);
9463       // Put Cond in a virtual register to make it available from the new blocks.
9464       ExportFromCurrentBlock(Cond);
9465     }
9466     UnhandledProbs -= I->Prob;
9467 
9468     switch (I->Kind) {
9469       case CC_JumpTable: {
9470         // FIXME: Optimize away range check based on pivot comparisons.
9471         JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first;
9472         JumpTable *JT = &JTCases[I->JTCasesIndex].second;
9473 
9474         // The jump block hasn't been inserted yet; insert it here.
9475         MachineBasicBlock *JumpMBB = JT->MBB;
9476         CurMF->insert(BBI, JumpMBB);
9477 
9478         auto JumpProb = I->Prob;
9479         auto FallthroughProb = UnhandledProbs;
9480 
9481         // If the default statement is a target of the jump table, we evenly
9482         // distribute the default probability to successors of CurMBB. Also
9483         // update the probability on the edge from JumpMBB to Fallthrough.
9484         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
9485                                               SE = JumpMBB->succ_end();
9486              SI != SE; ++SI) {
9487           if (*SI == DefaultMBB) {
9488             JumpProb += DefaultProb / 2;
9489             FallthroughProb -= DefaultProb / 2;
9490             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
9491             JumpMBB->normalizeSuccProbs();
9492             break;
9493           }
9494         }
9495 
9496         addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
9497         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
9498         CurMBB->normalizeSuccProbs();
9499 
9500         // The jump table header will be inserted in our current block, do the
9501         // range check, and fall through to our fallthrough block.
9502         JTH->HeaderBB = CurMBB;
9503         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
9504 
9505         // If we're in the right place, emit the jump table header right now.
9506         if (CurMBB == SwitchMBB) {
9507           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
9508           JTH->Emitted = true;
9509         }
9510         break;
9511       }
9512       case CC_BitTests: {
9513         // FIXME: Optimize away range check based on pivot comparisons.
9514         BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex];
9515 
9516         // The bit test blocks haven't been inserted yet; insert them here.
9517         for (BitTestCase &BTC : BTB->Cases)
9518           CurMF->insert(BBI, BTC.ThisBB);
9519 
9520         // Fill in fields of the BitTestBlock.
9521         BTB->Parent = CurMBB;
9522         BTB->Default = Fallthrough;
9523 
9524         BTB->DefaultProb = UnhandledProbs;
9525         // If the cases in bit test don't form a contiguous range, we evenly
9526         // distribute the probability on the edge to Fallthrough to two
9527         // successors of CurMBB.
9528         if (!BTB->ContiguousRange) {
9529           BTB->Prob += DefaultProb / 2;
9530           BTB->DefaultProb -= DefaultProb / 2;
9531         }
9532 
9533         // If we're in the right place, emit the bit test header right now.
9534         if (CurMBB == SwitchMBB) {
9535           visitBitTestHeader(*BTB, SwitchMBB);
9536           BTB->Emitted = true;
9537         }
9538         break;
9539       }
9540       case CC_Range: {
9541         const Value *RHS, *LHS, *MHS;
9542         ISD::CondCode CC;
9543         if (I->Low == I->High) {
9544           // Check Cond == I->Low.
9545           CC = ISD::SETEQ;
9546           LHS = Cond;
9547           RHS=I->Low;
9548           MHS = nullptr;
9549         } else {
9550           // Check I->Low <= Cond <= I->High.
9551           CC = ISD::SETLE;
9552           LHS = I->Low;
9553           MHS = Cond;
9554           RHS = I->High;
9555         }
9556 
9557         // The false probability is the sum of all unhandled cases.
9558         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, I->Prob,
9559                      UnhandledProbs);
9560 
9561         if (CurMBB == SwitchMBB)
9562           visitSwitchCase(CB, SwitchMBB);
9563         else
9564           SwitchCases.push_back(CB);
9565 
9566         break;
9567       }
9568     }
9569     CurMBB = Fallthrough;
9570   }
9571 }
9572 
9573 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
9574                                               CaseClusterIt First,
9575                                               CaseClusterIt Last) {
9576   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
9577     if (X.Prob != CC.Prob)
9578       return X.Prob > CC.Prob;
9579 
9580     // Ties are broken by comparing the case value.
9581     return X.Low->getValue().slt(CC.Low->getValue());
9582   });
9583 }
9584 
9585 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
9586                                         const SwitchWorkListItem &W,
9587                                         Value *Cond,
9588                                         MachineBasicBlock *SwitchMBB) {
9589   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
9590          "Clusters not sorted?");
9591 
9592   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
9593 
9594   // Balance the tree based on branch probabilities to create a near-optimal (in
9595   // terms of search time given key frequency) binary search tree. See e.g. Kurt
9596   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
9597   CaseClusterIt LastLeft = W.FirstCluster;
9598   CaseClusterIt FirstRight = W.LastCluster;
9599   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
9600   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
9601 
9602   // Move LastLeft and FirstRight towards each other from opposite directions to
9603   // find a partitioning of the clusters which balances the probability on both
9604   // sides. If LeftProb and RightProb are equal, alternate which side is
9605   // taken to ensure 0-probability nodes are distributed evenly.
9606   unsigned I = 0;
9607   while (LastLeft + 1 < FirstRight) {
9608     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
9609       LeftProb += (++LastLeft)->Prob;
9610     else
9611       RightProb += (--FirstRight)->Prob;
9612     I++;
9613   }
9614 
9615   for (;;) {
9616     // Our binary search tree differs from a typical BST in that ours can have up
9617     // to three values in each leaf. The pivot selection above doesn't take that
9618     // into account, which means the tree might require more nodes and be less
9619     // efficient. We compensate for this here.
9620 
9621     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
9622     unsigned NumRight = W.LastCluster - FirstRight + 1;
9623 
9624     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
9625       // If one side has less than 3 clusters, and the other has more than 3,
9626       // consider taking a cluster from the other side.
9627 
9628       if (NumLeft < NumRight) {
9629         // Consider moving the first cluster on the right to the left side.
9630         CaseCluster &CC = *FirstRight;
9631         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
9632         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
9633         if (LeftSideRank <= RightSideRank) {
9634           // Moving the cluster to the left does not demote it.
9635           ++LastLeft;
9636           ++FirstRight;
9637           continue;
9638         }
9639       } else {
9640         assert(NumRight < NumLeft);
9641         // Consider moving the last element on the left to the right side.
9642         CaseCluster &CC = *LastLeft;
9643         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
9644         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
9645         if (RightSideRank <= LeftSideRank) {
9646           // Moving the cluster to the right does not demot it.
9647           --LastLeft;
9648           --FirstRight;
9649           continue;
9650         }
9651       }
9652     }
9653     break;
9654   }
9655 
9656   assert(LastLeft + 1 == FirstRight);
9657   assert(LastLeft >= W.FirstCluster);
9658   assert(FirstRight <= W.LastCluster);
9659 
9660   // Use the first element on the right as pivot since we will make less-than
9661   // comparisons against it.
9662   CaseClusterIt PivotCluster = FirstRight;
9663   assert(PivotCluster > W.FirstCluster);
9664   assert(PivotCluster <= W.LastCluster);
9665 
9666   CaseClusterIt FirstLeft = W.FirstCluster;
9667   CaseClusterIt LastRight = W.LastCluster;
9668 
9669   const ConstantInt *Pivot = PivotCluster->Low;
9670 
9671   // New blocks will be inserted immediately after the current one.
9672   MachineFunction::iterator BBI(W.MBB);
9673   ++BBI;
9674 
9675   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
9676   // we can branch to its destination directly if it's squeezed exactly in
9677   // between the known lower bound and Pivot - 1.
9678   MachineBasicBlock *LeftMBB;
9679   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
9680       FirstLeft->Low == W.GE &&
9681       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
9682     LeftMBB = FirstLeft->MBB;
9683   } else {
9684     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
9685     FuncInfo.MF->insert(BBI, LeftMBB);
9686     WorkList.push_back(
9687         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
9688     // Put Cond in a virtual register to make it available from the new blocks.
9689     ExportFromCurrentBlock(Cond);
9690   }
9691 
9692   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
9693   // single cluster, RHS.Low == Pivot, and we can branch to its destination
9694   // directly if RHS.High equals the current upper bound.
9695   MachineBasicBlock *RightMBB;
9696   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
9697       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
9698     RightMBB = FirstRight->MBB;
9699   } else {
9700     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
9701     FuncInfo.MF->insert(BBI, RightMBB);
9702     WorkList.push_back(
9703         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
9704     // Put Cond in a virtual register to make it available from the new blocks.
9705     ExportFromCurrentBlock(Cond);
9706   }
9707 
9708   // Create the CaseBlock record that will be used to lower the branch.
9709   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
9710                LeftProb, RightProb);
9711 
9712   if (W.MBB == SwitchMBB)
9713     visitSwitchCase(CB, SwitchMBB);
9714   else
9715     SwitchCases.push_back(CB);
9716 }
9717 
9718 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
9719   // Extract cases from the switch.
9720   BranchProbabilityInfo *BPI = FuncInfo.BPI;
9721   CaseClusterVector Clusters;
9722   Clusters.reserve(SI.getNumCases());
9723   for (auto I : SI.cases()) {
9724     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
9725     const ConstantInt *CaseVal = I.getCaseValue();
9726     BranchProbability Prob =
9727         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
9728             : BranchProbability(1, SI.getNumCases() + 1);
9729     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
9730   }
9731 
9732   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
9733 
9734   // Cluster adjacent cases with the same destination. We do this at all
9735   // optimization levels because it's cheap to do and will make codegen faster
9736   // if there are many clusters.
9737   sortAndRangeify(Clusters);
9738 
9739   if (TM.getOptLevel() != CodeGenOpt::None) {
9740     // Replace an unreachable default with the most popular destination.
9741     // FIXME: Exploit unreachable default more aggressively.
9742     bool UnreachableDefault =
9743         isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg());
9744     if (UnreachableDefault && !Clusters.empty()) {
9745       DenseMap<const BasicBlock *, unsigned> Popularity;
9746       unsigned MaxPop = 0;
9747       const BasicBlock *MaxBB = nullptr;
9748       for (auto I : SI.cases()) {
9749         const BasicBlock *BB = I.getCaseSuccessor();
9750         if (++Popularity[BB] > MaxPop) {
9751           MaxPop = Popularity[BB];
9752           MaxBB = BB;
9753         }
9754       }
9755       // Set new default.
9756       assert(MaxPop > 0 && MaxBB);
9757       DefaultMBB = FuncInfo.MBBMap[MaxBB];
9758 
9759       // Remove cases that were pointing to the destination that is now the
9760       // default.
9761       CaseClusterVector New;
9762       New.reserve(Clusters.size());
9763       for (CaseCluster &CC : Clusters) {
9764         if (CC.MBB != DefaultMBB)
9765           New.push_back(CC);
9766       }
9767       Clusters = std::move(New);
9768     }
9769   }
9770 
9771   // If there is only the default destination, jump there directly.
9772   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
9773   if (Clusters.empty()) {
9774     SwitchMBB->addSuccessor(DefaultMBB);
9775     if (DefaultMBB != NextBlock(SwitchMBB)) {
9776       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
9777                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
9778     }
9779     return;
9780   }
9781 
9782   findJumpTables(Clusters, &SI, DefaultMBB);
9783   findBitTestClusters(Clusters, &SI);
9784 
9785   DEBUG({
9786     dbgs() << "Case clusters: ";
9787     for (const CaseCluster &C : Clusters) {
9788       if (C.Kind == CC_JumpTable) dbgs() << "JT:";
9789       if (C.Kind == CC_BitTests) dbgs() << "BT:";
9790 
9791       C.Low->getValue().print(dbgs(), true);
9792       if (C.Low != C.High) {
9793         dbgs() << '-';
9794         C.High->getValue().print(dbgs(), true);
9795       }
9796       dbgs() << ' ';
9797     }
9798     dbgs() << '\n';
9799   });
9800 
9801   assert(!Clusters.empty());
9802   SwitchWorkList WorkList;
9803   CaseClusterIt First = Clusters.begin();
9804   CaseClusterIt Last = Clusters.end() - 1;
9805   auto DefaultProb = getEdgeProbability(SwitchMBB, DefaultMBB);
9806   WorkList.push_back({SwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
9807 
9808   while (!WorkList.empty()) {
9809     SwitchWorkListItem W = WorkList.back();
9810     WorkList.pop_back();
9811     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
9812 
9813     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
9814         !DefaultMBB->getParent()->getFunction()->optForMinSize()) {
9815       // For optimized builds, lower large range as a balanced binary tree.
9816       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
9817       continue;
9818     }
9819 
9820     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
9821   }
9822 }
9823