xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 04a86966fbf46809d7a165b1f089e4d076f0f8a5)
1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements routines for translating from LLVM IR into SelectionDAG IR.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "SelectionDAGBuilder.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/ADT/Twine.h"
29 #include "llvm/Analysis/AliasAnalysis.h"
30 #include "llvm/Analysis/BlockFrequencyInfo.h"
31 #include "llvm/Analysis/BranchProbabilityInfo.h"
32 #include "llvm/Analysis/ConstantFolding.h"
33 #include "llvm/Analysis/EHPersonalities.h"
34 #include "llvm/Analysis/Loads.h"
35 #include "llvm/Analysis/MemoryLocation.h"
36 #include "llvm/Analysis/ProfileSummaryInfo.h"
37 #include "llvm/Analysis/TargetLibraryInfo.h"
38 #include "llvm/Analysis/ValueTracking.h"
39 #include "llvm/Analysis/VectorUtils.h"
40 #include "llvm/CodeGen/Analysis.h"
41 #include "llvm/CodeGen/FunctionLoweringInfo.h"
42 #include "llvm/CodeGen/GCMetadata.h"
43 #include "llvm/CodeGen/ISDOpcodes.h"
44 #include "llvm/CodeGen/MachineBasicBlock.h"
45 #include "llvm/CodeGen/MachineFrameInfo.h"
46 #include "llvm/CodeGen/MachineFunction.h"
47 #include "llvm/CodeGen/MachineInstr.h"
48 #include "llvm/CodeGen/MachineInstrBuilder.h"
49 #include "llvm/CodeGen/MachineJumpTableInfo.h"
50 #include "llvm/CodeGen/MachineMemOperand.h"
51 #include "llvm/CodeGen/MachineModuleInfo.h"
52 #include "llvm/CodeGen/MachineOperand.h"
53 #include "llvm/CodeGen/MachineRegisterInfo.h"
54 #include "llvm/CodeGen/RuntimeLibcalls.h"
55 #include "llvm/CodeGen/SelectionDAG.h"
56 #include "llvm/CodeGen/SelectionDAGNodes.h"
57 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
58 #include "llvm/CodeGen/StackMaps.h"
59 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
60 #include "llvm/CodeGen/TargetFrameLowering.h"
61 #include "llvm/CodeGen/TargetInstrInfo.h"
62 #include "llvm/CodeGen/TargetLowering.h"
63 #include "llvm/CodeGen/TargetOpcodes.h"
64 #include "llvm/CodeGen/TargetRegisterInfo.h"
65 #include "llvm/CodeGen/TargetSubtargetInfo.h"
66 #include "llvm/CodeGen/ValueTypes.h"
67 #include "llvm/CodeGen/WinEHFuncInfo.h"
68 #include "llvm/IR/Argument.h"
69 #include "llvm/IR/Attributes.h"
70 #include "llvm/IR/BasicBlock.h"
71 #include "llvm/IR/CFG.h"
72 #include "llvm/IR/CallSite.h"
73 #include "llvm/IR/CallingConv.h"
74 #include "llvm/IR/Constant.h"
75 #include "llvm/IR/ConstantRange.h"
76 #include "llvm/IR/Constants.h"
77 #include "llvm/IR/DataLayout.h"
78 #include "llvm/IR/DebugInfoMetadata.h"
79 #include "llvm/IR/DebugLoc.h"
80 #include "llvm/IR/DerivedTypes.h"
81 #include "llvm/IR/Function.h"
82 #include "llvm/IR/GetElementPtrTypeIterator.h"
83 #include "llvm/IR/InlineAsm.h"
84 #include "llvm/IR/InstrTypes.h"
85 #include "llvm/IR/Instruction.h"
86 #include "llvm/IR/Instructions.h"
87 #include "llvm/IR/IntrinsicInst.h"
88 #include "llvm/IR/Intrinsics.h"
89 #include "llvm/IR/IntrinsicsAArch64.h"
90 #include "llvm/IR/IntrinsicsWebAssembly.h"
91 #include "llvm/IR/LLVMContext.h"
92 #include "llvm/IR/Metadata.h"
93 #include "llvm/IR/Module.h"
94 #include "llvm/IR/Operator.h"
95 #include "llvm/IR/PatternMatch.h"
96 #include "llvm/IR/Statepoint.h"
97 #include "llvm/IR/Type.h"
98 #include "llvm/IR/User.h"
99 #include "llvm/IR/Value.h"
100 #include "llvm/MC/MCContext.h"
101 #include "llvm/MC/MCSymbol.h"
102 #include "llvm/Support/AtomicOrdering.h"
103 #include "llvm/Support/BranchProbability.h"
104 #include "llvm/Support/Casting.h"
105 #include "llvm/Support/CodeGen.h"
106 #include "llvm/Support/CommandLine.h"
107 #include "llvm/Support/Compiler.h"
108 #include "llvm/Support/Debug.h"
109 #include "llvm/Support/ErrorHandling.h"
110 #include "llvm/Support/MachineValueType.h"
111 #include "llvm/Support/MathExtras.h"
112 #include "llvm/Support/raw_ostream.h"
113 #include "llvm/Target/TargetIntrinsicInfo.h"
114 #include "llvm/Target/TargetMachine.h"
115 #include "llvm/Target/TargetOptions.h"
116 #include "llvm/Transforms/Utils/Local.h"
117 #include <algorithm>
118 #include <cassert>
119 #include <cstddef>
120 #include <cstdint>
121 #include <cstring>
122 #include <iterator>
123 #include <limits>
124 #include <numeric>
125 #include <tuple>
126 #include <utility>
127 #include <vector>
128 
129 using namespace llvm;
130 using namespace PatternMatch;
131 using namespace SwitchCG;
132 
133 #define DEBUG_TYPE "isel"
134 
135 /// LimitFloatPrecision - Generate low-precision inline sequences for
136 /// some float libcalls (6, 8 or 12 bits).
137 static unsigned LimitFloatPrecision;
138 
139 static cl::opt<unsigned, true>
140     LimitFPPrecision("limit-float-precision",
141                      cl::desc("Generate low-precision inline sequences "
142                               "for some float libcalls"),
143                      cl::location(LimitFloatPrecision), cl::Hidden,
144                      cl::init(0));
145 
146 static cl::opt<unsigned> SwitchPeelThreshold(
147     "switch-peel-threshold", cl::Hidden, cl::init(66),
148     cl::desc("Set the case probability threshold for peeling the case from a "
149              "switch statement. A value greater than 100 will void this "
150              "optimization"));
151 
152 // Limit the width of DAG chains. This is important in general to prevent
153 // DAG-based analysis from blowing up. For example, alias analysis and
154 // load clustering may not complete in reasonable time. It is difficult to
155 // recognize and avoid this situation within each individual analysis, and
156 // future analyses are likely to have the same behavior. Limiting DAG width is
157 // the safe approach and will be especially important with global DAGs.
158 //
159 // MaxParallelChains default is arbitrarily high to avoid affecting
160 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
161 // sequence over this should have been converted to llvm.memcpy by the
162 // frontend. It is easy to induce this behavior with .ll code such as:
163 // %buffer = alloca [4096 x i8]
164 // %data = load [4096 x i8]* %argPtr
165 // store [4096 x i8] %data, [4096 x i8]* %buffer
166 static const unsigned MaxParallelChains = 64;
167 
168 // Return the calling convention if the Value passed requires ABI mangling as it
169 // is a parameter to a function or a return value from a function which is not
170 // an intrinsic.
171 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) {
172   if (auto *R = dyn_cast<ReturnInst>(V))
173     return R->getParent()->getParent()->getCallingConv();
174 
175   if (auto *CI = dyn_cast<CallInst>(V)) {
176     const bool IsInlineAsm = CI->isInlineAsm();
177     const bool IsIndirectFunctionCall =
178         !IsInlineAsm && !CI->getCalledFunction();
179 
180     // It is possible that the call instruction is an inline asm statement or an
181     // indirect function call in which case the return value of
182     // getCalledFunction() would be nullptr.
183     const bool IsInstrinsicCall =
184         !IsInlineAsm && !IsIndirectFunctionCall &&
185         CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic;
186 
187     if (!IsInlineAsm && !IsInstrinsicCall)
188       return CI->getCallingConv();
189   }
190 
191   return None;
192 }
193 
194 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
195                                       const SDValue *Parts, unsigned NumParts,
196                                       MVT PartVT, EVT ValueVT, const Value *V,
197                                       Optional<CallingConv::ID> CC);
198 
199 /// getCopyFromParts - Create a value that contains the specified legal parts
200 /// combined into the value they represent.  If the parts combine to a type
201 /// larger than ValueVT then AssertOp can be used to specify whether the extra
202 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
203 /// (ISD::AssertSext).
204 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
205                                 const SDValue *Parts, unsigned NumParts,
206                                 MVT PartVT, EVT ValueVT, const Value *V,
207                                 Optional<CallingConv::ID> CC = None,
208                                 Optional<ISD::NodeType> AssertOp = None) {
209   if (ValueVT.isVector())
210     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
211                                   CC);
212 
213   assert(NumParts > 0 && "No parts to assemble!");
214   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
215   SDValue Val = Parts[0];
216 
217   if (NumParts > 1) {
218     // Assemble the value from multiple parts.
219     if (ValueVT.isInteger()) {
220       unsigned PartBits = PartVT.getSizeInBits();
221       unsigned ValueBits = ValueVT.getSizeInBits();
222 
223       // Assemble the power of 2 part.
224       unsigned RoundParts =
225           (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
226       unsigned RoundBits = PartBits * RoundParts;
227       EVT RoundVT = RoundBits == ValueBits ?
228         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
229       SDValue Lo, Hi;
230 
231       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
232 
233       if (RoundParts > 2) {
234         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
235                               PartVT, HalfVT, V);
236         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
237                               RoundParts / 2, PartVT, HalfVT, V);
238       } else {
239         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
240         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
241       }
242 
243       if (DAG.getDataLayout().isBigEndian())
244         std::swap(Lo, Hi);
245 
246       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
247 
248       if (RoundParts < NumParts) {
249         // Assemble the trailing non-power-of-2 part.
250         unsigned OddParts = NumParts - RoundParts;
251         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
252         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
253                               OddVT, V, CC);
254 
255         // Combine the round and odd parts.
256         Lo = Val;
257         if (DAG.getDataLayout().isBigEndian())
258           std::swap(Lo, Hi);
259         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
260         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
261         Hi =
262             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
263                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
264                                         TLI.getPointerTy(DAG.getDataLayout())));
265         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
266         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
267       }
268     } else if (PartVT.isFloatingPoint()) {
269       // FP split into multiple FP parts (for ppcf128)
270       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
271              "Unexpected split");
272       SDValue Lo, Hi;
273       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
274       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
275       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
276         std::swap(Lo, Hi);
277       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
278     } else {
279       // FP split into integer parts (soft fp)
280       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
281              !PartVT.isVector() && "Unexpected split");
282       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
283       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
284     }
285   }
286 
287   // There is now one part, held in Val.  Correct it to match ValueVT.
288   // PartEVT is the type of the register class that holds the value.
289   // ValueVT is the type of the inline asm operation.
290   EVT PartEVT = Val.getValueType();
291 
292   if (PartEVT == ValueVT)
293     return Val;
294 
295   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
296       ValueVT.bitsLT(PartEVT)) {
297     // For an FP value in an integer part, we need to truncate to the right
298     // width first.
299     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
300     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
301   }
302 
303   // Handle types that have the same size.
304   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
305     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
306 
307   // Handle types with different sizes.
308   if (PartEVT.isInteger() && ValueVT.isInteger()) {
309     if (ValueVT.bitsLT(PartEVT)) {
310       // For a truncate, see if we have any information to
311       // indicate whether the truncated bits will always be
312       // zero or sign-extension.
313       if (AssertOp.hasValue())
314         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
315                           DAG.getValueType(ValueVT));
316       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
317     }
318     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
319   }
320 
321   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
322     // FP_ROUND's are always exact here.
323     if (ValueVT.bitsLT(Val.getValueType()))
324       return DAG.getNode(
325           ISD::FP_ROUND, DL, ValueVT, Val,
326           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
327 
328     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
329   }
330 
331   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
332   // then truncating.
333   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
334       ValueVT.bitsLT(PartEVT)) {
335     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
336     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
337   }
338 
339   report_fatal_error("Unknown mismatch in getCopyFromParts!");
340 }
341 
342 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
343                                               const Twine &ErrMsg) {
344   const Instruction *I = dyn_cast_or_null<Instruction>(V);
345   if (!V)
346     return Ctx.emitError(ErrMsg);
347 
348   const char *AsmError = ", possible invalid constraint for vector type";
349   if (const CallInst *CI = dyn_cast<CallInst>(I))
350     if (isa<InlineAsm>(CI->getCalledValue()))
351       return Ctx.emitError(I, ErrMsg + AsmError);
352 
353   return Ctx.emitError(I, ErrMsg);
354 }
355 
356 /// getCopyFromPartsVector - Create a value that contains the specified legal
357 /// parts combined into the value they represent.  If the parts combine to a
358 /// type larger than ValueVT then AssertOp can be used to specify whether the
359 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
360 /// ValueVT (ISD::AssertSext).
361 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
362                                       const SDValue *Parts, unsigned NumParts,
363                                       MVT PartVT, EVT ValueVT, const Value *V,
364                                       Optional<CallingConv::ID> CallConv) {
365   assert(ValueVT.isVector() && "Not a vector value");
366   assert(NumParts > 0 && "No parts to assemble!");
367   const bool IsABIRegCopy = CallConv.hasValue();
368 
369   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
370   SDValue Val = Parts[0];
371 
372   // Handle a multi-element vector.
373   if (NumParts > 1) {
374     EVT IntermediateVT;
375     MVT RegisterVT;
376     unsigned NumIntermediates;
377     unsigned NumRegs;
378 
379     if (IsABIRegCopy) {
380       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
381           *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
382           NumIntermediates, RegisterVT);
383     } else {
384       NumRegs =
385           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
386                                      NumIntermediates, RegisterVT);
387     }
388 
389     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
390     NumParts = NumRegs; // Silence a compiler warning.
391     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
392     assert(RegisterVT.getSizeInBits() ==
393            Parts[0].getSimpleValueType().getSizeInBits() &&
394            "Part type sizes don't match!");
395 
396     // Assemble the parts into intermediate operands.
397     SmallVector<SDValue, 8> Ops(NumIntermediates);
398     if (NumIntermediates == NumParts) {
399       // If the register was not expanded, truncate or copy the value,
400       // as appropriate.
401       for (unsigned i = 0; i != NumParts; ++i)
402         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
403                                   PartVT, IntermediateVT, V);
404     } else if (NumParts > 0) {
405       // If the intermediate type was expanded, build the intermediate
406       // operands from the parts.
407       assert(NumParts % NumIntermediates == 0 &&
408              "Must expand into a divisible number of parts!");
409       unsigned Factor = NumParts / NumIntermediates;
410       for (unsigned i = 0; i != NumIntermediates; ++i)
411         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
412                                   PartVT, IntermediateVT, V);
413     }
414 
415     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
416     // intermediate operands.
417     EVT BuiltVectorTy =
418         EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
419                          (IntermediateVT.isVector()
420                               ? IntermediateVT.getVectorNumElements() * NumParts
421                               : NumIntermediates));
422     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
423                                                 : ISD::BUILD_VECTOR,
424                       DL, BuiltVectorTy, Ops);
425   }
426 
427   // There is now one part, held in Val.  Correct it to match ValueVT.
428   EVT PartEVT = Val.getValueType();
429 
430   if (PartEVT == ValueVT)
431     return Val;
432 
433   if (PartEVT.isVector()) {
434     // If the element type of the source/dest vectors are the same, but the
435     // parts vector has more elements than the value vector, then we have a
436     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
437     // elements we want.
438     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
439       assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
440              "Cannot narrow, it would be a lossy transformation");
441       return DAG.getNode(
442           ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
443           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
444     }
445 
446     // Vector/Vector bitcast.
447     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
448       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
449 
450     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
451       "Cannot handle this kind of promotion");
452     // Promoted vector extract
453     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
454 
455   }
456 
457   // Trivial bitcast if the types are the same size and the destination
458   // vector type is legal.
459   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
460       TLI.isTypeLegal(ValueVT))
461     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
462 
463   if (ValueVT.getVectorNumElements() != 1) {
464      // Certain ABIs require that vectors are passed as integers. For vectors
465      // are the same size, this is an obvious bitcast.
466      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
467        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
468      } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
469        // Bitcast Val back the original type and extract the corresponding
470        // vector we want.
471        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
472        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
473                                            ValueVT.getVectorElementType(), Elts);
474        Val = DAG.getBitcast(WiderVecType, Val);
475        return DAG.getNode(
476            ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
477            DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
478      }
479 
480      diagnosePossiblyInvalidConstraint(
481          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
482      return DAG.getUNDEF(ValueVT);
483   }
484 
485   // Handle cases such as i8 -> <1 x i1>
486   EVT ValueSVT = ValueVT.getVectorElementType();
487   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT)
488     Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
489                                     : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
490 
491   return DAG.getBuildVector(ValueVT, DL, Val);
492 }
493 
494 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
495                                  SDValue Val, SDValue *Parts, unsigned NumParts,
496                                  MVT PartVT, const Value *V,
497                                  Optional<CallingConv::ID> CallConv);
498 
499 /// getCopyToParts - Create a series of nodes that contain the specified value
500 /// split into legal parts.  If the parts contain more bits than Val, then, for
501 /// integers, ExtendKind can be used to specify how to generate the extra bits.
502 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
503                            SDValue *Parts, unsigned NumParts, MVT PartVT,
504                            const Value *V,
505                            Optional<CallingConv::ID> CallConv = None,
506                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
507   EVT ValueVT = Val.getValueType();
508 
509   // Handle the vector case separately.
510   if (ValueVT.isVector())
511     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
512                                 CallConv);
513 
514   unsigned PartBits = PartVT.getSizeInBits();
515   unsigned OrigNumParts = NumParts;
516   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
517          "Copying to an illegal type!");
518 
519   if (NumParts == 0)
520     return;
521 
522   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
523   EVT PartEVT = PartVT;
524   if (PartEVT == ValueVT) {
525     assert(NumParts == 1 && "No-op copy with multiple parts!");
526     Parts[0] = Val;
527     return;
528   }
529 
530   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
531     // If the parts cover more bits than the value has, promote the value.
532     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
533       assert(NumParts == 1 && "Do not know what to promote to!");
534       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
535     } else {
536       if (ValueVT.isFloatingPoint()) {
537         // FP values need to be bitcast, then extended if they are being put
538         // into a larger container.
539         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
540         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
541       }
542       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
543              ValueVT.isInteger() &&
544              "Unknown mismatch!");
545       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
546       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
547       if (PartVT == MVT::x86mmx)
548         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
549     }
550   } else if (PartBits == ValueVT.getSizeInBits()) {
551     // Different types of the same size.
552     assert(NumParts == 1 && PartEVT != ValueVT);
553     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
554   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
555     // If the parts cover less bits than value has, truncate the value.
556     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
557            ValueVT.isInteger() &&
558            "Unknown mismatch!");
559     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
560     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
561     if (PartVT == MVT::x86mmx)
562       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
563   }
564 
565   // The value may have changed - recompute ValueVT.
566   ValueVT = Val.getValueType();
567   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
568          "Failed to tile the value with PartVT!");
569 
570   if (NumParts == 1) {
571     if (PartEVT != ValueVT) {
572       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
573                                         "scalar-to-vector conversion failed");
574       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
575     }
576 
577     Parts[0] = Val;
578     return;
579   }
580 
581   // Expand the value into multiple parts.
582   if (NumParts & (NumParts - 1)) {
583     // The number of parts is not a power of 2.  Split off and copy the tail.
584     assert(PartVT.isInteger() && ValueVT.isInteger() &&
585            "Do not know what to expand to!");
586     unsigned RoundParts = 1 << Log2_32(NumParts);
587     unsigned RoundBits = RoundParts * PartBits;
588     unsigned OddParts = NumParts - RoundParts;
589     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
590       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
591 
592     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
593                    CallConv);
594 
595     if (DAG.getDataLayout().isBigEndian())
596       // The odd parts were reversed by getCopyToParts - unreverse them.
597       std::reverse(Parts + RoundParts, Parts + NumParts);
598 
599     NumParts = RoundParts;
600     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
601     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
602   }
603 
604   // The number of parts is a power of 2.  Repeatedly bisect the value using
605   // EXTRACT_ELEMENT.
606   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
607                          EVT::getIntegerVT(*DAG.getContext(),
608                                            ValueVT.getSizeInBits()),
609                          Val);
610 
611   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
612     for (unsigned i = 0; i < NumParts; i += StepSize) {
613       unsigned ThisBits = StepSize * PartBits / 2;
614       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
615       SDValue &Part0 = Parts[i];
616       SDValue &Part1 = Parts[i+StepSize/2];
617 
618       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
619                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
620       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
621                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
622 
623       if (ThisBits == PartBits && ThisVT != PartVT) {
624         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
625         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
626       }
627     }
628   }
629 
630   if (DAG.getDataLayout().isBigEndian())
631     std::reverse(Parts, Parts + OrigNumParts);
632 }
633 
634 static SDValue widenVectorToPartType(SelectionDAG &DAG,
635                                      SDValue Val, const SDLoc &DL, EVT PartVT) {
636   if (!PartVT.isVector())
637     return SDValue();
638 
639   EVT ValueVT = Val.getValueType();
640   unsigned PartNumElts = PartVT.getVectorNumElements();
641   unsigned ValueNumElts = ValueVT.getVectorNumElements();
642   if (PartNumElts > ValueNumElts &&
643       PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
644     EVT ElementVT = PartVT.getVectorElementType();
645     // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
646     // undef elements.
647     SmallVector<SDValue, 16> Ops;
648     DAG.ExtractVectorElements(Val, Ops);
649     SDValue EltUndef = DAG.getUNDEF(ElementVT);
650     for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
651       Ops.push_back(EltUndef);
652 
653     // FIXME: Use CONCAT for 2x -> 4x.
654     return DAG.getBuildVector(PartVT, DL, Ops);
655   }
656 
657   return SDValue();
658 }
659 
660 /// getCopyToPartsVector - Create a series of nodes that contain the specified
661 /// value split into legal parts.
662 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
663                                  SDValue Val, SDValue *Parts, unsigned NumParts,
664                                  MVT PartVT, const Value *V,
665                                  Optional<CallingConv::ID> CallConv) {
666   EVT ValueVT = Val.getValueType();
667   assert(ValueVT.isVector() && "Not a vector");
668   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
669   const bool IsABIRegCopy = CallConv.hasValue();
670 
671   if (NumParts == 1) {
672     EVT PartEVT = PartVT;
673     if (PartEVT == ValueVT) {
674       // Nothing to do.
675     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
676       // Bitconvert vector->vector case.
677       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
678     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
679       Val = Widened;
680     } else if (PartVT.isVector() &&
681                PartEVT.getVectorElementType().bitsGE(
682                  ValueVT.getVectorElementType()) &&
683                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
684 
685       // Promoted vector extract
686       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
687     } else {
688       if (ValueVT.getVectorNumElements() == 1) {
689         Val = DAG.getNode(
690             ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
691             DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
692       } else {
693         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
694                "lossy conversion of vector to scalar type");
695         EVT IntermediateType =
696             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
697         Val = DAG.getBitcast(IntermediateType, Val);
698         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
699       }
700     }
701 
702     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
703     Parts[0] = Val;
704     return;
705   }
706 
707   // Handle a multi-element vector.
708   EVT IntermediateVT;
709   MVT RegisterVT;
710   unsigned NumIntermediates;
711   unsigned NumRegs;
712   if (IsABIRegCopy) {
713     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
714         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
715         NumIntermediates, RegisterVT);
716   } else {
717     NumRegs =
718         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
719                                    NumIntermediates, RegisterVT);
720   }
721 
722   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
723   NumParts = NumRegs; // Silence a compiler warning.
724   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
725 
726   unsigned IntermediateNumElts = IntermediateVT.isVector() ?
727     IntermediateVT.getVectorNumElements() : 1;
728 
729   // Convert the vector to the appropriate type if necessary.
730   unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts;
731 
732   EVT BuiltVectorTy = EVT::getVectorVT(
733       *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
734   MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
735   if (ValueVT != BuiltVectorTy) {
736     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
737       Val = Widened;
738 
739     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
740   }
741 
742   // Split the vector into intermediate operands.
743   SmallVector<SDValue, 8> Ops(NumIntermediates);
744   for (unsigned i = 0; i != NumIntermediates; ++i) {
745     if (IntermediateVT.isVector()) {
746       Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
747                            DAG.getConstant(i * IntermediateNumElts, DL, IdxVT));
748     } else {
749       Ops[i] = DAG.getNode(
750           ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
751           DAG.getConstant(i, DL, IdxVT));
752     }
753   }
754 
755   // Split the intermediate operands into legal parts.
756   if (NumParts == NumIntermediates) {
757     // If the register was not expanded, promote or copy the value,
758     // as appropriate.
759     for (unsigned i = 0; i != NumParts; ++i)
760       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
761   } else if (NumParts > 0) {
762     // If the intermediate type was expanded, split each the value into
763     // legal parts.
764     assert(NumIntermediates != 0 && "division by zero");
765     assert(NumParts % NumIntermediates == 0 &&
766            "Must expand into a divisible number of parts!");
767     unsigned Factor = NumParts / NumIntermediates;
768     for (unsigned i = 0; i != NumIntermediates; ++i)
769       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
770                      CallConv);
771   }
772 }
773 
774 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
775                            EVT valuevt, Optional<CallingConv::ID> CC)
776     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
777       RegCount(1, regs.size()), CallConv(CC) {}
778 
779 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
780                            const DataLayout &DL, unsigned Reg, Type *Ty,
781                            Optional<CallingConv::ID> CC) {
782   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
783 
784   CallConv = CC;
785 
786   for (EVT ValueVT : ValueVTs) {
787     unsigned NumRegs =
788         isABIMangled()
789             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
790             : TLI.getNumRegisters(Context, ValueVT);
791     MVT RegisterVT =
792         isABIMangled()
793             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
794             : TLI.getRegisterType(Context, ValueVT);
795     for (unsigned i = 0; i != NumRegs; ++i)
796       Regs.push_back(Reg + i);
797     RegVTs.push_back(RegisterVT);
798     RegCount.push_back(NumRegs);
799     Reg += NumRegs;
800   }
801 }
802 
803 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
804                                       FunctionLoweringInfo &FuncInfo,
805                                       const SDLoc &dl, SDValue &Chain,
806                                       SDValue *Flag, const Value *V) const {
807   // A Value with type {} or [0 x %t] needs no registers.
808   if (ValueVTs.empty())
809     return SDValue();
810 
811   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
812 
813   // Assemble the legal parts into the final values.
814   SmallVector<SDValue, 4> Values(ValueVTs.size());
815   SmallVector<SDValue, 8> Parts;
816   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
817     // Copy the legal parts from the registers.
818     EVT ValueVT = ValueVTs[Value];
819     unsigned NumRegs = RegCount[Value];
820     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
821                                           *DAG.getContext(),
822                                           CallConv.getValue(), RegVTs[Value])
823                                     : RegVTs[Value];
824 
825     Parts.resize(NumRegs);
826     for (unsigned i = 0; i != NumRegs; ++i) {
827       SDValue P;
828       if (!Flag) {
829         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
830       } else {
831         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
832         *Flag = P.getValue(2);
833       }
834 
835       Chain = P.getValue(1);
836       Parts[i] = P;
837 
838       // If the source register was virtual and if we know something about it,
839       // add an assert node.
840       if (!Register::isVirtualRegister(Regs[Part + i]) ||
841           !RegisterVT.isInteger())
842         continue;
843 
844       const FunctionLoweringInfo::LiveOutInfo *LOI =
845         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
846       if (!LOI)
847         continue;
848 
849       unsigned RegSize = RegisterVT.getScalarSizeInBits();
850       unsigned NumSignBits = LOI->NumSignBits;
851       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
852 
853       if (NumZeroBits == RegSize) {
854         // The current value is a zero.
855         // Explicitly express that as it would be easier for
856         // optimizations to kick in.
857         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
858         continue;
859       }
860 
861       // FIXME: We capture more information than the dag can represent.  For
862       // now, just use the tightest assertzext/assertsext possible.
863       bool isSExt;
864       EVT FromVT(MVT::Other);
865       if (NumZeroBits) {
866         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
867         isSExt = false;
868       } else if (NumSignBits > 1) {
869         FromVT =
870             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
871         isSExt = true;
872       } else {
873         continue;
874       }
875       // Add an assertion node.
876       assert(FromVT != MVT::Other);
877       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
878                              RegisterVT, P, DAG.getValueType(FromVT));
879     }
880 
881     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
882                                      RegisterVT, ValueVT, V, CallConv);
883     Part += NumRegs;
884     Parts.clear();
885   }
886 
887   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
888 }
889 
890 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
891                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
892                                  const Value *V,
893                                  ISD::NodeType PreferredExtendType) const {
894   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
895   ISD::NodeType ExtendKind = PreferredExtendType;
896 
897   // Get the list of the values's legal parts.
898   unsigned NumRegs = Regs.size();
899   SmallVector<SDValue, 8> Parts(NumRegs);
900   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
901     unsigned NumParts = RegCount[Value];
902 
903     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
904                                           *DAG.getContext(),
905                                           CallConv.getValue(), RegVTs[Value])
906                                     : RegVTs[Value];
907 
908     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
909       ExtendKind = ISD::ZERO_EXTEND;
910 
911     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
912                    NumParts, RegisterVT, V, CallConv, ExtendKind);
913     Part += NumParts;
914   }
915 
916   // Copy the parts into the registers.
917   SmallVector<SDValue, 8> Chains(NumRegs);
918   for (unsigned i = 0; i != NumRegs; ++i) {
919     SDValue Part;
920     if (!Flag) {
921       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
922     } else {
923       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
924       *Flag = Part.getValue(1);
925     }
926 
927     Chains[i] = Part.getValue(0);
928   }
929 
930   if (NumRegs == 1 || Flag)
931     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
932     // flagged to it. That is the CopyToReg nodes and the user are considered
933     // a single scheduling unit. If we create a TokenFactor and return it as
934     // chain, then the TokenFactor is both a predecessor (operand) of the
935     // user as well as a successor (the TF operands are flagged to the user).
936     // c1, f1 = CopyToReg
937     // c2, f2 = CopyToReg
938     // c3     = TokenFactor c1, c2
939     // ...
940     //        = op c3, ..., f2
941     Chain = Chains[NumRegs-1];
942   else
943     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
944 }
945 
946 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
947                                         unsigned MatchingIdx, const SDLoc &dl,
948                                         SelectionDAG &DAG,
949                                         std::vector<SDValue> &Ops) const {
950   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
951 
952   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
953   if (HasMatching)
954     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
955   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
956     // Put the register class of the virtual registers in the flag word.  That
957     // way, later passes can recompute register class constraints for inline
958     // assembly as well as normal instructions.
959     // Don't do this for tied operands that can use the regclass information
960     // from the def.
961     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
962     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
963     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
964   }
965 
966   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
967   Ops.push_back(Res);
968 
969   if (Code == InlineAsm::Kind_Clobber) {
970     // Clobbers should always have a 1:1 mapping with registers, and may
971     // reference registers that have illegal (e.g. vector) types. Hence, we
972     // shouldn't try to apply any sort of splitting logic to them.
973     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
974            "No 1:1 mapping from clobbers to regs?");
975     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
976     (void)SP;
977     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
978       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
979       assert(
980           (Regs[I] != SP ||
981            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
982           "If we clobbered the stack pointer, MFI should know about it.");
983     }
984     return;
985   }
986 
987   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
988     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
989     MVT RegisterVT = RegVTs[Value];
990     for (unsigned i = 0; i != NumRegs; ++i) {
991       assert(Reg < Regs.size() && "Mismatch in # registers expected");
992       unsigned TheReg = Regs[Reg++];
993       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
994     }
995   }
996 }
997 
998 SmallVector<std::pair<unsigned, unsigned>, 4>
999 RegsForValue::getRegsAndSizes() const {
1000   SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
1001   unsigned I = 0;
1002   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1003     unsigned RegCount = std::get<0>(CountAndVT);
1004     MVT RegisterVT = std::get<1>(CountAndVT);
1005     unsigned RegisterSize = RegisterVT.getSizeInBits();
1006     for (unsigned E = I + RegCount; I != E; ++I)
1007       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1008   }
1009   return OutVec;
1010 }
1011 
1012 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1013                                const TargetLibraryInfo *li) {
1014   AA = aa;
1015   GFI = gfi;
1016   LibInfo = li;
1017   DL = &DAG.getDataLayout();
1018   Context = DAG.getContext();
1019   LPadToCallSiteMap.clear();
1020   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1021 }
1022 
1023 void SelectionDAGBuilder::clear() {
1024   NodeMap.clear();
1025   UnusedArgNodeMap.clear();
1026   PendingLoads.clear();
1027   PendingExports.clear();
1028   PendingConstrainedFP.clear();
1029   PendingConstrainedFPStrict.clear();
1030   CurInst = nullptr;
1031   HasTailCall = false;
1032   SDNodeOrder = LowestSDNodeOrder;
1033   StatepointLowering.clear();
1034 }
1035 
1036 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1037   DanglingDebugInfoMap.clear();
1038 }
1039 
1040 SDValue SelectionDAGBuilder::getMemoryRoot() {
1041   if (PendingLoads.empty())
1042     return DAG.getRoot();
1043 
1044   if (PendingLoads.size() == 1) {
1045     SDValue Root = PendingLoads[0];
1046     DAG.setRoot(Root);
1047     PendingLoads.clear();
1048     return Root;
1049   }
1050 
1051   // Otherwise, we have to make a token factor node.
1052   SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads);
1053   PendingLoads.clear();
1054   DAG.setRoot(Root);
1055   return Root;
1056 }
1057 
1058 SDValue SelectionDAGBuilder::getRoot() {
1059   // Chain up all pending constrained intrinsics together with all
1060   // pending loads, by simply appending them to PendingLoads and
1061   // then calling getMemoryRoot().
1062   PendingLoads.reserve(PendingLoads.size() +
1063                        PendingConstrainedFP.size() +
1064                        PendingConstrainedFPStrict.size());
1065   PendingLoads.append(PendingConstrainedFP.begin(),
1066                       PendingConstrainedFP.end());
1067   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1068                       PendingConstrainedFPStrict.end());
1069   PendingConstrainedFP.clear();
1070   PendingConstrainedFPStrict.clear();
1071   return getMemoryRoot();
1072 }
1073 
1074 SDValue SelectionDAGBuilder::getControlRoot() {
1075   SDValue Root = DAG.getRoot();
1076 
1077   // We need to emit pending fpexcept.strict constrained intrinsics,
1078   // so append them to the PendingExports list.
1079   PendingExports.append(PendingConstrainedFPStrict.begin(),
1080                         PendingConstrainedFPStrict.end());
1081   PendingConstrainedFPStrict.clear();
1082 
1083   if (PendingExports.empty())
1084     return Root;
1085 
1086   // Turn all of the CopyToReg chains into one factored node.
1087   if (Root.getOpcode() != ISD::EntryToken) {
1088     unsigned i = 0, e = PendingExports.size();
1089     for (; i != e; ++i) {
1090       assert(PendingExports[i].getNode()->getNumOperands() > 1);
1091       if (PendingExports[i].getNode()->getOperand(0) == Root)
1092         break;  // Don't add the root if we already indirectly depend on it.
1093     }
1094 
1095     if (i == e)
1096       PendingExports.push_back(Root);
1097   }
1098 
1099   Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
1100                      PendingExports);
1101   PendingExports.clear();
1102   DAG.setRoot(Root);
1103   return Root;
1104 }
1105 
1106 void SelectionDAGBuilder::visit(const Instruction &I) {
1107   // Set up outgoing PHI node register values before emitting the terminator.
1108   if (I.isTerminator()) {
1109     HandlePHINodesInSuccessorBlocks(I.getParent());
1110   }
1111 
1112   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1113   if (!isa<DbgInfoIntrinsic>(I))
1114     ++SDNodeOrder;
1115 
1116   CurInst = &I;
1117 
1118   visit(I.getOpcode(), I);
1119 
1120   if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
1121     // Propagate the fast-math-flags of this IR instruction to the DAG node that
1122     // maps to this instruction.
1123     // TODO: We could handle all flags (nsw, etc) here.
1124     // TODO: If an IR instruction maps to >1 node, only the final node will have
1125     //       flags set.
1126     if (SDNode *Node = getNodeForIRValue(&I)) {
1127       SDNodeFlags IncomingFlags;
1128       IncomingFlags.copyFMF(*FPMO);
1129       if (!Node->getFlags().isDefined())
1130         Node->setFlags(IncomingFlags);
1131       else
1132         Node->intersectFlagsWith(IncomingFlags);
1133     }
1134   }
1135   // Constrained FP intrinsics with fpexcept.ignore should also get
1136   // the NoFPExcept flag.
1137   if (auto *FPI = dyn_cast<ConstrainedFPIntrinsic>(&I))
1138     if (FPI->getExceptionBehavior() == fp::ExceptionBehavior::ebIgnore)
1139       if (SDNode *Node = getNodeForIRValue(&I)) {
1140         SDNodeFlags Flags = Node->getFlags();
1141         Flags.setNoFPExcept(true);
1142         Node->setFlags(Flags);
1143       }
1144 
1145   if (!I.isTerminator() && !HasTailCall &&
1146       !isStatepoint(&I)) // statepoints handle their exports internally
1147     CopyToExportRegsIfNeeded(&I);
1148 
1149   CurInst = nullptr;
1150 }
1151 
1152 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1153   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1154 }
1155 
1156 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1157   // Note: this doesn't use InstVisitor, because it has to work with
1158   // ConstantExpr's in addition to instructions.
1159   switch (Opcode) {
1160   default: llvm_unreachable("Unknown instruction type encountered!");
1161     // Build the switch statement using the Instruction.def file.
1162 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1163     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1164 #include "llvm/IR/Instruction.def"
1165   }
1166 }
1167 
1168 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1169                                                 const DIExpression *Expr) {
1170   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1171     const DbgValueInst *DI = DDI.getDI();
1172     DIVariable *DanglingVariable = DI->getVariable();
1173     DIExpression *DanglingExpr = DI->getExpression();
1174     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1175       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1176       return true;
1177     }
1178     return false;
1179   };
1180 
1181   for (auto &DDIMI : DanglingDebugInfoMap) {
1182     DanglingDebugInfoVector &DDIV = DDIMI.second;
1183 
1184     // If debug info is to be dropped, run it through final checks to see
1185     // whether it can be salvaged.
1186     for (auto &DDI : DDIV)
1187       if (isMatchingDbgValue(DDI))
1188         salvageUnresolvedDbgValue(DDI);
1189 
1190     DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
1191   }
1192 }
1193 
1194 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1195 // generate the debug data structures now that we've seen its definition.
1196 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1197                                                    SDValue Val) {
1198   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1199   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1200     return;
1201 
1202   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1203   for (auto &DDI : DDIV) {
1204     const DbgValueInst *DI = DDI.getDI();
1205     assert(DI && "Ill-formed DanglingDebugInfo");
1206     DebugLoc dl = DDI.getdl();
1207     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1208     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1209     DILocalVariable *Variable = DI->getVariable();
1210     DIExpression *Expr = DI->getExpression();
1211     assert(Variable->isValidLocationForIntrinsic(dl) &&
1212            "Expected inlined-at fields to agree");
1213     SDDbgValue *SDV;
1214     if (Val.getNode()) {
1215       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1216       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1217       // we couldn't resolve it directly when examining the DbgValue intrinsic
1218       // in the first place we should not be more successful here). Unless we
1219       // have some test case that prove this to be correct we should avoid
1220       // calling EmitFuncArgumentDbgValue here.
1221       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1222         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1223                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1224         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1225         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1226         // inserted after the definition of Val when emitting the instructions
1227         // after ISel. An alternative could be to teach
1228         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1229         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1230                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1231                    << ValSDNodeOrder << "\n");
1232         SDV = getDbgValue(Val, Variable, Expr, dl,
1233                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1234         DAG.AddDbgValue(SDV, Val.getNode(), false);
1235       } else
1236         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1237                           << "in EmitFuncArgumentDbgValue\n");
1238     } else {
1239       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1240       auto Undef =
1241           UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1242       auto SDV =
1243           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1244       DAG.AddDbgValue(SDV, nullptr, false);
1245     }
1246   }
1247   DDIV.clear();
1248 }
1249 
1250 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1251   Value *V = DDI.getDI()->getValue();
1252   DILocalVariable *Var = DDI.getDI()->getVariable();
1253   DIExpression *Expr = DDI.getDI()->getExpression();
1254   DebugLoc DL = DDI.getdl();
1255   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1256   unsigned SDOrder = DDI.getSDNodeOrder();
1257 
1258   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1259   // that DW_OP_stack_value is desired.
1260   assert(isa<DbgValueInst>(DDI.getDI()));
1261   bool StackValue = true;
1262 
1263   // Can this Value can be encoded without any further work?
1264   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder))
1265     return;
1266 
1267   // Attempt to salvage back through as many instructions as possible. Bail if
1268   // a non-instruction is seen, such as a constant expression or global
1269   // variable. FIXME: Further work could recover those too.
1270   while (isa<Instruction>(V)) {
1271     Instruction &VAsInst = *cast<Instruction>(V);
1272     DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
1273 
1274     // If we cannot salvage any further, and haven't yet found a suitable debug
1275     // expression, bail out.
1276     if (!NewExpr)
1277       break;
1278 
1279     // New value and expr now represent this debuginfo.
1280     V = VAsInst.getOperand(0);
1281     Expr = NewExpr;
1282 
1283     // Some kind of simplification occurred: check whether the operand of the
1284     // salvaged debug expression can be encoded in this DAG.
1285     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) {
1286       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1287                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1288       return;
1289     }
1290   }
1291 
1292   // This was the final opportunity to salvage this debug information, and it
1293   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1294   // any earlier variable location.
1295   auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1296   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1297   DAG.AddDbgValue(SDV, nullptr, false);
1298 
1299   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1300                     << "\n");
1301   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1302                     << "\n");
1303 }
1304 
1305 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var,
1306                                            DIExpression *Expr, DebugLoc dl,
1307                                            DebugLoc InstDL, unsigned Order) {
1308   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1309   SDDbgValue *SDV;
1310   if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1311       isa<ConstantPointerNull>(V)) {
1312     SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder);
1313     DAG.AddDbgValue(SDV, nullptr, false);
1314     return true;
1315   }
1316 
1317   // If the Value is a frame index, we can create a FrameIndex debug value
1318   // without relying on the DAG at all.
1319   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1320     auto SI = FuncInfo.StaticAllocaMap.find(AI);
1321     if (SI != FuncInfo.StaticAllocaMap.end()) {
1322       auto SDV =
1323           DAG.getFrameIndexDbgValue(Var, Expr, SI->second,
1324                                     /*IsIndirect*/ false, dl, SDNodeOrder);
1325       // Do not attach the SDNodeDbgValue to an SDNode: this variable location
1326       // is still available even if the SDNode gets optimized out.
1327       DAG.AddDbgValue(SDV, nullptr, false);
1328       return true;
1329     }
1330   }
1331 
1332   // Do not use getValue() in here; we don't want to generate code at
1333   // this point if it hasn't been done yet.
1334   SDValue N = NodeMap[V];
1335   if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1336     N = UnusedArgNodeMap[V];
1337   if (N.getNode()) {
1338     if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1339       return true;
1340     SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder);
1341     DAG.AddDbgValue(SDV, N.getNode(), false);
1342     return true;
1343   }
1344 
1345   // Special rules apply for the first dbg.values of parameter variables in a
1346   // function. Identify them by the fact they reference Argument Values, that
1347   // they're parameters, and they are parameters of the current function. We
1348   // need to let them dangle until they get an SDNode.
1349   bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() &&
1350                        !InstDL.getInlinedAt();
1351   if (!IsParamOfFunc) {
1352     // The value is not used in this block yet (or it would have an SDNode).
1353     // We still want the value to appear for the user if possible -- if it has
1354     // an associated VReg, we can refer to that instead.
1355     auto VMI = FuncInfo.ValueMap.find(V);
1356     if (VMI != FuncInfo.ValueMap.end()) {
1357       unsigned Reg = VMI->second;
1358       // If this is a PHI node, it may be split up into several MI PHI nodes
1359       // (in FunctionLoweringInfo::set).
1360       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1361                        V->getType(), None);
1362       if (RFV.occupiesMultipleRegs()) {
1363         unsigned Offset = 0;
1364         unsigned BitsToDescribe = 0;
1365         if (auto VarSize = Var->getSizeInBits())
1366           BitsToDescribe = *VarSize;
1367         if (auto Fragment = Expr->getFragmentInfo())
1368           BitsToDescribe = Fragment->SizeInBits;
1369         for (auto RegAndSize : RFV.getRegsAndSizes()) {
1370           unsigned RegisterSize = RegAndSize.second;
1371           // Bail out if all bits are described already.
1372           if (Offset >= BitsToDescribe)
1373             break;
1374           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1375               ? BitsToDescribe - Offset
1376               : RegisterSize;
1377           auto FragmentExpr = DIExpression::createFragmentExpression(
1378               Expr, Offset, FragmentSize);
1379           if (!FragmentExpr)
1380               continue;
1381           SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first,
1382                                     false, dl, SDNodeOrder);
1383           DAG.AddDbgValue(SDV, nullptr, false);
1384           Offset += RegisterSize;
1385         }
1386       } else {
1387         SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder);
1388         DAG.AddDbgValue(SDV, nullptr, false);
1389       }
1390       return true;
1391     }
1392   }
1393 
1394   return false;
1395 }
1396 
1397 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1398   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1399   for (auto &Pair : DanglingDebugInfoMap)
1400     for (auto &DDI : Pair.second)
1401       salvageUnresolvedDbgValue(DDI);
1402   clearDanglingDebugInfo();
1403 }
1404 
1405 /// getCopyFromRegs - If there was virtual register allocated for the value V
1406 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1407 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1408   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1409   SDValue Result;
1410 
1411   if (It != FuncInfo.ValueMap.end()) {
1412     unsigned InReg = It->second;
1413 
1414     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1415                      DAG.getDataLayout(), InReg, Ty,
1416                      None); // This is not an ABI copy.
1417     SDValue Chain = DAG.getEntryNode();
1418     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1419                                  V);
1420     resolveDanglingDebugInfo(V, Result);
1421   }
1422 
1423   return Result;
1424 }
1425 
1426 /// getValue - Return an SDValue for the given Value.
1427 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1428   // If we already have an SDValue for this value, use it. It's important
1429   // to do this first, so that we don't create a CopyFromReg if we already
1430   // have a regular SDValue.
1431   SDValue &N = NodeMap[V];
1432   if (N.getNode()) return N;
1433 
1434   // If there's a virtual register allocated and initialized for this
1435   // value, use it.
1436   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1437     return copyFromReg;
1438 
1439   // Otherwise create a new SDValue and remember it.
1440   SDValue Val = getValueImpl(V);
1441   NodeMap[V] = Val;
1442   resolveDanglingDebugInfo(V, Val);
1443   return Val;
1444 }
1445 
1446 // Return true if SDValue exists for the given Value
1447 bool SelectionDAGBuilder::findValue(const Value *V) const {
1448   return (NodeMap.find(V) != NodeMap.end()) ||
1449     (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
1450 }
1451 
1452 /// getNonRegisterValue - Return an SDValue for the given Value, but
1453 /// don't look in FuncInfo.ValueMap for a virtual register.
1454 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1455   // If we already have an SDValue for this value, use it.
1456   SDValue &N = NodeMap[V];
1457   if (N.getNode()) {
1458     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1459       // Remove the debug location from the node as the node is about to be used
1460       // in a location which may differ from the original debug location.  This
1461       // is relevant to Constant and ConstantFP nodes because they can appear
1462       // as constant expressions inside PHI nodes.
1463       N->setDebugLoc(DebugLoc());
1464     }
1465     return N;
1466   }
1467 
1468   // Otherwise create a new SDValue and remember it.
1469   SDValue Val = getValueImpl(V);
1470   NodeMap[V] = Val;
1471   resolveDanglingDebugInfo(V, Val);
1472   return Val;
1473 }
1474 
1475 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1476 /// Create an SDValue for the given value.
1477 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1478   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1479 
1480   if (const Constant *C = dyn_cast<Constant>(V)) {
1481     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1482 
1483     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1484       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1485 
1486     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1487       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1488 
1489     if (isa<ConstantPointerNull>(C)) {
1490       unsigned AS = V->getType()->getPointerAddressSpace();
1491       return DAG.getConstant(0, getCurSDLoc(),
1492                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1493     }
1494 
1495     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1496       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1497 
1498     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1499       return DAG.getUNDEF(VT);
1500 
1501     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1502       visit(CE->getOpcode(), *CE);
1503       SDValue N1 = NodeMap[V];
1504       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1505       return N1;
1506     }
1507 
1508     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1509       SmallVector<SDValue, 4> Constants;
1510       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1511            OI != OE; ++OI) {
1512         SDNode *Val = getValue(*OI).getNode();
1513         // If the operand is an empty aggregate, there are no values.
1514         if (!Val) continue;
1515         // Add each leaf value from the operand to the Constants list
1516         // to form a flattened list of all the values.
1517         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1518           Constants.push_back(SDValue(Val, i));
1519       }
1520 
1521       return DAG.getMergeValues(Constants, getCurSDLoc());
1522     }
1523 
1524     if (const ConstantDataSequential *CDS =
1525           dyn_cast<ConstantDataSequential>(C)) {
1526       SmallVector<SDValue, 4> Ops;
1527       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1528         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1529         // Add each leaf value from the operand to the Constants list
1530         // to form a flattened list of all the values.
1531         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1532           Ops.push_back(SDValue(Val, i));
1533       }
1534 
1535       if (isa<ArrayType>(CDS->getType()))
1536         return DAG.getMergeValues(Ops, getCurSDLoc());
1537       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1538     }
1539 
1540     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1541       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1542              "Unknown struct or array constant!");
1543 
1544       SmallVector<EVT, 4> ValueVTs;
1545       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1546       unsigned NumElts = ValueVTs.size();
1547       if (NumElts == 0)
1548         return SDValue(); // empty struct
1549       SmallVector<SDValue, 4> Constants(NumElts);
1550       for (unsigned i = 0; i != NumElts; ++i) {
1551         EVT EltVT = ValueVTs[i];
1552         if (isa<UndefValue>(C))
1553           Constants[i] = DAG.getUNDEF(EltVT);
1554         else if (EltVT.isFloatingPoint())
1555           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1556         else
1557           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1558       }
1559 
1560       return DAG.getMergeValues(Constants, getCurSDLoc());
1561     }
1562 
1563     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1564       return DAG.getBlockAddress(BA, VT);
1565 
1566     VectorType *VecTy = cast<VectorType>(V->getType());
1567     unsigned NumElements = VecTy->getNumElements();
1568 
1569     // Now that we know the number and type of the elements, get that number of
1570     // elements into the Ops array based on what kind of constant it is.
1571     SmallVector<SDValue, 16> Ops;
1572     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1573       for (unsigned i = 0; i != NumElements; ++i)
1574         Ops.push_back(getValue(CV->getOperand(i)));
1575     } else {
1576       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1577       EVT EltVT =
1578           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1579 
1580       SDValue Op;
1581       if (EltVT.isFloatingPoint())
1582         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1583       else
1584         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1585       Ops.assign(NumElements, Op);
1586     }
1587 
1588     // Create a BUILD_VECTOR node.
1589     return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1590   }
1591 
1592   // If this is a static alloca, generate it as the frameindex instead of
1593   // computation.
1594   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1595     DenseMap<const AllocaInst*, int>::iterator SI =
1596       FuncInfo.StaticAllocaMap.find(AI);
1597     if (SI != FuncInfo.StaticAllocaMap.end())
1598       return DAG.getFrameIndex(SI->second,
1599                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1600   }
1601 
1602   // If this is an instruction which fast-isel has deferred, select it now.
1603   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1604     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1605 
1606     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1607                      Inst->getType(), getABIRegCopyCC(V));
1608     SDValue Chain = DAG.getEntryNode();
1609     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1610   }
1611 
1612   llvm_unreachable("Can't get register for value!");
1613 }
1614 
1615 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1616   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1617   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1618   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1619   bool IsSEH = isAsynchronousEHPersonality(Pers);
1620   bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX;
1621   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1622   if (!IsSEH)
1623     CatchPadMBB->setIsEHScopeEntry();
1624   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1625   if (IsMSVCCXX || IsCoreCLR)
1626     CatchPadMBB->setIsEHFuncletEntry();
1627   // Wasm does not need catchpads anymore
1628   if (!IsWasmCXX)
1629     DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other,
1630                             getControlRoot()));
1631 }
1632 
1633 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1634   // Update machine-CFG edge.
1635   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1636   FuncInfo.MBB->addSuccessor(TargetMBB);
1637 
1638   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1639   bool IsSEH = isAsynchronousEHPersonality(Pers);
1640   if (IsSEH) {
1641     // If this is not a fall-through branch or optimizations are switched off,
1642     // emit the branch.
1643     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1644         TM.getOptLevel() == CodeGenOpt::None)
1645       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1646                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1647     return;
1648   }
1649 
1650   // Figure out the funclet membership for the catchret's successor.
1651   // This will be used by the FuncletLayout pass to determine how to order the
1652   // BB's.
1653   // A 'catchret' returns to the outer scope's color.
1654   Value *ParentPad = I.getCatchSwitchParentPad();
1655   const BasicBlock *SuccessorColor;
1656   if (isa<ConstantTokenNone>(ParentPad))
1657     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1658   else
1659     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1660   assert(SuccessorColor && "No parent funclet for catchret!");
1661   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1662   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1663 
1664   // Create the terminator node.
1665   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1666                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1667                             DAG.getBasicBlock(SuccessorColorMBB));
1668   DAG.setRoot(Ret);
1669 }
1670 
1671 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1672   // Don't emit any special code for the cleanuppad instruction. It just marks
1673   // the start of an EH scope/funclet.
1674   FuncInfo.MBB->setIsEHScopeEntry();
1675   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1676   if (Pers != EHPersonality::Wasm_CXX) {
1677     FuncInfo.MBB->setIsEHFuncletEntry();
1678     FuncInfo.MBB->setIsCleanupFuncletEntry();
1679   }
1680 }
1681 
1682 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
1683 // the control flow always stops at the single catch pad, as it does for a
1684 // cleanup pad. In case the exception caught is not of the types the catch pad
1685 // catches, it will be rethrown by a rethrow.
1686 static void findWasmUnwindDestinations(
1687     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1688     BranchProbability Prob,
1689     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1690         &UnwindDests) {
1691   while (EHPadBB) {
1692     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1693     if (isa<CleanupPadInst>(Pad)) {
1694       // Stop on cleanup pads.
1695       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1696       UnwindDests.back().first->setIsEHScopeEntry();
1697       break;
1698     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1699       // Add the catchpad handlers to the possible destinations. We don't
1700       // continue to the unwind destination of the catchswitch for wasm.
1701       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1702         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1703         UnwindDests.back().first->setIsEHScopeEntry();
1704       }
1705       break;
1706     } else {
1707       continue;
1708     }
1709   }
1710 }
1711 
1712 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1713 /// many places it could ultimately go. In the IR, we have a single unwind
1714 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1715 /// This function skips over imaginary basic blocks that hold catchswitch
1716 /// instructions, and finds all the "real" machine
1717 /// basic block destinations. As those destinations may not be successors of
1718 /// EHPadBB, here we also calculate the edge probability to those destinations.
1719 /// The passed-in Prob is the edge probability to EHPadBB.
1720 static void findUnwindDestinations(
1721     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1722     BranchProbability Prob,
1723     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1724         &UnwindDests) {
1725   EHPersonality Personality =
1726     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1727   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1728   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1729   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1730   bool IsSEH = isAsynchronousEHPersonality(Personality);
1731 
1732   if (IsWasmCXX) {
1733     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1734     assert(UnwindDests.size() <= 1 &&
1735            "There should be at most one unwind destination for wasm");
1736     return;
1737   }
1738 
1739   while (EHPadBB) {
1740     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1741     BasicBlock *NewEHPadBB = nullptr;
1742     if (isa<LandingPadInst>(Pad)) {
1743       // Stop on landingpads. They are not funclets.
1744       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1745       break;
1746     } else if (isa<CleanupPadInst>(Pad)) {
1747       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1748       // personalities.
1749       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1750       UnwindDests.back().first->setIsEHScopeEntry();
1751       UnwindDests.back().first->setIsEHFuncletEntry();
1752       break;
1753     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1754       // Add the catchpad handlers to the possible destinations.
1755       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1756         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1757         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1758         if (IsMSVCCXX || IsCoreCLR)
1759           UnwindDests.back().first->setIsEHFuncletEntry();
1760         if (!IsSEH)
1761           UnwindDests.back().first->setIsEHScopeEntry();
1762       }
1763       NewEHPadBB = CatchSwitch->getUnwindDest();
1764     } else {
1765       continue;
1766     }
1767 
1768     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1769     if (BPI && NewEHPadBB)
1770       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1771     EHPadBB = NewEHPadBB;
1772   }
1773 }
1774 
1775 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1776   // Update successor info.
1777   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1778   auto UnwindDest = I.getUnwindDest();
1779   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1780   BranchProbability UnwindDestProb =
1781       (BPI && UnwindDest)
1782           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1783           : BranchProbability::getZero();
1784   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1785   for (auto &UnwindDest : UnwindDests) {
1786     UnwindDest.first->setIsEHPad();
1787     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1788   }
1789   FuncInfo.MBB->normalizeSuccProbs();
1790 
1791   // Create the terminator node.
1792   SDValue Ret =
1793       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1794   DAG.setRoot(Ret);
1795 }
1796 
1797 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1798   report_fatal_error("visitCatchSwitch not yet implemented!");
1799 }
1800 
1801 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1802   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1803   auto &DL = DAG.getDataLayout();
1804   SDValue Chain = getControlRoot();
1805   SmallVector<ISD::OutputArg, 8> Outs;
1806   SmallVector<SDValue, 8> OutVals;
1807 
1808   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1809   // lower
1810   //
1811   //   %val = call <ty> @llvm.experimental.deoptimize()
1812   //   ret <ty> %val
1813   //
1814   // differently.
1815   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1816     LowerDeoptimizingReturn();
1817     return;
1818   }
1819 
1820   if (!FuncInfo.CanLowerReturn) {
1821     unsigned DemoteReg = FuncInfo.DemoteRegister;
1822     const Function *F = I.getParent()->getParent();
1823 
1824     // Emit a store of the return value through the virtual register.
1825     // Leave Outs empty so that LowerReturn won't try to load return
1826     // registers the usual way.
1827     SmallVector<EVT, 1> PtrValueVTs;
1828     ComputeValueVTs(TLI, DL,
1829                     F->getReturnType()->getPointerTo(
1830                         DAG.getDataLayout().getAllocaAddrSpace()),
1831                     PtrValueVTs);
1832 
1833     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1834                                         DemoteReg, PtrValueVTs[0]);
1835     SDValue RetOp = getValue(I.getOperand(0));
1836 
1837     SmallVector<EVT, 4> ValueVTs, MemVTs;
1838     SmallVector<uint64_t, 4> Offsets;
1839     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1840                     &Offsets);
1841     unsigned NumValues = ValueVTs.size();
1842 
1843     SmallVector<SDValue, 4> Chains(NumValues);
1844     for (unsigned i = 0; i != NumValues; ++i) {
1845       // An aggregate return value cannot wrap around the address space, so
1846       // offsets to its parts don't wrap either.
1847       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
1848 
1849       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1850       if (MemVTs[i] != ValueVTs[i])
1851         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1852       Chains[i] = DAG.getStore(Chain, getCurSDLoc(), Val,
1853           // FIXME: better loc info would be nice.
1854           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
1855     }
1856 
1857     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1858                         MVT::Other, Chains);
1859   } else if (I.getNumOperands() != 0) {
1860     SmallVector<EVT, 4> ValueVTs;
1861     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1862     unsigned NumValues = ValueVTs.size();
1863     if (NumValues) {
1864       SDValue RetOp = getValue(I.getOperand(0));
1865 
1866       const Function *F = I.getParent()->getParent();
1867 
1868       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1869           I.getOperand(0)->getType(), F->getCallingConv(),
1870           /*IsVarArg*/ false);
1871 
1872       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1873       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1874                                           Attribute::SExt))
1875         ExtendKind = ISD::SIGN_EXTEND;
1876       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1877                                                Attribute::ZExt))
1878         ExtendKind = ISD::ZERO_EXTEND;
1879 
1880       LLVMContext &Context = F->getContext();
1881       bool RetInReg = F->getAttributes().hasAttribute(
1882           AttributeList::ReturnIndex, Attribute::InReg);
1883 
1884       for (unsigned j = 0; j != NumValues; ++j) {
1885         EVT VT = ValueVTs[j];
1886 
1887         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1888           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1889 
1890         CallingConv::ID CC = F->getCallingConv();
1891 
1892         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1893         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1894         SmallVector<SDValue, 4> Parts(NumParts);
1895         getCopyToParts(DAG, getCurSDLoc(),
1896                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1897                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1898 
1899         // 'inreg' on function refers to return value
1900         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1901         if (RetInReg)
1902           Flags.setInReg();
1903 
1904         if (I.getOperand(0)->getType()->isPointerTy()) {
1905           Flags.setPointer();
1906           Flags.setPointerAddrSpace(
1907               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
1908         }
1909 
1910         if (NeedsRegBlock) {
1911           Flags.setInConsecutiveRegs();
1912           if (j == NumValues - 1)
1913             Flags.setInConsecutiveRegsLast();
1914         }
1915 
1916         // Propagate extension type if any
1917         if (ExtendKind == ISD::SIGN_EXTEND)
1918           Flags.setSExt();
1919         else if (ExtendKind == ISD::ZERO_EXTEND)
1920           Flags.setZExt();
1921 
1922         for (unsigned i = 0; i < NumParts; ++i) {
1923           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1924                                         VT, /*isfixed=*/true, 0, 0));
1925           OutVals.push_back(Parts[i]);
1926         }
1927       }
1928     }
1929   }
1930 
1931   // Push in swifterror virtual register as the last element of Outs. This makes
1932   // sure swifterror virtual register will be returned in the swifterror
1933   // physical register.
1934   const Function *F = I.getParent()->getParent();
1935   if (TLI.supportSwiftError() &&
1936       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1937     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
1938     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1939     Flags.setSwiftError();
1940     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1941                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1942                                   true /*isfixed*/, 1 /*origidx*/,
1943                                   0 /*partOffs*/));
1944     // Create SDNode for the swifterror virtual register.
1945     OutVals.push_back(
1946         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
1947                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
1948                         EVT(TLI.getPointerTy(DL))));
1949   }
1950 
1951   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1952   CallingConv::ID CallConv =
1953     DAG.getMachineFunction().getFunction().getCallingConv();
1954   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1955       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1956 
1957   // Verify that the target's LowerReturn behaved as expected.
1958   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1959          "LowerReturn didn't return a valid chain!");
1960 
1961   // Update the DAG with the new chain value resulting from return lowering.
1962   DAG.setRoot(Chain);
1963 }
1964 
1965 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1966 /// created for it, emit nodes to copy the value into the virtual
1967 /// registers.
1968 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1969   // Skip empty types
1970   if (V->getType()->isEmptyTy())
1971     return;
1972 
1973   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1974   if (VMI != FuncInfo.ValueMap.end()) {
1975     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1976     CopyValueToVirtualRegister(V, VMI->second);
1977   }
1978 }
1979 
1980 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1981 /// the current basic block, add it to ValueMap now so that we'll get a
1982 /// CopyTo/FromReg.
1983 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1984   // No need to export constants.
1985   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1986 
1987   // Already exported?
1988   if (FuncInfo.isExportedInst(V)) return;
1989 
1990   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1991   CopyValueToVirtualRegister(V, Reg);
1992 }
1993 
1994 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1995                                                      const BasicBlock *FromBB) {
1996   // The operands of the setcc have to be in this block.  We don't know
1997   // how to export them from some other block.
1998   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1999     // Can export from current BB.
2000     if (VI->getParent() == FromBB)
2001       return true;
2002 
2003     // Is already exported, noop.
2004     return FuncInfo.isExportedInst(V);
2005   }
2006 
2007   // If this is an argument, we can export it if the BB is the entry block or
2008   // if it is already exported.
2009   if (isa<Argument>(V)) {
2010     if (FromBB == &FromBB->getParent()->getEntryBlock())
2011       return true;
2012 
2013     // Otherwise, can only export this if it is already exported.
2014     return FuncInfo.isExportedInst(V);
2015   }
2016 
2017   // Otherwise, constants can always be exported.
2018   return true;
2019 }
2020 
2021 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2022 BranchProbability
2023 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2024                                         const MachineBasicBlock *Dst) const {
2025   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2026   const BasicBlock *SrcBB = Src->getBasicBlock();
2027   const BasicBlock *DstBB = Dst->getBasicBlock();
2028   if (!BPI) {
2029     // If BPI is not available, set the default probability as 1 / N, where N is
2030     // the number of successors.
2031     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2032     return BranchProbability(1, SuccSize);
2033   }
2034   return BPI->getEdgeProbability(SrcBB, DstBB);
2035 }
2036 
2037 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2038                                                MachineBasicBlock *Dst,
2039                                                BranchProbability Prob) {
2040   if (!FuncInfo.BPI)
2041     Src->addSuccessorWithoutProb(Dst);
2042   else {
2043     if (Prob.isUnknown())
2044       Prob = getEdgeProbability(Src, Dst);
2045     Src->addSuccessor(Dst, Prob);
2046   }
2047 }
2048 
2049 static bool InBlock(const Value *V, const BasicBlock *BB) {
2050   if (const Instruction *I = dyn_cast<Instruction>(V))
2051     return I->getParent() == BB;
2052   return true;
2053 }
2054 
2055 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2056 /// This function emits a branch and is used at the leaves of an OR or an
2057 /// AND operator tree.
2058 void
2059 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2060                                                   MachineBasicBlock *TBB,
2061                                                   MachineBasicBlock *FBB,
2062                                                   MachineBasicBlock *CurBB,
2063                                                   MachineBasicBlock *SwitchBB,
2064                                                   BranchProbability TProb,
2065                                                   BranchProbability FProb,
2066                                                   bool InvertCond) {
2067   const BasicBlock *BB = CurBB->getBasicBlock();
2068 
2069   // If the leaf of the tree is a comparison, merge the condition into
2070   // the caseblock.
2071   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2072     // The operands of the cmp have to be in this block.  We don't know
2073     // how to export them from some other block.  If this is the first block
2074     // of the sequence, no exporting is needed.
2075     if (CurBB == SwitchBB ||
2076         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2077          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2078       ISD::CondCode Condition;
2079       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2080         ICmpInst::Predicate Pred =
2081             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2082         Condition = getICmpCondCode(Pred);
2083       } else {
2084         const FCmpInst *FC = cast<FCmpInst>(Cond);
2085         FCmpInst::Predicate Pred =
2086             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2087         Condition = getFCmpCondCode(Pred);
2088         if (TM.Options.NoNaNsFPMath)
2089           Condition = getFCmpCodeWithoutNaN(Condition);
2090       }
2091 
2092       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2093                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2094       SL->SwitchCases.push_back(CB);
2095       return;
2096     }
2097   }
2098 
2099   // Create a CaseBlock record representing this branch.
2100   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2101   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2102                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2103   SL->SwitchCases.push_back(CB);
2104 }
2105 
2106 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2107                                                MachineBasicBlock *TBB,
2108                                                MachineBasicBlock *FBB,
2109                                                MachineBasicBlock *CurBB,
2110                                                MachineBasicBlock *SwitchBB,
2111                                                Instruction::BinaryOps Opc,
2112                                                BranchProbability TProb,
2113                                                BranchProbability FProb,
2114                                                bool InvertCond) {
2115   // Skip over not part of the tree and remember to invert op and operands at
2116   // next level.
2117   Value *NotCond;
2118   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2119       InBlock(NotCond, CurBB->getBasicBlock())) {
2120     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2121                          !InvertCond);
2122     return;
2123   }
2124 
2125   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2126   // Compute the effective opcode for Cond, taking into account whether it needs
2127   // to be inverted, e.g.
2128   //   and (not (or A, B)), C
2129   // gets lowered as
2130   //   and (and (not A, not B), C)
2131   unsigned BOpc = 0;
2132   if (BOp) {
2133     BOpc = BOp->getOpcode();
2134     if (InvertCond) {
2135       if (BOpc == Instruction::And)
2136         BOpc = Instruction::Or;
2137       else if (BOpc == Instruction::Or)
2138         BOpc = Instruction::And;
2139     }
2140   }
2141 
2142   // If this node is not part of the or/and tree, emit it as a branch.
2143   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
2144       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
2145       BOp->getParent() != CurBB->getBasicBlock() ||
2146       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
2147       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
2148     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2149                                  TProb, FProb, InvertCond);
2150     return;
2151   }
2152 
2153   //  Create TmpBB after CurBB.
2154   MachineFunction::iterator BBI(CurBB);
2155   MachineFunction &MF = DAG.getMachineFunction();
2156   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2157   CurBB->getParent()->insert(++BBI, TmpBB);
2158 
2159   if (Opc == Instruction::Or) {
2160     // Codegen X | Y as:
2161     // BB1:
2162     //   jmp_if_X TBB
2163     //   jmp TmpBB
2164     // TmpBB:
2165     //   jmp_if_Y TBB
2166     //   jmp FBB
2167     //
2168 
2169     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2170     // The requirement is that
2171     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2172     //     = TrueProb for original BB.
2173     // Assuming the original probabilities are A and B, one choice is to set
2174     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2175     // A/(1+B) and 2B/(1+B). This choice assumes that
2176     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2177     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2178     // TmpBB, but the math is more complicated.
2179 
2180     auto NewTrueProb = TProb / 2;
2181     auto NewFalseProb = TProb / 2 + FProb;
2182     // Emit the LHS condition.
2183     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
2184                          NewTrueProb, NewFalseProb, InvertCond);
2185 
2186     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2187     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2188     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2189     // Emit the RHS condition into TmpBB.
2190     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2191                          Probs[0], Probs[1], InvertCond);
2192   } else {
2193     assert(Opc == Instruction::And && "Unknown merge op!");
2194     // Codegen X & Y as:
2195     // BB1:
2196     //   jmp_if_X TmpBB
2197     //   jmp FBB
2198     // TmpBB:
2199     //   jmp_if_Y TBB
2200     //   jmp FBB
2201     //
2202     //  This requires creation of TmpBB after CurBB.
2203 
2204     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2205     // The requirement is that
2206     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2207     //     = FalseProb for original BB.
2208     // Assuming the original probabilities are A and B, one choice is to set
2209     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2210     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2211     // TrueProb for BB1 * FalseProb for TmpBB.
2212 
2213     auto NewTrueProb = TProb + FProb / 2;
2214     auto NewFalseProb = FProb / 2;
2215     // Emit the LHS condition.
2216     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
2217                          NewTrueProb, NewFalseProb, InvertCond);
2218 
2219     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2220     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2221     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2222     // Emit the RHS condition into TmpBB.
2223     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2224                          Probs[0], Probs[1], InvertCond);
2225   }
2226 }
2227 
2228 /// If the set of cases should be emitted as a series of branches, return true.
2229 /// If we should emit this as a bunch of and/or'd together conditions, return
2230 /// false.
2231 bool
2232 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2233   if (Cases.size() != 2) return true;
2234 
2235   // If this is two comparisons of the same values or'd or and'd together, they
2236   // will get folded into a single comparison, so don't emit two blocks.
2237   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2238        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2239       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2240        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2241     return false;
2242   }
2243 
2244   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2245   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2246   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2247       Cases[0].CC == Cases[1].CC &&
2248       isa<Constant>(Cases[0].CmpRHS) &&
2249       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2250     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2251       return false;
2252     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2253       return false;
2254   }
2255 
2256   return true;
2257 }
2258 
2259 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2260   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2261 
2262   // Update machine-CFG edges.
2263   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2264 
2265   if (I.isUnconditional()) {
2266     // Update machine-CFG edges.
2267     BrMBB->addSuccessor(Succ0MBB);
2268 
2269     // If this is not a fall-through branch or optimizations are switched off,
2270     // emit the branch.
2271     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2272       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2273                               MVT::Other, getControlRoot(),
2274                               DAG.getBasicBlock(Succ0MBB)));
2275 
2276     return;
2277   }
2278 
2279   // If this condition is one of the special cases we handle, do special stuff
2280   // now.
2281   const Value *CondVal = I.getCondition();
2282   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2283 
2284   // If this is a series of conditions that are or'd or and'd together, emit
2285   // this as a sequence of branches instead of setcc's with and/or operations.
2286   // As long as jumps are not expensive, this should improve performance.
2287   // For example, instead of something like:
2288   //     cmp A, B
2289   //     C = seteq
2290   //     cmp D, E
2291   //     F = setle
2292   //     or C, F
2293   //     jnz foo
2294   // Emit:
2295   //     cmp A, B
2296   //     je foo
2297   //     cmp D, E
2298   //     jle foo
2299   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
2300     Instruction::BinaryOps Opcode = BOp->getOpcode();
2301     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
2302         !I.hasMetadata(LLVMContext::MD_unpredictable) &&
2303         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
2304       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
2305                            Opcode,
2306                            getEdgeProbability(BrMBB, Succ0MBB),
2307                            getEdgeProbability(BrMBB, Succ1MBB),
2308                            /*InvertCond=*/false);
2309       // If the compares in later blocks need to use values not currently
2310       // exported from this block, export them now.  This block should always
2311       // be the first entry.
2312       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2313 
2314       // Allow some cases to be rejected.
2315       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2316         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2317           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2318           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2319         }
2320 
2321         // Emit the branch for this block.
2322         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2323         SL->SwitchCases.erase(SL->SwitchCases.begin());
2324         return;
2325       }
2326 
2327       // Okay, we decided not to do this, remove any inserted MBB's and clear
2328       // SwitchCases.
2329       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2330         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2331 
2332       SL->SwitchCases.clear();
2333     }
2334   }
2335 
2336   // Create a CaseBlock record representing this branch.
2337   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2338                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2339 
2340   // Use visitSwitchCase to actually insert the fast branch sequence for this
2341   // cond branch.
2342   visitSwitchCase(CB, BrMBB);
2343 }
2344 
2345 /// visitSwitchCase - Emits the necessary code to represent a single node in
2346 /// the binary search tree resulting from lowering a switch instruction.
2347 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2348                                           MachineBasicBlock *SwitchBB) {
2349   SDValue Cond;
2350   SDValue CondLHS = getValue(CB.CmpLHS);
2351   SDLoc dl = CB.DL;
2352 
2353   if (CB.CC == ISD::SETTRUE) {
2354     // Branch or fall through to TrueBB.
2355     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2356     SwitchBB->normalizeSuccProbs();
2357     if (CB.TrueBB != NextBlock(SwitchBB)) {
2358       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2359                               DAG.getBasicBlock(CB.TrueBB)));
2360     }
2361     return;
2362   }
2363 
2364   auto &TLI = DAG.getTargetLoweringInfo();
2365   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2366 
2367   // Build the setcc now.
2368   if (!CB.CmpMHS) {
2369     // Fold "(X == true)" to X and "(X == false)" to !X to
2370     // handle common cases produced by branch lowering.
2371     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2372         CB.CC == ISD::SETEQ)
2373       Cond = CondLHS;
2374     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2375              CB.CC == ISD::SETEQ) {
2376       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2377       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2378     } else {
2379       SDValue CondRHS = getValue(CB.CmpRHS);
2380 
2381       // If a pointer's DAG type is larger than its memory type then the DAG
2382       // values are zero-extended. This breaks signed comparisons so truncate
2383       // back to the underlying type before doing the compare.
2384       if (CondLHS.getValueType() != MemVT) {
2385         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2386         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2387       }
2388       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2389     }
2390   } else {
2391     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2392 
2393     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2394     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2395 
2396     SDValue CmpOp = getValue(CB.CmpMHS);
2397     EVT VT = CmpOp.getValueType();
2398 
2399     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2400       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2401                           ISD::SETLE);
2402     } else {
2403       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2404                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2405       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2406                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2407     }
2408   }
2409 
2410   // Update successor info
2411   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2412   // TrueBB and FalseBB are always different unless the incoming IR is
2413   // degenerate. This only happens when running llc on weird IR.
2414   if (CB.TrueBB != CB.FalseBB)
2415     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2416   SwitchBB->normalizeSuccProbs();
2417 
2418   // If the lhs block is the next block, invert the condition so that we can
2419   // fall through to the lhs instead of the rhs block.
2420   if (CB.TrueBB == NextBlock(SwitchBB)) {
2421     std::swap(CB.TrueBB, CB.FalseBB);
2422     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2423     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2424   }
2425 
2426   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2427                                MVT::Other, getControlRoot(), Cond,
2428                                DAG.getBasicBlock(CB.TrueBB));
2429 
2430   // Insert the false branch. Do this even if it's a fall through branch,
2431   // this makes it easier to do DAG optimizations which require inverting
2432   // the branch condition.
2433   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2434                        DAG.getBasicBlock(CB.FalseBB));
2435 
2436   DAG.setRoot(BrCond);
2437 }
2438 
2439 /// visitJumpTable - Emit JumpTable node in the current MBB
2440 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2441   // Emit the code for the jump table
2442   assert(JT.Reg != -1U && "Should lower JT Header first!");
2443   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2444   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2445                                      JT.Reg, PTy);
2446   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2447   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2448                                     MVT::Other, Index.getValue(1),
2449                                     Table, Index);
2450   DAG.setRoot(BrJumpTable);
2451 }
2452 
2453 /// visitJumpTableHeader - This function emits necessary code to produce index
2454 /// in the JumpTable from switch case.
2455 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2456                                                JumpTableHeader &JTH,
2457                                                MachineBasicBlock *SwitchBB) {
2458   SDLoc dl = getCurSDLoc();
2459 
2460   // Subtract the lowest switch case value from the value being switched on.
2461   SDValue SwitchOp = getValue(JTH.SValue);
2462   EVT VT = SwitchOp.getValueType();
2463   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2464                             DAG.getConstant(JTH.First, dl, VT));
2465 
2466   // The SDNode we just created, which holds the value being switched on minus
2467   // the smallest case value, needs to be copied to a virtual register so it
2468   // can be used as an index into the jump table in a subsequent basic block.
2469   // This value may be smaller or larger than the target's pointer type, and
2470   // therefore require extension or truncating.
2471   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2472   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2473 
2474   unsigned JumpTableReg =
2475       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2476   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2477                                     JumpTableReg, SwitchOp);
2478   JT.Reg = JumpTableReg;
2479 
2480   if (!JTH.OmitRangeCheck) {
2481     // Emit the range check for the jump table, and branch to the default block
2482     // for the switch statement if the value being switched on exceeds the
2483     // largest case in the switch.
2484     SDValue CMP = DAG.getSetCC(
2485         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2486                                    Sub.getValueType()),
2487         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2488 
2489     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2490                                  MVT::Other, CopyTo, CMP,
2491                                  DAG.getBasicBlock(JT.Default));
2492 
2493     // Avoid emitting unnecessary branches to the next block.
2494     if (JT.MBB != NextBlock(SwitchBB))
2495       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2496                            DAG.getBasicBlock(JT.MBB));
2497 
2498     DAG.setRoot(BrCond);
2499   } else {
2500     // Avoid emitting unnecessary branches to the next block.
2501     if (JT.MBB != NextBlock(SwitchBB))
2502       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2503                               DAG.getBasicBlock(JT.MBB)));
2504     else
2505       DAG.setRoot(CopyTo);
2506   }
2507 }
2508 
2509 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2510 /// variable if there exists one.
2511 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2512                                  SDValue &Chain) {
2513   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2514   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2515   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2516   MachineFunction &MF = DAG.getMachineFunction();
2517   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2518   MachineSDNode *Node =
2519       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2520   if (Global) {
2521     MachinePointerInfo MPInfo(Global);
2522     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2523                  MachineMemOperand::MODereferenceable;
2524     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2525         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy));
2526     DAG.setNodeMemRefs(Node, {MemRef});
2527   }
2528   if (PtrTy != PtrMemTy)
2529     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2530   return SDValue(Node, 0);
2531 }
2532 
2533 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2534 /// tail spliced into a stack protector check success bb.
2535 ///
2536 /// For a high level explanation of how this fits into the stack protector
2537 /// generation see the comment on the declaration of class
2538 /// StackProtectorDescriptor.
2539 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2540                                                   MachineBasicBlock *ParentBB) {
2541 
2542   // First create the loads to the guard/stack slot for the comparison.
2543   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2544   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2545   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2546 
2547   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2548   int FI = MFI.getStackProtectorIndex();
2549 
2550   SDValue Guard;
2551   SDLoc dl = getCurSDLoc();
2552   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2553   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2554   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2555 
2556   // Generate code to load the content of the guard slot.
2557   SDValue GuardVal = DAG.getLoad(
2558       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2559       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2560       MachineMemOperand::MOVolatile);
2561 
2562   if (TLI.useStackGuardXorFP())
2563     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2564 
2565   // Retrieve guard check function, nullptr if instrumentation is inlined.
2566   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2567     // The target provides a guard check function to validate the guard value.
2568     // Generate a call to that function with the content of the guard slot as
2569     // argument.
2570     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2571     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2572 
2573     TargetLowering::ArgListTy Args;
2574     TargetLowering::ArgListEntry Entry;
2575     Entry.Node = GuardVal;
2576     Entry.Ty = FnTy->getParamType(0);
2577     if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
2578       Entry.IsInReg = true;
2579     Args.push_back(Entry);
2580 
2581     TargetLowering::CallLoweringInfo CLI(DAG);
2582     CLI.setDebugLoc(getCurSDLoc())
2583         .setChain(DAG.getEntryNode())
2584         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2585                    getValue(GuardCheckFn), std::move(Args));
2586 
2587     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2588     DAG.setRoot(Result.second);
2589     return;
2590   }
2591 
2592   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2593   // Otherwise, emit a volatile load to retrieve the stack guard value.
2594   SDValue Chain = DAG.getEntryNode();
2595   if (TLI.useLoadStackGuardNode()) {
2596     Guard = getLoadStackGuard(DAG, dl, Chain);
2597   } else {
2598     const Value *IRGuard = TLI.getSDagStackGuard(M);
2599     SDValue GuardPtr = getValue(IRGuard);
2600 
2601     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2602                         MachinePointerInfo(IRGuard, 0), Align,
2603                         MachineMemOperand::MOVolatile);
2604   }
2605 
2606   // Perform the comparison via a subtract/getsetcc.
2607   EVT VT = Guard.getValueType();
2608   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
2609 
2610   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2611                                                         *DAG.getContext(),
2612                                                         Sub.getValueType()),
2613                              Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
2614 
2615   // If the sub is not 0, then we know the guard/stackslot do not equal, so
2616   // branch to failure MBB.
2617   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2618                                MVT::Other, GuardVal.getOperand(0),
2619                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2620   // Otherwise branch to success MBB.
2621   SDValue Br = DAG.getNode(ISD::BR, dl,
2622                            MVT::Other, BrCond,
2623                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2624 
2625   DAG.setRoot(Br);
2626 }
2627 
2628 /// Codegen the failure basic block for a stack protector check.
2629 ///
2630 /// A failure stack protector machine basic block consists simply of a call to
2631 /// __stack_chk_fail().
2632 ///
2633 /// For a high level explanation of how this fits into the stack protector
2634 /// generation see the comment on the declaration of class
2635 /// StackProtectorDescriptor.
2636 void
2637 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2638   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2639   TargetLowering::MakeLibCallOptions CallOptions;
2640   CallOptions.setDiscardResult(true);
2641   SDValue Chain =
2642       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2643                       None, CallOptions, getCurSDLoc()).second;
2644   // On PS4, the "return address" must still be within the calling function,
2645   // even if it's at the very end, so emit an explicit TRAP here.
2646   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2647   if (TM.getTargetTriple().isPS4CPU())
2648     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2649 
2650   DAG.setRoot(Chain);
2651 }
2652 
2653 /// visitBitTestHeader - This function emits necessary code to produce value
2654 /// suitable for "bit tests"
2655 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2656                                              MachineBasicBlock *SwitchBB) {
2657   SDLoc dl = getCurSDLoc();
2658 
2659   // Subtract the minimum value.
2660   SDValue SwitchOp = getValue(B.SValue);
2661   EVT VT = SwitchOp.getValueType();
2662   SDValue RangeSub =
2663       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2664 
2665   // Determine the type of the test operands.
2666   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2667   bool UsePtrType = false;
2668   if (!TLI.isTypeLegal(VT)) {
2669     UsePtrType = true;
2670   } else {
2671     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2672       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2673         // Switch table case range are encoded into series of masks.
2674         // Just use pointer type, it's guaranteed to fit.
2675         UsePtrType = true;
2676         break;
2677       }
2678   }
2679   SDValue Sub = RangeSub;
2680   if (UsePtrType) {
2681     VT = TLI.getPointerTy(DAG.getDataLayout());
2682     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2683   }
2684 
2685   B.RegVT = VT.getSimpleVT();
2686   B.Reg = FuncInfo.CreateReg(B.RegVT);
2687   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2688 
2689   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2690 
2691   if (!B.OmitRangeCheck)
2692     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2693   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2694   SwitchBB->normalizeSuccProbs();
2695 
2696   SDValue Root = CopyTo;
2697   if (!B.OmitRangeCheck) {
2698     // Conditional branch to the default block.
2699     SDValue RangeCmp = DAG.getSetCC(dl,
2700         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2701                                RangeSub.getValueType()),
2702         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2703         ISD::SETUGT);
2704 
2705     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2706                        DAG.getBasicBlock(B.Default));
2707   }
2708 
2709   // Avoid emitting unnecessary branches to the next block.
2710   if (MBB != NextBlock(SwitchBB))
2711     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2712 
2713   DAG.setRoot(Root);
2714 }
2715 
2716 /// visitBitTestCase - this function produces one "bit test"
2717 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2718                                            MachineBasicBlock* NextMBB,
2719                                            BranchProbability BranchProbToNext,
2720                                            unsigned Reg,
2721                                            BitTestCase &B,
2722                                            MachineBasicBlock *SwitchBB) {
2723   SDLoc dl = getCurSDLoc();
2724   MVT VT = BB.RegVT;
2725   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2726   SDValue Cmp;
2727   unsigned PopCount = countPopulation(B.Mask);
2728   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2729   if (PopCount == 1) {
2730     // Testing for a single bit; just compare the shift count with what it
2731     // would need to be to shift a 1 bit in that position.
2732     Cmp = DAG.getSetCC(
2733         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2734         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2735         ISD::SETEQ);
2736   } else if (PopCount == BB.Range) {
2737     // There is only one zero bit in the range, test for it directly.
2738     Cmp = DAG.getSetCC(
2739         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2740         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2741         ISD::SETNE);
2742   } else {
2743     // Make desired shift
2744     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2745                                     DAG.getConstant(1, dl, VT), ShiftOp);
2746 
2747     // Emit bit tests and jumps
2748     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2749                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2750     Cmp = DAG.getSetCC(
2751         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2752         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2753   }
2754 
2755   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2756   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2757   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2758   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2759   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2760   // one as they are relative probabilities (and thus work more like weights),
2761   // and hence we need to normalize them to let the sum of them become one.
2762   SwitchBB->normalizeSuccProbs();
2763 
2764   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2765                               MVT::Other, getControlRoot(),
2766                               Cmp, DAG.getBasicBlock(B.TargetBB));
2767 
2768   // Avoid emitting unnecessary branches to the next block.
2769   if (NextMBB != NextBlock(SwitchBB))
2770     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2771                         DAG.getBasicBlock(NextMBB));
2772 
2773   DAG.setRoot(BrAnd);
2774 }
2775 
2776 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2777   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2778 
2779   // Retrieve successors. Look through artificial IR level blocks like
2780   // catchswitch for successors.
2781   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2782   const BasicBlock *EHPadBB = I.getSuccessor(1);
2783 
2784   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2785   // have to do anything here to lower funclet bundles.
2786   assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt,
2787                                         LLVMContext::OB_funclet,
2788                                         LLVMContext::OB_cfguardtarget}) &&
2789          "Cannot lower invokes with arbitrary operand bundles yet!");
2790 
2791   const Value *Callee(I.getCalledValue());
2792   const Function *Fn = dyn_cast<Function>(Callee);
2793   if (isa<InlineAsm>(Callee))
2794     visitInlineAsm(&I);
2795   else if (Fn && Fn->isIntrinsic()) {
2796     switch (Fn->getIntrinsicID()) {
2797     default:
2798       llvm_unreachable("Cannot invoke this intrinsic");
2799     case Intrinsic::donothing:
2800       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2801       break;
2802     case Intrinsic::experimental_patchpoint_void:
2803     case Intrinsic::experimental_patchpoint_i64:
2804       visitPatchpoint(&I, EHPadBB);
2805       break;
2806     case Intrinsic::experimental_gc_statepoint:
2807       LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2808       break;
2809     case Intrinsic::wasm_rethrow_in_catch: {
2810       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2811       // special because it can be invoked, so we manually lower it to a DAG
2812       // node here.
2813       SmallVector<SDValue, 8> Ops;
2814       Ops.push_back(getRoot()); // inchain
2815       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2816       Ops.push_back(
2817           DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(),
2818                                 TLI.getPointerTy(DAG.getDataLayout())));
2819       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2820       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2821       break;
2822     }
2823     }
2824   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2825     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2826     // Eventually we will support lowering the @llvm.experimental.deoptimize
2827     // intrinsic, and right now there are no plans to support other intrinsics
2828     // with deopt state.
2829     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2830   } else {
2831     LowerCallTo(&I, getValue(Callee), false, EHPadBB);
2832   }
2833 
2834   // If the value of the invoke is used outside of its defining block, make it
2835   // available as a virtual register.
2836   // We already took care of the exported value for the statepoint instruction
2837   // during call to the LowerStatepoint.
2838   if (!isStatepoint(I)) {
2839     CopyToExportRegsIfNeeded(&I);
2840   }
2841 
2842   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2843   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2844   BranchProbability EHPadBBProb =
2845       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2846           : BranchProbability::getZero();
2847   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2848 
2849   // Update successor info.
2850   addSuccessorWithProb(InvokeMBB, Return);
2851   for (auto &UnwindDest : UnwindDests) {
2852     UnwindDest.first->setIsEHPad();
2853     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2854   }
2855   InvokeMBB->normalizeSuccProbs();
2856 
2857   // Drop into normal successor.
2858   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2859                           DAG.getBasicBlock(Return)));
2860 }
2861 
2862 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2863   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2864 
2865   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2866   // have to do anything here to lower funclet bundles.
2867   assert(!I.hasOperandBundlesOtherThan(
2868              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2869          "Cannot lower callbrs with arbitrary operand bundles yet!");
2870 
2871   assert(isa<InlineAsm>(I.getCalledValue()) &&
2872          "Only know how to handle inlineasm callbr");
2873   visitInlineAsm(&I);
2874 
2875   // Retrieve successors.
2876   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2877 
2878   // Update successor info.
2879   addSuccessorWithProb(CallBrMBB, Return);
2880   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2881     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2882     addSuccessorWithProb(CallBrMBB, Target);
2883   }
2884   CallBrMBB->normalizeSuccProbs();
2885 
2886   // Drop into default successor.
2887   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2888                           MVT::Other, getControlRoot(),
2889                           DAG.getBasicBlock(Return)));
2890 }
2891 
2892 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2893   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2894 }
2895 
2896 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2897   assert(FuncInfo.MBB->isEHPad() &&
2898          "Call to landingpad not in landing pad!");
2899 
2900   // If there aren't registers to copy the values into (e.g., during SjLj
2901   // exceptions), then don't bother to create these DAG nodes.
2902   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2903   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2904   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2905       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2906     return;
2907 
2908   // If landingpad's return type is token type, we don't create DAG nodes
2909   // for its exception pointer and selector value. The extraction of exception
2910   // pointer or selector value from token type landingpads is not currently
2911   // supported.
2912   if (LP.getType()->isTokenTy())
2913     return;
2914 
2915   SmallVector<EVT, 2> ValueVTs;
2916   SDLoc dl = getCurSDLoc();
2917   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2918   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2919 
2920   // Get the two live-in registers as SDValues. The physregs have already been
2921   // copied into virtual registers.
2922   SDValue Ops[2];
2923   if (FuncInfo.ExceptionPointerVirtReg) {
2924     Ops[0] = DAG.getZExtOrTrunc(
2925         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2926                            FuncInfo.ExceptionPointerVirtReg,
2927                            TLI.getPointerTy(DAG.getDataLayout())),
2928         dl, ValueVTs[0]);
2929   } else {
2930     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2931   }
2932   Ops[1] = DAG.getZExtOrTrunc(
2933       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2934                          FuncInfo.ExceptionSelectorVirtReg,
2935                          TLI.getPointerTy(DAG.getDataLayout())),
2936       dl, ValueVTs[1]);
2937 
2938   // Merge into one.
2939   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2940                             DAG.getVTList(ValueVTs), Ops);
2941   setValue(&LP, Res);
2942 }
2943 
2944 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2945                                            MachineBasicBlock *Last) {
2946   // Update JTCases.
2947   for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
2948     if (SL->JTCases[i].first.HeaderBB == First)
2949       SL->JTCases[i].first.HeaderBB = Last;
2950 
2951   // Update BitTestCases.
2952   for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
2953     if (SL->BitTestCases[i].Parent == First)
2954       SL->BitTestCases[i].Parent = Last;
2955 }
2956 
2957 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2958   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2959 
2960   // Update machine-CFG edges with unique successors.
2961   SmallSet<BasicBlock*, 32> Done;
2962   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2963     BasicBlock *BB = I.getSuccessor(i);
2964     bool Inserted = Done.insert(BB).second;
2965     if (!Inserted)
2966         continue;
2967 
2968     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2969     addSuccessorWithProb(IndirectBrMBB, Succ);
2970   }
2971   IndirectBrMBB->normalizeSuccProbs();
2972 
2973   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2974                           MVT::Other, getControlRoot(),
2975                           getValue(I.getAddress())));
2976 }
2977 
2978 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2979   if (!DAG.getTarget().Options.TrapUnreachable)
2980     return;
2981 
2982   // We may be able to ignore unreachable behind a noreturn call.
2983   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
2984     const BasicBlock &BB = *I.getParent();
2985     if (&I != &BB.front()) {
2986       BasicBlock::const_iterator PredI =
2987         std::prev(BasicBlock::const_iterator(&I));
2988       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
2989         if (Call->doesNotReturn())
2990           return;
2991       }
2992     }
2993   }
2994 
2995   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2996 }
2997 
2998 void SelectionDAGBuilder::visitFSub(const User &I) {
2999   // -0.0 - X --> fneg
3000   Type *Ty = I.getType();
3001   if (isa<Constant>(I.getOperand(0)) &&
3002       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
3003     SDValue Op2 = getValue(I.getOperand(1));
3004     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
3005                              Op2.getValueType(), Op2));
3006     return;
3007   }
3008 
3009   visitBinary(I, ISD::FSUB);
3010 }
3011 
3012 /// Checks if the given instruction performs a vector reduction, in which case
3013 /// we have the freedom to alter the elements in the result as long as the
3014 /// reduction of them stays unchanged.
3015 static bool isVectorReductionOp(const User *I) {
3016   const Instruction *Inst = dyn_cast<Instruction>(I);
3017   if (!Inst || !Inst->getType()->isVectorTy())
3018     return false;
3019 
3020   auto OpCode = Inst->getOpcode();
3021   switch (OpCode) {
3022   case Instruction::Add:
3023   case Instruction::Mul:
3024   case Instruction::And:
3025   case Instruction::Or:
3026   case Instruction::Xor:
3027     break;
3028   case Instruction::FAdd:
3029   case Instruction::FMul:
3030     if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
3031       if (FPOp->getFastMathFlags().isFast())
3032         break;
3033     LLVM_FALLTHROUGH;
3034   default:
3035     return false;
3036   }
3037 
3038   unsigned ElemNum = Inst->getType()->getVectorNumElements();
3039   // Ensure the reduction size is a power of 2.
3040   if (!isPowerOf2_32(ElemNum))
3041     return false;
3042 
3043   unsigned ElemNumToReduce = ElemNum;
3044 
3045   // Do DFS search on the def-use chain from the given instruction. We only
3046   // allow four kinds of operations during the search until we reach the
3047   // instruction that extracts the first element from the vector:
3048   //
3049   //   1. The reduction operation of the same opcode as the given instruction.
3050   //
3051   //   2. PHI node.
3052   //
3053   //   3. ShuffleVector instruction together with a reduction operation that
3054   //      does a partial reduction.
3055   //
3056   //   4. ExtractElement that extracts the first element from the vector, and we
3057   //      stop searching the def-use chain here.
3058   //
3059   // 3 & 4 above perform a reduction on all elements of the vector. We push defs
3060   // from 1-3 to the stack to continue the DFS. The given instruction is not
3061   // a reduction operation if we meet any other instructions other than those
3062   // listed above.
3063 
3064   SmallVector<const User *, 16> UsersToVisit{Inst};
3065   SmallPtrSet<const User *, 16> Visited;
3066   bool ReduxExtracted = false;
3067 
3068   while (!UsersToVisit.empty()) {
3069     auto User = UsersToVisit.back();
3070     UsersToVisit.pop_back();
3071     if (!Visited.insert(User).second)
3072       continue;
3073 
3074     for (const auto *U : User->users()) {
3075       auto Inst = dyn_cast<Instruction>(U);
3076       if (!Inst)
3077         return false;
3078 
3079       if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
3080         if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
3081           if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
3082             return false;
3083         UsersToVisit.push_back(U);
3084       } else if (const ShuffleVectorInst *ShufInst =
3085                      dyn_cast<ShuffleVectorInst>(U)) {
3086         // Detect the following pattern: A ShuffleVector instruction together
3087         // with a reduction that do partial reduction on the first and second
3088         // ElemNumToReduce / 2 elements, and store the result in
3089         // ElemNumToReduce / 2 elements in another vector.
3090 
3091         unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
3092         if (ResultElements < ElemNum)
3093           return false;
3094 
3095         if (ElemNumToReduce == 1)
3096           return false;
3097         if (!isa<UndefValue>(U->getOperand(1)))
3098           return false;
3099         for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
3100           if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
3101             return false;
3102         for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
3103           if (ShufInst->getMaskValue(i) != -1)
3104             return false;
3105 
3106         // There is only one user of this ShuffleVector instruction, which
3107         // must be a reduction operation.
3108         if (!U->hasOneUse())
3109           return false;
3110 
3111         auto U2 = dyn_cast<Instruction>(*U->user_begin());
3112         if (!U2 || U2->getOpcode() != OpCode)
3113           return false;
3114 
3115         // Check operands of the reduction operation.
3116         if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
3117             (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
3118           UsersToVisit.push_back(U2);
3119           ElemNumToReduce /= 2;
3120         } else
3121           return false;
3122       } else if (isa<ExtractElementInst>(U)) {
3123         // At this moment we should have reduced all elements in the vector.
3124         if (ElemNumToReduce != 1)
3125           return false;
3126 
3127         const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
3128         if (!Val || !Val->isZero())
3129           return false;
3130 
3131         ReduxExtracted = true;
3132       } else
3133         return false;
3134     }
3135   }
3136   return ReduxExtracted;
3137 }
3138 
3139 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3140   SDNodeFlags Flags;
3141 
3142   SDValue Op = getValue(I.getOperand(0));
3143   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3144                                     Op, Flags);
3145   setValue(&I, UnNodeValue);
3146 }
3147 
3148 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3149   SDNodeFlags Flags;
3150   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3151     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3152     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3153   }
3154   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
3155     Flags.setExact(ExactOp->isExact());
3156   }
3157   if (isVectorReductionOp(&I)) {
3158     Flags.setVectorReduction(true);
3159     LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
3160 
3161     // If no flags are set we will propagate the incoming flags, if any flags
3162     // are set, we will intersect them with the incoming flag and so we need to
3163     // copy the FMF flags here.
3164     if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) {
3165       Flags.copyFMF(*FPOp);
3166     }
3167   }
3168 
3169   SDValue Op1 = getValue(I.getOperand(0));
3170   SDValue Op2 = getValue(I.getOperand(1));
3171   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3172                                      Op1, Op2, Flags);
3173   setValue(&I, BinNodeValue);
3174 }
3175 
3176 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3177   SDValue Op1 = getValue(I.getOperand(0));
3178   SDValue Op2 = getValue(I.getOperand(1));
3179 
3180   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3181       Op1.getValueType(), DAG.getDataLayout());
3182 
3183   // Coerce the shift amount to the right type if we can.
3184   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3185     unsigned ShiftSize = ShiftTy.getSizeInBits();
3186     unsigned Op2Size = Op2.getValueSizeInBits();
3187     SDLoc DL = getCurSDLoc();
3188 
3189     // If the operand is smaller than the shift count type, promote it.
3190     if (ShiftSize > Op2Size)
3191       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3192 
3193     // If the operand is larger than the shift count type but the shift
3194     // count type has enough bits to represent any shift value, truncate
3195     // it now. This is a common case and it exposes the truncate to
3196     // optimization early.
3197     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
3198       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3199     // Otherwise we'll need to temporarily settle for some other convenient
3200     // type.  Type legalization will make adjustments once the shiftee is split.
3201     else
3202       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3203   }
3204 
3205   bool nuw = false;
3206   bool nsw = false;
3207   bool exact = false;
3208 
3209   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3210 
3211     if (const OverflowingBinaryOperator *OFBinOp =
3212             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3213       nuw = OFBinOp->hasNoUnsignedWrap();
3214       nsw = OFBinOp->hasNoSignedWrap();
3215     }
3216     if (const PossiblyExactOperator *ExactOp =
3217             dyn_cast<const PossiblyExactOperator>(&I))
3218       exact = ExactOp->isExact();
3219   }
3220   SDNodeFlags Flags;
3221   Flags.setExact(exact);
3222   Flags.setNoSignedWrap(nsw);
3223   Flags.setNoUnsignedWrap(nuw);
3224   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3225                             Flags);
3226   setValue(&I, Res);
3227 }
3228 
3229 void SelectionDAGBuilder::visitSDiv(const User &I) {
3230   SDValue Op1 = getValue(I.getOperand(0));
3231   SDValue Op2 = getValue(I.getOperand(1));
3232 
3233   SDNodeFlags Flags;
3234   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3235                  cast<PossiblyExactOperator>(&I)->isExact());
3236   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3237                            Op2, Flags));
3238 }
3239 
3240 void SelectionDAGBuilder::visitICmp(const User &I) {
3241   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3242   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3243     predicate = IC->getPredicate();
3244   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3245     predicate = ICmpInst::Predicate(IC->getPredicate());
3246   SDValue Op1 = getValue(I.getOperand(0));
3247   SDValue Op2 = getValue(I.getOperand(1));
3248   ISD::CondCode Opcode = getICmpCondCode(predicate);
3249 
3250   auto &TLI = DAG.getTargetLoweringInfo();
3251   EVT MemVT =
3252       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3253 
3254   // If a pointer's DAG type is larger than its memory type then the DAG values
3255   // are zero-extended. This breaks signed comparisons so truncate back to the
3256   // underlying type before doing the compare.
3257   if (Op1.getValueType() != MemVT) {
3258     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3259     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3260   }
3261 
3262   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3263                                                         I.getType());
3264   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3265 }
3266 
3267 void SelectionDAGBuilder::visitFCmp(const User &I) {
3268   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3269   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3270     predicate = FC->getPredicate();
3271   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3272     predicate = FCmpInst::Predicate(FC->getPredicate());
3273   SDValue Op1 = getValue(I.getOperand(0));
3274   SDValue Op2 = getValue(I.getOperand(1));
3275 
3276   ISD::CondCode Condition = getFCmpCondCode(predicate);
3277   auto *FPMO = dyn_cast<FPMathOperator>(&I);
3278   if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
3279     Condition = getFCmpCodeWithoutNaN(Condition);
3280 
3281   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3282                                                         I.getType());
3283   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3284 }
3285 
3286 // Check if the condition of the select has one use or two users that are both
3287 // selects with the same condition.
3288 static bool hasOnlySelectUsers(const Value *Cond) {
3289   return llvm::all_of(Cond->users(), [](const Value *V) {
3290     return isa<SelectInst>(V);
3291   });
3292 }
3293 
3294 void SelectionDAGBuilder::visitSelect(const User &I) {
3295   SmallVector<EVT, 4> ValueVTs;
3296   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3297                   ValueVTs);
3298   unsigned NumValues = ValueVTs.size();
3299   if (NumValues == 0) return;
3300 
3301   SmallVector<SDValue, 4> Values(NumValues);
3302   SDValue Cond     = getValue(I.getOperand(0));
3303   SDValue LHSVal   = getValue(I.getOperand(1));
3304   SDValue RHSVal   = getValue(I.getOperand(2));
3305   auto BaseOps = {Cond};
3306   ISD::NodeType OpCode = Cond.getValueType().isVector() ?
3307     ISD::VSELECT : ISD::SELECT;
3308 
3309   bool IsUnaryAbs = false;
3310 
3311   // Min/max matching is only viable if all output VTs are the same.
3312   if (is_splat(ValueVTs)) {
3313     EVT VT = ValueVTs[0];
3314     LLVMContext &Ctx = *DAG.getContext();
3315     auto &TLI = DAG.getTargetLoweringInfo();
3316 
3317     // We care about the legality of the operation after it has been type
3318     // legalized.
3319     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3320       VT = TLI.getTypeToTransformTo(Ctx, VT);
3321 
3322     // If the vselect is legal, assume we want to leave this as a vector setcc +
3323     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3324     // min/max is legal on the scalar type.
3325     bool UseScalarMinMax = VT.isVector() &&
3326       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3327 
3328     Value *LHS, *RHS;
3329     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3330     ISD::NodeType Opc = ISD::DELETED_NODE;
3331     switch (SPR.Flavor) {
3332     case SPF_UMAX:    Opc = ISD::UMAX; break;
3333     case SPF_UMIN:    Opc = ISD::UMIN; break;
3334     case SPF_SMAX:    Opc = ISD::SMAX; break;
3335     case SPF_SMIN:    Opc = ISD::SMIN; break;
3336     case SPF_FMINNUM:
3337       switch (SPR.NaNBehavior) {
3338       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3339       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3340       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3341       case SPNB_RETURNS_ANY: {
3342         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3343           Opc = ISD::FMINNUM;
3344         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3345           Opc = ISD::FMINIMUM;
3346         else if (UseScalarMinMax)
3347           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3348             ISD::FMINNUM : ISD::FMINIMUM;
3349         break;
3350       }
3351       }
3352       break;
3353     case SPF_FMAXNUM:
3354       switch (SPR.NaNBehavior) {
3355       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3356       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3357       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3358       case SPNB_RETURNS_ANY:
3359 
3360         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3361           Opc = ISD::FMAXNUM;
3362         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3363           Opc = ISD::FMAXIMUM;
3364         else if (UseScalarMinMax)
3365           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3366             ISD::FMAXNUM : ISD::FMAXIMUM;
3367         break;
3368       }
3369       break;
3370     case SPF_ABS:
3371       IsUnaryAbs = true;
3372       Opc = ISD::ABS;
3373       break;
3374     case SPF_NABS:
3375       // TODO: we need to produce sub(0, abs(X)).
3376     default: break;
3377     }
3378 
3379     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3380         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3381          (UseScalarMinMax &&
3382           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3383         // If the underlying comparison instruction is used by any other
3384         // instruction, the consumed instructions won't be destroyed, so it is
3385         // not profitable to convert to a min/max.
3386         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3387       OpCode = Opc;
3388       LHSVal = getValue(LHS);
3389       RHSVal = getValue(RHS);
3390       BaseOps = {};
3391     }
3392 
3393     if (IsUnaryAbs) {
3394       OpCode = Opc;
3395       LHSVal = getValue(LHS);
3396       BaseOps = {};
3397     }
3398   }
3399 
3400   if (IsUnaryAbs) {
3401     for (unsigned i = 0; i != NumValues; ++i) {
3402       Values[i] =
3403           DAG.getNode(OpCode, getCurSDLoc(),
3404                       LHSVal.getNode()->getValueType(LHSVal.getResNo() + i),
3405                       SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3406     }
3407   } else {
3408     for (unsigned i = 0; i != NumValues; ++i) {
3409       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3410       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3411       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3412       Values[i] = DAG.getNode(
3413           OpCode, getCurSDLoc(),
3414           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops);
3415     }
3416   }
3417 
3418   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3419                            DAG.getVTList(ValueVTs), Values));
3420 }
3421 
3422 void SelectionDAGBuilder::visitTrunc(const User &I) {
3423   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3424   SDValue N = getValue(I.getOperand(0));
3425   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3426                                                         I.getType());
3427   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3428 }
3429 
3430 void SelectionDAGBuilder::visitZExt(const User &I) {
3431   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3432   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3433   SDValue N = getValue(I.getOperand(0));
3434   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3435                                                         I.getType());
3436   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3437 }
3438 
3439 void SelectionDAGBuilder::visitSExt(const User &I) {
3440   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3441   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3442   SDValue N = getValue(I.getOperand(0));
3443   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3444                                                         I.getType());
3445   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3446 }
3447 
3448 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3449   // FPTrunc is never a no-op cast, no need to check
3450   SDValue N = getValue(I.getOperand(0));
3451   SDLoc dl = getCurSDLoc();
3452   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3453   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3454   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3455                            DAG.getTargetConstant(
3456                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3457 }
3458 
3459 void SelectionDAGBuilder::visitFPExt(const User &I) {
3460   // FPExt is never a no-op cast, no need to check
3461   SDValue N = getValue(I.getOperand(0));
3462   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3463                                                         I.getType());
3464   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3465 }
3466 
3467 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3468   // FPToUI is never a no-op cast, no need to check
3469   SDValue N = getValue(I.getOperand(0));
3470   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3471                                                         I.getType());
3472   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3473 }
3474 
3475 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3476   // FPToSI is never a no-op cast, no need to check
3477   SDValue N = getValue(I.getOperand(0));
3478   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3479                                                         I.getType());
3480   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3481 }
3482 
3483 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3484   // UIToFP is never a no-op cast, no need to check
3485   SDValue N = getValue(I.getOperand(0));
3486   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3487                                                         I.getType());
3488   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3489 }
3490 
3491 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3492   // SIToFP is never a no-op cast, no need to check
3493   SDValue N = getValue(I.getOperand(0));
3494   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3495                                                         I.getType());
3496   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3497 }
3498 
3499 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3500   // What to do depends on the size of the integer and the size of the pointer.
3501   // We can either truncate, zero extend, or no-op, accordingly.
3502   SDValue N = getValue(I.getOperand(0));
3503   auto &TLI = DAG.getTargetLoweringInfo();
3504   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3505                                                         I.getType());
3506   EVT PtrMemVT =
3507       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3508   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3509   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3510   setValue(&I, N);
3511 }
3512 
3513 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3514   // What to do depends on the size of the integer and the size of the pointer.
3515   // We can either truncate, zero extend, or no-op, accordingly.
3516   SDValue N = getValue(I.getOperand(0));
3517   auto &TLI = DAG.getTargetLoweringInfo();
3518   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3519   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3520   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3521   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3522   setValue(&I, N);
3523 }
3524 
3525 void SelectionDAGBuilder::visitBitCast(const User &I) {
3526   SDValue N = getValue(I.getOperand(0));
3527   SDLoc dl = getCurSDLoc();
3528   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3529                                                         I.getType());
3530 
3531   // BitCast assures us that source and destination are the same size so this is
3532   // either a BITCAST or a no-op.
3533   if (DestVT != N.getValueType())
3534     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3535                              DestVT, N)); // convert types.
3536   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3537   // might fold any kind of constant expression to an integer constant and that
3538   // is not what we are looking for. Only recognize a bitcast of a genuine
3539   // constant integer as an opaque constant.
3540   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3541     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3542                                  /*isOpaque*/true));
3543   else
3544     setValue(&I, N);            // noop cast.
3545 }
3546 
3547 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3548   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3549   const Value *SV = I.getOperand(0);
3550   SDValue N = getValue(SV);
3551   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3552 
3553   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3554   unsigned DestAS = I.getType()->getPointerAddressSpace();
3555 
3556   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3557     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3558 
3559   setValue(&I, N);
3560 }
3561 
3562 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3563   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3564   SDValue InVec = getValue(I.getOperand(0));
3565   SDValue InVal = getValue(I.getOperand(1));
3566   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3567                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3568   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3569                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3570                            InVec, InVal, InIdx));
3571 }
3572 
3573 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3574   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3575   SDValue InVec = getValue(I.getOperand(0));
3576   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3577                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3578   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3579                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3580                            InVec, InIdx));
3581 }
3582 
3583 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3584   SDValue Src1 = getValue(I.getOperand(0));
3585   SDValue Src2 = getValue(I.getOperand(1));
3586   Constant *MaskV = cast<Constant>(I.getOperand(2));
3587   SDLoc DL = getCurSDLoc();
3588   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3589   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3590   EVT SrcVT = Src1.getValueType();
3591   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3592 
3593   if (MaskV->isNullValue() && VT.isScalableVector()) {
3594     // Canonical splat form of first element of first input vector.
3595     SDValue FirstElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
3596                                    SrcVT.getScalarType(), Src1,
3597                                    DAG.getConstant(0, DL,
3598                                    TLI.getVectorIdxTy(DAG.getDataLayout())));
3599     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3600     return;
3601   }
3602 
3603   // For now, we only handle splats for scalable vectors.
3604   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3605   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3606   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3607 
3608   SmallVector<int, 8> Mask;
3609   ShuffleVectorInst::getShuffleMask(MaskV, Mask);
3610   unsigned MaskNumElts = Mask.size();
3611 
3612   if (SrcNumElts == MaskNumElts) {
3613     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3614     return;
3615   }
3616 
3617   // Normalize the shuffle vector since mask and vector length don't match.
3618   if (SrcNumElts < MaskNumElts) {
3619     // Mask is longer than the source vectors. We can use concatenate vector to
3620     // make the mask and vectors lengths match.
3621 
3622     if (MaskNumElts % SrcNumElts == 0) {
3623       // Mask length is a multiple of the source vector length.
3624       // Check if the shuffle is some kind of concatenation of the input
3625       // vectors.
3626       unsigned NumConcat = MaskNumElts / SrcNumElts;
3627       bool IsConcat = true;
3628       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3629       for (unsigned i = 0; i != MaskNumElts; ++i) {
3630         int Idx = Mask[i];
3631         if (Idx < 0)
3632           continue;
3633         // Ensure the indices in each SrcVT sized piece are sequential and that
3634         // the same source is used for the whole piece.
3635         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3636             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3637              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3638           IsConcat = false;
3639           break;
3640         }
3641         // Remember which source this index came from.
3642         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3643       }
3644 
3645       // The shuffle is concatenating multiple vectors together. Just emit
3646       // a CONCAT_VECTORS operation.
3647       if (IsConcat) {
3648         SmallVector<SDValue, 8> ConcatOps;
3649         for (auto Src : ConcatSrcs) {
3650           if (Src < 0)
3651             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3652           else if (Src == 0)
3653             ConcatOps.push_back(Src1);
3654           else
3655             ConcatOps.push_back(Src2);
3656         }
3657         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3658         return;
3659       }
3660     }
3661 
3662     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3663     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3664     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3665                                     PaddedMaskNumElts);
3666 
3667     // Pad both vectors with undefs to make them the same length as the mask.
3668     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3669 
3670     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3671     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3672     MOps1[0] = Src1;
3673     MOps2[0] = Src2;
3674 
3675     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3676     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3677 
3678     // Readjust mask for new input vector length.
3679     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3680     for (unsigned i = 0; i != MaskNumElts; ++i) {
3681       int Idx = Mask[i];
3682       if (Idx >= (int)SrcNumElts)
3683         Idx -= SrcNumElts - PaddedMaskNumElts;
3684       MappedOps[i] = Idx;
3685     }
3686 
3687     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3688 
3689     // If the concatenated vector was padded, extract a subvector with the
3690     // correct number of elements.
3691     if (MaskNumElts != PaddedMaskNumElts)
3692       Result = DAG.getNode(
3693           ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3694           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
3695 
3696     setValue(&I, Result);
3697     return;
3698   }
3699 
3700   if (SrcNumElts > MaskNumElts) {
3701     // Analyze the access pattern of the vector to see if we can extract
3702     // two subvectors and do the shuffle.
3703     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3704     bool CanExtract = true;
3705     for (int Idx : Mask) {
3706       unsigned Input = 0;
3707       if (Idx < 0)
3708         continue;
3709 
3710       if (Idx >= (int)SrcNumElts) {
3711         Input = 1;
3712         Idx -= SrcNumElts;
3713       }
3714 
3715       // If all the indices come from the same MaskNumElts sized portion of
3716       // the sources we can use extract. Also make sure the extract wouldn't
3717       // extract past the end of the source.
3718       int NewStartIdx = alignDown(Idx, MaskNumElts);
3719       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3720           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3721         CanExtract = false;
3722       // Make sure we always update StartIdx as we use it to track if all
3723       // elements are undef.
3724       StartIdx[Input] = NewStartIdx;
3725     }
3726 
3727     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3728       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3729       return;
3730     }
3731     if (CanExtract) {
3732       // Extract appropriate subvector and generate a vector shuffle
3733       for (unsigned Input = 0; Input < 2; ++Input) {
3734         SDValue &Src = Input == 0 ? Src1 : Src2;
3735         if (StartIdx[Input] < 0)
3736           Src = DAG.getUNDEF(VT);
3737         else {
3738           Src = DAG.getNode(
3739               ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3740               DAG.getConstant(StartIdx[Input], DL,
3741                               TLI.getVectorIdxTy(DAG.getDataLayout())));
3742         }
3743       }
3744 
3745       // Calculate new mask.
3746       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3747       for (int &Idx : MappedOps) {
3748         if (Idx >= (int)SrcNumElts)
3749           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3750         else if (Idx >= 0)
3751           Idx -= StartIdx[0];
3752       }
3753 
3754       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3755       return;
3756     }
3757   }
3758 
3759   // We can't use either concat vectors or extract subvectors so fall back to
3760   // replacing the shuffle with extract and build vector.
3761   // to insert and build vector.
3762   EVT EltVT = VT.getVectorElementType();
3763   EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
3764   SmallVector<SDValue,8> Ops;
3765   for (int Idx : Mask) {
3766     SDValue Res;
3767 
3768     if (Idx < 0) {
3769       Res = DAG.getUNDEF(EltVT);
3770     } else {
3771       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3772       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3773 
3774       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
3775                         EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
3776     }
3777 
3778     Ops.push_back(Res);
3779   }
3780 
3781   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3782 }
3783 
3784 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3785   ArrayRef<unsigned> Indices;
3786   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3787     Indices = IV->getIndices();
3788   else
3789     Indices = cast<ConstantExpr>(&I)->getIndices();
3790 
3791   const Value *Op0 = I.getOperand(0);
3792   const Value *Op1 = I.getOperand(1);
3793   Type *AggTy = I.getType();
3794   Type *ValTy = Op1->getType();
3795   bool IntoUndef = isa<UndefValue>(Op0);
3796   bool FromUndef = isa<UndefValue>(Op1);
3797 
3798   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3799 
3800   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3801   SmallVector<EVT, 4> AggValueVTs;
3802   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3803   SmallVector<EVT, 4> ValValueVTs;
3804   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3805 
3806   unsigned NumAggValues = AggValueVTs.size();
3807   unsigned NumValValues = ValValueVTs.size();
3808   SmallVector<SDValue, 4> Values(NumAggValues);
3809 
3810   // Ignore an insertvalue that produces an empty object
3811   if (!NumAggValues) {
3812     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3813     return;
3814   }
3815 
3816   SDValue Agg = getValue(Op0);
3817   unsigned i = 0;
3818   // Copy the beginning value(s) from the original aggregate.
3819   for (; i != LinearIndex; ++i)
3820     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3821                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3822   // Copy values from the inserted value(s).
3823   if (NumValValues) {
3824     SDValue Val = getValue(Op1);
3825     for (; i != LinearIndex + NumValValues; ++i)
3826       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3827                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3828   }
3829   // Copy remaining value(s) from the original aggregate.
3830   for (; i != NumAggValues; ++i)
3831     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3832                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3833 
3834   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3835                            DAG.getVTList(AggValueVTs), Values));
3836 }
3837 
3838 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3839   ArrayRef<unsigned> Indices;
3840   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3841     Indices = EV->getIndices();
3842   else
3843     Indices = cast<ConstantExpr>(&I)->getIndices();
3844 
3845   const Value *Op0 = I.getOperand(0);
3846   Type *AggTy = Op0->getType();
3847   Type *ValTy = I.getType();
3848   bool OutOfUndef = isa<UndefValue>(Op0);
3849 
3850   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3851 
3852   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3853   SmallVector<EVT, 4> ValValueVTs;
3854   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3855 
3856   unsigned NumValValues = ValValueVTs.size();
3857 
3858   // Ignore a extractvalue that produces an empty object
3859   if (!NumValValues) {
3860     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3861     return;
3862   }
3863 
3864   SmallVector<SDValue, 4> Values(NumValValues);
3865 
3866   SDValue Agg = getValue(Op0);
3867   // Copy out the selected value(s).
3868   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3869     Values[i - LinearIndex] =
3870       OutOfUndef ?
3871         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3872         SDValue(Agg.getNode(), Agg.getResNo() + i);
3873 
3874   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3875                            DAG.getVTList(ValValueVTs), Values));
3876 }
3877 
3878 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3879   Value *Op0 = I.getOperand(0);
3880   // Note that the pointer operand may be a vector of pointers. Take the scalar
3881   // element which holds a pointer.
3882   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3883   SDValue N = getValue(Op0);
3884   SDLoc dl = getCurSDLoc();
3885   auto &TLI = DAG.getTargetLoweringInfo();
3886   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3887   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3888 
3889   // Normalize Vector GEP - all scalar operands should be converted to the
3890   // splat vector.
3891   unsigned VectorWidth = I.getType()->isVectorTy() ?
3892     I.getType()->getVectorNumElements() : 0;
3893 
3894   if (VectorWidth && !N.getValueType().isVector()) {
3895     LLVMContext &Context = *DAG.getContext();
3896     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
3897     N = DAG.getSplatBuildVector(VT, dl, N);
3898   }
3899 
3900   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3901        GTI != E; ++GTI) {
3902     const Value *Idx = GTI.getOperand();
3903     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3904       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3905       if (Field) {
3906         // N = N + Offset
3907         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3908 
3909         // In an inbounds GEP with an offset that is nonnegative even when
3910         // interpreted as signed, assume there is no unsigned overflow.
3911         SDNodeFlags Flags;
3912         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3913           Flags.setNoUnsignedWrap(true);
3914 
3915         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3916                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3917       }
3918     } else {
3919       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3920       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3921       APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
3922 
3923       // If this is a scalar constant or a splat vector of constants,
3924       // handle it quickly.
3925       const auto *C = dyn_cast<Constant>(Idx);
3926       if (C && isa<VectorType>(C->getType()))
3927         C = C->getSplatValue();
3928 
3929       if (const auto *CI = dyn_cast_or_null<ConstantInt>(C)) {
3930         if (CI->isZero())
3931           continue;
3932         APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
3933         LLVMContext &Context = *DAG.getContext();
3934         SDValue OffsVal = VectorWidth ?
3935           DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
3936           DAG.getConstant(Offs, dl, IdxTy);
3937 
3938         // In an inbounds GEP with an offset that is nonnegative even when
3939         // interpreted as signed, assume there is no unsigned overflow.
3940         SDNodeFlags Flags;
3941         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3942           Flags.setNoUnsignedWrap(true);
3943 
3944         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3945 
3946         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3947         continue;
3948       }
3949 
3950       // N = N + Idx * ElementSize;
3951       SDValue IdxN = getValue(Idx);
3952 
3953       if (!IdxN.getValueType().isVector() && VectorWidth) {
3954         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
3955         IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3956       }
3957 
3958       // If the index is smaller or larger than intptr_t, truncate or extend
3959       // it.
3960       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3961 
3962       // If this is a multiply by a power of two, turn it into a shl
3963       // immediately.  This is a very common case.
3964       if (ElementSize != 1) {
3965         if (ElementSize.isPowerOf2()) {
3966           unsigned Amt = ElementSize.logBase2();
3967           IdxN = DAG.getNode(ISD::SHL, dl,
3968                              N.getValueType(), IdxN,
3969                              DAG.getConstant(Amt, dl, IdxN.getValueType()));
3970         } else {
3971           SDValue Scale = DAG.getConstant(ElementSize.getZExtValue(), dl,
3972                                           IdxN.getValueType());
3973           IdxN = DAG.getNode(ISD::MUL, dl,
3974                              N.getValueType(), IdxN, Scale);
3975         }
3976       }
3977 
3978       N = DAG.getNode(ISD::ADD, dl,
3979                       N.getValueType(), N, IdxN);
3980     }
3981   }
3982 
3983   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
3984     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
3985 
3986   setValue(&I, N);
3987 }
3988 
3989 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3990   // If this is a fixed sized alloca in the entry block of the function,
3991   // allocate it statically on the stack.
3992   if (FuncInfo.StaticAllocaMap.count(&I))
3993     return;   // getValue will auto-populate this.
3994 
3995   SDLoc dl = getCurSDLoc();
3996   Type *Ty = I.getAllocatedType();
3997   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3998   auto &DL = DAG.getDataLayout();
3999   uint64_t TySize = DL.getTypeAllocSize(Ty);
4000   unsigned Align =
4001       std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
4002 
4003   SDValue AllocSize = getValue(I.getArraySize());
4004 
4005   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
4006   if (AllocSize.getValueType() != IntPtr)
4007     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4008 
4009   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
4010                           AllocSize,
4011                           DAG.getConstant(TySize, dl, IntPtr));
4012 
4013   // Handle alignment.  If the requested alignment is less than or equal to
4014   // the stack alignment, ignore it.  If the size is greater than or equal to
4015   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4016   unsigned StackAlign =
4017       DAG.getSubtarget().getFrameLowering()->getStackAlignment();
4018   if (Align <= StackAlign)
4019     Align = 0;
4020 
4021   // Round the size of the allocation up to the stack alignment size
4022   // by add SA-1 to the size. This doesn't overflow because we're computing
4023   // an address inside an alloca.
4024   SDNodeFlags Flags;
4025   Flags.setNoUnsignedWrap(true);
4026   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4027                           DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
4028 
4029   // Mask out the low bits for alignment purposes.
4030   AllocSize =
4031       DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4032                   DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
4033 
4034   SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
4035   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4036   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4037   setValue(&I, DSA);
4038   DAG.setRoot(DSA.getValue(1));
4039 
4040   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4041 }
4042 
4043 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4044   if (I.isAtomic())
4045     return visitAtomicLoad(I);
4046 
4047   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4048   const Value *SV = I.getOperand(0);
4049   if (TLI.supportSwiftError()) {
4050     // Swifterror values can come from either a function parameter with
4051     // swifterror attribute or an alloca with swifterror attribute.
4052     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4053       if (Arg->hasSwiftErrorAttr())
4054         return visitLoadFromSwiftError(I);
4055     }
4056 
4057     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4058       if (Alloca->isSwiftError())
4059         return visitLoadFromSwiftError(I);
4060     }
4061   }
4062 
4063   SDValue Ptr = getValue(SV);
4064 
4065   Type *Ty = I.getType();
4066 
4067   bool isVolatile = I.isVolatile();
4068   bool isNonTemporal = I.hasMetadata(LLVMContext::MD_nontemporal);
4069   bool isInvariant = I.hasMetadata(LLVMContext::MD_invariant_load);
4070   bool isDereferenceable =
4071       isDereferenceablePointer(SV, I.getType(), DAG.getDataLayout());
4072   unsigned Alignment = I.getAlignment();
4073 
4074   AAMDNodes AAInfo;
4075   I.getAAMetadata(AAInfo);
4076   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4077 
4078   SmallVector<EVT, 4> ValueVTs, MemVTs;
4079   SmallVector<uint64_t, 4> Offsets;
4080   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4081   unsigned NumValues = ValueVTs.size();
4082   if (NumValues == 0)
4083     return;
4084 
4085   SDValue Root;
4086   bool ConstantMemory = false;
4087   if (isVolatile)
4088     // Serialize volatile loads with other side effects.
4089     Root = getRoot();
4090   else if (NumValues > MaxParallelChains)
4091     Root = getMemoryRoot();
4092   else if (AA &&
4093            AA->pointsToConstantMemory(MemoryLocation(
4094                SV,
4095                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4096                AAInfo))) {
4097     // Do not serialize (non-volatile) loads of constant memory with anything.
4098     Root = DAG.getEntryNode();
4099     ConstantMemory = true;
4100   } else {
4101     // Do not serialize non-volatile loads against each other.
4102     Root = DAG.getRoot();
4103   }
4104 
4105   SDLoc dl = getCurSDLoc();
4106 
4107   if (isVolatile)
4108     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4109 
4110   // An aggregate load cannot wrap around the address space, so offsets to its
4111   // parts don't wrap either.
4112   SDNodeFlags Flags;
4113   Flags.setNoUnsignedWrap(true);
4114 
4115   SmallVector<SDValue, 4> Values(NumValues);
4116   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4117   EVT PtrVT = Ptr.getValueType();
4118   unsigned ChainI = 0;
4119   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4120     // Serializing loads here may result in excessive register pressure, and
4121     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4122     // could recover a bit by hoisting nodes upward in the chain by recognizing
4123     // they are side-effect free or do not alias. The optimizer should really
4124     // avoid this case by converting large object/array copies to llvm.memcpy
4125     // (MaxParallelChains should always remain as failsafe).
4126     if (ChainI == MaxParallelChains) {
4127       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4128       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4129                                   makeArrayRef(Chains.data(), ChainI));
4130       Root = Chain;
4131       ChainI = 0;
4132     }
4133     SDValue A = DAG.getNode(ISD::ADD, dl,
4134                             PtrVT, Ptr,
4135                             DAG.getConstant(Offsets[i], dl, PtrVT),
4136                             Flags);
4137     auto MMOFlags = MachineMemOperand::MONone;
4138     if (isVolatile)
4139       MMOFlags |= MachineMemOperand::MOVolatile;
4140     if (isNonTemporal)
4141       MMOFlags |= MachineMemOperand::MONonTemporal;
4142     if (isInvariant)
4143       MMOFlags |= MachineMemOperand::MOInvariant;
4144     if (isDereferenceable)
4145       MMOFlags |= MachineMemOperand::MODereferenceable;
4146     MMOFlags |= TLI.getMMOFlags(I);
4147 
4148     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4149                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4150                             MMOFlags, AAInfo, Ranges);
4151     Chains[ChainI] = L.getValue(1);
4152 
4153     if (MemVTs[i] != ValueVTs[i])
4154       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4155 
4156     Values[i] = L;
4157   }
4158 
4159   if (!ConstantMemory) {
4160     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4161                                 makeArrayRef(Chains.data(), ChainI));
4162     if (isVolatile)
4163       DAG.setRoot(Chain);
4164     else
4165       PendingLoads.push_back(Chain);
4166   }
4167 
4168   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4169                            DAG.getVTList(ValueVTs), Values));
4170 }
4171 
4172 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4173   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4174          "call visitStoreToSwiftError when backend supports swifterror");
4175 
4176   SmallVector<EVT, 4> ValueVTs;
4177   SmallVector<uint64_t, 4> Offsets;
4178   const Value *SrcV = I.getOperand(0);
4179   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4180                   SrcV->getType(), ValueVTs, &Offsets);
4181   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4182          "expect a single EVT for swifterror");
4183 
4184   SDValue Src = getValue(SrcV);
4185   // Create a virtual register, then update the virtual register.
4186   Register VReg =
4187       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4188   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4189   // Chain can be getRoot or getControlRoot.
4190   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4191                                       SDValue(Src.getNode(), Src.getResNo()));
4192   DAG.setRoot(CopyNode);
4193 }
4194 
4195 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4196   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4197          "call visitLoadFromSwiftError when backend supports swifterror");
4198 
4199   assert(!I.isVolatile() &&
4200          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4201          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4202          "Support volatile, non temporal, invariant for load_from_swift_error");
4203 
4204   const Value *SV = I.getOperand(0);
4205   Type *Ty = I.getType();
4206   AAMDNodes AAInfo;
4207   I.getAAMetadata(AAInfo);
4208   assert(
4209       (!AA ||
4210        !AA->pointsToConstantMemory(MemoryLocation(
4211            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4212            AAInfo))) &&
4213       "load_from_swift_error should not be constant memory");
4214 
4215   SmallVector<EVT, 4> ValueVTs;
4216   SmallVector<uint64_t, 4> Offsets;
4217   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4218                   ValueVTs, &Offsets);
4219   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4220          "expect a single EVT for swifterror");
4221 
4222   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4223   SDValue L = DAG.getCopyFromReg(
4224       getRoot(), getCurSDLoc(),
4225       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4226 
4227   setValue(&I, L);
4228 }
4229 
4230 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4231   if (I.isAtomic())
4232     return visitAtomicStore(I);
4233 
4234   const Value *SrcV = I.getOperand(0);
4235   const Value *PtrV = I.getOperand(1);
4236 
4237   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4238   if (TLI.supportSwiftError()) {
4239     // Swifterror values can come from either a function parameter with
4240     // swifterror attribute or an alloca with swifterror attribute.
4241     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4242       if (Arg->hasSwiftErrorAttr())
4243         return visitStoreToSwiftError(I);
4244     }
4245 
4246     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4247       if (Alloca->isSwiftError())
4248         return visitStoreToSwiftError(I);
4249     }
4250   }
4251 
4252   SmallVector<EVT, 4> ValueVTs, MemVTs;
4253   SmallVector<uint64_t, 4> Offsets;
4254   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4255                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4256   unsigned NumValues = ValueVTs.size();
4257   if (NumValues == 0)
4258     return;
4259 
4260   // Get the lowered operands. Note that we do this after
4261   // checking if NumResults is zero, because with zero results
4262   // the operands won't have values in the map.
4263   SDValue Src = getValue(SrcV);
4264   SDValue Ptr = getValue(PtrV);
4265 
4266   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4267   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4268   SDLoc dl = getCurSDLoc();
4269   unsigned Alignment = I.getAlignment();
4270   AAMDNodes AAInfo;
4271   I.getAAMetadata(AAInfo);
4272 
4273   auto MMOFlags = MachineMemOperand::MONone;
4274   if (I.isVolatile())
4275     MMOFlags |= MachineMemOperand::MOVolatile;
4276   if (I.hasMetadata(LLVMContext::MD_nontemporal))
4277     MMOFlags |= MachineMemOperand::MONonTemporal;
4278   MMOFlags |= TLI.getMMOFlags(I);
4279 
4280   // An aggregate load cannot wrap around the address space, so offsets to its
4281   // parts don't wrap either.
4282   SDNodeFlags Flags;
4283   Flags.setNoUnsignedWrap(true);
4284 
4285   unsigned ChainI = 0;
4286   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4287     // See visitLoad comments.
4288     if (ChainI == MaxParallelChains) {
4289       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4290                                   makeArrayRef(Chains.data(), ChainI));
4291       Root = Chain;
4292       ChainI = 0;
4293     }
4294     SDValue Add = DAG.getMemBasePlusOffset(Ptr, Offsets[i], dl, Flags);
4295     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4296     if (MemVTs[i] != ValueVTs[i])
4297       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4298     SDValue St =
4299         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4300                      Alignment, MMOFlags, AAInfo);
4301     Chains[ChainI] = St;
4302   }
4303 
4304   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4305                                   makeArrayRef(Chains.data(), ChainI));
4306   DAG.setRoot(StoreNode);
4307 }
4308 
4309 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4310                                            bool IsCompressing) {
4311   SDLoc sdl = getCurSDLoc();
4312 
4313   auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4314                            unsigned& Alignment) {
4315     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4316     Src0 = I.getArgOperand(0);
4317     Ptr = I.getArgOperand(1);
4318     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
4319     Mask = I.getArgOperand(3);
4320   };
4321   auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4322                            unsigned& Alignment) {
4323     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4324     Src0 = I.getArgOperand(0);
4325     Ptr = I.getArgOperand(1);
4326     Mask = I.getArgOperand(2);
4327     Alignment = 0;
4328   };
4329 
4330   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4331   unsigned Alignment;
4332   if (IsCompressing)
4333     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4334   else
4335     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4336 
4337   SDValue Ptr = getValue(PtrOperand);
4338   SDValue Src0 = getValue(Src0Operand);
4339   SDValue Mask = getValue(MaskOperand);
4340   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4341 
4342   EVT VT = Src0.getValueType();
4343   if (!Alignment)
4344     Alignment = DAG.getEVTAlignment(VT);
4345 
4346   AAMDNodes AAInfo;
4347   I.getAAMetadata(AAInfo);
4348 
4349   MachineMemOperand *MMO =
4350     DAG.getMachineFunction().
4351     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4352                           MachineMemOperand::MOStore,
4353                           // TODO: Make MachineMemOperands aware of scalable
4354                           // vectors.
4355                           VT.getStoreSize().getKnownMinSize(),
4356                           Alignment, AAInfo);
4357   SDValue StoreNode =
4358       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4359                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4360   DAG.setRoot(StoreNode);
4361   setValue(&I, StoreNode);
4362 }
4363 
4364 // Get a uniform base for the Gather/Scatter intrinsic.
4365 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4366 // We try to represent it as a base pointer + vector of indices.
4367 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4368 // The first operand of the GEP may be a single pointer or a vector of pointers
4369 // Example:
4370 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4371 //  or
4372 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4373 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4374 //
4375 // When the first GEP operand is a single pointer - it is the uniform base we
4376 // are looking for. If first operand of the GEP is a splat vector - we
4377 // extract the splat value and use it as a uniform base.
4378 // In all other cases the function returns 'false'.
4379 static bool getUniformBase(const Value *&Ptr, SDValue &Base, SDValue &Index,
4380                            ISD::MemIndexType &IndexType, SDValue &Scale,
4381                            SelectionDAGBuilder *SDB) {
4382   SelectionDAG& DAG = SDB->DAG;
4383   LLVMContext &Context = *DAG.getContext();
4384 
4385   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4386   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4387   if (!GEP)
4388     return false;
4389 
4390   const Value *GEPPtr = GEP->getPointerOperand();
4391   if (!GEPPtr->getType()->isVectorTy())
4392     Ptr = GEPPtr;
4393   else if (!(Ptr = getSplatValue(GEPPtr)))
4394     return false;
4395 
4396   unsigned FinalIndex = GEP->getNumOperands() - 1;
4397   Value *IndexVal = GEP->getOperand(FinalIndex);
4398   gep_type_iterator GTI = gep_type_begin(*GEP);
4399 
4400   // Ensure all the other indices are 0.
4401   for (unsigned i = 1; i < FinalIndex; ++i, ++GTI) {
4402     auto *C = dyn_cast<Constant>(GEP->getOperand(i));
4403     if (!C)
4404       return false;
4405     if (isa<VectorType>(C->getType()))
4406       C = C->getSplatValue();
4407     auto *CI = dyn_cast_or_null<ConstantInt>(C);
4408     if (!CI || !CI->isZero())
4409       return false;
4410   }
4411 
4412   // The operands of the GEP may be defined in another basic block.
4413   // In this case we'll not find nodes for the operands.
4414   if (!SDB->findValue(Ptr))
4415     return false;
4416   Constant *C = dyn_cast<Constant>(IndexVal);
4417   if (!C && !SDB->findValue(IndexVal))
4418     return false;
4419 
4420   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4421   const DataLayout &DL = DAG.getDataLayout();
4422   StructType *STy = GTI.getStructTypeOrNull();
4423 
4424   if (STy) {
4425     const StructLayout *SL = DL.getStructLayout(STy);
4426     if (isa<VectorType>(C->getType())) {
4427       C = C->getSplatValue();
4428       // FIXME: If getSplatValue may return nullptr for a structure?
4429       // If not, the following check can be removed.
4430       if (!C)
4431         return false;
4432     }
4433     auto *CI = cast<ConstantInt>(C);
4434     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4435     Index = DAG.getConstant(SL->getElementOffset(CI->getZExtValue()),
4436                             SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4437   } else {
4438     Scale = DAG.getTargetConstant(
4439                 DL.getTypeAllocSize(GEP->getResultElementType()),
4440                 SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4441     Index = SDB->getValue(IndexVal);
4442   }
4443   Base = SDB->getValue(Ptr);
4444   IndexType = ISD::SIGNED_SCALED;
4445 
4446   if (STy || !Index.getValueType().isVector()) {
4447     unsigned GEPWidth = GEP->getType()->getVectorNumElements();
4448     EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
4449     Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
4450   }
4451   return true;
4452 }
4453 
4454 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4455   SDLoc sdl = getCurSDLoc();
4456 
4457   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4458   const Value *Ptr = I.getArgOperand(1);
4459   SDValue Src0 = getValue(I.getArgOperand(0));
4460   SDValue Mask = getValue(I.getArgOperand(3));
4461   EVT VT = Src0.getValueType();
4462   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
4463   if (!Alignment)
4464     Alignment = DAG.getEVTAlignment(VT);
4465   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4466 
4467   AAMDNodes AAInfo;
4468   I.getAAMetadata(AAInfo);
4469 
4470   SDValue Base;
4471   SDValue Index;
4472   ISD::MemIndexType IndexType;
4473   SDValue Scale;
4474   const Value *BasePtr = Ptr;
4475   bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale,
4476                                     this);
4477 
4478   const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
4479   MachineMemOperand *MMO = DAG.getMachineFunction().
4480     getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
4481                          MachineMemOperand::MOStore,
4482                          // TODO: Make MachineMemOperands aware of scalable
4483                          // vectors.
4484                          VT.getStoreSize().getKnownMinSize(),
4485                          Alignment, AAInfo);
4486   if (!UniformBase) {
4487     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4488     Index = getValue(Ptr);
4489     IndexType = ISD::SIGNED_SCALED;
4490     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4491   }
4492   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4493   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4494                                          Ops, MMO, IndexType);
4495   DAG.setRoot(Scatter);
4496   setValue(&I, Scatter);
4497 }
4498 
4499 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4500   SDLoc sdl = getCurSDLoc();
4501 
4502   auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4503                            unsigned& Alignment) {
4504     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4505     Ptr = I.getArgOperand(0);
4506     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
4507     Mask = I.getArgOperand(2);
4508     Src0 = I.getArgOperand(3);
4509   };
4510   auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4511                            unsigned& Alignment) {
4512     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4513     Ptr = I.getArgOperand(0);
4514     Alignment = 0;
4515     Mask = I.getArgOperand(1);
4516     Src0 = I.getArgOperand(2);
4517   };
4518 
4519   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4520   unsigned Alignment;
4521   if (IsExpanding)
4522     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4523   else
4524     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4525 
4526   SDValue Ptr = getValue(PtrOperand);
4527   SDValue Src0 = getValue(Src0Operand);
4528   SDValue Mask = getValue(MaskOperand);
4529   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4530 
4531   EVT VT = Src0.getValueType();
4532   if (!Alignment)
4533     Alignment = DAG.getEVTAlignment(VT);
4534 
4535   AAMDNodes AAInfo;
4536   I.getAAMetadata(AAInfo);
4537   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4538 
4539   // Do not serialize masked loads of constant memory with anything.
4540   MemoryLocation ML;
4541   if (VT.isScalableVector())
4542     ML = MemoryLocation(PtrOperand);
4543   else
4544     ML = MemoryLocation(PtrOperand, LocationSize::precise(
4545                            DAG.getDataLayout().getTypeStoreSize(I.getType())),
4546                            AAInfo);
4547   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4548 
4549   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4550 
4551   MachineMemOperand *MMO =
4552     DAG.getMachineFunction().
4553     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4554                           MachineMemOperand::MOLoad,
4555                           // TODO: Make MachineMemOperands aware of scalable
4556                           // vectors.
4557                           VT.getStoreSize().getKnownMinSize(),
4558                           Alignment, AAInfo, Ranges);
4559 
4560   SDValue Load =
4561       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4562                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4563   if (AddToChain)
4564     PendingLoads.push_back(Load.getValue(1));
4565   setValue(&I, Load);
4566 }
4567 
4568 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4569   SDLoc sdl = getCurSDLoc();
4570 
4571   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4572   const Value *Ptr = I.getArgOperand(0);
4573   SDValue Src0 = getValue(I.getArgOperand(3));
4574   SDValue Mask = getValue(I.getArgOperand(2));
4575 
4576   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4577   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4578   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
4579   if (!Alignment)
4580     Alignment = DAG.getEVTAlignment(VT);
4581 
4582   AAMDNodes AAInfo;
4583   I.getAAMetadata(AAInfo);
4584   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4585 
4586   SDValue Root = DAG.getRoot();
4587   SDValue Base;
4588   SDValue Index;
4589   ISD::MemIndexType IndexType;
4590   SDValue Scale;
4591   const Value *BasePtr = Ptr;
4592   bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale,
4593                                     this);
4594   bool ConstantMemory = false;
4595   if (UniformBase && AA &&
4596       AA->pointsToConstantMemory(
4597           MemoryLocation(BasePtr,
4598                          LocationSize::precise(
4599                              DAG.getDataLayout().getTypeStoreSize(I.getType())),
4600                          AAInfo))) {
4601     // Do not serialize (non-volatile) loads of constant memory with anything.
4602     Root = DAG.getEntryNode();
4603     ConstantMemory = true;
4604   }
4605 
4606   MachineMemOperand *MMO =
4607     DAG.getMachineFunction().
4608     getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
4609                          MachineMemOperand::MOLoad,
4610                          // TODO: Make MachineMemOperands aware of scalable
4611                          // vectors.
4612                          VT.getStoreSize().getKnownMinSize(),
4613                          Alignment, AAInfo, Ranges);
4614 
4615   if (!UniformBase) {
4616     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4617     Index = getValue(Ptr);
4618     IndexType = ISD::SIGNED_SCALED;
4619     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4620   }
4621   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4622   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4623                                        Ops, MMO, IndexType);
4624 
4625   SDValue OutChain = Gather.getValue(1);
4626   if (!ConstantMemory)
4627     PendingLoads.push_back(OutChain);
4628   setValue(&I, Gather);
4629 }
4630 
4631 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4632   SDLoc dl = getCurSDLoc();
4633   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4634   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4635   SyncScope::ID SSID = I.getSyncScopeID();
4636 
4637   SDValue InChain = getRoot();
4638 
4639   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4640   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4641 
4642   auto Alignment = DAG.getEVTAlignment(MemVT);
4643 
4644   auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
4645   if (I.isVolatile())
4646     Flags |= MachineMemOperand::MOVolatile;
4647   Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
4648 
4649   MachineFunction &MF = DAG.getMachineFunction();
4650   MachineMemOperand *MMO =
4651     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4652                             Flags, MemVT.getStoreSize(), Alignment,
4653                             AAMDNodes(), nullptr, SSID, SuccessOrdering,
4654                             FailureOrdering);
4655 
4656   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4657                                    dl, MemVT, VTs, InChain,
4658                                    getValue(I.getPointerOperand()),
4659                                    getValue(I.getCompareOperand()),
4660                                    getValue(I.getNewValOperand()), MMO);
4661 
4662   SDValue OutChain = L.getValue(2);
4663 
4664   setValue(&I, L);
4665   DAG.setRoot(OutChain);
4666 }
4667 
4668 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4669   SDLoc dl = getCurSDLoc();
4670   ISD::NodeType NT;
4671   switch (I.getOperation()) {
4672   default: llvm_unreachable("Unknown atomicrmw operation");
4673   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4674   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4675   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4676   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4677   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4678   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4679   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4680   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4681   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4682   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4683   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4684   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4685   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4686   }
4687   AtomicOrdering Ordering = I.getOrdering();
4688   SyncScope::ID SSID = I.getSyncScopeID();
4689 
4690   SDValue InChain = getRoot();
4691 
4692   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4693   auto Alignment = DAG.getEVTAlignment(MemVT);
4694 
4695   auto Flags = MachineMemOperand::MOLoad |  MachineMemOperand::MOStore;
4696   if (I.isVolatile())
4697     Flags |= MachineMemOperand::MOVolatile;
4698   Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
4699 
4700   MachineFunction &MF = DAG.getMachineFunction();
4701   MachineMemOperand *MMO =
4702     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
4703                             MemVT.getStoreSize(), Alignment, AAMDNodes(),
4704                             nullptr, SSID, Ordering);
4705 
4706   SDValue L =
4707     DAG.getAtomic(NT, dl, MemVT, InChain,
4708                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4709                   MMO);
4710 
4711   SDValue OutChain = L.getValue(1);
4712 
4713   setValue(&I, L);
4714   DAG.setRoot(OutChain);
4715 }
4716 
4717 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4718   SDLoc dl = getCurSDLoc();
4719   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4720   SDValue Ops[3];
4721   Ops[0] = getRoot();
4722   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4723                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4724   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4725                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4726   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4727 }
4728 
4729 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4730   SDLoc dl = getCurSDLoc();
4731   AtomicOrdering Order = I.getOrdering();
4732   SyncScope::ID SSID = I.getSyncScopeID();
4733 
4734   SDValue InChain = getRoot();
4735 
4736   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4737   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4738   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4739 
4740   if (!TLI.supportsUnalignedAtomics() &&
4741       I.getAlignment() < MemVT.getSizeInBits() / 8)
4742     report_fatal_error("Cannot generate unaligned atomic load");
4743 
4744   auto Flags = MachineMemOperand::MOLoad;
4745   if (I.isVolatile())
4746     Flags |= MachineMemOperand::MOVolatile;
4747   if (I.hasMetadata(LLVMContext::MD_invariant_load))
4748     Flags |= MachineMemOperand::MOInvariant;
4749   if (isDereferenceablePointer(I.getPointerOperand(), I.getType(),
4750                                DAG.getDataLayout()))
4751     Flags |= MachineMemOperand::MODereferenceable;
4752 
4753   Flags |= TLI.getMMOFlags(I);
4754 
4755   MachineMemOperand *MMO =
4756       DAG.getMachineFunction().
4757       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4758                            Flags, MemVT.getStoreSize(),
4759                            I.getAlignment() ? I.getAlignment() :
4760                                               DAG.getEVTAlignment(MemVT),
4761                            AAMDNodes(), nullptr, SSID, Order);
4762 
4763   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4764 
4765   SDValue Ptr = getValue(I.getPointerOperand());
4766 
4767   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4768     // TODO: Once this is better exercised by tests, it should be merged with
4769     // the normal path for loads to prevent future divergence.
4770     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4771     if (MemVT != VT)
4772       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4773 
4774     setValue(&I, L);
4775     SDValue OutChain = L.getValue(1);
4776     if (!I.isUnordered())
4777       DAG.setRoot(OutChain);
4778     else
4779       PendingLoads.push_back(OutChain);
4780     return;
4781   }
4782 
4783   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4784                             Ptr, MMO);
4785 
4786   SDValue OutChain = L.getValue(1);
4787   if (MemVT != VT)
4788     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4789 
4790   setValue(&I, L);
4791   DAG.setRoot(OutChain);
4792 }
4793 
4794 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4795   SDLoc dl = getCurSDLoc();
4796 
4797   AtomicOrdering Ordering = I.getOrdering();
4798   SyncScope::ID SSID = I.getSyncScopeID();
4799 
4800   SDValue InChain = getRoot();
4801 
4802   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4803   EVT MemVT =
4804       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4805 
4806   if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4807     report_fatal_error("Cannot generate unaligned atomic store");
4808 
4809   auto Flags = MachineMemOperand::MOStore;
4810   if (I.isVolatile())
4811     Flags |= MachineMemOperand::MOVolatile;
4812   Flags |= TLI.getMMOFlags(I);
4813 
4814   MachineFunction &MF = DAG.getMachineFunction();
4815   MachineMemOperand *MMO =
4816     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
4817                             MemVT.getStoreSize(), I.getAlignment(), AAMDNodes(),
4818                             nullptr, SSID, Ordering);
4819 
4820   SDValue Val = getValue(I.getValueOperand());
4821   if (Val.getValueType() != MemVT)
4822     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4823   SDValue Ptr = getValue(I.getPointerOperand());
4824 
4825   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4826     // TODO: Once this is better exercised by tests, it should be merged with
4827     // the normal path for stores to prevent future divergence.
4828     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4829     DAG.setRoot(S);
4830     return;
4831   }
4832   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4833                                    Ptr, Val, MMO);
4834 
4835 
4836   DAG.setRoot(OutChain);
4837 }
4838 
4839 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4840 /// node.
4841 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4842                                                unsigned Intrinsic) {
4843   // Ignore the callsite's attributes. A specific call site may be marked with
4844   // readnone, but the lowering code will expect the chain based on the
4845   // definition.
4846   const Function *F = I.getCalledFunction();
4847   bool HasChain = !F->doesNotAccessMemory();
4848   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4849 
4850   // Build the operand list.
4851   SmallVector<SDValue, 8> Ops;
4852   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4853     if (OnlyLoad) {
4854       // We don't need to serialize loads against other loads.
4855       Ops.push_back(DAG.getRoot());
4856     } else {
4857       Ops.push_back(getRoot());
4858     }
4859   }
4860 
4861   // Info is set by getTgtMemInstrinsic
4862   TargetLowering::IntrinsicInfo Info;
4863   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4864   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4865                                                DAG.getMachineFunction(),
4866                                                Intrinsic);
4867 
4868   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4869   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4870       Info.opc == ISD::INTRINSIC_W_CHAIN)
4871     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4872                                         TLI.getPointerTy(DAG.getDataLayout())));
4873 
4874   // Add all operands of the call to the operand list.
4875   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4876     const Value *Arg = I.getArgOperand(i);
4877     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4878       Ops.push_back(getValue(Arg));
4879       continue;
4880     }
4881 
4882     // Use TargetConstant instead of a regular constant for immarg.
4883     EVT VT = TLI.getValueType(*DL, Arg->getType(), true);
4884     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4885       assert(CI->getBitWidth() <= 64 &&
4886              "large intrinsic immediates not handled");
4887       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4888     } else {
4889       Ops.push_back(
4890           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4891     }
4892   }
4893 
4894   SmallVector<EVT, 4> ValueVTs;
4895   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4896 
4897   if (HasChain)
4898     ValueVTs.push_back(MVT::Other);
4899 
4900   SDVTList VTs = DAG.getVTList(ValueVTs);
4901 
4902   // Create the node.
4903   SDValue Result;
4904   if (IsTgtIntrinsic) {
4905     // This is target intrinsic that touches memory
4906     AAMDNodes AAInfo;
4907     I.getAAMetadata(AAInfo);
4908     Result = DAG.getMemIntrinsicNode(
4909         Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4910         MachinePointerInfo(Info.ptrVal, Info.offset),
4911         Info.align ? Info.align->value() : 0, Info.flags, Info.size, AAInfo);
4912   } else if (!HasChain) {
4913     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4914   } else if (!I.getType()->isVoidTy()) {
4915     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4916   } else {
4917     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4918   }
4919 
4920   if (HasChain) {
4921     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4922     if (OnlyLoad)
4923       PendingLoads.push_back(Chain);
4924     else
4925       DAG.setRoot(Chain);
4926   }
4927 
4928   if (!I.getType()->isVoidTy()) {
4929     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4930       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4931       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4932     } else
4933       Result = lowerRangeToAssertZExt(DAG, I, Result);
4934 
4935     setValue(&I, Result);
4936   }
4937 }
4938 
4939 /// GetSignificand - Get the significand and build it into a floating-point
4940 /// number with exponent of 1:
4941 ///
4942 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4943 ///
4944 /// where Op is the hexadecimal representation of floating point value.
4945 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4946   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4947                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4948   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4949                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4950   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4951 }
4952 
4953 /// GetExponent - Get the exponent:
4954 ///
4955 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4956 ///
4957 /// where Op is the hexadecimal representation of floating point value.
4958 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4959                            const TargetLowering &TLI, const SDLoc &dl) {
4960   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4961                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4962   SDValue t1 = DAG.getNode(
4963       ISD::SRL, dl, MVT::i32, t0,
4964       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4965   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4966                            DAG.getConstant(127, dl, MVT::i32));
4967   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4968 }
4969 
4970 /// getF32Constant - Get 32-bit floating point constant.
4971 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4972                               const SDLoc &dl) {
4973   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4974                            MVT::f32);
4975 }
4976 
4977 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4978                                        SelectionDAG &DAG) {
4979   // TODO: What fast-math-flags should be set on the floating-point nodes?
4980 
4981   //   IntegerPartOfX = ((int32_t)(t0);
4982   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4983 
4984   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4985   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4986   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4987 
4988   //   IntegerPartOfX <<= 23;
4989   IntegerPartOfX = DAG.getNode(
4990       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4991       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4992                                   DAG.getDataLayout())));
4993 
4994   SDValue TwoToFractionalPartOfX;
4995   if (LimitFloatPrecision <= 6) {
4996     // For floating-point precision of 6:
4997     //
4998     //   TwoToFractionalPartOfX =
4999     //     0.997535578f +
5000     //       (0.735607626f + 0.252464424f * x) * x;
5001     //
5002     // error 0.0144103317, which is 6 bits
5003     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5004                              getF32Constant(DAG, 0x3e814304, dl));
5005     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5006                              getF32Constant(DAG, 0x3f3c50c8, dl));
5007     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5008     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5009                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
5010   } else if (LimitFloatPrecision <= 12) {
5011     // For floating-point precision of 12:
5012     //
5013     //   TwoToFractionalPartOfX =
5014     //     0.999892986f +
5015     //       (0.696457318f +
5016     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
5017     //
5018     // error 0.000107046256, which is 13 to 14 bits
5019     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5020                              getF32Constant(DAG, 0x3da235e3, dl));
5021     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5022                              getF32Constant(DAG, 0x3e65b8f3, dl));
5023     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5024     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5025                              getF32Constant(DAG, 0x3f324b07, dl));
5026     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5027     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5028                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
5029   } else { // LimitFloatPrecision <= 18
5030     // For floating-point precision of 18:
5031     //
5032     //   TwoToFractionalPartOfX =
5033     //     0.999999982f +
5034     //       (0.693148872f +
5035     //         (0.240227044f +
5036     //           (0.554906021e-1f +
5037     //             (0.961591928e-2f +
5038     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5039     // error 2.47208000*10^(-7), which is better than 18 bits
5040     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5041                              getF32Constant(DAG, 0x3924b03e, dl));
5042     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5043                              getF32Constant(DAG, 0x3ab24b87, dl));
5044     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5045     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5046                              getF32Constant(DAG, 0x3c1d8c17, dl));
5047     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5048     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5049                              getF32Constant(DAG, 0x3d634a1d, dl));
5050     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5051     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5052                              getF32Constant(DAG, 0x3e75fe14, dl));
5053     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5054     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5055                               getF32Constant(DAG, 0x3f317234, dl));
5056     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5057     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5058                                          getF32Constant(DAG, 0x3f800000, dl));
5059   }
5060 
5061   // Add the exponent into the result in integer domain.
5062   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5063   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5064                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5065 }
5066 
5067 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5068 /// limited-precision mode.
5069 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5070                          const TargetLowering &TLI) {
5071   if (Op.getValueType() == MVT::f32 &&
5072       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5073 
5074     // Put the exponent in the right bit position for later addition to the
5075     // final result:
5076     //
5077     // t0 = Op * log2(e)
5078 
5079     // TODO: What fast-math-flags should be set here?
5080     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5081                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5082     return getLimitedPrecisionExp2(t0, dl, DAG);
5083   }
5084 
5085   // No special expansion.
5086   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
5087 }
5088 
5089 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5090 /// limited-precision mode.
5091 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5092                          const TargetLowering &TLI) {
5093   // TODO: What fast-math-flags should be set on the floating-point nodes?
5094 
5095   if (Op.getValueType() == MVT::f32 &&
5096       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5097     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5098 
5099     // Scale the exponent by log(2).
5100     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5101     SDValue LogOfExponent =
5102         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5103                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5104 
5105     // Get the significand and build it into a floating-point number with
5106     // exponent of 1.
5107     SDValue X = GetSignificand(DAG, Op1, dl);
5108 
5109     SDValue LogOfMantissa;
5110     if (LimitFloatPrecision <= 6) {
5111       // For floating-point precision of 6:
5112       //
5113       //   LogofMantissa =
5114       //     -1.1609546f +
5115       //       (1.4034025f - 0.23903021f * x) * x;
5116       //
5117       // error 0.0034276066, which is better than 8 bits
5118       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5119                                getF32Constant(DAG, 0xbe74c456, dl));
5120       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5121                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5122       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5123       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5124                                   getF32Constant(DAG, 0x3f949a29, dl));
5125     } else if (LimitFloatPrecision <= 12) {
5126       // For floating-point precision of 12:
5127       //
5128       //   LogOfMantissa =
5129       //     -1.7417939f +
5130       //       (2.8212026f +
5131       //         (-1.4699568f +
5132       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5133       //
5134       // error 0.000061011436, which is 14 bits
5135       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5136                                getF32Constant(DAG, 0xbd67b6d6, dl));
5137       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5138                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5139       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5140       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5141                                getF32Constant(DAG, 0x3fbc278b, dl));
5142       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5143       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5144                                getF32Constant(DAG, 0x40348e95, dl));
5145       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5146       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5147                                   getF32Constant(DAG, 0x3fdef31a, dl));
5148     } else { // LimitFloatPrecision <= 18
5149       // For floating-point precision of 18:
5150       //
5151       //   LogOfMantissa =
5152       //     -2.1072184f +
5153       //       (4.2372794f +
5154       //         (-3.7029485f +
5155       //           (2.2781945f +
5156       //             (-0.87823314f +
5157       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5158       //
5159       // error 0.0000023660568, which is better than 18 bits
5160       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5161                                getF32Constant(DAG, 0xbc91e5ac, dl));
5162       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5163                                getF32Constant(DAG, 0x3e4350aa, dl));
5164       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5165       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5166                                getF32Constant(DAG, 0x3f60d3e3, dl));
5167       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5168       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5169                                getF32Constant(DAG, 0x4011cdf0, dl));
5170       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5171       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5172                                getF32Constant(DAG, 0x406cfd1c, dl));
5173       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5174       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5175                                getF32Constant(DAG, 0x408797cb, dl));
5176       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5177       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5178                                   getF32Constant(DAG, 0x4006dcab, dl));
5179     }
5180 
5181     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5182   }
5183 
5184   // No special expansion.
5185   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
5186 }
5187 
5188 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5189 /// limited-precision mode.
5190 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5191                           const TargetLowering &TLI) {
5192   // TODO: What fast-math-flags should be set on the floating-point nodes?
5193 
5194   if (Op.getValueType() == MVT::f32 &&
5195       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5196     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5197 
5198     // Get the exponent.
5199     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5200 
5201     // Get the significand and build it into a floating-point number with
5202     // exponent of 1.
5203     SDValue X = GetSignificand(DAG, Op1, dl);
5204 
5205     // Different possible minimax approximations of significand in
5206     // floating-point for various degrees of accuracy over [1,2].
5207     SDValue Log2ofMantissa;
5208     if (LimitFloatPrecision <= 6) {
5209       // For floating-point precision of 6:
5210       //
5211       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5212       //
5213       // error 0.0049451742, which is more than 7 bits
5214       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5215                                getF32Constant(DAG, 0xbeb08fe0, dl));
5216       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5217                                getF32Constant(DAG, 0x40019463, dl));
5218       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5219       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5220                                    getF32Constant(DAG, 0x3fd6633d, dl));
5221     } else if (LimitFloatPrecision <= 12) {
5222       // For floating-point precision of 12:
5223       //
5224       //   Log2ofMantissa =
5225       //     -2.51285454f +
5226       //       (4.07009056f +
5227       //         (-2.12067489f +
5228       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5229       //
5230       // error 0.0000876136000, which is better than 13 bits
5231       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5232                                getF32Constant(DAG, 0xbda7262e, dl));
5233       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5234                                getF32Constant(DAG, 0x3f25280b, dl));
5235       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5236       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5237                                getF32Constant(DAG, 0x4007b923, dl));
5238       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5239       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5240                                getF32Constant(DAG, 0x40823e2f, dl));
5241       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5242       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5243                                    getF32Constant(DAG, 0x4020d29c, dl));
5244     } else { // LimitFloatPrecision <= 18
5245       // For floating-point precision of 18:
5246       //
5247       //   Log2ofMantissa =
5248       //     -3.0400495f +
5249       //       (6.1129976f +
5250       //         (-5.3420409f +
5251       //           (3.2865683f +
5252       //             (-1.2669343f +
5253       //               (0.27515199f -
5254       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5255       //
5256       // error 0.0000018516, which is better than 18 bits
5257       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5258                                getF32Constant(DAG, 0xbcd2769e, dl));
5259       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5260                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5261       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5262       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5263                                getF32Constant(DAG, 0x3fa22ae7, dl));
5264       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5265       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5266                                getF32Constant(DAG, 0x40525723, dl));
5267       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5268       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5269                                getF32Constant(DAG, 0x40aaf200, dl));
5270       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5271       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5272                                getF32Constant(DAG, 0x40c39dad, dl));
5273       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5274       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5275                                    getF32Constant(DAG, 0x4042902c, dl));
5276     }
5277 
5278     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5279   }
5280 
5281   // No special expansion.
5282   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
5283 }
5284 
5285 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5286 /// limited-precision mode.
5287 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5288                            const TargetLowering &TLI) {
5289   // TODO: What fast-math-flags should be set on the floating-point nodes?
5290 
5291   if (Op.getValueType() == MVT::f32 &&
5292       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5293     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5294 
5295     // Scale the exponent by log10(2) [0.30102999f].
5296     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5297     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5298                                         getF32Constant(DAG, 0x3e9a209a, dl));
5299 
5300     // Get the significand and build it into a floating-point number with
5301     // exponent of 1.
5302     SDValue X = GetSignificand(DAG, Op1, dl);
5303 
5304     SDValue Log10ofMantissa;
5305     if (LimitFloatPrecision <= 6) {
5306       // For floating-point precision of 6:
5307       //
5308       //   Log10ofMantissa =
5309       //     -0.50419619f +
5310       //       (0.60948995f - 0.10380950f * x) * x;
5311       //
5312       // error 0.0014886165, which is 6 bits
5313       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5314                                getF32Constant(DAG, 0xbdd49a13, dl));
5315       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5316                                getF32Constant(DAG, 0x3f1c0789, dl));
5317       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5318       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5319                                     getF32Constant(DAG, 0x3f011300, dl));
5320     } else if (LimitFloatPrecision <= 12) {
5321       // For floating-point precision of 12:
5322       //
5323       //   Log10ofMantissa =
5324       //     -0.64831180f +
5325       //       (0.91751397f +
5326       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5327       //
5328       // error 0.00019228036, which is better than 12 bits
5329       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5330                                getF32Constant(DAG, 0x3d431f31, dl));
5331       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5332                                getF32Constant(DAG, 0x3ea21fb2, dl));
5333       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5334       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5335                                getF32Constant(DAG, 0x3f6ae232, dl));
5336       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5337       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5338                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5339     } else { // LimitFloatPrecision <= 18
5340       // For floating-point precision of 18:
5341       //
5342       //   Log10ofMantissa =
5343       //     -0.84299375f +
5344       //       (1.5327582f +
5345       //         (-1.0688956f +
5346       //           (0.49102474f +
5347       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5348       //
5349       // error 0.0000037995730, which is better than 18 bits
5350       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5351                                getF32Constant(DAG, 0x3c5d51ce, dl));
5352       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5353                                getF32Constant(DAG, 0x3e00685a, dl));
5354       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5355       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5356                                getF32Constant(DAG, 0x3efb6798, dl));
5357       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5358       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5359                                getF32Constant(DAG, 0x3f88d192, dl));
5360       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5361       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5362                                getF32Constant(DAG, 0x3fc4316c, dl));
5363       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5364       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5365                                     getF32Constant(DAG, 0x3f57ce70, dl));
5366     }
5367 
5368     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5369   }
5370 
5371   // No special expansion.
5372   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
5373 }
5374 
5375 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5376 /// limited-precision mode.
5377 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5378                           const TargetLowering &TLI) {
5379   if (Op.getValueType() == MVT::f32 &&
5380       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5381     return getLimitedPrecisionExp2(Op, dl, DAG);
5382 
5383   // No special expansion.
5384   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
5385 }
5386 
5387 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5388 /// limited-precision mode with x == 10.0f.
5389 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5390                          SelectionDAG &DAG, const TargetLowering &TLI) {
5391   bool IsExp10 = false;
5392   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5393       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5394     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5395       APFloat Ten(10.0f);
5396       IsExp10 = LHSC->isExactlyValue(Ten);
5397     }
5398   }
5399 
5400   // TODO: What fast-math-flags should be set on the FMUL node?
5401   if (IsExp10) {
5402     // Put the exponent in the right bit position for later addition to the
5403     // final result:
5404     //
5405     //   #define LOG2OF10 3.3219281f
5406     //   t0 = Op * LOG2OF10;
5407     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5408                              getF32Constant(DAG, 0x40549a78, dl));
5409     return getLimitedPrecisionExp2(t0, dl, DAG);
5410   }
5411 
5412   // No special expansion.
5413   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
5414 }
5415 
5416 /// ExpandPowI - Expand a llvm.powi intrinsic.
5417 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5418                           SelectionDAG &DAG) {
5419   // If RHS is a constant, we can expand this out to a multiplication tree,
5420   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5421   // optimizing for size, we only want to do this if the expansion would produce
5422   // a small number of multiplies, otherwise we do the full expansion.
5423   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5424     // Get the exponent as a positive value.
5425     unsigned Val = RHSC->getSExtValue();
5426     if ((int)Val < 0) Val = -Val;
5427 
5428     // powi(x, 0) -> 1.0
5429     if (Val == 0)
5430       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5431 
5432     bool OptForSize = DAG.shouldOptForSize();
5433     if (!OptForSize ||
5434         // If optimizing for size, don't insert too many multiplies.
5435         // This inserts up to 5 multiplies.
5436         countPopulation(Val) + Log2_32(Val) < 7) {
5437       // We use the simple binary decomposition method to generate the multiply
5438       // sequence.  There are more optimal ways to do this (for example,
5439       // powi(x,15) generates one more multiply than it should), but this has
5440       // the benefit of being both really simple and much better than a libcall.
5441       SDValue Res;  // Logically starts equal to 1.0
5442       SDValue CurSquare = LHS;
5443       // TODO: Intrinsics should have fast-math-flags that propagate to these
5444       // nodes.
5445       while (Val) {
5446         if (Val & 1) {
5447           if (Res.getNode())
5448             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5449           else
5450             Res = CurSquare;  // 1.0*CurSquare.
5451         }
5452 
5453         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5454                                 CurSquare, CurSquare);
5455         Val >>= 1;
5456       }
5457 
5458       // If the original was negative, invert the result, producing 1/(x*x*x).
5459       if (RHSC->getSExtValue() < 0)
5460         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5461                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5462       return Res;
5463     }
5464   }
5465 
5466   // Otherwise, expand to a libcall.
5467   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5468 }
5469 
5470 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5471                             SDValue LHS, SDValue RHS, SDValue Scale,
5472                             SelectionDAG &DAG, const TargetLowering &TLI) {
5473   EVT VT = LHS.getValueType();
5474   bool Signed = Opcode == ISD::SDIVFIX;
5475   LLVMContext &Ctx = *DAG.getContext();
5476 
5477   // If the type is legal but the operation isn't, this node might survive all
5478   // the way to operation legalization. If we end up there and we do not have
5479   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5480   // node.
5481 
5482   // Coax the legalizer into expanding the node during type legalization instead
5483   // by bumping the size by one bit. This will force it to Promote, enabling the
5484   // early expansion and avoiding the need to expand later.
5485 
5486   // We don't have to do this if Scale is 0; that can always be expanded.
5487 
5488   // FIXME: We wouldn't have to do this (or any of the early
5489   // expansion/promotion) if it was possible to expand a libcall of an
5490   // illegal type during operation legalization. But it's not, so things
5491   // get a bit hacky.
5492   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5493   if (ScaleInt > 0 &&
5494       (TLI.isTypeLegal(VT) ||
5495        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5496     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5497         Opcode, VT, ScaleInt);
5498     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5499       EVT PromVT;
5500       if (VT.isScalarInteger())
5501         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5502       else if (VT.isVector()) {
5503         PromVT = VT.getVectorElementType();
5504         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5505         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5506       } else
5507         llvm_unreachable("Wrong VT for DIVFIX?");
5508       if (Signed) {
5509         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5510         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5511       } else {
5512         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5513         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5514       }
5515       // TODO: Saturation.
5516       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5517       return DAG.getZExtOrTrunc(Res, DL, VT);
5518     }
5519   }
5520 
5521   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5522 }
5523 
5524 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5525 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5526 static void
5527 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
5528                      const SDValue &N) {
5529   switch (N.getOpcode()) {
5530   case ISD::CopyFromReg: {
5531     SDValue Op = N.getOperand(1);
5532     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5533                       Op.getValueType().getSizeInBits());
5534     return;
5535   }
5536   case ISD::BITCAST:
5537   case ISD::AssertZext:
5538   case ISD::AssertSext:
5539   case ISD::TRUNCATE:
5540     getUnderlyingArgRegs(Regs, N.getOperand(0));
5541     return;
5542   case ISD::BUILD_PAIR:
5543   case ISD::BUILD_VECTOR:
5544   case ISD::CONCAT_VECTORS:
5545     for (SDValue Op : N->op_values())
5546       getUnderlyingArgRegs(Regs, Op);
5547     return;
5548   default:
5549     return;
5550   }
5551 }
5552 
5553 /// If the DbgValueInst is a dbg_value of a function argument, create the
5554 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5555 /// instruction selection, they will be inserted to the entry BB.
5556 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5557     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5558     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5559   const Argument *Arg = dyn_cast<Argument>(V);
5560   if (!Arg)
5561     return false;
5562 
5563   if (!IsDbgDeclare) {
5564     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5565     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5566     // the entry block.
5567     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5568     if (!IsInEntryBlock)
5569       return false;
5570 
5571     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5572     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5573     // variable that also is a param.
5574     //
5575     // Although, if we are at the top of the entry block already, we can still
5576     // emit using ArgDbgValue. This might catch some situations when the
5577     // dbg.value refers to an argument that isn't used in the entry block, so
5578     // any CopyToReg node would be optimized out and the only way to express
5579     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5580     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5581     // we should only emit as ArgDbgValue if the Variable is an argument to the
5582     // current function, and the dbg.value intrinsic is found in the entry
5583     // block.
5584     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5585         !DL->getInlinedAt();
5586     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5587     if (!IsInPrologue && !VariableIsFunctionInputArg)
5588       return false;
5589 
5590     // Here we assume that a function argument on IR level only can be used to
5591     // describe one input parameter on source level. If we for example have
5592     // source code like this
5593     //
5594     //    struct A { long x, y; };
5595     //    void foo(struct A a, long b) {
5596     //      ...
5597     //      b = a.x;
5598     //      ...
5599     //    }
5600     //
5601     // and IR like this
5602     //
5603     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5604     //  entry:
5605     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5606     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5607     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5608     //    ...
5609     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5610     //    ...
5611     //
5612     // then the last dbg.value is describing a parameter "b" using a value that
5613     // is an argument. But since we already has used %a1 to describe a parameter
5614     // we should not handle that last dbg.value here (that would result in an
5615     // incorrect hoisting of the DBG_VALUE to the function entry).
5616     // Notice that we allow one dbg.value per IR level argument, to accommodate
5617     // for the situation with fragments above.
5618     if (VariableIsFunctionInputArg) {
5619       unsigned ArgNo = Arg->getArgNo();
5620       if (ArgNo >= FuncInfo.DescribedArgs.size())
5621         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5622       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5623         return false;
5624       FuncInfo.DescribedArgs.set(ArgNo);
5625     }
5626   }
5627 
5628   MachineFunction &MF = DAG.getMachineFunction();
5629   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5630 
5631   Optional<MachineOperand> Op;
5632   // Some arguments' frame index is recorded during argument lowering.
5633   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5634   if (FI != std::numeric_limits<int>::max())
5635     Op = MachineOperand::CreateFI(FI);
5636 
5637   SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes;
5638   if (!Op && N.getNode()) {
5639     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5640     Register Reg;
5641     if (ArgRegsAndSizes.size() == 1)
5642       Reg = ArgRegsAndSizes.front().first;
5643 
5644     if (Reg && Reg.isVirtual()) {
5645       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5646       Register PR = RegInfo.getLiveInPhysReg(Reg);
5647       if (PR)
5648         Reg = PR;
5649     }
5650     if (Reg) {
5651       Op = MachineOperand::CreateReg(Reg, false);
5652     }
5653   }
5654 
5655   if (!Op && N.getNode()) {
5656     // Check if frame index is available.
5657     SDValue LCandidate = peekThroughBitcasts(N);
5658     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5659       if (FrameIndexSDNode *FINode =
5660           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5661         Op = MachineOperand::CreateFI(FINode->getIndex());
5662   }
5663 
5664   if (!Op) {
5665     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5666     auto splitMultiRegDbgValue
5667       = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) {
5668       unsigned Offset = 0;
5669       for (auto RegAndSize : SplitRegs) {
5670         // If the expression is already a fragment, the current register
5671         // offset+size might extend beyond the fragment. In this case, only
5672         // the register bits that are inside the fragment are relevant.
5673         int RegFragmentSizeInBits = RegAndSize.second;
5674         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5675           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5676           // The register is entirely outside the expression fragment,
5677           // so is irrelevant for debug info.
5678           if (Offset >= ExprFragmentSizeInBits)
5679             break;
5680           // The register is partially outside the expression fragment, only
5681           // the low bits within the fragment are relevant for debug info.
5682           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5683             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5684           }
5685         }
5686 
5687         auto FragmentExpr = DIExpression::createFragmentExpression(
5688             Expr, Offset, RegFragmentSizeInBits);
5689         Offset += RegAndSize.second;
5690         // If a valid fragment expression cannot be created, the variable's
5691         // correct value cannot be determined and so it is set as Undef.
5692         if (!FragmentExpr) {
5693           SDDbgValue *SDV = DAG.getConstantDbgValue(
5694               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5695           DAG.AddDbgValue(SDV, nullptr, false);
5696           continue;
5697         }
5698         assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?");
5699         FuncInfo.ArgDbgValues.push_back(
5700           BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), false,
5701                   RegAndSize.first, Variable, *FragmentExpr));
5702       }
5703     };
5704 
5705     // Check if ValueMap has reg number.
5706     DenseMap<const Value *, unsigned>::const_iterator
5707       VMI = FuncInfo.ValueMap.find(V);
5708     if (VMI != FuncInfo.ValueMap.end()) {
5709       const auto &TLI = DAG.getTargetLoweringInfo();
5710       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5711                        V->getType(), getABIRegCopyCC(V));
5712       if (RFV.occupiesMultipleRegs()) {
5713         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5714         return true;
5715       }
5716 
5717       Op = MachineOperand::CreateReg(VMI->second, false);
5718     } else if (ArgRegsAndSizes.size() > 1) {
5719       // This was split due to the calling convention, and no virtual register
5720       // mapping exists for the value.
5721       splitMultiRegDbgValue(ArgRegsAndSizes);
5722       return true;
5723     }
5724   }
5725 
5726   if (!Op)
5727     return false;
5728 
5729   assert(Variable->isValidLocationForIntrinsic(DL) &&
5730          "Expected inlined-at fields to agree");
5731 
5732   // If the argument arrives in a stack slot, then what the IR thought was a
5733   // normal Value is actually in memory, and we must add a deref to load it.
5734   if (Op->isFI()) {
5735     int FI = Op->getIndex();
5736     unsigned Size = DAG.getMachineFunction().getFrameInfo().getObjectSize(FI);
5737     if (Expr->isImplicit()) {
5738       SmallVector<uint64_t, 2> Ops = {dwarf::DW_OP_deref_size, Size};
5739       Expr = DIExpression::prependOpcodes(Expr, Ops);
5740     } else {
5741       Expr = DIExpression::prepend(Expr, DIExpression::DerefBefore);
5742     }
5743   }
5744 
5745   // If this location was specified with a dbg.declare, then it and its
5746   // expression calculate the address of the variable. Append a deref to
5747   // force it to be a memory location.
5748   if (IsDbgDeclare)
5749     Expr = DIExpression::append(Expr, {dwarf::DW_OP_deref});
5750 
5751   FuncInfo.ArgDbgValues.push_back(
5752       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), false,
5753               *Op, Variable, Expr));
5754 
5755   return true;
5756 }
5757 
5758 /// Return the appropriate SDDbgValue based on N.
5759 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5760                                              DILocalVariable *Variable,
5761                                              DIExpression *Expr,
5762                                              const DebugLoc &dl,
5763                                              unsigned DbgSDNodeOrder) {
5764   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5765     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5766     // stack slot locations.
5767     //
5768     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5769     // debug values here after optimization:
5770     //
5771     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5772     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5773     //
5774     // Both describe the direct values of their associated variables.
5775     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5776                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5777   }
5778   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5779                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5780 }
5781 
5782 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5783   switch (Intrinsic) {
5784   case Intrinsic::smul_fix:
5785     return ISD::SMULFIX;
5786   case Intrinsic::umul_fix:
5787     return ISD::UMULFIX;
5788   case Intrinsic::smul_fix_sat:
5789     return ISD::SMULFIXSAT;
5790   case Intrinsic::umul_fix_sat:
5791     return ISD::UMULFIXSAT;
5792   case Intrinsic::sdiv_fix:
5793     return ISD::SDIVFIX;
5794   case Intrinsic::udiv_fix:
5795     return ISD::UDIVFIX;
5796   default:
5797     llvm_unreachable("Unhandled fixed point intrinsic");
5798   }
5799 }
5800 
5801 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5802                                            const char *FunctionName) {
5803   assert(FunctionName && "FunctionName must not be nullptr");
5804   SDValue Callee = DAG.getExternalSymbol(
5805       FunctionName,
5806       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5807   LowerCallTo(&I, Callee, I.isTailCall());
5808 }
5809 
5810 /// Lower the call to the specified intrinsic function.
5811 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5812                                              unsigned Intrinsic) {
5813   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5814   SDLoc sdl = getCurSDLoc();
5815   DebugLoc dl = getCurDebugLoc();
5816   SDValue Res;
5817 
5818   switch (Intrinsic) {
5819   default:
5820     // By default, turn this into a target intrinsic node.
5821     visitTargetIntrinsic(I, Intrinsic);
5822     return;
5823   case Intrinsic::vastart:  visitVAStart(I); return;
5824   case Intrinsic::vaend:    visitVAEnd(I); return;
5825   case Intrinsic::vacopy:   visitVACopy(I); return;
5826   case Intrinsic::returnaddress:
5827     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5828                              TLI.getPointerTy(DAG.getDataLayout()),
5829                              getValue(I.getArgOperand(0))));
5830     return;
5831   case Intrinsic::addressofreturnaddress:
5832     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5833                              TLI.getPointerTy(DAG.getDataLayout())));
5834     return;
5835   case Intrinsic::sponentry:
5836     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5837                              TLI.getFrameIndexTy(DAG.getDataLayout())));
5838     return;
5839   case Intrinsic::frameaddress:
5840     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5841                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5842                              getValue(I.getArgOperand(0))));
5843     return;
5844   case Intrinsic::read_register: {
5845     Value *Reg = I.getArgOperand(0);
5846     SDValue Chain = getRoot();
5847     SDValue RegName =
5848         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5849     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5850     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5851       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5852     setValue(&I, Res);
5853     DAG.setRoot(Res.getValue(1));
5854     return;
5855   }
5856   case Intrinsic::write_register: {
5857     Value *Reg = I.getArgOperand(0);
5858     Value *RegValue = I.getArgOperand(1);
5859     SDValue Chain = getRoot();
5860     SDValue RegName =
5861         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5862     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5863                             RegName, getValue(RegValue)));
5864     return;
5865   }
5866   case Intrinsic::memcpy: {
5867     const auto &MCI = cast<MemCpyInst>(I);
5868     SDValue Op1 = getValue(I.getArgOperand(0));
5869     SDValue Op2 = getValue(I.getArgOperand(1));
5870     SDValue Op3 = getValue(I.getArgOperand(2));
5871     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5872     unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
5873     unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
5874     unsigned Align = MinAlign(DstAlign, SrcAlign);
5875     bool isVol = MCI.isVolatile();
5876     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5877     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5878     // node.
5879     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5880     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Align, isVol,
5881                                false, isTC,
5882                                MachinePointerInfo(I.getArgOperand(0)),
5883                                MachinePointerInfo(I.getArgOperand(1)));
5884     updateDAGForMaybeTailCall(MC);
5885     return;
5886   }
5887   case Intrinsic::memset: {
5888     const auto &MSI = cast<MemSetInst>(I);
5889     SDValue Op1 = getValue(I.getArgOperand(0));
5890     SDValue Op2 = getValue(I.getArgOperand(1));
5891     SDValue Op3 = getValue(I.getArgOperand(2));
5892     // @llvm.memset defines 0 and 1 to both mean no alignment.
5893     unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
5894     bool isVol = MSI.isVolatile();
5895     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5896     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5897     SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Align, isVol,
5898                                isTC, MachinePointerInfo(I.getArgOperand(0)));
5899     updateDAGForMaybeTailCall(MS);
5900     return;
5901   }
5902   case Intrinsic::memmove: {
5903     const auto &MMI = cast<MemMoveInst>(I);
5904     SDValue Op1 = getValue(I.getArgOperand(0));
5905     SDValue Op2 = getValue(I.getArgOperand(1));
5906     SDValue Op3 = getValue(I.getArgOperand(2));
5907     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5908     unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
5909     unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
5910     unsigned Align = MinAlign(DstAlign, SrcAlign);
5911     bool isVol = MMI.isVolatile();
5912     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5913     // FIXME: Support passing different dest/src alignments to the memmove DAG
5914     // node.
5915     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5916     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Align, isVol,
5917                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5918                                 MachinePointerInfo(I.getArgOperand(1)));
5919     updateDAGForMaybeTailCall(MM);
5920     return;
5921   }
5922   case Intrinsic::memcpy_element_unordered_atomic: {
5923     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5924     SDValue Dst = getValue(MI.getRawDest());
5925     SDValue Src = getValue(MI.getRawSource());
5926     SDValue Length = getValue(MI.getLength());
5927 
5928     unsigned DstAlign = MI.getDestAlignment();
5929     unsigned SrcAlign = MI.getSourceAlignment();
5930     Type *LengthTy = MI.getLength()->getType();
5931     unsigned ElemSz = MI.getElementSizeInBytes();
5932     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5933     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5934                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5935                                      MachinePointerInfo(MI.getRawDest()),
5936                                      MachinePointerInfo(MI.getRawSource()));
5937     updateDAGForMaybeTailCall(MC);
5938     return;
5939   }
5940   case Intrinsic::memmove_element_unordered_atomic: {
5941     auto &MI = cast<AtomicMemMoveInst>(I);
5942     SDValue Dst = getValue(MI.getRawDest());
5943     SDValue Src = getValue(MI.getRawSource());
5944     SDValue Length = getValue(MI.getLength());
5945 
5946     unsigned DstAlign = MI.getDestAlignment();
5947     unsigned SrcAlign = MI.getSourceAlignment();
5948     Type *LengthTy = MI.getLength()->getType();
5949     unsigned ElemSz = MI.getElementSizeInBytes();
5950     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5951     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5952                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5953                                       MachinePointerInfo(MI.getRawDest()),
5954                                       MachinePointerInfo(MI.getRawSource()));
5955     updateDAGForMaybeTailCall(MC);
5956     return;
5957   }
5958   case Intrinsic::memset_element_unordered_atomic: {
5959     auto &MI = cast<AtomicMemSetInst>(I);
5960     SDValue Dst = getValue(MI.getRawDest());
5961     SDValue Val = getValue(MI.getValue());
5962     SDValue Length = getValue(MI.getLength());
5963 
5964     unsigned DstAlign = MI.getDestAlignment();
5965     Type *LengthTy = MI.getLength()->getType();
5966     unsigned ElemSz = MI.getElementSizeInBytes();
5967     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5968     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5969                                      LengthTy, ElemSz, isTC,
5970                                      MachinePointerInfo(MI.getRawDest()));
5971     updateDAGForMaybeTailCall(MC);
5972     return;
5973   }
5974   case Intrinsic::dbg_addr:
5975   case Intrinsic::dbg_declare: {
5976     const auto &DI = cast<DbgVariableIntrinsic>(I);
5977     DILocalVariable *Variable = DI.getVariable();
5978     DIExpression *Expression = DI.getExpression();
5979     dropDanglingDebugInfo(Variable, Expression);
5980     assert(Variable && "Missing variable");
5981 
5982     // Check if address has undef value.
5983     const Value *Address = DI.getVariableLocation();
5984     if (!Address || isa<UndefValue>(Address) ||
5985         (Address->use_empty() && !isa<Argument>(Address))) {
5986       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5987       return;
5988     }
5989 
5990     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5991 
5992     // Check if this variable can be described by a frame index, typically
5993     // either as a static alloca or a byval parameter.
5994     int FI = std::numeric_limits<int>::max();
5995     if (const auto *AI =
5996             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5997       if (AI->isStaticAlloca()) {
5998         auto I = FuncInfo.StaticAllocaMap.find(AI);
5999         if (I != FuncInfo.StaticAllocaMap.end())
6000           FI = I->second;
6001       }
6002     } else if (const auto *Arg = dyn_cast<Argument>(
6003                    Address->stripInBoundsConstantOffsets())) {
6004       FI = FuncInfo.getArgumentFrameIndex(Arg);
6005     }
6006 
6007     // llvm.dbg.addr is control dependent and always generates indirect
6008     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
6009     // the MachineFunction variable table.
6010     if (FI != std::numeric_limits<int>::max()) {
6011       if (Intrinsic == Intrinsic::dbg_addr) {
6012         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
6013             Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
6014         DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
6015       }
6016       return;
6017     }
6018 
6019     SDValue &N = NodeMap[Address];
6020     if (!N.getNode() && isa<Argument>(Address))
6021       // Check unused arguments map.
6022       N = UnusedArgNodeMap[Address];
6023     SDDbgValue *SDV;
6024     if (N.getNode()) {
6025       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
6026         Address = BCI->getOperand(0);
6027       // Parameters are handled specially.
6028       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
6029       if (isParameter && FINode) {
6030         // Byval parameter. We have a frame index at this point.
6031         SDV =
6032             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
6033                                       /*IsIndirect*/ true, dl, SDNodeOrder);
6034       } else if (isa<Argument>(Address)) {
6035         // Address is an argument, so try to emit its dbg value using
6036         // virtual register info from the FuncInfo.ValueMap.
6037         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
6038         return;
6039       } else {
6040         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
6041                               true, dl, SDNodeOrder);
6042       }
6043       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
6044     } else {
6045       // If Address is an argument then try to emit its dbg value using
6046       // virtual register info from the FuncInfo.ValueMap.
6047       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
6048                                     N)) {
6049         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
6050       }
6051     }
6052     return;
6053   }
6054   case Intrinsic::dbg_label: {
6055     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6056     DILabel *Label = DI.getLabel();
6057     assert(Label && "Missing label");
6058 
6059     SDDbgLabel *SDV;
6060     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6061     DAG.AddDbgLabel(SDV);
6062     return;
6063   }
6064   case Intrinsic::dbg_value: {
6065     const DbgValueInst &DI = cast<DbgValueInst>(I);
6066     assert(DI.getVariable() && "Missing variable");
6067 
6068     DILocalVariable *Variable = DI.getVariable();
6069     DIExpression *Expression = DI.getExpression();
6070     dropDanglingDebugInfo(Variable, Expression);
6071     const Value *V = DI.getValue();
6072     if (!V)
6073       return;
6074 
6075     if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
6076         SDNodeOrder))
6077       return;
6078 
6079     // TODO: Dangling debug info will eventually either be resolved or produce
6080     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
6081     // between the original dbg.value location and its resolved DBG_VALUE, which
6082     // we should ideally fill with an extra Undef DBG_VALUE.
6083 
6084     DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
6085     return;
6086   }
6087 
6088   case Intrinsic::eh_typeid_for: {
6089     // Find the type id for the given typeinfo.
6090     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6091     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6092     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6093     setValue(&I, Res);
6094     return;
6095   }
6096 
6097   case Intrinsic::eh_return_i32:
6098   case Intrinsic::eh_return_i64:
6099     DAG.getMachineFunction().setCallsEHReturn(true);
6100     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6101                             MVT::Other,
6102                             getControlRoot(),
6103                             getValue(I.getArgOperand(0)),
6104                             getValue(I.getArgOperand(1))));
6105     return;
6106   case Intrinsic::eh_unwind_init:
6107     DAG.getMachineFunction().setCallsUnwindInit(true);
6108     return;
6109   case Intrinsic::eh_dwarf_cfa:
6110     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6111                              TLI.getPointerTy(DAG.getDataLayout()),
6112                              getValue(I.getArgOperand(0))));
6113     return;
6114   case Intrinsic::eh_sjlj_callsite: {
6115     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6116     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
6117     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
6118     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6119 
6120     MMI.setCurrentCallSite(CI->getZExtValue());
6121     return;
6122   }
6123   case Intrinsic::eh_sjlj_functioncontext: {
6124     // Get and store the index of the function context.
6125     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6126     AllocaInst *FnCtx =
6127       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6128     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6129     MFI.setFunctionContextIndex(FI);
6130     return;
6131   }
6132   case Intrinsic::eh_sjlj_setjmp: {
6133     SDValue Ops[2];
6134     Ops[0] = getRoot();
6135     Ops[1] = getValue(I.getArgOperand(0));
6136     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6137                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6138     setValue(&I, Op.getValue(0));
6139     DAG.setRoot(Op.getValue(1));
6140     return;
6141   }
6142   case Intrinsic::eh_sjlj_longjmp:
6143     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6144                             getRoot(), getValue(I.getArgOperand(0))));
6145     return;
6146   case Intrinsic::eh_sjlj_setup_dispatch:
6147     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6148                             getRoot()));
6149     return;
6150   case Intrinsic::masked_gather:
6151     visitMaskedGather(I);
6152     return;
6153   case Intrinsic::masked_load:
6154     visitMaskedLoad(I);
6155     return;
6156   case Intrinsic::masked_scatter:
6157     visitMaskedScatter(I);
6158     return;
6159   case Intrinsic::masked_store:
6160     visitMaskedStore(I);
6161     return;
6162   case Intrinsic::masked_expandload:
6163     visitMaskedLoad(I, true /* IsExpanding */);
6164     return;
6165   case Intrinsic::masked_compressstore:
6166     visitMaskedStore(I, true /* IsCompressing */);
6167     return;
6168   case Intrinsic::powi:
6169     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6170                             getValue(I.getArgOperand(1)), DAG));
6171     return;
6172   case Intrinsic::log:
6173     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6174     return;
6175   case Intrinsic::log2:
6176     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6177     return;
6178   case Intrinsic::log10:
6179     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6180     return;
6181   case Intrinsic::exp:
6182     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6183     return;
6184   case Intrinsic::exp2:
6185     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6186     return;
6187   case Intrinsic::pow:
6188     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6189                            getValue(I.getArgOperand(1)), DAG, TLI));
6190     return;
6191   case Intrinsic::sqrt:
6192   case Intrinsic::fabs:
6193   case Intrinsic::sin:
6194   case Intrinsic::cos:
6195   case Intrinsic::floor:
6196   case Intrinsic::ceil:
6197   case Intrinsic::trunc:
6198   case Intrinsic::rint:
6199   case Intrinsic::nearbyint:
6200   case Intrinsic::round:
6201   case Intrinsic::canonicalize: {
6202     unsigned Opcode;
6203     switch (Intrinsic) {
6204     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6205     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6206     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6207     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6208     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6209     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6210     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6211     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6212     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6213     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6214     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6215     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6216     }
6217 
6218     setValue(&I, DAG.getNode(Opcode, sdl,
6219                              getValue(I.getArgOperand(0)).getValueType(),
6220                              getValue(I.getArgOperand(0))));
6221     return;
6222   }
6223   case Intrinsic::lround:
6224   case Intrinsic::llround:
6225   case Intrinsic::lrint:
6226   case Intrinsic::llrint: {
6227     unsigned Opcode;
6228     switch (Intrinsic) {
6229     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6230     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6231     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6232     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6233     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6234     }
6235 
6236     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6237     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6238                              getValue(I.getArgOperand(0))));
6239     return;
6240   }
6241   case Intrinsic::minnum:
6242     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6243                              getValue(I.getArgOperand(0)).getValueType(),
6244                              getValue(I.getArgOperand(0)),
6245                              getValue(I.getArgOperand(1))));
6246     return;
6247   case Intrinsic::maxnum:
6248     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6249                              getValue(I.getArgOperand(0)).getValueType(),
6250                              getValue(I.getArgOperand(0)),
6251                              getValue(I.getArgOperand(1))));
6252     return;
6253   case Intrinsic::minimum:
6254     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6255                              getValue(I.getArgOperand(0)).getValueType(),
6256                              getValue(I.getArgOperand(0)),
6257                              getValue(I.getArgOperand(1))));
6258     return;
6259   case Intrinsic::maximum:
6260     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6261                              getValue(I.getArgOperand(0)).getValueType(),
6262                              getValue(I.getArgOperand(0)),
6263                              getValue(I.getArgOperand(1))));
6264     return;
6265   case Intrinsic::copysign:
6266     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6267                              getValue(I.getArgOperand(0)).getValueType(),
6268                              getValue(I.getArgOperand(0)),
6269                              getValue(I.getArgOperand(1))));
6270     return;
6271   case Intrinsic::fma:
6272     setValue(&I, DAG.getNode(ISD::FMA, sdl,
6273                              getValue(I.getArgOperand(0)).getValueType(),
6274                              getValue(I.getArgOperand(0)),
6275                              getValue(I.getArgOperand(1)),
6276                              getValue(I.getArgOperand(2))));
6277     return;
6278 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)                   \
6279   case Intrinsic::INTRINSIC:
6280 #include "llvm/IR/ConstrainedOps.def"
6281     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6282     return;
6283   case Intrinsic::fmuladd: {
6284     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6285     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6286         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6287       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6288                                getValue(I.getArgOperand(0)).getValueType(),
6289                                getValue(I.getArgOperand(0)),
6290                                getValue(I.getArgOperand(1)),
6291                                getValue(I.getArgOperand(2))));
6292     } else {
6293       // TODO: Intrinsic calls should have fast-math-flags.
6294       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
6295                                 getValue(I.getArgOperand(0)).getValueType(),
6296                                 getValue(I.getArgOperand(0)),
6297                                 getValue(I.getArgOperand(1)));
6298       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6299                                 getValue(I.getArgOperand(0)).getValueType(),
6300                                 Mul,
6301                                 getValue(I.getArgOperand(2)));
6302       setValue(&I, Add);
6303     }
6304     return;
6305   }
6306   case Intrinsic::convert_to_fp16:
6307     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6308                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6309                                          getValue(I.getArgOperand(0)),
6310                                          DAG.getTargetConstant(0, sdl,
6311                                                                MVT::i32))));
6312     return;
6313   case Intrinsic::convert_from_fp16:
6314     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6315                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6316                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6317                                          getValue(I.getArgOperand(0)))));
6318     return;
6319   case Intrinsic::pcmarker: {
6320     SDValue Tmp = getValue(I.getArgOperand(0));
6321     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6322     return;
6323   }
6324   case Intrinsic::readcyclecounter: {
6325     SDValue Op = getRoot();
6326     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6327                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6328     setValue(&I, Res);
6329     DAG.setRoot(Res.getValue(1));
6330     return;
6331   }
6332   case Intrinsic::bitreverse:
6333     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6334                              getValue(I.getArgOperand(0)).getValueType(),
6335                              getValue(I.getArgOperand(0))));
6336     return;
6337   case Intrinsic::bswap:
6338     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6339                              getValue(I.getArgOperand(0)).getValueType(),
6340                              getValue(I.getArgOperand(0))));
6341     return;
6342   case Intrinsic::cttz: {
6343     SDValue Arg = getValue(I.getArgOperand(0));
6344     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6345     EVT Ty = Arg.getValueType();
6346     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6347                              sdl, Ty, Arg));
6348     return;
6349   }
6350   case Intrinsic::ctlz: {
6351     SDValue Arg = getValue(I.getArgOperand(0));
6352     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6353     EVT Ty = Arg.getValueType();
6354     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6355                              sdl, Ty, Arg));
6356     return;
6357   }
6358   case Intrinsic::ctpop: {
6359     SDValue Arg = getValue(I.getArgOperand(0));
6360     EVT Ty = Arg.getValueType();
6361     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6362     return;
6363   }
6364   case Intrinsic::fshl:
6365   case Intrinsic::fshr: {
6366     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6367     SDValue X = getValue(I.getArgOperand(0));
6368     SDValue Y = getValue(I.getArgOperand(1));
6369     SDValue Z = getValue(I.getArgOperand(2));
6370     EVT VT = X.getValueType();
6371     SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
6372     SDValue Zero = DAG.getConstant(0, sdl, VT);
6373     SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
6374 
6375     auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6376     if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
6377       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6378       return;
6379     }
6380 
6381     // When X == Y, this is rotate. If the data type has a power-of-2 size, we
6382     // avoid the select that is necessary in the general case to filter out
6383     // the 0-shift possibility that leads to UB.
6384     if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
6385       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6386       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6387         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6388         return;
6389       }
6390 
6391       // Some targets only rotate one way. Try the opposite direction.
6392       RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
6393       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6394         // Negate the shift amount because it is safe to ignore the high bits.
6395         SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6396         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
6397         return;
6398       }
6399 
6400       // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
6401       // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
6402       SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6403       SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
6404       SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
6405       SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
6406       setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
6407       return;
6408     }
6409 
6410     // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
6411     // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
6412     SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
6413     SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
6414     SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
6415     SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
6416 
6417     // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
6418     // and that is undefined. We must compare and select to avoid UB.
6419     EVT CCVT = MVT::i1;
6420     if (VT.isVector())
6421       CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
6422 
6423     // For fshl, 0-shift returns the 1st arg (X).
6424     // For fshr, 0-shift returns the 2nd arg (Y).
6425     SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
6426     setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
6427     return;
6428   }
6429   case Intrinsic::sadd_sat: {
6430     SDValue Op1 = getValue(I.getArgOperand(0));
6431     SDValue Op2 = getValue(I.getArgOperand(1));
6432     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6433     return;
6434   }
6435   case Intrinsic::uadd_sat: {
6436     SDValue Op1 = getValue(I.getArgOperand(0));
6437     SDValue Op2 = getValue(I.getArgOperand(1));
6438     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6439     return;
6440   }
6441   case Intrinsic::ssub_sat: {
6442     SDValue Op1 = getValue(I.getArgOperand(0));
6443     SDValue Op2 = getValue(I.getArgOperand(1));
6444     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6445     return;
6446   }
6447   case Intrinsic::usub_sat: {
6448     SDValue Op1 = getValue(I.getArgOperand(0));
6449     SDValue Op2 = getValue(I.getArgOperand(1));
6450     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6451     return;
6452   }
6453   case Intrinsic::smul_fix:
6454   case Intrinsic::umul_fix:
6455   case Intrinsic::smul_fix_sat:
6456   case Intrinsic::umul_fix_sat: {
6457     SDValue Op1 = getValue(I.getArgOperand(0));
6458     SDValue Op2 = getValue(I.getArgOperand(1));
6459     SDValue Op3 = getValue(I.getArgOperand(2));
6460     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6461                              Op1.getValueType(), Op1, Op2, Op3));
6462     return;
6463   }
6464   case Intrinsic::sdiv_fix:
6465   case Intrinsic::udiv_fix: {
6466     SDValue Op1 = getValue(I.getArgOperand(0));
6467     SDValue Op2 = getValue(I.getArgOperand(1));
6468     SDValue Op3 = getValue(I.getArgOperand(2));
6469     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6470                               Op1, Op2, Op3, DAG, TLI));
6471     return;
6472   }
6473   case Intrinsic::stacksave: {
6474     SDValue Op = getRoot();
6475     Res = DAG.getNode(
6476         ISD::STACKSAVE, sdl,
6477         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
6478     setValue(&I, Res);
6479     DAG.setRoot(Res.getValue(1));
6480     return;
6481   }
6482   case Intrinsic::stackrestore:
6483     Res = getValue(I.getArgOperand(0));
6484     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6485     return;
6486   case Intrinsic::get_dynamic_area_offset: {
6487     SDValue Op = getRoot();
6488     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6489     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6490     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6491     // target.
6492     if (PtrTy.getSizeInBits() < ResTy.getSizeInBits())
6493       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6494                          " intrinsic!");
6495     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6496                       Op);
6497     DAG.setRoot(Op);
6498     setValue(&I, Res);
6499     return;
6500   }
6501   case Intrinsic::stackguard: {
6502     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6503     MachineFunction &MF = DAG.getMachineFunction();
6504     const Module &M = *MF.getFunction().getParent();
6505     SDValue Chain = getRoot();
6506     if (TLI.useLoadStackGuardNode()) {
6507       Res = getLoadStackGuard(DAG, sdl, Chain);
6508     } else {
6509       const Value *Global = TLI.getSDagStackGuard(M);
6510       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
6511       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6512                         MachinePointerInfo(Global, 0), Align,
6513                         MachineMemOperand::MOVolatile);
6514     }
6515     if (TLI.useStackGuardXorFP())
6516       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6517     DAG.setRoot(Chain);
6518     setValue(&I, Res);
6519     return;
6520   }
6521   case Intrinsic::stackprotector: {
6522     // Emit code into the DAG to store the stack guard onto the stack.
6523     MachineFunction &MF = DAG.getMachineFunction();
6524     MachineFrameInfo &MFI = MF.getFrameInfo();
6525     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6526     SDValue Src, Chain = getRoot();
6527 
6528     if (TLI.useLoadStackGuardNode())
6529       Src = getLoadStackGuard(DAG, sdl, Chain);
6530     else
6531       Src = getValue(I.getArgOperand(0));   // The guard's value.
6532 
6533     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6534 
6535     int FI = FuncInfo.StaticAllocaMap[Slot];
6536     MFI.setStackProtectorIndex(FI);
6537 
6538     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6539 
6540     // Store the stack protector onto the stack.
6541     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
6542                                                  DAG.getMachineFunction(), FI),
6543                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
6544     setValue(&I, Res);
6545     DAG.setRoot(Res);
6546     return;
6547   }
6548   case Intrinsic::objectsize:
6549     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6550 
6551   case Intrinsic::is_constant:
6552     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6553 
6554   case Intrinsic::annotation:
6555   case Intrinsic::ptr_annotation:
6556   case Intrinsic::launder_invariant_group:
6557   case Intrinsic::strip_invariant_group:
6558     // Drop the intrinsic, but forward the value
6559     setValue(&I, getValue(I.getOperand(0)));
6560     return;
6561   case Intrinsic::assume:
6562   case Intrinsic::var_annotation:
6563   case Intrinsic::sideeffect:
6564     // Discard annotate attributes, assumptions, and artificial side-effects.
6565     return;
6566 
6567   case Intrinsic::codeview_annotation: {
6568     // Emit a label associated with this metadata.
6569     MachineFunction &MF = DAG.getMachineFunction();
6570     MCSymbol *Label =
6571         MF.getMMI().getContext().createTempSymbol("annotation", true);
6572     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6573     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6574     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6575     DAG.setRoot(Res);
6576     return;
6577   }
6578 
6579   case Intrinsic::init_trampoline: {
6580     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6581 
6582     SDValue Ops[6];
6583     Ops[0] = getRoot();
6584     Ops[1] = getValue(I.getArgOperand(0));
6585     Ops[2] = getValue(I.getArgOperand(1));
6586     Ops[3] = getValue(I.getArgOperand(2));
6587     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6588     Ops[5] = DAG.getSrcValue(F);
6589 
6590     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6591 
6592     DAG.setRoot(Res);
6593     return;
6594   }
6595   case Intrinsic::adjust_trampoline:
6596     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6597                              TLI.getPointerTy(DAG.getDataLayout()),
6598                              getValue(I.getArgOperand(0))));
6599     return;
6600   case Intrinsic::gcroot: {
6601     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6602            "only valid in functions with gc specified, enforced by Verifier");
6603     assert(GFI && "implied by previous");
6604     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6605     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6606 
6607     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6608     GFI->addStackRoot(FI->getIndex(), TypeMap);
6609     return;
6610   }
6611   case Intrinsic::gcread:
6612   case Intrinsic::gcwrite:
6613     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6614   case Intrinsic::flt_rounds:
6615     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
6616     return;
6617 
6618   case Intrinsic::expect:
6619     // Just replace __builtin_expect(exp, c) with EXP.
6620     setValue(&I, getValue(I.getArgOperand(0)));
6621     return;
6622 
6623   case Intrinsic::debugtrap:
6624   case Intrinsic::trap: {
6625     StringRef TrapFuncName =
6626         I.getAttributes()
6627             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6628             .getValueAsString();
6629     if (TrapFuncName.empty()) {
6630       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
6631         ISD::TRAP : ISD::DEBUGTRAP;
6632       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
6633       return;
6634     }
6635     TargetLowering::ArgListTy Args;
6636 
6637     TargetLowering::CallLoweringInfo CLI(DAG);
6638     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6639         CallingConv::C, I.getType(),
6640         DAG.getExternalSymbol(TrapFuncName.data(),
6641                               TLI.getPointerTy(DAG.getDataLayout())),
6642         std::move(Args));
6643 
6644     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6645     DAG.setRoot(Result.second);
6646     return;
6647   }
6648 
6649   case Intrinsic::uadd_with_overflow:
6650   case Intrinsic::sadd_with_overflow:
6651   case Intrinsic::usub_with_overflow:
6652   case Intrinsic::ssub_with_overflow:
6653   case Intrinsic::umul_with_overflow:
6654   case Intrinsic::smul_with_overflow: {
6655     ISD::NodeType Op;
6656     switch (Intrinsic) {
6657     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6658     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6659     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6660     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6661     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6662     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6663     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6664     }
6665     SDValue Op1 = getValue(I.getArgOperand(0));
6666     SDValue Op2 = getValue(I.getArgOperand(1));
6667 
6668     EVT ResultVT = Op1.getValueType();
6669     EVT OverflowVT = MVT::i1;
6670     if (ResultVT.isVector())
6671       OverflowVT = EVT::getVectorVT(
6672           *Context, OverflowVT, ResultVT.getVectorNumElements());
6673 
6674     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6675     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6676     return;
6677   }
6678   case Intrinsic::prefetch: {
6679     SDValue Ops[5];
6680     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6681     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6682     Ops[0] = DAG.getRoot();
6683     Ops[1] = getValue(I.getArgOperand(0));
6684     Ops[2] = getValue(I.getArgOperand(1));
6685     Ops[3] = getValue(I.getArgOperand(2));
6686     Ops[4] = getValue(I.getArgOperand(3));
6687     SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
6688                                              DAG.getVTList(MVT::Other), Ops,
6689                                              EVT::getIntegerVT(*Context, 8),
6690                                              MachinePointerInfo(I.getArgOperand(0)),
6691                                              0, /* align */
6692                                              Flags);
6693 
6694     // Chain the prefetch in parallell with any pending loads, to stay out of
6695     // the way of later optimizations.
6696     PendingLoads.push_back(Result);
6697     Result = getRoot();
6698     DAG.setRoot(Result);
6699     return;
6700   }
6701   case Intrinsic::lifetime_start:
6702   case Intrinsic::lifetime_end: {
6703     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6704     // Stack coloring is not enabled in O0, discard region information.
6705     if (TM.getOptLevel() == CodeGenOpt::None)
6706       return;
6707 
6708     const int64_t ObjectSize =
6709         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6710     Value *const ObjectPtr = I.getArgOperand(1);
6711     SmallVector<const Value *, 4> Allocas;
6712     GetUnderlyingObjects(ObjectPtr, Allocas, *DL);
6713 
6714     for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(),
6715            E = Allocas.end(); Object != E; ++Object) {
6716       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
6717 
6718       // Could not find an Alloca.
6719       if (!LifetimeObject)
6720         continue;
6721 
6722       // First check that the Alloca is static, otherwise it won't have a
6723       // valid frame index.
6724       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6725       if (SI == FuncInfo.StaticAllocaMap.end())
6726         return;
6727 
6728       const int FrameIndex = SI->second;
6729       int64_t Offset;
6730       if (GetPointerBaseWithConstantOffset(
6731               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6732         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6733       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6734                                 Offset);
6735       DAG.setRoot(Res);
6736     }
6737     return;
6738   }
6739   case Intrinsic::invariant_start:
6740     // Discard region information.
6741     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6742     return;
6743   case Intrinsic::invariant_end:
6744     // Discard region information.
6745     return;
6746   case Intrinsic::clear_cache:
6747     /// FunctionName may be null.
6748     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6749       lowerCallToExternalSymbol(I, FunctionName);
6750     return;
6751   case Intrinsic::donothing:
6752     // ignore
6753     return;
6754   case Intrinsic::experimental_stackmap:
6755     visitStackmap(I);
6756     return;
6757   case Intrinsic::experimental_patchpoint_void:
6758   case Intrinsic::experimental_patchpoint_i64:
6759     visitPatchpoint(&I);
6760     return;
6761   case Intrinsic::experimental_gc_statepoint:
6762     LowerStatepoint(ImmutableStatepoint(&I));
6763     return;
6764   case Intrinsic::experimental_gc_result:
6765     visitGCResult(cast<GCResultInst>(I));
6766     return;
6767   case Intrinsic::experimental_gc_relocate:
6768     visitGCRelocate(cast<GCRelocateInst>(I));
6769     return;
6770   case Intrinsic::instrprof_increment:
6771     llvm_unreachable("instrprof failed to lower an increment");
6772   case Intrinsic::instrprof_value_profile:
6773     llvm_unreachable("instrprof failed to lower a value profiling call");
6774   case Intrinsic::localescape: {
6775     MachineFunction &MF = DAG.getMachineFunction();
6776     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6777 
6778     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6779     // is the same on all targets.
6780     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6781       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6782       if (isa<ConstantPointerNull>(Arg))
6783         continue; // Skip null pointers. They represent a hole in index space.
6784       AllocaInst *Slot = cast<AllocaInst>(Arg);
6785       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6786              "can only escape static allocas");
6787       int FI = FuncInfo.StaticAllocaMap[Slot];
6788       MCSymbol *FrameAllocSym =
6789           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6790               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6791       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6792               TII->get(TargetOpcode::LOCAL_ESCAPE))
6793           .addSym(FrameAllocSym)
6794           .addFrameIndex(FI);
6795     }
6796 
6797     return;
6798   }
6799 
6800   case Intrinsic::localrecover: {
6801     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6802     MachineFunction &MF = DAG.getMachineFunction();
6803     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
6804 
6805     // Get the symbol that defines the frame offset.
6806     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6807     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6808     unsigned IdxVal =
6809         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6810     MCSymbol *FrameAllocSym =
6811         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6812             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6813 
6814     // Create a MCSymbol for the label to avoid any target lowering
6815     // that would make this PC relative.
6816     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6817     SDValue OffsetVal =
6818         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6819 
6820     // Add the offset to the FP.
6821     Value *FP = I.getArgOperand(1);
6822     SDValue FPVal = getValue(FP);
6823     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
6824     setValue(&I, Add);
6825 
6826     return;
6827   }
6828 
6829   case Intrinsic::eh_exceptionpointer:
6830   case Intrinsic::eh_exceptioncode: {
6831     // Get the exception pointer vreg, copy from it, and resize it to fit.
6832     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6833     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6834     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6835     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6836     SDValue N =
6837         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6838     if (Intrinsic == Intrinsic::eh_exceptioncode)
6839       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6840     setValue(&I, N);
6841     return;
6842   }
6843   case Intrinsic::xray_customevent: {
6844     // Here we want to make sure that the intrinsic behaves as if it has a
6845     // specific calling convention, and only for x86_64.
6846     // FIXME: Support other platforms later.
6847     const auto &Triple = DAG.getTarget().getTargetTriple();
6848     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6849       return;
6850 
6851     SDLoc DL = getCurSDLoc();
6852     SmallVector<SDValue, 8> Ops;
6853 
6854     // We want to say that we always want the arguments in registers.
6855     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6856     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6857     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6858     SDValue Chain = getRoot();
6859     Ops.push_back(LogEntryVal);
6860     Ops.push_back(StrSizeVal);
6861     Ops.push_back(Chain);
6862 
6863     // We need to enforce the calling convention for the callsite, so that
6864     // argument ordering is enforced correctly, and that register allocation can
6865     // see that some registers may be assumed clobbered and have to preserve
6866     // them across calls to the intrinsic.
6867     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6868                                            DL, NodeTys, Ops);
6869     SDValue patchableNode = SDValue(MN, 0);
6870     DAG.setRoot(patchableNode);
6871     setValue(&I, patchableNode);
6872     return;
6873   }
6874   case Intrinsic::xray_typedevent: {
6875     // Here we want to make sure that the intrinsic behaves as if it has a
6876     // specific calling convention, and only for x86_64.
6877     // FIXME: Support other platforms later.
6878     const auto &Triple = DAG.getTarget().getTargetTriple();
6879     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6880       return;
6881 
6882     SDLoc DL = getCurSDLoc();
6883     SmallVector<SDValue, 8> Ops;
6884 
6885     // We want to say that we always want the arguments in registers.
6886     // It's unclear to me how manipulating the selection DAG here forces callers
6887     // to provide arguments in registers instead of on the stack.
6888     SDValue LogTypeId = getValue(I.getArgOperand(0));
6889     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6890     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6891     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6892     SDValue Chain = getRoot();
6893     Ops.push_back(LogTypeId);
6894     Ops.push_back(LogEntryVal);
6895     Ops.push_back(StrSizeVal);
6896     Ops.push_back(Chain);
6897 
6898     // We need to enforce the calling convention for the callsite, so that
6899     // argument ordering is enforced correctly, and that register allocation can
6900     // see that some registers may be assumed clobbered and have to preserve
6901     // them across calls to the intrinsic.
6902     MachineSDNode *MN = DAG.getMachineNode(
6903         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6904     SDValue patchableNode = SDValue(MN, 0);
6905     DAG.setRoot(patchableNode);
6906     setValue(&I, patchableNode);
6907     return;
6908   }
6909   case Intrinsic::experimental_deoptimize:
6910     LowerDeoptimizeCall(&I);
6911     return;
6912 
6913   case Intrinsic::experimental_vector_reduce_v2_fadd:
6914   case Intrinsic::experimental_vector_reduce_v2_fmul:
6915   case Intrinsic::experimental_vector_reduce_add:
6916   case Intrinsic::experimental_vector_reduce_mul:
6917   case Intrinsic::experimental_vector_reduce_and:
6918   case Intrinsic::experimental_vector_reduce_or:
6919   case Intrinsic::experimental_vector_reduce_xor:
6920   case Intrinsic::experimental_vector_reduce_smax:
6921   case Intrinsic::experimental_vector_reduce_smin:
6922   case Intrinsic::experimental_vector_reduce_umax:
6923   case Intrinsic::experimental_vector_reduce_umin:
6924   case Intrinsic::experimental_vector_reduce_fmax:
6925   case Intrinsic::experimental_vector_reduce_fmin:
6926     visitVectorReduce(I, Intrinsic);
6927     return;
6928 
6929   case Intrinsic::icall_branch_funnel: {
6930     SmallVector<SDValue, 16> Ops;
6931     Ops.push_back(getValue(I.getArgOperand(0)));
6932 
6933     int64_t Offset;
6934     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6935         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6936     if (!Base)
6937       report_fatal_error(
6938           "llvm.icall.branch.funnel operand must be a GlobalValue");
6939     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6940 
6941     struct BranchFunnelTarget {
6942       int64_t Offset;
6943       SDValue Target;
6944     };
6945     SmallVector<BranchFunnelTarget, 8> Targets;
6946 
6947     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6948       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6949           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6950       if (ElemBase != Base)
6951         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6952                            "to the same GlobalValue");
6953 
6954       SDValue Val = getValue(I.getArgOperand(Op + 1));
6955       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6956       if (!GA)
6957         report_fatal_error(
6958             "llvm.icall.branch.funnel operand must be a GlobalValue");
6959       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6960                                      GA->getGlobal(), getCurSDLoc(),
6961                                      Val.getValueType(), GA->getOffset())});
6962     }
6963     llvm::sort(Targets,
6964                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6965                  return T1.Offset < T2.Offset;
6966                });
6967 
6968     for (auto &T : Targets) {
6969       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6970       Ops.push_back(T.Target);
6971     }
6972 
6973     Ops.push_back(DAG.getRoot()); // Chain
6974     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6975                                  getCurSDLoc(), MVT::Other, Ops),
6976               0);
6977     DAG.setRoot(N);
6978     setValue(&I, N);
6979     HasTailCall = true;
6980     return;
6981   }
6982 
6983   case Intrinsic::wasm_landingpad_index:
6984     // Information this intrinsic contained has been transferred to
6985     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
6986     // delete it now.
6987     return;
6988 
6989   case Intrinsic::aarch64_settag:
6990   case Intrinsic::aarch64_settag_zero: {
6991     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6992     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
6993     SDValue Val = TSI.EmitTargetCodeForSetTag(
6994         DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)),
6995         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
6996         ZeroMemory);
6997     DAG.setRoot(Val);
6998     setValue(&I, Val);
6999     return;
7000   }
7001   case Intrinsic::ptrmask: {
7002     SDValue Ptr = getValue(I.getOperand(0));
7003     SDValue Const = getValue(I.getOperand(1));
7004 
7005     EVT DestVT =
7006         EVT(DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
7007 
7008     setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), DestVT, Ptr,
7009                              DAG.getZExtOrTrunc(Const, getCurSDLoc(), DestVT)));
7010     return;
7011   }
7012   }
7013 }
7014 
7015 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7016     const ConstrainedFPIntrinsic &FPI) {
7017   SDLoc sdl = getCurSDLoc();
7018 
7019   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7020   SmallVector<EVT, 4> ValueVTs;
7021   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
7022   ValueVTs.push_back(MVT::Other); // Out chain
7023 
7024   // We do not need to serialize constrained FP intrinsics against
7025   // each other or against (nonvolatile) loads, so they can be
7026   // chained like loads.
7027   SDValue Chain = DAG.getRoot();
7028   SmallVector<SDValue, 4> Opers;
7029   Opers.push_back(Chain);
7030   if (FPI.isUnaryOp()) {
7031     Opers.push_back(getValue(FPI.getArgOperand(0)));
7032   } else if (FPI.isTernaryOp()) {
7033     Opers.push_back(getValue(FPI.getArgOperand(0)));
7034     Opers.push_back(getValue(FPI.getArgOperand(1)));
7035     Opers.push_back(getValue(FPI.getArgOperand(2)));
7036   } else {
7037     Opers.push_back(getValue(FPI.getArgOperand(0)));
7038     Opers.push_back(getValue(FPI.getArgOperand(1)));
7039   }
7040 
7041   unsigned Opcode;
7042   switch (FPI.getIntrinsicID()) {
7043   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7044 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)                   \
7045   case Intrinsic::INTRINSIC:                                                   \
7046     Opcode = ISD::STRICT_##DAGN;                                               \
7047     break;
7048 #include "llvm/IR/ConstrainedOps.def"
7049   }
7050 
7051   // A few strict DAG nodes carry additional operands that are not
7052   // set up by the default code above.
7053   switch (Opcode) {
7054   default: break;
7055   case ISD::STRICT_FP_ROUND:
7056     Opers.push_back(
7057         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7058     break;
7059   case ISD::STRICT_FSETCC:
7060   case ISD::STRICT_FSETCCS: {
7061     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7062     Opers.push_back(DAG.getCondCode(getFCmpCondCode(FPCmp->getPredicate())));
7063     break;
7064   }
7065   }
7066 
7067   SDVTList VTs = DAG.getVTList(ValueVTs);
7068   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers);
7069 
7070   assert(Result.getNode()->getNumValues() == 2);
7071 
7072   // Push node to the appropriate list so that future instructions can be
7073   // chained up correctly.
7074   SDValue OutChain = Result.getValue(1);
7075   switch (FPI.getExceptionBehavior().getValue()) {
7076   case fp::ExceptionBehavior::ebIgnore:
7077     // The only reason why ebIgnore nodes still need to be chained is that
7078     // they might depend on the current rounding mode, and therefore must
7079     // not be moved across instruction that may change that mode.
7080     LLVM_FALLTHROUGH;
7081   case fp::ExceptionBehavior::ebMayTrap:
7082     // These must not be moved across calls or instructions that may change
7083     // floating-point exception masks.
7084     PendingConstrainedFP.push_back(OutChain);
7085     break;
7086   case fp::ExceptionBehavior::ebStrict:
7087     // These must not be moved across calls or instructions that may change
7088     // floating-point exception masks or read floating-point exception flags.
7089     // In addition, they cannot be optimized out even if unused.
7090     PendingConstrainedFPStrict.push_back(OutChain);
7091     break;
7092   }
7093 
7094   SDValue FPResult = Result.getValue(0);
7095   setValue(&FPI, FPResult);
7096 }
7097 
7098 std::pair<SDValue, SDValue>
7099 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7100                                     const BasicBlock *EHPadBB) {
7101   MachineFunction &MF = DAG.getMachineFunction();
7102   MachineModuleInfo &MMI = MF.getMMI();
7103   MCSymbol *BeginLabel = nullptr;
7104 
7105   if (EHPadBB) {
7106     // Insert a label before the invoke call to mark the try range.  This can be
7107     // used to detect deletion of the invoke via the MachineModuleInfo.
7108     BeginLabel = MMI.getContext().createTempSymbol();
7109 
7110     // For SjLj, keep track of which landing pads go with which invokes
7111     // so as to maintain the ordering of pads in the LSDA.
7112     unsigned CallSiteIndex = MMI.getCurrentCallSite();
7113     if (CallSiteIndex) {
7114       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7115       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7116 
7117       // Now that the call site is handled, stop tracking it.
7118       MMI.setCurrentCallSite(0);
7119     }
7120 
7121     // Both PendingLoads and PendingExports must be flushed here;
7122     // this call might not return.
7123     (void)getRoot();
7124     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
7125 
7126     CLI.setChain(getRoot());
7127   }
7128   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7129   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7130 
7131   assert((CLI.IsTailCall || Result.second.getNode()) &&
7132          "Non-null chain expected with non-tail call!");
7133   assert((Result.second.getNode() || !Result.first.getNode()) &&
7134          "Null value expected with tail call!");
7135 
7136   if (!Result.second.getNode()) {
7137     // As a special case, a null chain means that a tail call has been emitted
7138     // and the DAG root is already updated.
7139     HasTailCall = true;
7140 
7141     // Since there's no actual continuation from this block, nothing can be
7142     // relying on us setting vregs for them.
7143     PendingExports.clear();
7144   } else {
7145     DAG.setRoot(Result.second);
7146   }
7147 
7148   if (EHPadBB) {
7149     // Insert a label at the end of the invoke call to mark the try range.  This
7150     // can be used to detect deletion of the invoke via the MachineModuleInfo.
7151     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7152     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
7153 
7154     // Inform MachineModuleInfo of range.
7155     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7156     // There is a platform (e.g. wasm) that uses funclet style IR but does not
7157     // actually use outlined funclets and their LSDA info style.
7158     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7159       assert(CLI.CS);
7160       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
7161       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
7162                                 BeginLabel, EndLabel);
7163     } else if (!isScopedEHPersonality(Pers)) {
7164       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7165     }
7166   }
7167 
7168   return Result;
7169 }
7170 
7171 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
7172                                       bool isTailCall,
7173                                       const BasicBlock *EHPadBB) {
7174   auto &DL = DAG.getDataLayout();
7175   FunctionType *FTy = CS.getFunctionType();
7176   Type *RetTy = CS.getType();
7177 
7178   TargetLowering::ArgListTy Args;
7179   Args.reserve(CS.arg_size());
7180 
7181   const Value *SwiftErrorVal = nullptr;
7182   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7183 
7184   if (isTailCall) {
7185     // Avoid emitting tail calls in functions with the disable-tail-calls
7186     // attribute.
7187     auto *Caller = CS.getInstruction()->getParent()->getParent();
7188     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7189         "true")
7190       isTailCall = false;
7191 
7192     // We can't tail call inside a function with a swifterror argument. Lowering
7193     // does not support this yet. It would have to move into the swifterror
7194     // register before the call.
7195     if (TLI.supportSwiftError() &&
7196         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7197       isTailCall = false;
7198   }
7199 
7200   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
7201        i != e; ++i) {
7202     TargetLowering::ArgListEntry Entry;
7203     const Value *V = *i;
7204 
7205     // Skip empty types
7206     if (V->getType()->isEmptyTy())
7207       continue;
7208 
7209     SDValue ArgNode = getValue(V);
7210     Entry.Node = ArgNode; Entry.Ty = V->getType();
7211 
7212     Entry.setAttributes(&CS, i - CS.arg_begin());
7213 
7214     // Use swifterror virtual register as input to the call.
7215     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7216       SwiftErrorVal = V;
7217       // We find the virtual register for the actual swifterror argument.
7218       // Instead of using the Value, we use the virtual register instead.
7219       Entry.Node = DAG.getRegister(
7220           SwiftError.getOrCreateVRegUseAt(CS.getInstruction(), FuncInfo.MBB, V),
7221           EVT(TLI.getPointerTy(DL)));
7222     }
7223 
7224     Args.push_back(Entry);
7225 
7226     // If we have an explicit sret argument that is an Instruction, (i.e., it
7227     // might point to function-local memory), we can't meaningfully tail-call.
7228     if (Entry.IsSRet && isa<Instruction>(V))
7229       isTailCall = false;
7230   }
7231 
7232   // If call site has a cfguardtarget operand bundle, create and add an
7233   // additional ArgListEntry.
7234   if (auto Bundle = CS.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7235     TargetLowering::ArgListEntry Entry;
7236     Value *V = Bundle->Inputs[0];
7237     SDValue ArgNode = getValue(V);
7238     Entry.Node = ArgNode;
7239     Entry.Ty = V->getType();
7240     Entry.IsCFGuardTarget = true;
7241     Args.push_back(Entry);
7242   }
7243 
7244   // Check if target-independent constraints permit a tail call here.
7245   // Target-dependent constraints are checked within TLI->LowerCallTo.
7246   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
7247     isTailCall = false;
7248 
7249   // Disable tail calls if there is an swifterror argument. Targets have not
7250   // been updated to support tail calls.
7251   if (TLI.supportSwiftError() && SwiftErrorVal)
7252     isTailCall = false;
7253 
7254   TargetLowering::CallLoweringInfo CLI(DAG);
7255   CLI.setDebugLoc(getCurSDLoc())
7256       .setChain(getRoot())
7257       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
7258       .setTailCall(isTailCall)
7259       .setConvergent(CS.isConvergent());
7260   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7261 
7262   if (Result.first.getNode()) {
7263     const Instruction *Inst = CS.getInstruction();
7264     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
7265     setValue(Inst, Result.first);
7266   }
7267 
7268   // The last element of CLI.InVals has the SDValue for swifterror return.
7269   // Here we copy it to a virtual register and update SwiftErrorMap for
7270   // book-keeping.
7271   if (SwiftErrorVal && TLI.supportSwiftError()) {
7272     // Get the last element of InVals.
7273     SDValue Src = CLI.InVals.back();
7274     Register VReg = SwiftError.getOrCreateVRegDefAt(
7275         CS.getInstruction(), FuncInfo.MBB, SwiftErrorVal);
7276     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7277     DAG.setRoot(CopyNode);
7278   }
7279 }
7280 
7281 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7282                              SelectionDAGBuilder &Builder) {
7283   // Check to see if this load can be trivially constant folded, e.g. if the
7284   // input is from a string literal.
7285   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7286     // Cast pointer to the type we really want to load.
7287     Type *LoadTy =
7288         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7289     if (LoadVT.isVector())
7290       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
7291 
7292     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7293                                          PointerType::getUnqual(LoadTy));
7294 
7295     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
7296             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
7297       return Builder.getValue(LoadCst);
7298   }
7299 
7300   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7301   // still constant memory, the input chain can be the entry node.
7302   SDValue Root;
7303   bool ConstantMemory = false;
7304 
7305   // Do not serialize (non-volatile) loads of constant memory with anything.
7306   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7307     Root = Builder.DAG.getEntryNode();
7308     ConstantMemory = true;
7309   } else {
7310     // Do not serialize non-volatile loads against each other.
7311     Root = Builder.DAG.getRoot();
7312   }
7313 
7314   SDValue Ptr = Builder.getValue(PtrVal);
7315   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
7316                                         Ptr, MachinePointerInfo(PtrVal),
7317                                         /* Alignment = */ 1);
7318 
7319   if (!ConstantMemory)
7320     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7321   return LoadVal;
7322 }
7323 
7324 /// Record the value for an instruction that produces an integer result,
7325 /// converting the type where necessary.
7326 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7327                                                   SDValue Value,
7328                                                   bool IsSigned) {
7329   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7330                                                     I.getType(), true);
7331   if (IsSigned)
7332     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7333   else
7334     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7335   setValue(&I, Value);
7336 }
7337 
7338 /// See if we can lower a memcmp call into an optimized form. If so, return
7339 /// true and lower it. Otherwise return false, and it will be lowered like a
7340 /// normal call.
7341 /// The caller already checked that \p I calls the appropriate LibFunc with a
7342 /// correct prototype.
7343 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
7344   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7345   const Value *Size = I.getArgOperand(2);
7346   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7347   if (CSize && CSize->getZExtValue() == 0) {
7348     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7349                                                           I.getType(), true);
7350     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7351     return true;
7352   }
7353 
7354   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7355   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7356       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7357       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7358   if (Res.first.getNode()) {
7359     processIntegerCallValue(I, Res.first, true);
7360     PendingLoads.push_back(Res.second);
7361     return true;
7362   }
7363 
7364   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7365   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7366   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7367     return false;
7368 
7369   // If the target has a fast compare for the given size, it will return a
7370   // preferred load type for that size. Require that the load VT is legal and
7371   // that the target supports unaligned loads of that type. Otherwise, return
7372   // INVALID.
7373   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7374     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7375     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7376     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7377       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7378       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7379       // TODO: Check alignment of src and dest ptrs.
7380       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7381       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7382       if (!TLI.isTypeLegal(LVT) ||
7383           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7384           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7385         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7386     }
7387 
7388     return LVT;
7389   };
7390 
7391   // This turns into unaligned loads. We only do this if the target natively
7392   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7393   // we'll only produce a small number of byte loads.
7394   MVT LoadVT;
7395   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7396   switch (NumBitsToCompare) {
7397   default:
7398     return false;
7399   case 16:
7400     LoadVT = MVT::i16;
7401     break;
7402   case 32:
7403     LoadVT = MVT::i32;
7404     break;
7405   case 64:
7406   case 128:
7407   case 256:
7408     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7409     break;
7410   }
7411 
7412   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7413     return false;
7414 
7415   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7416   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7417 
7418   // Bitcast to a wide integer type if the loads are vectors.
7419   if (LoadVT.isVector()) {
7420     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7421     LoadL = DAG.getBitcast(CmpVT, LoadL);
7422     LoadR = DAG.getBitcast(CmpVT, LoadR);
7423   }
7424 
7425   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7426   processIntegerCallValue(I, Cmp, false);
7427   return true;
7428 }
7429 
7430 /// See if we can lower a memchr call into an optimized form. If so, return
7431 /// true and lower it. Otherwise return false, and it will be lowered like a
7432 /// normal call.
7433 /// The caller already checked that \p I calls the appropriate LibFunc with a
7434 /// correct prototype.
7435 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7436   const Value *Src = I.getArgOperand(0);
7437   const Value *Char = I.getArgOperand(1);
7438   const Value *Length = I.getArgOperand(2);
7439 
7440   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7441   std::pair<SDValue, SDValue> Res =
7442     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7443                                 getValue(Src), getValue(Char), getValue(Length),
7444                                 MachinePointerInfo(Src));
7445   if (Res.first.getNode()) {
7446     setValue(&I, Res.first);
7447     PendingLoads.push_back(Res.second);
7448     return true;
7449   }
7450 
7451   return false;
7452 }
7453 
7454 /// See if we can lower a mempcpy call into an optimized form. If so, return
7455 /// true and lower it. Otherwise return false, and it will be lowered like a
7456 /// normal call.
7457 /// The caller already checked that \p I calls the appropriate LibFunc with a
7458 /// correct prototype.
7459 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7460   SDValue Dst = getValue(I.getArgOperand(0));
7461   SDValue Src = getValue(I.getArgOperand(1));
7462   SDValue Size = getValue(I.getArgOperand(2));
7463 
7464   unsigned DstAlign = DAG.InferPtrAlignment(Dst);
7465   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
7466   unsigned Align = std::min(DstAlign, SrcAlign);
7467   if (Align == 0) // Alignment of one or both could not be inferred.
7468     Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
7469 
7470   bool isVol = false;
7471   SDLoc sdl = getCurSDLoc();
7472 
7473   // In the mempcpy context we need to pass in a false value for isTailCall
7474   // because the return pointer needs to be adjusted by the size of
7475   // the copied memory.
7476   SDValue Root = isVol ? getRoot() : getMemoryRoot();
7477   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Align, isVol,
7478                              false, /*isTailCall=*/false,
7479                              MachinePointerInfo(I.getArgOperand(0)),
7480                              MachinePointerInfo(I.getArgOperand(1)));
7481   assert(MC.getNode() != nullptr &&
7482          "** memcpy should not be lowered as TailCall in mempcpy context **");
7483   DAG.setRoot(MC);
7484 
7485   // Check if Size needs to be truncated or extended.
7486   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7487 
7488   // Adjust return pointer to point just past the last dst byte.
7489   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7490                                     Dst, Size);
7491   setValue(&I, DstPlusSize);
7492   return true;
7493 }
7494 
7495 /// See if we can lower a strcpy call into an optimized form.  If so, return
7496 /// true and lower it, otherwise return false and it will be lowered like a
7497 /// normal call.
7498 /// The caller already checked that \p I calls the appropriate LibFunc with a
7499 /// correct prototype.
7500 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7501   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7502 
7503   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7504   std::pair<SDValue, SDValue> Res =
7505     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7506                                 getValue(Arg0), getValue(Arg1),
7507                                 MachinePointerInfo(Arg0),
7508                                 MachinePointerInfo(Arg1), isStpcpy);
7509   if (Res.first.getNode()) {
7510     setValue(&I, Res.first);
7511     DAG.setRoot(Res.second);
7512     return true;
7513   }
7514 
7515   return false;
7516 }
7517 
7518 /// See if we can lower a strcmp call into an optimized form.  If so, return
7519 /// true and lower it, otherwise return false and it will be lowered like a
7520 /// normal call.
7521 /// The caller already checked that \p I calls the appropriate LibFunc with a
7522 /// correct prototype.
7523 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7524   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7525 
7526   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7527   std::pair<SDValue, SDValue> Res =
7528     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7529                                 getValue(Arg0), getValue(Arg1),
7530                                 MachinePointerInfo(Arg0),
7531                                 MachinePointerInfo(Arg1));
7532   if (Res.first.getNode()) {
7533     processIntegerCallValue(I, Res.first, true);
7534     PendingLoads.push_back(Res.second);
7535     return true;
7536   }
7537 
7538   return false;
7539 }
7540 
7541 /// See if we can lower a strlen call into an optimized form.  If so, return
7542 /// true and lower it, otherwise return false and it will be lowered like a
7543 /// normal call.
7544 /// The caller already checked that \p I calls the appropriate LibFunc with a
7545 /// correct prototype.
7546 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7547   const Value *Arg0 = I.getArgOperand(0);
7548 
7549   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7550   std::pair<SDValue, SDValue> Res =
7551     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7552                                 getValue(Arg0), MachinePointerInfo(Arg0));
7553   if (Res.first.getNode()) {
7554     processIntegerCallValue(I, Res.first, false);
7555     PendingLoads.push_back(Res.second);
7556     return true;
7557   }
7558 
7559   return false;
7560 }
7561 
7562 /// See if we can lower a strnlen call into an optimized form.  If so, return
7563 /// true and lower it, otherwise return false and it will be lowered like a
7564 /// normal call.
7565 /// The caller already checked that \p I calls the appropriate LibFunc with a
7566 /// correct prototype.
7567 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7568   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7569 
7570   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7571   std::pair<SDValue, SDValue> Res =
7572     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7573                                  getValue(Arg0), getValue(Arg1),
7574                                  MachinePointerInfo(Arg0));
7575   if (Res.first.getNode()) {
7576     processIntegerCallValue(I, Res.first, false);
7577     PendingLoads.push_back(Res.second);
7578     return true;
7579   }
7580 
7581   return false;
7582 }
7583 
7584 /// See if we can lower a unary floating-point operation into an SDNode with
7585 /// the specified Opcode.  If so, return true and lower it, otherwise return
7586 /// false and it will be lowered like a normal call.
7587 /// The caller already checked that \p I calls the appropriate LibFunc with a
7588 /// correct prototype.
7589 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7590                                               unsigned Opcode) {
7591   // We already checked this call's prototype; verify it doesn't modify errno.
7592   if (!I.onlyReadsMemory())
7593     return false;
7594 
7595   SDValue Tmp = getValue(I.getArgOperand(0));
7596   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
7597   return true;
7598 }
7599 
7600 /// See if we can lower a binary floating-point operation into an SDNode with
7601 /// the specified Opcode. If so, return true and lower it. Otherwise return
7602 /// false, and it will be lowered like a normal call.
7603 /// The caller already checked that \p I calls the appropriate LibFunc with a
7604 /// correct prototype.
7605 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7606                                                unsigned Opcode) {
7607   // We already checked this call's prototype; verify it doesn't modify errno.
7608   if (!I.onlyReadsMemory())
7609     return false;
7610 
7611   SDValue Tmp0 = getValue(I.getArgOperand(0));
7612   SDValue Tmp1 = getValue(I.getArgOperand(1));
7613   EVT VT = Tmp0.getValueType();
7614   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
7615   return true;
7616 }
7617 
7618 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7619   // Handle inline assembly differently.
7620   if (isa<InlineAsm>(I.getCalledValue())) {
7621     visitInlineAsm(&I);
7622     return;
7623   }
7624 
7625   if (Function *F = I.getCalledFunction()) {
7626     if (F->isDeclaration()) {
7627       // Is this an LLVM intrinsic or a target-specific intrinsic?
7628       unsigned IID = F->getIntrinsicID();
7629       if (!IID)
7630         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7631           IID = II->getIntrinsicID(F);
7632 
7633       if (IID) {
7634         visitIntrinsicCall(I, IID);
7635         return;
7636       }
7637     }
7638 
7639     // Check for well-known libc/libm calls.  If the function is internal, it
7640     // can't be a library call.  Don't do the check if marked as nobuiltin for
7641     // some reason or the call site requires strict floating point semantics.
7642     LibFunc Func;
7643     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7644         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7645         LibInfo->hasOptimizedCodeGen(Func)) {
7646       switch (Func) {
7647       default: break;
7648       case LibFunc_copysign:
7649       case LibFunc_copysignf:
7650       case LibFunc_copysignl:
7651         // We already checked this call's prototype; verify it doesn't modify
7652         // errno.
7653         if (I.onlyReadsMemory()) {
7654           SDValue LHS = getValue(I.getArgOperand(0));
7655           SDValue RHS = getValue(I.getArgOperand(1));
7656           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7657                                    LHS.getValueType(), LHS, RHS));
7658           return;
7659         }
7660         break;
7661       case LibFunc_fabs:
7662       case LibFunc_fabsf:
7663       case LibFunc_fabsl:
7664         if (visitUnaryFloatCall(I, ISD::FABS))
7665           return;
7666         break;
7667       case LibFunc_fmin:
7668       case LibFunc_fminf:
7669       case LibFunc_fminl:
7670         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7671           return;
7672         break;
7673       case LibFunc_fmax:
7674       case LibFunc_fmaxf:
7675       case LibFunc_fmaxl:
7676         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7677           return;
7678         break;
7679       case LibFunc_sin:
7680       case LibFunc_sinf:
7681       case LibFunc_sinl:
7682         if (visitUnaryFloatCall(I, ISD::FSIN))
7683           return;
7684         break;
7685       case LibFunc_cos:
7686       case LibFunc_cosf:
7687       case LibFunc_cosl:
7688         if (visitUnaryFloatCall(I, ISD::FCOS))
7689           return;
7690         break;
7691       case LibFunc_sqrt:
7692       case LibFunc_sqrtf:
7693       case LibFunc_sqrtl:
7694       case LibFunc_sqrt_finite:
7695       case LibFunc_sqrtf_finite:
7696       case LibFunc_sqrtl_finite:
7697         if (visitUnaryFloatCall(I, ISD::FSQRT))
7698           return;
7699         break;
7700       case LibFunc_floor:
7701       case LibFunc_floorf:
7702       case LibFunc_floorl:
7703         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7704           return;
7705         break;
7706       case LibFunc_nearbyint:
7707       case LibFunc_nearbyintf:
7708       case LibFunc_nearbyintl:
7709         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7710           return;
7711         break;
7712       case LibFunc_ceil:
7713       case LibFunc_ceilf:
7714       case LibFunc_ceill:
7715         if (visitUnaryFloatCall(I, ISD::FCEIL))
7716           return;
7717         break;
7718       case LibFunc_rint:
7719       case LibFunc_rintf:
7720       case LibFunc_rintl:
7721         if (visitUnaryFloatCall(I, ISD::FRINT))
7722           return;
7723         break;
7724       case LibFunc_round:
7725       case LibFunc_roundf:
7726       case LibFunc_roundl:
7727         if (visitUnaryFloatCall(I, ISD::FROUND))
7728           return;
7729         break;
7730       case LibFunc_trunc:
7731       case LibFunc_truncf:
7732       case LibFunc_truncl:
7733         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7734           return;
7735         break;
7736       case LibFunc_log2:
7737       case LibFunc_log2f:
7738       case LibFunc_log2l:
7739         if (visitUnaryFloatCall(I, ISD::FLOG2))
7740           return;
7741         break;
7742       case LibFunc_exp2:
7743       case LibFunc_exp2f:
7744       case LibFunc_exp2l:
7745         if (visitUnaryFloatCall(I, ISD::FEXP2))
7746           return;
7747         break;
7748       case LibFunc_memcmp:
7749         if (visitMemCmpCall(I))
7750           return;
7751         break;
7752       case LibFunc_mempcpy:
7753         if (visitMemPCpyCall(I))
7754           return;
7755         break;
7756       case LibFunc_memchr:
7757         if (visitMemChrCall(I))
7758           return;
7759         break;
7760       case LibFunc_strcpy:
7761         if (visitStrCpyCall(I, false))
7762           return;
7763         break;
7764       case LibFunc_stpcpy:
7765         if (visitStrCpyCall(I, true))
7766           return;
7767         break;
7768       case LibFunc_strcmp:
7769         if (visitStrCmpCall(I))
7770           return;
7771         break;
7772       case LibFunc_strlen:
7773         if (visitStrLenCall(I))
7774           return;
7775         break;
7776       case LibFunc_strnlen:
7777         if (visitStrNLenCall(I))
7778           return;
7779         break;
7780       }
7781     }
7782   }
7783 
7784   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7785   // have to do anything here to lower funclet bundles.
7786   // CFGuardTarget bundles are lowered in LowerCallTo.
7787   assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt,
7788                                         LLVMContext::OB_funclet,
7789                                         LLVMContext::OB_cfguardtarget}) &&
7790          "Cannot lower calls with arbitrary operand bundles!");
7791 
7792   SDValue Callee = getValue(I.getCalledValue());
7793 
7794   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7795     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7796   else
7797     // Check if we can potentially perform a tail call. More detailed checking
7798     // is be done within LowerCallTo, after more information about the call is
7799     // known.
7800     LowerCallTo(&I, Callee, I.isTailCall());
7801 }
7802 
7803 namespace {
7804 
7805 /// AsmOperandInfo - This contains information for each constraint that we are
7806 /// lowering.
7807 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7808 public:
7809   /// CallOperand - If this is the result output operand or a clobber
7810   /// this is null, otherwise it is the incoming operand to the CallInst.
7811   /// This gets modified as the asm is processed.
7812   SDValue CallOperand;
7813 
7814   /// AssignedRegs - If this is a register or register class operand, this
7815   /// contains the set of register corresponding to the operand.
7816   RegsForValue AssignedRegs;
7817 
7818   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7819     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7820   }
7821 
7822   /// Whether or not this operand accesses memory
7823   bool hasMemory(const TargetLowering &TLI) const {
7824     // Indirect operand accesses access memory.
7825     if (isIndirect)
7826       return true;
7827 
7828     for (const auto &Code : Codes)
7829       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7830         return true;
7831 
7832     return false;
7833   }
7834 
7835   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7836   /// corresponds to.  If there is no Value* for this operand, it returns
7837   /// MVT::Other.
7838   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7839                            const DataLayout &DL) const {
7840     if (!CallOperandVal) return MVT::Other;
7841 
7842     if (isa<BasicBlock>(CallOperandVal))
7843       return TLI.getPointerTy(DL);
7844 
7845     llvm::Type *OpTy = CallOperandVal->getType();
7846 
7847     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7848     // If this is an indirect operand, the operand is a pointer to the
7849     // accessed type.
7850     if (isIndirect) {
7851       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7852       if (!PtrTy)
7853         report_fatal_error("Indirect operand for inline asm not a pointer!");
7854       OpTy = PtrTy->getElementType();
7855     }
7856 
7857     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7858     if (StructType *STy = dyn_cast<StructType>(OpTy))
7859       if (STy->getNumElements() == 1)
7860         OpTy = STy->getElementType(0);
7861 
7862     // If OpTy is not a single value, it may be a struct/union that we
7863     // can tile with integers.
7864     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7865       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7866       switch (BitSize) {
7867       default: break;
7868       case 1:
7869       case 8:
7870       case 16:
7871       case 32:
7872       case 64:
7873       case 128:
7874         OpTy = IntegerType::get(Context, BitSize);
7875         break;
7876       }
7877     }
7878 
7879     return TLI.getValueType(DL, OpTy, true);
7880   }
7881 };
7882 
7883 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
7884 
7885 } // end anonymous namespace
7886 
7887 /// Make sure that the output operand \p OpInfo and its corresponding input
7888 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7889 /// out).
7890 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7891                                SDISelAsmOperandInfo &MatchingOpInfo,
7892                                SelectionDAG &DAG) {
7893   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7894     return;
7895 
7896   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7897   const auto &TLI = DAG.getTargetLoweringInfo();
7898 
7899   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7900       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7901                                        OpInfo.ConstraintVT);
7902   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7903       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7904                                        MatchingOpInfo.ConstraintVT);
7905   if ((OpInfo.ConstraintVT.isInteger() !=
7906        MatchingOpInfo.ConstraintVT.isInteger()) ||
7907       (MatchRC.second != InputRC.second)) {
7908     // FIXME: error out in a more elegant fashion
7909     report_fatal_error("Unsupported asm: input constraint"
7910                        " with a matching output constraint of"
7911                        " incompatible type!");
7912   }
7913   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7914 }
7915 
7916 /// Get a direct memory input to behave well as an indirect operand.
7917 /// This may introduce stores, hence the need for a \p Chain.
7918 /// \return The (possibly updated) chain.
7919 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7920                                         SDISelAsmOperandInfo &OpInfo,
7921                                         SelectionDAG &DAG) {
7922   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7923 
7924   // If we don't have an indirect input, put it in the constpool if we can,
7925   // otherwise spill it to a stack slot.
7926   // TODO: This isn't quite right. We need to handle these according to
7927   // the addressing mode that the constraint wants. Also, this may take
7928   // an additional register for the computation and we don't want that
7929   // either.
7930 
7931   // If the operand is a float, integer, or vector constant, spill to a
7932   // constant pool entry to get its address.
7933   const Value *OpVal = OpInfo.CallOperandVal;
7934   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7935       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7936     OpInfo.CallOperand = DAG.getConstantPool(
7937         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7938     return Chain;
7939   }
7940 
7941   // Otherwise, create a stack slot and emit a store to it before the asm.
7942   Type *Ty = OpVal->getType();
7943   auto &DL = DAG.getDataLayout();
7944   uint64_t TySize = DL.getTypeAllocSize(Ty);
7945   unsigned Align = DL.getPrefTypeAlignment(Ty);
7946   MachineFunction &MF = DAG.getMachineFunction();
7947   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7948   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7949   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7950                             MachinePointerInfo::getFixedStack(MF, SSFI),
7951                             TLI.getMemValueType(DL, Ty));
7952   OpInfo.CallOperand = StackSlot;
7953 
7954   return Chain;
7955 }
7956 
7957 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7958 /// specified operand.  We prefer to assign virtual registers, to allow the
7959 /// register allocator to handle the assignment process.  However, if the asm
7960 /// uses features that we can't model on machineinstrs, we have SDISel do the
7961 /// allocation.  This produces generally horrible, but correct, code.
7962 ///
7963 ///   OpInfo describes the operand
7964 ///   RefOpInfo describes the matching operand if any, the operand otherwise
7965 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
7966                                  SDISelAsmOperandInfo &OpInfo,
7967                                  SDISelAsmOperandInfo &RefOpInfo) {
7968   LLVMContext &Context = *DAG.getContext();
7969   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7970 
7971   MachineFunction &MF = DAG.getMachineFunction();
7972   SmallVector<unsigned, 4> Regs;
7973   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7974 
7975   // No work to do for memory operations.
7976   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
7977     return;
7978 
7979   // If this is a constraint for a single physreg, or a constraint for a
7980   // register class, find it.
7981   unsigned AssignedReg;
7982   const TargetRegisterClass *RC;
7983   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
7984       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
7985   // RC is unset only on failure. Return immediately.
7986   if (!RC)
7987     return;
7988 
7989   // Get the actual register value type.  This is important, because the user
7990   // may have asked for (e.g.) the AX register in i32 type.  We need to
7991   // remember that AX is actually i16 to get the right extension.
7992   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
7993 
7994   if (OpInfo.ConstraintVT != MVT::Other) {
7995     // If this is an FP operand in an integer register (or visa versa), or more
7996     // generally if the operand value disagrees with the register class we plan
7997     // to stick it in, fix the operand type.
7998     //
7999     // If this is an input value, the bitcast to the new type is done now.
8000     // Bitcast for output value is done at the end of visitInlineAsm().
8001     if ((OpInfo.Type == InlineAsm::isOutput ||
8002          OpInfo.Type == InlineAsm::isInput) &&
8003         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
8004       // Try to convert to the first EVT that the reg class contains.  If the
8005       // types are identical size, use a bitcast to convert (e.g. two differing
8006       // vector types).  Note: output bitcast is done at the end of
8007       // visitInlineAsm().
8008       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
8009         // Exclude indirect inputs while they are unsupported because the code
8010         // to perform the load is missing and thus OpInfo.CallOperand still
8011         // refers to the input address rather than the pointed-to value.
8012         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
8013           OpInfo.CallOperand =
8014               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
8015         OpInfo.ConstraintVT = RegVT;
8016         // If the operand is an FP value and we want it in integer registers,
8017         // use the corresponding integer type. This turns an f64 value into
8018         // i64, which can be passed with two i32 values on a 32-bit machine.
8019       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
8020         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
8021         if (OpInfo.Type == InlineAsm::isInput)
8022           OpInfo.CallOperand =
8023               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
8024         OpInfo.ConstraintVT = VT;
8025       }
8026     }
8027   }
8028 
8029   // No need to allocate a matching input constraint since the constraint it's
8030   // matching to has already been allocated.
8031   if (OpInfo.isMatchingInputConstraint())
8032     return;
8033 
8034   EVT ValueVT = OpInfo.ConstraintVT;
8035   if (OpInfo.ConstraintVT == MVT::Other)
8036     ValueVT = RegVT;
8037 
8038   // Initialize NumRegs.
8039   unsigned NumRegs = 1;
8040   if (OpInfo.ConstraintVT != MVT::Other)
8041     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
8042 
8043   // If this is a constraint for a specific physical register, like {r17},
8044   // assign it now.
8045 
8046   // If this associated to a specific register, initialize iterator to correct
8047   // place. If virtual, make sure we have enough registers
8048 
8049   // Initialize iterator if necessary
8050   TargetRegisterClass::iterator I = RC->begin();
8051   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8052 
8053   // Do not check for single registers.
8054   if (AssignedReg) {
8055       for (; *I != AssignedReg; ++I)
8056         assert(I != RC->end() && "AssignedReg should be member of RC");
8057   }
8058 
8059   for (; NumRegs; --NumRegs, ++I) {
8060     assert(I != RC->end() && "Ran out of registers to allocate!");
8061     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
8062     Regs.push_back(R);
8063   }
8064 
8065   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
8066 }
8067 
8068 static unsigned
8069 findMatchingInlineAsmOperand(unsigned OperandNo,
8070                              const std::vector<SDValue> &AsmNodeOperands) {
8071   // Scan until we find the definition we already emitted of this operand.
8072   unsigned CurOp = InlineAsm::Op_FirstOperand;
8073   for (; OperandNo; --OperandNo) {
8074     // Advance to the next operand.
8075     unsigned OpFlag =
8076         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8077     assert((InlineAsm::isRegDefKind(OpFlag) ||
8078             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8079             InlineAsm::isMemKind(OpFlag)) &&
8080            "Skipped past definitions?");
8081     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8082   }
8083   return CurOp;
8084 }
8085 
8086 namespace {
8087 
8088 class ExtraFlags {
8089   unsigned Flags = 0;
8090 
8091 public:
8092   explicit ExtraFlags(ImmutableCallSite CS) {
8093     const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
8094     if (IA->hasSideEffects())
8095       Flags |= InlineAsm::Extra_HasSideEffects;
8096     if (IA->isAlignStack())
8097       Flags |= InlineAsm::Extra_IsAlignStack;
8098     if (CS.isConvergent())
8099       Flags |= InlineAsm::Extra_IsConvergent;
8100     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8101   }
8102 
8103   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8104     // Ideally, we would only check against memory constraints.  However, the
8105     // meaning of an Other constraint can be target-specific and we can't easily
8106     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8107     // for Other constraints as well.
8108     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8109         OpInfo.ConstraintType == TargetLowering::C_Other) {
8110       if (OpInfo.Type == InlineAsm::isInput)
8111         Flags |= InlineAsm::Extra_MayLoad;
8112       else if (OpInfo.Type == InlineAsm::isOutput)
8113         Flags |= InlineAsm::Extra_MayStore;
8114       else if (OpInfo.Type == InlineAsm::isClobber)
8115         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8116     }
8117   }
8118 
8119   unsigned get() const { return Flags; }
8120 };
8121 
8122 } // end anonymous namespace
8123 
8124 /// visitInlineAsm - Handle a call to an InlineAsm object.
8125 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
8126   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
8127 
8128   /// ConstraintOperands - Information about all of the constraints.
8129   SDISelAsmOperandInfoVector ConstraintOperands;
8130 
8131   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8132   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8133       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
8134 
8135   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8136   // AsmDialect, MayLoad, MayStore).
8137   bool HasSideEffect = IA->hasSideEffects();
8138   ExtraFlags ExtraInfo(CS);
8139 
8140   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
8141   unsigned ResNo = 0;   // ResNo - The result number of the next output.
8142   for (auto &T : TargetConstraints) {
8143     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8144     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8145 
8146     // Compute the value type for each operand.
8147     if (OpInfo.Type == InlineAsm::isInput ||
8148         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
8149       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
8150 
8151       // Process the call argument. BasicBlocks are labels, currently appearing
8152       // only in asm's.
8153       const Instruction *I = CS.getInstruction();
8154       if (isa<CallBrInst>(I) &&
8155           (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() -
8156                           cast<CallBrInst>(I)->getNumIndirectDests())) {
8157         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
8158         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
8159         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
8160       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
8161         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
8162       } else {
8163         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8164       }
8165 
8166       OpInfo.ConstraintVT =
8167           OpInfo
8168               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
8169               .getSimpleVT();
8170     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8171       // The return value of the call is this value.  As such, there is no
8172       // corresponding argument.
8173       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8174       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
8175         OpInfo.ConstraintVT = TLI.getSimpleValueType(
8176             DAG.getDataLayout(), STy->getElementType(ResNo));
8177       } else {
8178         assert(ResNo == 0 && "Asm only has one result!");
8179         OpInfo.ConstraintVT =
8180             TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
8181       }
8182       ++ResNo;
8183     } else {
8184       OpInfo.ConstraintVT = MVT::Other;
8185     }
8186 
8187     if (!HasSideEffect)
8188       HasSideEffect = OpInfo.hasMemory(TLI);
8189 
8190     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8191     // FIXME: Could we compute this on OpInfo rather than T?
8192 
8193     // Compute the constraint code and ConstraintType to use.
8194     TLI.ComputeConstraintToUse(T, SDValue());
8195 
8196     if (T.ConstraintType == TargetLowering::C_Immediate &&
8197         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8198       // We've delayed emitting a diagnostic like the "n" constraint because
8199       // inlining could cause an integer showing up.
8200       return emitInlineAsmError(
8201           CS, "constraint '" + Twine(T.ConstraintCode) + "' expects an "
8202                   "integer constant expression");
8203 
8204     ExtraInfo.update(T);
8205   }
8206 
8207 
8208   // We won't need to flush pending loads if this asm doesn't touch
8209   // memory and is nonvolatile.
8210   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8211 
8212   bool IsCallBr = isa<CallBrInst>(CS.getInstruction());
8213   if (IsCallBr) {
8214     // If this is a callbr we need to flush pending exports since inlineasm_br
8215     // is a terminator. We need to do this before nodes are glued to
8216     // the inlineasm_br node.
8217     Chain = getControlRoot();
8218   }
8219 
8220   // Second pass over the constraints: compute which constraint option to use.
8221   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8222     // If this is an output operand with a matching input operand, look up the
8223     // matching input. If their types mismatch, e.g. one is an integer, the
8224     // other is floating point, or their sizes are different, flag it as an
8225     // error.
8226     if (OpInfo.hasMatchingInput()) {
8227       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8228       patchMatchingInput(OpInfo, Input, DAG);
8229     }
8230 
8231     // Compute the constraint code and ConstraintType to use.
8232     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8233 
8234     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8235         OpInfo.Type == InlineAsm::isClobber)
8236       continue;
8237 
8238     // If this is a memory input, and if the operand is not indirect, do what we
8239     // need to provide an address for the memory input.
8240     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8241         !OpInfo.isIndirect) {
8242       assert((OpInfo.isMultipleAlternative ||
8243               (OpInfo.Type == InlineAsm::isInput)) &&
8244              "Can only indirectify direct input operands!");
8245 
8246       // Memory operands really want the address of the value.
8247       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8248 
8249       // There is no longer a Value* corresponding to this operand.
8250       OpInfo.CallOperandVal = nullptr;
8251 
8252       // It is now an indirect operand.
8253       OpInfo.isIndirect = true;
8254     }
8255 
8256   }
8257 
8258   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8259   std::vector<SDValue> AsmNodeOperands;
8260   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8261   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8262       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
8263 
8264   // If we have a !srcloc metadata node associated with it, we want to attach
8265   // this to the ultimately generated inline asm machineinstr.  To do this, we
8266   // pass in the third operand as this (potentially null) inline asm MDNode.
8267   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
8268   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8269 
8270   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8271   // bits as operand 3.
8272   AsmNodeOperands.push_back(DAG.getTargetConstant(
8273       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8274 
8275   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8276   // this, assign virtual and physical registers for inputs and otput.
8277   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8278     // Assign Registers.
8279     SDISelAsmOperandInfo &RefOpInfo =
8280         OpInfo.isMatchingInputConstraint()
8281             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8282             : OpInfo;
8283     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8284 
8285     switch (OpInfo.Type) {
8286     case InlineAsm::isOutput:
8287       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8288         unsigned ConstraintID =
8289             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8290         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8291                "Failed to convert memory constraint code to constraint id.");
8292 
8293         // Add information to the INLINEASM node to know about this output.
8294         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8295         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8296         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8297                                                         MVT::i32));
8298         AsmNodeOperands.push_back(OpInfo.CallOperand);
8299       } else {
8300         // Otherwise, this outputs to a register (directly for C_Register /
8301         // C_RegisterClass, and a target-defined fashion for
8302         // C_Immediate/C_Other). Find a register that we can use.
8303         if (OpInfo.AssignedRegs.Regs.empty()) {
8304           emitInlineAsmError(
8305               CS, "couldn't allocate output register for constraint '" +
8306                       Twine(OpInfo.ConstraintCode) + "'");
8307           return;
8308         }
8309 
8310         // Add information to the INLINEASM node to know that this register is
8311         // set.
8312         OpInfo.AssignedRegs.AddInlineAsmOperands(
8313             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8314                                   : InlineAsm::Kind_RegDef,
8315             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8316       }
8317       break;
8318 
8319     case InlineAsm::isInput: {
8320       SDValue InOperandVal = OpInfo.CallOperand;
8321 
8322       if (OpInfo.isMatchingInputConstraint()) {
8323         // If this is required to match an output register we have already set,
8324         // just use its register.
8325         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8326                                                   AsmNodeOperands);
8327         unsigned OpFlag =
8328           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8329         if (InlineAsm::isRegDefKind(OpFlag) ||
8330             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8331           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8332           if (OpInfo.isIndirect) {
8333             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8334             emitInlineAsmError(CS, "inline asm not supported yet:"
8335                                    " don't know how to handle tied "
8336                                    "indirect register inputs");
8337             return;
8338           }
8339 
8340           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
8341           SmallVector<unsigned, 4> Regs;
8342 
8343           if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
8344             unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8345             MachineRegisterInfo &RegInfo =
8346                 DAG.getMachineFunction().getRegInfo();
8347             for (unsigned i = 0; i != NumRegs; ++i)
8348               Regs.push_back(RegInfo.createVirtualRegister(RC));
8349           } else {
8350             emitInlineAsmError(CS, "inline asm error: This value type register "
8351                                    "class is not natively supported!");
8352             return;
8353           }
8354 
8355           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8356 
8357           SDLoc dl = getCurSDLoc();
8358           // Use the produced MatchedRegs object to
8359           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8360                                     CS.getInstruction());
8361           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8362                                            true, OpInfo.getMatchedOperand(), dl,
8363                                            DAG, AsmNodeOperands);
8364           break;
8365         }
8366 
8367         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8368         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8369                "Unexpected number of operands");
8370         // Add information to the INLINEASM node to know about this input.
8371         // See InlineAsm.h isUseOperandTiedToDef.
8372         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8373         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8374                                                     OpInfo.getMatchedOperand());
8375         AsmNodeOperands.push_back(DAG.getTargetConstant(
8376             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8377         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8378         break;
8379       }
8380 
8381       // Treat indirect 'X' constraint as memory.
8382       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
8383           OpInfo.isIndirect)
8384         OpInfo.ConstraintType = TargetLowering::C_Memory;
8385 
8386       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8387           OpInfo.ConstraintType == TargetLowering::C_Other) {
8388         std::vector<SDValue> Ops;
8389         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8390                                           Ops, DAG);
8391         if (Ops.empty()) {
8392           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8393             if (isa<ConstantSDNode>(InOperandVal)) {
8394               emitInlineAsmError(CS, "value out of range for constraint '" +
8395                                  Twine(OpInfo.ConstraintCode) + "'");
8396               return;
8397             }
8398 
8399           emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
8400                                      Twine(OpInfo.ConstraintCode) + "'");
8401           return;
8402         }
8403 
8404         // Add information to the INLINEASM node to know about this input.
8405         unsigned ResOpType =
8406           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8407         AsmNodeOperands.push_back(DAG.getTargetConstant(
8408             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8409         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
8410         break;
8411       }
8412 
8413       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8414         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8415         assert(InOperandVal.getValueType() ==
8416                    TLI.getPointerTy(DAG.getDataLayout()) &&
8417                "Memory operands expect pointer values");
8418 
8419         unsigned ConstraintID =
8420             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8421         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8422                "Failed to convert memory constraint code to constraint id.");
8423 
8424         // Add information to the INLINEASM node to know about this input.
8425         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8426         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8427         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8428                                                         getCurSDLoc(),
8429                                                         MVT::i32));
8430         AsmNodeOperands.push_back(InOperandVal);
8431         break;
8432       }
8433 
8434       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8435               OpInfo.ConstraintType == TargetLowering::C_Register) &&
8436              "Unknown constraint type!");
8437 
8438       // TODO: Support this.
8439       if (OpInfo.isIndirect) {
8440         emitInlineAsmError(
8441             CS, "Don't know how to handle indirect register inputs yet "
8442                 "for constraint '" +
8443                     Twine(OpInfo.ConstraintCode) + "'");
8444         return;
8445       }
8446 
8447       // Copy the input into the appropriate registers.
8448       if (OpInfo.AssignedRegs.Regs.empty()) {
8449         emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
8450                                    Twine(OpInfo.ConstraintCode) + "'");
8451         return;
8452       }
8453 
8454       SDLoc dl = getCurSDLoc();
8455 
8456       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
8457                                         Chain, &Flag, CS.getInstruction());
8458 
8459       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8460                                                dl, DAG, AsmNodeOperands);
8461       break;
8462     }
8463     case InlineAsm::isClobber:
8464       // Add the clobbered value to the operand list, so that the register
8465       // allocator is aware that the physreg got clobbered.
8466       if (!OpInfo.AssignedRegs.Regs.empty())
8467         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8468                                                  false, 0, getCurSDLoc(), DAG,
8469                                                  AsmNodeOperands);
8470       break;
8471     }
8472   }
8473 
8474   // Finish up input operands.  Set the input chain and add the flag last.
8475   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8476   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8477 
8478   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8479   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8480                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8481   Flag = Chain.getValue(1);
8482 
8483   // Do additional work to generate outputs.
8484 
8485   SmallVector<EVT, 1> ResultVTs;
8486   SmallVector<SDValue, 1> ResultValues;
8487   SmallVector<SDValue, 8> OutChains;
8488 
8489   llvm::Type *CSResultType = CS.getType();
8490   ArrayRef<Type *> ResultTypes;
8491   if (StructType *StructResult = dyn_cast<StructType>(CSResultType))
8492     ResultTypes = StructResult->elements();
8493   else if (!CSResultType->isVoidTy())
8494     ResultTypes = makeArrayRef(CSResultType);
8495 
8496   auto CurResultType = ResultTypes.begin();
8497   auto handleRegAssign = [&](SDValue V) {
8498     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8499     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8500     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8501     ++CurResultType;
8502     // If the type of the inline asm call site return value is different but has
8503     // same size as the type of the asm output bitcast it.  One example of this
8504     // is for vectors with different width / number of elements.  This can
8505     // happen for register classes that can contain multiple different value
8506     // types.  The preg or vreg allocated may not have the same VT as was
8507     // expected.
8508     //
8509     // This can also happen for a return value that disagrees with the register
8510     // class it is put in, eg. a double in a general-purpose register on a
8511     // 32-bit machine.
8512     if (ResultVT != V.getValueType() &&
8513         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8514       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8515     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8516              V.getValueType().isInteger()) {
8517       // If a result value was tied to an input value, the computed result
8518       // may have a wider width than the expected result.  Extract the
8519       // relevant portion.
8520       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8521     }
8522     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8523     ResultVTs.push_back(ResultVT);
8524     ResultValues.push_back(V);
8525   };
8526 
8527   // Deal with output operands.
8528   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8529     if (OpInfo.Type == InlineAsm::isOutput) {
8530       SDValue Val;
8531       // Skip trivial output operands.
8532       if (OpInfo.AssignedRegs.Regs.empty())
8533         continue;
8534 
8535       switch (OpInfo.ConstraintType) {
8536       case TargetLowering::C_Register:
8537       case TargetLowering::C_RegisterClass:
8538         Val = OpInfo.AssignedRegs.getCopyFromRegs(
8539             DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction());
8540         break;
8541       case TargetLowering::C_Immediate:
8542       case TargetLowering::C_Other:
8543         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
8544                                               OpInfo, DAG);
8545         break;
8546       case TargetLowering::C_Memory:
8547         break; // Already handled.
8548       case TargetLowering::C_Unknown:
8549         assert(false && "Unexpected unknown constraint");
8550       }
8551 
8552       // Indirect output manifest as stores. Record output chains.
8553       if (OpInfo.isIndirect) {
8554         const Value *Ptr = OpInfo.CallOperandVal;
8555         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8556         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8557                                      MachinePointerInfo(Ptr));
8558         OutChains.push_back(Store);
8559       } else {
8560         // generate CopyFromRegs to associated registers.
8561         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8562         if (Val.getOpcode() == ISD::MERGE_VALUES) {
8563           for (const SDValue &V : Val->op_values())
8564             handleRegAssign(V);
8565         } else
8566           handleRegAssign(Val);
8567       }
8568     }
8569   }
8570 
8571   // Set results.
8572   if (!ResultValues.empty()) {
8573     assert(CurResultType == ResultTypes.end() &&
8574            "Mismatch in number of ResultTypes");
8575     assert(ResultValues.size() == ResultTypes.size() &&
8576            "Mismatch in number of output operands in asm result");
8577 
8578     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8579                             DAG.getVTList(ResultVTs), ResultValues);
8580     setValue(CS.getInstruction(), V);
8581   }
8582 
8583   // Collect store chains.
8584   if (!OutChains.empty())
8585     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8586 
8587   // Only Update Root if inline assembly has a memory effect.
8588   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
8589     DAG.setRoot(Chain);
8590 }
8591 
8592 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
8593                                              const Twine &Message) {
8594   LLVMContext &Ctx = *DAG.getContext();
8595   Ctx.emitError(CS.getInstruction(), Message);
8596 
8597   // Make sure we leave the DAG in a valid state
8598   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8599   SmallVector<EVT, 1> ValueVTs;
8600   ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8601 
8602   if (ValueVTs.empty())
8603     return;
8604 
8605   SmallVector<SDValue, 1> Ops;
8606   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8607     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8608 
8609   setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
8610 }
8611 
8612 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8613   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8614                           MVT::Other, getRoot(),
8615                           getValue(I.getArgOperand(0)),
8616                           DAG.getSrcValue(I.getArgOperand(0))));
8617 }
8618 
8619 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8620   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8621   const DataLayout &DL = DAG.getDataLayout();
8622   SDValue V = DAG.getVAArg(
8623       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
8624       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
8625       DL.getABITypeAlignment(I.getType()));
8626   DAG.setRoot(V.getValue(1));
8627 
8628   if (I.getType()->isPointerTy())
8629     V = DAG.getPtrExtOrTrunc(
8630         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
8631   setValue(&I, V);
8632 }
8633 
8634 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8635   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8636                           MVT::Other, getRoot(),
8637                           getValue(I.getArgOperand(0)),
8638                           DAG.getSrcValue(I.getArgOperand(0))));
8639 }
8640 
8641 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8642   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8643                           MVT::Other, getRoot(),
8644                           getValue(I.getArgOperand(0)),
8645                           getValue(I.getArgOperand(1)),
8646                           DAG.getSrcValue(I.getArgOperand(0)),
8647                           DAG.getSrcValue(I.getArgOperand(1))));
8648 }
8649 
8650 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8651                                                     const Instruction &I,
8652                                                     SDValue Op) {
8653   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8654   if (!Range)
8655     return Op;
8656 
8657   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8658   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
8659     return Op;
8660 
8661   APInt Lo = CR.getUnsignedMin();
8662   if (!Lo.isMinValue())
8663     return Op;
8664 
8665   APInt Hi = CR.getUnsignedMax();
8666   unsigned Bits = std::max(Hi.getActiveBits(),
8667                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8668 
8669   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8670 
8671   SDLoc SL = getCurSDLoc();
8672 
8673   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8674                              DAG.getValueType(SmallVT));
8675   unsigned NumVals = Op.getNode()->getNumValues();
8676   if (NumVals == 1)
8677     return ZExt;
8678 
8679   SmallVector<SDValue, 4> Ops;
8680 
8681   Ops.push_back(ZExt);
8682   for (unsigned I = 1; I != NumVals; ++I)
8683     Ops.push_back(Op.getValue(I));
8684 
8685   return DAG.getMergeValues(Ops, SL);
8686 }
8687 
8688 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8689 /// the call being lowered.
8690 ///
8691 /// This is a helper for lowering intrinsics that follow a target calling
8692 /// convention or require stack pointer adjustment. Only a subset of the
8693 /// intrinsic's operands need to participate in the calling convention.
8694 void SelectionDAGBuilder::populateCallLoweringInfo(
8695     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
8696     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8697     bool IsPatchPoint) {
8698   TargetLowering::ArgListTy Args;
8699   Args.reserve(NumArgs);
8700 
8701   // Populate the argument list.
8702   // Attributes for args start at offset 1, after the return attribute.
8703   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8704        ArgI != ArgE; ++ArgI) {
8705     const Value *V = Call->getOperand(ArgI);
8706 
8707     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8708 
8709     TargetLowering::ArgListEntry Entry;
8710     Entry.Node = getValue(V);
8711     Entry.Ty = V->getType();
8712     Entry.setAttributes(Call, ArgI);
8713     Args.push_back(Entry);
8714   }
8715 
8716   CLI.setDebugLoc(getCurSDLoc())
8717       .setChain(getRoot())
8718       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
8719       .setDiscardResult(Call->use_empty())
8720       .setIsPatchPoint(IsPatchPoint);
8721 }
8722 
8723 /// Add a stack map intrinsic call's live variable operands to a stackmap
8724 /// or patchpoint target node's operand list.
8725 ///
8726 /// Constants are converted to TargetConstants purely as an optimization to
8727 /// avoid constant materialization and register allocation.
8728 ///
8729 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8730 /// generate addess computation nodes, and so FinalizeISel can convert the
8731 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8732 /// address materialization and register allocation, but may also be required
8733 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8734 /// alloca in the entry block, then the runtime may assume that the alloca's
8735 /// StackMap location can be read immediately after compilation and that the
8736 /// location is valid at any point during execution (this is similar to the
8737 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8738 /// only available in a register, then the runtime would need to trap when
8739 /// execution reaches the StackMap in order to read the alloca's location.
8740 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
8741                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8742                                 SelectionDAGBuilder &Builder) {
8743   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
8744     SDValue OpVal = Builder.getValue(CS.getArgument(i));
8745     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8746       Ops.push_back(
8747         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8748       Ops.push_back(
8749         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8750     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8751       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8752       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8753           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8754     } else
8755       Ops.push_back(OpVal);
8756   }
8757 }
8758 
8759 /// Lower llvm.experimental.stackmap directly to its target opcode.
8760 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8761   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8762   //                                  [live variables...])
8763 
8764   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8765 
8766   SDValue Chain, InFlag, Callee, NullPtr;
8767   SmallVector<SDValue, 32> Ops;
8768 
8769   SDLoc DL = getCurSDLoc();
8770   Callee = getValue(CI.getCalledValue());
8771   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8772 
8773   // The stackmap intrinsic only records the live variables (the arguments
8774   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8775   // intrinsic, this won't be lowered to a function call. This means we don't
8776   // have to worry about calling conventions and target specific lowering code.
8777   // Instead we perform the call lowering right here.
8778   //
8779   // chain, flag = CALLSEQ_START(chain, 0, 0)
8780   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8781   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8782   //
8783   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8784   InFlag = Chain.getValue(1);
8785 
8786   // Add the <id> and <numBytes> constants.
8787   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8788   Ops.push_back(DAG.getTargetConstant(
8789                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8790   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8791   Ops.push_back(DAG.getTargetConstant(
8792                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8793                   MVT::i32));
8794 
8795   // Push live variables for the stack map.
8796   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
8797 
8798   // We are not pushing any register mask info here on the operands list,
8799   // because the stackmap doesn't clobber anything.
8800 
8801   // Push the chain and the glue flag.
8802   Ops.push_back(Chain);
8803   Ops.push_back(InFlag);
8804 
8805   // Create the STACKMAP node.
8806   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8807   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8808   Chain = SDValue(SM, 0);
8809   InFlag = Chain.getValue(1);
8810 
8811   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8812 
8813   // Stackmaps don't generate values, so nothing goes into the NodeMap.
8814 
8815   // Set the root to the target-lowered call chain.
8816   DAG.setRoot(Chain);
8817 
8818   // Inform the Frame Information that we have a stackmap in this function.
8819   FuncInfo.MF->getFrameInfo().setHasStackMap();
8820 }
8821 
8822 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8823 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
8824                                           const BasicBlock *EHPadBB) {
8825   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8826   //                                                 i32 <numBytes>,
8827   //                                                 i8* <target>,
8828   //                                                 i32 <numArgs>,
8829   //                                                 [Args...],
8830   //                                                 [live variables...])
8831 
8832   CallingConv::ID CC = CS.getCallingConv();
8833   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8834   bool HasDef = !CS->getType()->isVoidTy();
8835   SDLoc dl = getCurSDLoc();
8836   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
8837 
8838   // Handle immediate and symbolic callees.
8839   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8840     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8841                                    /*isTarget=*/true);
8842   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8843     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8844                                          SDLoc(SymbolicCallee),
8845                                          SymbolicCallee->getValueType(0));
8846 
8847   // Get the real number of arguments participating in the call <numArgs>
8848   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
8849   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8850 
8851   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8852   // Intrinsics include all meta-operands up to but not including CC.
8853   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8854   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
8855          "Not enough arguments provided to the patchpoint intrinsic");
8856 
8857   // For AnyRegCC the arguments are lowered later on manually.
8858   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8859   Type *ReturnTy =
8860     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
8861 
8862   TargetLowering::CallLoweringInfo CLI(DAG);
8863   populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()),
8864                            NumMetaOpers, NumCallArgs, Callee, ReturnTy, true);
8865   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8866 
8867   SDNode *CallEnd = Result.second.getNode();
8868   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8869     CallEnd = CallEnd->getOperand(0).getNode();
8870 
8871   /// Get a call instruction from the call sequence chain.
8872   /// Tail calls are not allowed.
8873   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8874          "Expected a callseq node.");
8875   SDNode *Call = CallEnd->getOperand(0).getNode();
8876   bool HasGlue = Call->getGluedNode();
8877 
8878   // Replace the target specific call node with the patchable intrinsic.
8879   SmallVector<SDValue, 8> Ops;
8880 
8881   // Add the <id> and <numBytes> constants.
8882   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
8883   Ops.push_back(DAG.getTargetConstant(
8884                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8885   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
8886   Ops.push_back(DAG.getTargetConstant(
8887                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8888                   MVT::i32));
8889 
8890   // Add the callee.
8891   Ops.push_back(Callee);
8892 
8893   // Adjust <numArgs> to account for any arguments that have been passed on the
8894   // stack instead.
8895   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8896   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8897   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8898   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8899 
8900   // Add the calling convention
8901   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8902 
8903   // Add the arguments we omitted previously. The register allocator should
8904   // place these in any free register.
8905   if (IsAnyRegCC)
8906     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8907       Ops.push_back(getValue(CS.getArgument(i)));
8908 
8909   // Push the arguments from the call instruction up to the register mask.
8910   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8911   Ops.append(Call->op_begin() + 2, e);
8912 
8913   // Push live variables for the stack map.
8914   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
8915 
8916   // Push the register mask info.
8917   if (HasGlue)
8918     Ops.push_back(*(Call->op_end()-2));
8919   else
8920     Ops.push_back(*(Call->op_end()-1));
8921 
8922   // Push the chain (this is originally the first operand of the call, but
8923   // becomes now the last or second to last operand).
8924   Ops.push_back(*(Call->op_begin()));
8925 
8926   // Push the glue flag (last operand).
8927   if (HasGlue)
8928     Ops.push_back(*(Call->op_end()-1));
8929 
8930   SDVTList NodeTys;
8931   if (IsAnyRegCC && HasDef) {
8932     // Create the return types based on the intrinsic definition
8933     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8934     SmallVector<EVT, 3> ValueVTs;
8935     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8936     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8937 
8938     // There is always a chain and a glue type at the end
8939     ValueVTs.push_back(MVT::Other);
8940     ValueVTs.push_back(MVT::Glue);
8941     NodeTys = DAG.getVTList(ValueVTs);
8942   } else
8943     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8944 
8945   // Replace the target specific call node with a PATCHPOINT node.
8946   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8947                                          dl, NodeTys, Ops);
8948 
8949   // Update the NodeMap.
8950   if (HasDef) {
8951     if (IsAnyRegCC)
8952       setValue(CS.getInstruction(), SDValue(MN, 0));
8953     else
8954       setValue(CS.getInstruction(), Result.first);
8955   }
8956 
8957   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8958   // call sequence. Furthermore the location of the chain and glue can change
8959   // when the AnyReg calling convention is used and the intrinsic returns a
8960   // value.
8961   if (IsAnyRegCC && HasDef) {
8962     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8963     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8964     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8965   } else
8966     DAG.ReplaceAllUsesWith(Call, MN);
8967   DAG.DeleteNode(Call);
8968 
8969   // Inform the Frame Information that we have a patchpoint in this function.
8970   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8971 }
8972 
8973 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8974                                             unsigned Intrinsic) {
8975   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8976   SDValue Op1 = getValue(I.getArgOperand(0));
8977   SDValue Op2;
8978   if (I.getNumArgOperands() > 1)
8979     Op2 = getValue(I.getArgOperand(1));
8980   SDLoc dl = getCurSDLoc();
8981   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8982   SDValue Res;
8983   FastMathFlags FMF;
8984   if (isa<FPMathOperator>(I))
8985     FMF = I.getFastMathFlags();
8986 
8987   switch (Intrinsic) {
8988   case Intrinsic::experimental_vector_reduce_v2_fadd:
8989     if (FMF.allowReassoc())
8990       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
8991                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2));
8992     else
8993       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
8994     break;
8995   case Intrinsic::experimental_vector_reduce_v2_fmul:
8996     if (FMF.allowReassoc())
8997       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
8998                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2));
8999     else
9000       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
9001     break;
9002   case Intrinsic::experimental_vector_reduce_add:
9003     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
9004     break;
9005   case Intrinsic::experimental_vector_reduce_mul:
9006     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
9007     break;
9008   case Intrinsic::experimental_vector_reduce_and:
9009     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
9010     break;
9011   case Intrinsic::experimental_vector_reduce_or:
9012     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
9013     break;
9014   case Intrinsic::experimental_vector_reduce_xor:
9015     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
9016     break;
9017   case Intrinsic::experimental_vector_reduce_smax:
9018     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
9019     break;
9020   case Intrinsic::experimental_vector_reduce_smin:
9021     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
9022     break;
9023   case Intrinsic::experimental_vector_reduce_umax:
9024     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
9025     break;
9026   case Intrinsic::experimental_vector_reduce_umin:
9027     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
9028     break;
9029   case Intrinsic::experimental_vector_reduce_fmax:
9030     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
9031     break;
9032   case Intrinsic::experimental_vector_reduce_fmin:
9033     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
9034     break;
9035   default:
9036     llvm_unreachable("Unhandled vector reduce intrinsic");
9037   }
9038   setValue(&I, Res);
9039 }
9040 
9041 /// Returns an AttributeList representing the attributes applied to the return
9042 /// value of the given call.
9043 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
9044   SmallVector<Attribute::AttrKind, 2> Attrs;
9045   if (CLI.RetSExt)
9046     Attrs.push_back(Attribute::SExt);
9047   if (CLI.RetZExt)
9048     Attrs.push_back(Attribute::ZExt);
9049   if (CLI.IsInReg)
9050     Attrs.push_back(Attribute::InReg);
9051 
9052   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
9053                             Attrs);
9054 }
9055 
9056 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
9057 /// implementation, which just calls LowerCall.
9058 /// FIXME: When all targets are
9059 /// migrated to using LowerCall, this hook should be integrated into SDISel.
9060 std::pair<SDValue, SDValue>
9061 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
9062   // Handle the incoming return values from the call.
9063   CLI.Ins.clear();
9064   Type *OrigRetTy = CLI.RetTy;
9065   SmallVector<EVT, 4> RetTys;
9066   SmallVector<uint64_t, 4> Offsets;
9067   auto &DL = CLI.DAG.getDataLayout();
9068   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9069 
9070   if (CLI.IsPostTypeLegalization) {
9071     // If we are lowering a libcall after legalization, split the return type.
9072     SmallVector<EVT, 4> OldRetTys;
9073     SmallVector<uint64_t, 4> OldOffsets;
9074     RetTys.swap(OldRetTys);
9075     Offsets.swap(OldOffsets);
9076 
9077     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9078       EVT RetVT = OldRetTys[i];
9079       uint64_t Offset = OldOffsets[i];
9080       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9081       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9082       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9083       RetTys.append(NumRegs, RegisterVT);
9084       for (unsigned j = 0; j != NumRegs; ++j)
9085         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9086     }
9087   }
9088 
9089   SmallVector<ISD::OutputArg, 4> Outs;
9090   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9091 
9092   bool CanLowerReturn =
9093       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9094                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9095 
9096   SDValue DemoteStackSlot;
9097   int DemoteStackIdx = -100;
9098   if (!CanLowerReturn) {
9099     // FIXME: equivalent assert?
9100     // assert(!CS.hasInAllocaArgument() &&
9101     //        "sret demotion is incompatible with inalloca");
9102     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9103     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
9104     MachineFunction &MF = CLI.DAG.getMachineFunction();
9105     DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
9106     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9107                                               DL.getAllocaAddrSpace());
9108 
9109     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9110     ArgListEntry Entry;
9111     Entry.Node = DemoteStackSlot;
9112     Entry.Ty = StackSlotPtrType;
9113     Entry.IsSExt = false;
9114     Entry.IsZExt = false;
9115     Entry.IsInReg = false;
9116     Entry.IsSRet = true;
9117     Entry.IsNest = false;
9118     Entry.IsByVal = false;
9119     Entry.IsReturned = false;
9120     Entry.IsSwiftSelf = false;
9121     Entry.IsSwiftError = false;
9122     Entry.IsCFGuardTarget = false;
9123     Entry.Alignment = Align;
9124     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9125     CLI.NumFixedArgs += 1;
9126     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9127 
9128     // sret demotion isn't compatible with tail-calls, since the sret argument
9129     // points into the callers stack frame.
9130     CLI.IsTailCall = false;
9131   } else {
9132     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9133         CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
9134     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9135       ISD::ArgFlagsTy Flags;
9136       if (NeedsRegBlock) {
9137         Flags.setInConsecutiveRegs();
9138         if (I == RetTys.size() - 1)
9139           Flags.setInConsecutiveRegsLast();
9140       }
9141       EVT VT = RetTys[I];
9142       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9143                                                      CLI.CallConv, VT);
9144       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9145                                                        CLI.CallConv, VT);
9146       for (unsigned i = 0; i != NumRegs; ++i) {
9147         ISD::InputArg MyFlags;
9148         MyFlags.Flags = Flags;
9149         MyFlags.VT = RegisterVT;
9150         MyFlags.ArgVT = VT;
9151         MyFlags.Used = CLI.IsReturnValueUsed;
9152         if (CLI.RetTy->isPointerTy()) {
9153           MyFlags.Flags.setPointer();
9154           MyFlags.Flags.setPointerAddrSpace(
9155               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9156         }
9157         if (CLI.RetSExt)
9158           MyFlags.Flags.setSExt();
9159         if (CLI.RetZExt)
9160           MyFlags.Flags.setZExt();
9161         if (CLI.IsInReg)
9162           MyFlags.Flags.setInReg();
9163         CLI.Ins.push_back(MyFlags);
9164       }
9165     }
9166   }
9167 
9168   // We push in swifterror return as the last element of CLI.Ins.
9169   ArgListTy &Args = CLI.getArgs();
9170   if (supportSwiftError()) {
9171     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9172       if (Args[i].IsSwiftError) {
9173         ISD::InputArg MyFlags;
9174         MyFlags.VT = getPointerTy(DL);
9175         MyFlags.ArgVT = EVT(getPointerTy(DL));
9176         MyFlags.Flags.setSwiftError();
9177         CLI.Ins.push_back(MyFlags);
9178       }
9179     }
9180   }
9181 
9182   // Handle all of the outgoing arguments.
9183   CLI.Outs.clear();
9184   CLI.OutVals.clear();
9185   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9186     SmallVector<EVT, 4> ValueVTs;
9187     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9188     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9189     Type *FinalType = Args[i].Ty;
9190     if (Args[i].IsByVal)
9191       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
9192     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9193         FinalType, CLI.CallConv, CLI.IsVarArg);
9194     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9195          ++Value) {
9196       EVT VT = ValueVTs[Value];
9197       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9198       SDValue Op = SDValue(Args[i].Node.getNode(),
9199                            Args[i].Node.getResNo() + Value);
9200       ISD::ArgFlagsTy Flags;
9201 
9202       // Certain targets (such as MIPS), may have a different ABI alignment
9203       // for a type depending on the context. Give the target a chance to
9204       // specify the alignment it wants.
9205       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9206 
9207       if (Args[i].Ty->isPointerTy()) {
9208         Flags.setPointer();
9209         Flags.setPointerAddrSpace(
9210             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9211       }
9212       if (Args[i].IsZExt)
9213         Flags.setZExt();
9214       if (Args[i].IsSExt)
9215         Flags.setSExt();
9216       if (Args[i].IsInReg) {
9217         // If we are using vectorcall calling convention, a structure that is
9218         // passed InReg - is surely an HVA
9219         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9220             isa<StructType>(FinalType)) {
9221           // The first value of a structure is marked
9222           if (0 == Value)
9223             Flags.setHvaStart();
9224           Flags.setHva();
9225         }
9226         // Set InReg Flag
9227         Flags.setInReg();
9228       }
9229       if (Args[i].IsSRet)
9230         Flags.setSRet();
9231       if (Args[i].IsSwiftSelf)
9232         Flags.setSwiftSelf();
9233       if (Args[i].IsSwiftError)
9234         Flags.setSwiftError();
9235       if (Args[i].IsCFGuardTarget)
9236         Flags.setCFGuardTarget();
9237       if (Args[i].IsByVal)
9238         Flags.setByVal();
9239       if (Args[i].IsInAlloca) {
9240         Flags.setInAlloca();
9241         // Set the byval flag for CCAssignFn callbacks that don't know about
9242         // inalloca.  This way we can know how many bytes we should've allocated
9243         // and how many bytes a callee cleanup function will pop.  If we port
9244         // inalloca to more targets, we'll have to add custom inalloca handling
9245         // in the various CC lowering callbacks.
9246         Flags.setByVal();
9247       }
9248       if (Args[i].IsByVal || Args[i].IsInAlloca) {
9249         PointerType *Ty = cast<PointerType>(Args[i].Ty);
9250         Type *ElementTy = Ty->getElementType();
9251 
9252         unsigned FrameSize = DL.getTypeAllocSize(
9253             Args[i].ByValType ? Args[i].ByValType : ElementTy);
9254         Flags.setByValSize(FrameSize);
9255 
9256         // info is not there but there are cases it cannot get right.
9257         unsigned FrameAlign;
9258         if (Args[i].Alignment)
9259           FrameAlign = Args[i].Alignment;
9260         else
9261           FrameAlign = getByValTypeAlignment(ElementTy, DL);
9262         Flags.setByValAlign(Align(FrameAlign));
9263       }
9264       if (Args[i].IsNest)
9265         Flags.setNest();
9266       if (NeedsRegBlock)
9267         Flags.setInConsecutiveRegs();
9268       Flags.setOrigAlign(OriginalAlignment);
9269 
9270       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9271                                                  CLI.CallConv, VT);
9272       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9273                                                         CLI.CallConv, VT);
9274       SmallVector<SDValue, 4> Parts(NumParts);
9275       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9276 
9277       if (Args[i].IsSExt)
9278         ExtendKind = ISD::SIGN_EXTEND;
9279       else if (Args[i].IsZExt)
9280         ExtendKind = ISD::ZERO_EXTEND;
9281 
9282       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9283       // for now.
9284       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9285           CanLowerReturn) {
9286         assert((CLI.RetTy == Args[i].Ty ||
9287                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9288                  CLI.RetTy->getPointerAddressSpace() ==
9289                      Args[i].Ty->getPointerAddressSpace())) &&
9290                RetTys.size() == NumValues && "unexpected use of 'returned'");
9291         // Before passing 'returned' to the target lowering code, ensure that
9292         // either the register MVT and the actual EVT are the same size or that
9293         // the return value and argument are extended in the same way; in these
9294         // cases it's safe to pass the argument register value unchanged as the
9295         // return register value (although it's at the target's option whether
9296         // to do so)
9297         // TODO: allow code generation to take advantage of partially preserved
9298         // registers rather than clobbering the entire register when the
9299         // parameter extension method is not compatible with the return
9300         // extension method
9301         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9302             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9303              CLI.RetZExt == Args[i].IsZExt))
9304           Flags.setReturned();
9305       }
9306 
9307       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
9308                      CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
9309 
9310       for (unsigned j = 0; j != NumParts; ++j) {
9311         // if it isn't first piece, alignment must be 1
9312         // For scalable vectors the scalable part is currently handled
9313         // by individual targets, so we just use the known minimum size here.
9314         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
9315                     i < CLI.NumFixedArgs, i,
9316                     j*Parts[j].getValueType().getStoreSize().getKnownMinSize());
9317         if (NumParts > 1 && j == 0)
9318           MyFlags.Flags.setSplit();
9319         else if (j != 0) {
9320           MyFlags.Flags.setOrigAlign(Align::None());
9321           if (j == NumParts - 1)
9322             MyFlags.Flags.setSplitEnd();
9323         }
9324 
9325         CLI.Outs.push_back(MyFlags);
9326         CLI.OutVals.push_back(Parts[j]);
9327       }
9328 
9329       if (NeedsRegBlock && Value == NumValues - 1)
9330         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9331     }
9332   }
9333 
9334   SmallVector<SDValue, 4> InVals;
9335   CLI.Chain = LowerCall(CLI, InVals);
9336 
9337   // Update CLI.InVals to use outside of this function.
9338   CLI.InVals = InVals;
9339 
9340   // Verify that the target's LowerCall behaved as expected.
9341   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9342          "LowerCall didn't return a valid chain!");
9343   assert((!CLI.IsTailCall || InVals.empty()) &&
9344          "LowerCall emitted a return value for a tail call!");
9345   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9346          "LowerCall didn't emit the correct number of values!");
9347 
9348   // For a tail call, the return value is merely live-out and there aren't
9349   // any nodes in the DAG representing it. Return a special value to
9350   // indicate that a tail call has been emitted and no more Instructions
9351   // should be processed in the current block.
9352   if (CLI.IsTailCall) {
9353     CLI.DAG.setRoot(CLI.Chain);
9354     return std::make_pair(SDValue(), SDValue());
9355   }
9356 
9357 #ifndef NDEBUG
9358   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9359     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9360     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9361            "LowerCall emitted a value with the wrong type!");
9362   }
9363 #endif
9364 
9365   SmallVector<SDValue, 4> ReturnValues;
9366   if (!CanLowerReturn) {
9367     // The instruction result is the result of loading from the
9368     // hidden sret parameter.
9369     SmallVector<EVT, 1> PVTs;
9370     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9371 
9372     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9373     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9374     EVT PtrVT = PVTs[0];
9375 
9376     unsigned NumValues = RetTys.size();
9377     ReturnValues.resize(NumValues);
9378     SmallVector<SDValue, 4> Chains(NumValues);
9379 
9380     // An aggregate return value cannot wrap around the address space, so
9381     // offsets to its parts don't wrap either.
9382     SDNodeFlags Flags;
9383     Flags.setNoUnsignedWrap(true);
9384 
9385     for (unsigned i = 0; i < NumValues; ++i) {
9386       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9387                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9388                                                         PtrVT), Flags);
9389       SDValue L = CLI.DAG.getLoad(
9390           RetTys[i], CLI.DL, CLI.Chain, Add,
9391           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9392                                             DemoteStackIdx, Offsets[i]),
9393           /* Alignment = */ 1);
9394       ReturnValues[i] = L;
9395       Chains[i] = L.getValue(1);
9396     }
9397 
9398     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9399   } else {
9400     // Collect the legal value parts into potentially illegal values
9401     // that correspond to the original function's return values.
9402     Optional<ISD::NodeType> AssertOp;
9403     if (CLI.RetSExt)
9404       AssertOp = ISD::AssertSext;
9405     else if (CLI.RetZExt)
9406       AssertOp = ISD::AssertZext;
9407     unsigned CurReg = 0;
9408     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9409       EVT VT = RetTys[I];
9410       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9411                                                      CLI.CallConv, VT);
9412       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9413                                                        CLI.CallConv, VT);
9414 
9415       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9416                                               NumRegs, RegisterVT, VT, nullptr,
9417                                               CLI.CallConv, AssertOp));
9418       CurReg += NumRegs;
9419     }
9420 
9421     // For a function returning void, there is no return value. We can't create
9422     // such a node, so we just return a null return value in that case. In
9423     // that case, nothing will actually look at the value.
9424     if (ReturnValues.empty())
9425       return std::make_pair(SDValue(), CLI.Chain);
9426   }
9427 
9428   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9429                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9430   return std::make_pair(Res, CLI.Chain);
9431 }
9432 
9433 void TargetLowering::LowerOperationWrapper(SDNode *N,
9434                                            SmallVectorImpl<SDValue> &Results,
9435                                            SelectionDAG &DAG) const {
9436   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
9437     Results.push_back(Res);
9438 }
9439 
9440 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9441   llvm_unreachable("LowerOperation not implemented for this target!");
9442 }
9443 
9444 void
9445 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9446   SDValue Op = getNonRegisterValue(V);
9447   assert((Op.getOpcode() != ISD::CopyFromReg ||
9448           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9449          "Copy from a reg to the same reg!");
9450   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
9451 
9452   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9453   // If this is an InlineAsm we have to match the registers required, not the
9454   // notional registers required by the type.
9455 
9456   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9457                    None); // This is not an ABI copy.
9458   SDValue Chain = DAG.getEntryNode();
9459 
9460   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
9461                               FuncInfo.PreferredExtendType.end())
9462                                  ? ISD::ANY_EXTEND
9463                                  : FuncInfo.PreferredExtendType[V];
9464   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9465   PendingExports.push_back(Chain);
9466 }
9467 
9468 #include "llvm/CodeGen/SelectionDAGISel.h"
9469 
9470 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9471 /// entry block, return true.  This includes arguments used by switches, since
9472 /// the switch may expand into multiple basic blocks.
9473 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9474   // With FastISel active, we may be splitting blocks, so force creation
9475   // of virtual registers for all non-dead arguments.
9476   if (FastISel)
9477     return A->use_empty();
9478 
9479   const BasicBlock &Entry = A->getParent()->front();
9480   for (const User *U : A->users())
9481     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9482       return false;  // Use not in entry block.
9483 
9484   return true;
9485 }
9486 
9487 using ArgCopyElisionMapTy =
9488     DenseMap<const Argument *,
9489              std::pair<const AllocaInst *, const StoreInst *>>;
9490 
9491 /// Scan the entry block of the function in FuncInfo for arguments that look
9492 /// like copies into a local alloca. Record any copied arguments in
9493 /// ArgCopyElisionCandidates.
9494 static void
9495 findArgumentCopyElisionCandidates(const DataLayout &DL,
9496                                   FunctionLoweringInfo *FuncInfo,
9497                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
9498   // Record the state of every static alloca used in the entry block. Argument
9499   // allocas are all used in the entry block, so we need approximately as many
9500   // entries as we have arguments.
9501   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
9502   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
9503   unsigned NumArgs = FuncInfo->Fn->arg_size();
9504   StaticAllocas.reserve(NumArgs * 2);
9505 
9506   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
9507     if (!V)
9508       return nullptr;
9509     V = V->stripPointerCasts();
9510     const auto *AI = dyn_cast<AllocaInst>(V);
9511     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
9512       return nullptr;
9513     auto Iter = StaticAllocas.insert({AI, Unknown});
9514     return &Iter.first->second;
9515   };
9516 
9517   // Look for stores of arguments to static allocas. Look through bitcasts and
9518   // GEPs to handle type coercions, as long as the alloca is fully initialized
9519   // by the store. Any non-store use of an alloca escapes it and any subsequent
9520   // unanalyzed store might write it.
9521   // FIXME: Handle structs initialized with multiple stores.
9522   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9523     // Look for stores, and handle non-store uses conservatively.
9524     const auto *SI = dyn_cast<StoreInst>(&I);
9525     if (!SI) {
9526       // We will look through cast uses, so ignore them completely.
9527       if (I.isCast())
9528         continue;
9529       // Ignore debug info intrinsics, they don't escape or store to allocas.
9530       if (isa<DbgInfoIntrinsic>(I))
9531         continue;
9532       // This is an unknown instruction. Assume it escapes or writes to all
9533       // static alloca operands.
9534       for (const Use &U : I.operands()) {
9535         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9536           *Info = StaticAllocaInfo::Clobbered;
9537       }
9538       continue;
9539     }
9540 
9541     // If the stored value is a static alloca, mark it as escaped.
9542     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9543       *Info = StaticAllocaInfo::Clobbered;
9544 
9545     // Check if the destination is a static alloca.
9546     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9547     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9548     if (!Info)
9549       continue;
9550     const AllocaInst *AI = cast<AllocaInst>(Dst);
9551 
9552     // Skip allocas that have been initialized or clobbered.
9553     if (*Info != StaticAllocaInfo::Unknown)
9554       continue;
9555 
9556     // Check if the stored value is an argument, and that this store fully
9557     // initializes the alloca. Don't elide copies from the same argument twice.
9558     const Value *Val = SI->getValueOperand()->stripPointerCasts();
9559     const auto *Arg = dyn_cast<Argument>(Val);
9560     if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
9561         Arg->getType()->isEmptyTy() ||
9562         DL.getTypeStoreSize(Arg->getType()) !=
9563             DL.getTypeAllocSize(AI->getAllocatedType()) ||
9564         ArgCopyElisionCandidates.count(Arg)) {
9565       *Info = StaticAllocaInfo::Clobbered;
9566       continue;
9567     }
9568 
9569     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9570                       << '\n');
9571 
9572     // Mark this alloca and store for argument copy elision.
9573     *Info = StaticAllocaInfo::Elidable;
9574     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9575 
9576     // Stop scanning if we've seen all arguments. This will happen early in -O0
9577     // builds, which is useful, because -O0 builds have large entry blocks and
9578     // many allocas.
9579     if (ArgCopyElisionCandidates.size() == NumArgs)
9580       break;
9581   }
9582 }
9583 
9584 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9585 /// ArgVal is a load from a suitable fixed stack object.
9586 static void tryToElideArgumentCopy(
9587     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
9588     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
9589     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
9590     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
9591     SDValue ArgVal, bool &ArgHasUses) {
9592   // Check if this is a load from a fixed stack object.
9593   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
9594   if (!LNode)
9595     return;
9596   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
9597   if (!FINode)
9598     return;
9599 
9600   // Check that the fixed stack object is the right size and alignment.
9601   // Look at the alignment that the user wrote on the alloca instead of looking
9602   // at the stack object.
9603   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
9604   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
9605   const AllocaInst *AI = ArgCopyIter->second.first;
9606   int FixedIndex = FINode->getIndex();
9607   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
9608   int OldIndex = AllocaIndex;
9609   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
9610   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
9611     LLVM_DEBUG(
9612         dbgs() << "  argument copy elision failed due to bad fixed stack "
9613                   "object size\n");
9614     return;
9615   }
9616   unsigned RequiredAlignment = AI->getAlignment();
9617   if (!RequiredAlignment) {
9618     RequiredAlignment = FuncInfo.MF->getDataLayout().getABITypeAlignment(
9619         AI->getAllocatedType());
9620   }
9621   if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
9622     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
9623                          "greater than stack argument alignment ("
9624                       << RequiredAlignment << " vs "
9625                       << MFI.getObjectAlignment(FixedIndex) << ")\n");
9626     return;
9627   }
9628 
9629   // Perform the elision. Delete the old stack object and replace its only use
9630   // in the variable info map. Mark the stack object as mutable.
9631   LLVM_DEBUG({
9632     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
9633            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
9634            << '\n';
9635   });
9636   MFI.RemoveStackObject(OldIndex);
9637   MFI.setIsImmutableObjectIndex(FixedIndex, false);
9638   AllocaIndex = FixedIndex;
9639   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9640   Chains.push_back(ArgVal.getValue(1));
9641 
9642   // Avoid emitting code for the store implementing the copy.
9643   const StoreInst *SI = ArgCopyIter->second.second;
9644   ElidedArgCopyInstrs.insert(SI);
9645 
9646   // Check for uses of the argument again so that we can avoid exporting ArgVal
9647   // if it is't used by anything other than the store.
9648   for (const Value *U : Arg.users()) {
9649     if (U != SI) {
9650       ArgHasUses = true;
9651       break;
9652     }
9653   }
9654 }
9655 
9656 void SelectionDAGISel::LowerArguments(const Function &F) {
9657   SelectionDAG &DAG = SDB->DAG;
9658   SDLoc dl = SDB->getCurSDLoc();
9659   const DataLayout &DL = DAG.getDataLayout();
9660   SmallVector<ISD::InputArg, 16> Ins;
9661 
9662   if (!FuncInfo->CanLowerReturn) {
9663     // Put in an sret pointer parameter before all the other parameters.
9664     SmallVector<EVT, 1> ValueVTs;
9665     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9666                     F.getReturnType()->getPointerTo(
9667                         DAG.getDataLayout().getAllocaAddrSpace()),
9668                     ValueVTs);
9669 
9670     // NOTE: Assuming that a pointer will never break down to more than one VT
9671     // or one register.
9672     ISD::ArgFlagsTy Flags;
9673     Flags.setSRet();
9674     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9675     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9676                          ISD::InputArg::NoArgIndex, 0);
9677     Ins.push_back(RetArg);
9678   }
9679 
9680   // Look for stores of arguments to static allocas. Mark such arguments with a
9681   // flag to ask the target to give us the memory location of that argument if
9682   // available.
9683   ArgCopyElisionMapTy ArgCopyElisionCandidates;
9684   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
9685                                     ArgCopyElisionCandidates);
9686 
9687   // Set up the incoming argument description vector.
9688   for (const Argument &Arg : F.args()) {
9689     unsigned ArgNo = Arg.getArgNo();
9690     SmallVector<EVT, 4> ValueVTs;
9691     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9692     bool isArgValueUsed = !Arg.use_empty();
9693     unsigned PartBase = 0;
9694     Type *FinalType = Arg.getType();
9695     if (Arg.hasAttribute(Attribute::ByVal))
9696       FinalType = Arg.getParamByValType();
9697     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9698         FinalType, F.getCallingConv(), F.isVarArg());
9699     for (unsigned Value = 0, NumValues = ValueVTs.size();
9700          Value != NumValues; ++Value) {
9701       EVT VT = ValueVTs[Value];
9702       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9703       ISD::ArgFlagsTy Flags;
9704 
9705       // Certain targets (such as MIPS), may have a different ABI alignment
9706       // for a type depending on the context. Give the target a chance to
9707       // specify the alignment it wants.
9708       const Align OriginalAlignment(
9709           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
9710 
9711       if (Arg.getType()->isPointerTy()) {
9712         Flags.setPointer();
9713         Flags.setPointerAddrSpace(
9714             cast<PointerType>(Arg.getType())->getAddressSpace());
9715       }
9716       if (Arg.hasAttribute(Attribute::ZExt))
9717         Flags.setZExt();
9718       if (Arg.hasAttribute(Attribute::SExt))
9719         Flags.setSExt();
9720       if (Arg.hasAttribute(Attribute::InReg)) {
9721         // If we are using vectorcall calling convention, a structure that is
9722         // passed InReg - is surely an HVA
9723         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9724             isa<StructType>(Arg.getType())) {
9725           // The first value of a structure is marked
9726           if (0 == Value)
9727             Flags.setHvaStart();
9728           Flags.setHva();
9729         }
9730         // Set InReg Flag
9731         Flags.setInReg();
9732       }
9733       if (Arg.hasAttribute(Attribute::StructRet))
9734         Flags.setSRet();
9735       if (Arg.hasAttribute(Attribute::SwiftSelf))
9736         Flags.setSwiftSelf();
9737       if (Arg.hasAttribute(Attribute::SwiftError))
9738         Flags.setSwiftError();
9739       if (Arg.hasAttribute(Attribute::ByVal))
9740         Flags.setByVal();
9741       if (Arg.hasAttribute(Attribute::InAlloca)) {
9742         Flags.setInAlloca();
9743         // Set the byval flag for CCAssignFn callbacks that don't know about
9744         // inalloca.  This way we can know how many bytes we should've allocated
9745         // and how many bytes a callee cleanup function will pop.  If we port
9746         // inalloca to more targets, we'll have to add custom inalloca handling
9747         // in the various CC lowering callbacks.
9748         Flags.setByVal();
9749       }
9750       if (F.getCallingConv() == CallingConv::X86_INTR) {
9751         // IA Interrupt passes frame (1st parameter) by value in the stack.
9752         if (ArgNo == 0)
9753           Flags.setByVal();
9754       }
9755       if (Flags.isByVal() || Flags.isInAlloca()) {
9756         Type *ElementTy = Arg.getParamByValType();
9757 
9758         // For ByVal, size and alignment should be passed from FE.  BE will
9759         // guess if this info is not there but there are cases it cannot get
9760         // right.
9761         unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType());
9762         Flags.setByValSize(FrameSize);
9763 
9764         unsigned FrameAlign;
9765         if (Arg.getParamAlignment())
9766           FrameAlign = Arg.getParamAlignment();
9767         else
9768           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
9769         Flags.setByValAlign(Align(FrameAlign));
9770       }
9771       if (Arg.hasAttribute(Attribute::Nest))
9772         Flags.setNest();
9773       if (NeedsRegBlock)
9774         Flags.setInConsecutiveRegs();
9775       Flags.setOrigAlign(OriginalAlignment);
9776       if (ArgCopyElisionCandidates.count(&Arg))
9777         Flags.setCopyElisionCandidate();
9778       if (Arg.hasAttribute(Attribute::Returned))
9779         Flags.setReturned();
9780 
9781       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9782           *CurDAG->getContext(), F.getCallingConv(), VT);
9783       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9784           *CurDAG->getContext(), F.getCallingConv(), VT);
9785       for (unsigned i = 0; i != NumRegs; ++i) {
9786         // For scalable vectors, use the minimum size; individual targets
9787         // are responsible for handling scalable vector arguments and
9788         // return values.
9789         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9790                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
9791         if (NumRegs > 1 && i == 0)
9792           MyFlags.Flags.setSplit();
9793         // if it isn't first piece, alignment must be 1
9794         else if (i > 0) {
9795           MyFlags.Flags.setOrigAlign(Align::None());
9796           if (i == NumRegs - 1)
9797             MyFlags.Flags.setSplitEnd();
9798         }
9799         Ins.push_back(MyFlags);
9800       }
9801       if (NeedsRegBlock && Value == NumValues - 1)
9802         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9803       PartBase += VT.getStoreSize().getKnownMinSize();
9804     }
9805   }
9806 
9807   // Call the target to set up the argument values.
9808   SmallVector<SDValue, 8> InVals;
9809   SDValue NewRoot = TLI->LowerFormalArguments(
9810       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9811 
9812   // Verify that the target's LowerFormalArguments behaved as expected.
9813   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9814          "LowerFormalArguments didn't return a valid chain!");
9815   assert(InVals.size() == Ins.size() &&
9816          "LowerFormalArguments didn't emit the correct number of values!");
9817   LLVM_DEBUG({
9818     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
9819       assert(InVals[i].getNode() &&
9820              "LowerFormalArguments emitted a null value!");
9821       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
9822              "LowerFormalArguments emitted a value with the wrong type!");
9823     }
9824   });
9825 
9826   // Update the DAG with the new chain value resulting from argument lowering.
9827   DAG.setRoot(NewRoot);
9828 
9829   // Set up the argument values.
9830   unsigned i = 0;
9831   if (!FuncInfo->CanLowerReturn) {
9832     // Create a virtual register for the sret pointer, and put in a copy
9833     // from the sret argument into it.
9834     SmallVector<EVT, 1> ValueVTs;
9835     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9836                     F.getReturnType()->getPointerTo(
9837                         DAG.getDataLayout().getAllocaAddrSpace()),
9838                     ValueVTs);
9839     MVT VT = ValueVTs[0].getSimpleVT();
9840     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
9841     Optional<ISD::NodeType> AssertOp = None;
9842     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
9843                                         nullptr, F.getCallingConv(), AssertOp);
9844 
9845     MachineFunction& MF = SDB->DAG.getMachineFunction();
9846     MachineRegisterInfo& RegInfo = MF.getRegInfo();
9847     Register SRetReg =
9848         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
9849     FuncInfo->DemoteRegister = SRetReg;
9850     NewRoot =
9851         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
9852     DAG.setRoot(NewRoot);
9853 
9854     // i indexes lowered arguments.  Bump it past the hidden sret argument.
9855     ++i;
9856   }
9857 
9858   SmallVector<SDValue, 4> Chains;
9859   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
9860   for (const Argument &Arg : F.args()) {
9861     SmallVector<SDValue, 4> ArgValues;
9862     SmallVector<EVT, 4> ValueVTs;
9863     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9864     unsigned NumValues = ValueVTs.size();
9865     if (NumValues == 0)
9866       continue;
9867 
9868     bool ArgHasUses = !Arg.use_empty();
9869 
9870     // Elide the copying store if the target loaded this argument from a
9871     // suitable fixed stack object.
9872     if (Ins[i].Flags.isCopyElisionCandidate()) {
9873       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
9874                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
9875                              InVals[i], ArgHasUses);
9876     }
9877 
9878     // If this argument is unused then remember its value. It is used to generate
9879     // debugging information.
9880     bool isSwiftErrorArg =
9881         TLI->supportSwiftError() &&
9882         Arg.hasAttribute(Attribute::SwiftError);
9883     if (!ArgHasUses && !isSwiftErrorArg) {
9884       SDB->setUnusedArgValue(&Arg, InVals[i]);
9885 
9886       // Also remember any frame index for use in FastISel.
9887       if (FrameIndexSDNode *FI =
9888           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9889         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9890     }
9891 
9892     for (unsigned Val = 0; Val != NumValues; ++Val) {
9893       EVT VT = ValueVTs[Val];
9894       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
9895                                                       F.getCallingConv(), VT);
9896       unsigned NumParts = TLI->getNumRegistersForCallingConv(
9897           *CurDAG->getContext(), F.getCallingConv(), VT);
9898 
9899       // Even an apparent 'unused' swifterror argument needs to be returned. So
9900       // we do generate a copy for it that can be used on return from the
9901       // function.
9902       if (ArgHasUses || isSwiftErrorArg) {
9903         Optional<ISD::NodeType> AssertOp;
9904         if (Arg.hasAttribute(Attribute::SExt))
9905           AssertOp = ISD::AssertSext;
9906         else if (Arg.hasAttribute(Attribute::ZExt))
9907           AssertOp = ISD::AssertZext;
9908 
9909         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9910                                              PartVT, VT, nullptr,
9911                                              F.getCallingConv(), AssertOp));
9912       }
9913 
9914       i += NumParts;
9915     }
9916 
9917     // We don't need to do anything else for unused arguments.
9918     if (ArgValues.empty())
9919       continue;
9920 
9921     // Note down frame index.
9922     if (FrameIndexSDNode *FI =
9923         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9924       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9925 
9926     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9927                                      SDB->getCurSDLoc());
9928 
9929     SDB->setValue(&Arg, Res);
9930     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9931       // We want to associate the argument with the frame index, among
9932       // involved operands, that correspond to the lowest address. The
9933       // getCopyFromParts function, called earlier, is swapping the order of
9934       // the operands to BUILD_PAIR depending on endianness. The result of
9935       // that swapping is that the least significant bits of the argument will
9936       // be in the first operand of the BUILD_PAIR node, and the most
9937       // significant bits will be in the second operand.
9938       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9939       if (LoadSDNode *LNode =
9940           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9941         if (FrameIndexSDNode *FI =
9942             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9943           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9944     }
9945 
9946     // Analyses past this point are naive and don't expect an assertion.
9947     if (Res.getOpcode() == ISD::AssertZext)
9948       Res = Res.getOperand(0);
9949 
9950     // Update the SwiftErrorVRegDefMap.
9951     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9952       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9953       if (Register::isVirtualRegister(Reg))
9954         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
9955                                    Reg);
9956     }
9957 
9958     // If this argument is live outside of the entry block, insert a copy from
9959     // wherever we got it to the vreg that other BB's will reference it as.
9960     if (Res.getOpcode() == ISD::CopyFromReg) {
9961       // If we can, though, try to skip creating an unnecessary vreg.
9962       // FIXME: This isn't very clean... it would be nice to make this more
9963       // general.
9964       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9965       if (Register::isVirtualRegister(Reg)) {
9966         FuncInfo->ValueMap[&Arg] = Reg;
9967         continue;
9968       }
9969     }
9970     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9971       FuncInfo->InitializeRegForValue(&Arg);
9972       SDB->CopyToExportRegsIfNeeded(&Arg);
9973     }
9974   }
9975 
9976   if (!Chains.empty()) {
9977     Chains.push_back(NewRoot);
9978     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9979   }
9980 
9981   DAG.setRoot(NewRoot);
9982 
9983   assert(i == InVals.size() && "Argument register count mismatch!");
9984 
9985   // If any argument copy elisions occurred and we have debug info, update the
9986   // stale frame indices used in the dbg.declare variable info table.
9987   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
9988   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
9989     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
9990       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
9991       if (I != ArgCopyElisionFrameIndexMap.end())
9992         VI.Slot = I->second;
9993     }
9994   }
9995 
9996   // Finally, if the target has anything special to do, allow it to do so.
9997   EmitFunctionEntryCode();
9998 }
9999 
10000 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
10001 /// ensure constants are generated when needed.  Remember the virtual registers
10002 /// that need to be added to the Machine PHI nodes as input.  We cannot just
10003 /// directly add them, because expansion might result in multiple MBB's for one
10004 /// BB.  As such, the start of the BB might correspond to a different MBB than
10005 /// the end.
10006 void
10007 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
10008   const Instruction *TI = LLVMBB->getTerminator();
10009 
10010   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
10011 
10012   // Check PHI nodes in successors that expect a value to be available from this
10013   // block.
10014   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
10015     const BasicBlock *SuccBB = TI->getSuccessor(succ);
10016     if (!isa<PHINode>(SuccBB->begin())) continue;
10017     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
10018 
10019     // If this terminator has multiple identical successors (common for
10020     // switches), only handle each succ once.
10021     if (!SuccsHandled.insert(SuccMBB).second)
10022       continue;
10023 
10024     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
10025 
10026     // At this point we know that there is a 1-1 correspondence between LLVM PHI
10027     // nodes and Machine PHI nodes, but the incoming operands have not been
10028     // emitted yet.
10029     for (const PHINode &PN : SuccBB->phis()) {
10030       // Ignore dead phi's.
10031       if (PN.use_empty())
10032         continue;
10033 
10034       // Skip empty types
10035       if (PN.getType()->isEmptyTy())
10036         continue;
10037 
10038       unsigned Reg;
10039       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
10040 
10041       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
10042         unsigned &RegOut = ConstantsOut[C];
10043         if (RegOut == 0) {
10044           RegOut = FuncInfo.CreateRegs(C);
10045           CopyValueToVirtualRegister(C, RegOut);
10046         }
10047         Reg = RegOut;
10048       } else {
10049         DenseMap<const Value *, unsigned>::iterator I =
10050           FuncInfo.ValueMap.find(PHIOp);
10051         if (I != FuncInfo.ValueMap.end())
10052           Reg = I->second;
10053         else {
10054           assert(isa<AllocaInst>(PHIOp) &&
10055                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10056                  "Didn't codegen value into a register!??");
10057           Reg = FuncInfo.CreateRegs(PHIOp);
10058           CopyValueToVirtualRegister(PHIOp, Reg);
10059         }
10060       }
10061 
10062       // Remember that this register needs to added to the machine PHI node as
10063       // the input for this MBB.
10064       SmallVector<EVT, 4> ValueVTs;
10065       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10066       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
10067       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
10068         EVT VT = ValueVTs[vti];
10069         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
10070         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
10071           FuncInfo.PHINodesToUpdate.push_back(
10072               std::make_pair(&*MBBI++, Reg + i));
10073         Reg += NumRegisters;
10074       }
10075     }
10076   }
10077 
10078   ConstantsOut.clear();
10079 }
10080 
10081 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
10082 /// is 0.
10083 MachineBasicBlock *
10084 SelectionDAGBuilder::StackProtectorDescriptor::
10085 AddSuccessorMBB(const BasicBlock *BB,
10086                 MachineBasicBlock *ParentMBB,
10087                 bool IsLikely,
10088                 MachineBasicBlock *SuccMBB) {
10089   // If SuccBB has not been created yet, create it.
10090   if (!SuccMBB) {
10091     MachineFunction *MF = ParentMBB->getParent();
10092     MachineFunction::iterator BBI(ParentMBB);
10093     SuccMBB = MF->CreateMachineBasicBlock(BB);
10094     MF->insert(++BBI, SuccMBB);
10095   }
10096   // Add it as a successor of ParentMBB.
10097   ParentMBB->addSuccessor(
10098       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
10099   return SuccMBB;
10100 }
10101 
10102 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10103   MachineFunction::iterator I(MBB);
10104   if (++I == FuncInfo.MF->end())
10105     return nullptr;
10106   return &*I;
10107 }
10108 
10109 /// During lowering new call nodes can be created (such as memset, etc.).
10110 /// Those will become new roots of the current DAG, but complications arise
10111 /// when they are tail calls. In such cases, the call lowering will update
10112 /// the root, but the builder still needs to know that a tail call has been
10113 /// lowered in order to avoid generating an additional return.
10114 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10115   // If the node is null, we do have a tail call.
10116   if (MaybeTC.getNode() != nullptr)
10117     DAG.setRoot(MaybeTC);
10118   else
10119     HasTailCall = true;
10120 }
10121 
10122 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10123                                         MachineBasicBlock *SwitchMBB,
10124                                         MachineBasicBlock *DefaultMBB) {
10125   MachineFunction *CurMF = FuncInfo.MF;
10126   MachineBasicBlock *NextMBB = nullptr;
10127   MachineFunction::iterator BBI(W.MBB);
10128   if (++BBI != FuncInfo.MF->end())
10129     NextMBB = &*BBI;
10130 
10131   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10132 
10133   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10134 
10135   if (Size == 2 && W.MBB == SwitchMBB) {
10136     // If any two of the cases has the same destination, and if one value
10137     // is the same as the other, but has one bit unset that the other has set,
10138     // use bit manipulation to do two compares at once.  For example:
10139     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10140     // TODO: This could be extended to merge any 2 cases in switches with 3
10141     // cases.
10142     // TODO: Handle cases where W.CaseBB != SwitchBB.
10143     CaseCluster &Small = *W.FirstCluster;
10144     CaseCluster &Big = *W.LastCluster;
10145 
10146     if (Small.Low == Small.High && Big.Low == Big.High &&
10147         Small.MBB == Big.MBB) {
10148       const APInt &SmallValue = Small.Low->getValue();
10149       const APInt &BigValue = Big.Low->getValue();
10150 
10151       // Check that there is only one bit different.
10152       APInt CommonBit = BigValue ^ SmallValue;
10153       if (CommonBit.isPowerOf2()) {
10154         SDValue CondLHS = getValue(Cond);
10155         EVT VT = CondLHS.getValueType();
10156         SDLoc DL = getCurSDLoc();
10157 
10158         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10159                                  DAG.getConstant(CommonBit, DL, VT));
10160         SDValue Cond = DAG.getSetCC(
10161             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10162             ISD::SETEQ);
10163 
10164         // Update successor info.
10165         // Both Small and Big will jump to Small.BB, so we sum up the
10166         // probabilities.
10167         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10168         if (BPI)
10169           addSuccessorWithProb(
10170               SwitchMBB, DefaultMBB,
10171               // The default destination is the first successor in IR.
10172               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10173         else
10174           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10175 
10176         // Insert the true branch.
10177         SDValue BrCond =
10178             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10179                         DAG.getBasicBlock(Small.MBB));
10180         // Insert the false branch.
10181         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10182                              DAG.getBasicBlock(DefaultMBB));
10183 
10184         DAG.setRoot(BrCond);
10185         return;
10186       }
10187     }
10188   }
10189 
10190   if (TM.getOptLevel() != CodeGenOpt::None) {
10191     // Here, we order cases by probability so the most likely case will be
10192     // checked first. However, two clusters can have the same probability in
10193     // which case their relative ordering is non-deterministic. So we use Low
10194     // as a tie-breaker as clusters are guaranteed to never overlap.
10195     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10196                [](const CaseCluster &a, const CaseCluster &b) {
10197       return a.Prob != b.Prob ?
10198              a.Prob > b.Prob :
10199              a.Low->getValue().slt(b.Low->getValue());
10200     });
10201 
10202     // Rearrange the case blocks so that the last one falls through if possible
10203     // without changing the order of probabilities.
10204     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10205       --I;
10206       if (I->Prob > W.LastCluster->Prob)
10207         break;
10208       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10209         std::swap(*I, *W.LastCluster);
10210         break;
10211       }
10212     }
10213   }
10214 
10215   // Compute total probability.
10216   BranchProbability DefaultProb = W.DefaultProb;
10217   BranchProbability UnhandledProbs = DefaultProb;
10218   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10219     UnhandledProbs += I->Prob;
10220 
10221   MachineBasicBlock *CurMBB = W.MBB;
10222   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10223     bool FallthroughUnreachable = false;
10224     MachineBasicBlock *Fallthrough;
10225     if (I == W.LastCluster) {
10226       // For the last cluster, fall through to the default destination.
10227       Fallthrough = DefaultMBB;
10228       FallthroughUnreachable = isa<UnreachableInst>(
10229           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10230     } else {
10231       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10232       CurMF->insert(BBI, Fallthrough);
10233       // Put Cond in a virtual register to make it available from the new blocks.
10234       ExportFromCurrentBlock(Cond);
10235     }
10236     UnhandledProbs -= I->Prob;
10237 
10238     switch (I->Kind) {
10239       case CC_JumpTable: {
10240         // FIXME: Optimize away range check based on pivot comparisons.
10241         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10242         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10243 
10244         // The jump block hasn't been inserted yet; insert it here.
10245         MachineBasicBlock *JumpMBB = JT->MBB;
10246         CurMF->insert(BBI, JumpMBB);
10247 
10248         auto JumpProb = I->Prob;
10249         auto FallthroughProb = UnhandledProbs;
10250 
10251         // If the default statement is a target of the jump table, we evenly
10252         // distribute the default probability to successors of CurMBB. Also
10253         // update the probability on the edge from JumpMBB to Fallthrough.
10254         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10255                                               SE = JumpMBB->succ_end();
10256              SI != SE; ++SI) {
10257           if (*SI == DefaultMBB) {
10258             JumpProb += DefaultProb / 2;
10259             FallthroughProb -= DefaultProb / 2;
10260             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10261             JumpMBB->normalizeSuccProbs();
10262             break;
10263           }
10264         }
10265 
10266         if (FallthroughUnreachable) {
10267           // Skip the range check if the fallthrough block is unreachable.
10268           JTH->OmitRangeCheck = true;
10269         }
10270 
10271         if (!JTH->OmitRangeCheck)
10272           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10273         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10274         CurMBB->normalizeSuccProbs();
10275 
10276         // The jump table header will be inserted in our current block, do the
10277         // range check, and fall through to our fallthrough block.
10278         JTH->HeaderBB = CurMBB;
10279         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10280 
10281         // If we're in the right place, emit the jump table header right now.
10282         if (CurMBB == SwitchMBB) {
10283           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10284           JTH->Emitted = true;
10285         }
10286         break;
10287       }
10288       case CC_BitTests: {
10289         // FIXME: Optimize away range check based on pivot comparisons.
10290         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10291 
10292         // The bit test blocks haven't been inserted yet; insert them here.
10293         for (BitTestCase &BTC : BTB->Cases)
10294           CurMF->insert(BBI, BTC.ThisBB);
10295 
10296         // Fill in fields of the BitTestBlock.
10297         BTB->Parent = CurMBB;
10298         BTB->Default = Fallthrough;
10299 
10300         BTB->DefaultProb = UnhandledProbs;
10301         // If the cases in bit test don't form a contiguous range, we evenly
10302         // distribute the probability on the edge to Fallthrough to two
10303         // successors of CurMBB.
10304         if (!BTB->ContiguousRange) {
10305           BTB->Prob += DefaultProb / 2;
10306           BTB->DefaultProb -= DefaultProb / 2;
10307         }
10308 
10309         if (FallthroughUnreachable) {
10310           // Skip the range check if the fallthrough block is unreachable.
10311           BTB->OmitRangeCheck = true;
10312         }
10313 
10314         // If we're in the right place, emit the bit test header right now.
10315         if (CurMBB == SwitchMBB) {
10316           visitBitTestHeader(*BTB, SwitchMBB);
10317           BTB->Emitted = true;
10318         }
10319         break;
10320       }
10321       case CC_Range: {
10322         const Value *RHS, *LHS, *MHS;
10323         ISD::CondCode CC;
10324         if (I->Low == I->High) {
10325           // Check Cond == I->Low.
10326           CC = ISD::SETEQ;
10327           LHS = Cond;
10328           RHS=I->Low;
10329           MHS = nullptr;
10330         } else {
10331           // Check I->Low <= Cond <= I->High.
10332           CC = ISD::SETLE;
10333           LHS = I->Low;
10334           MHS = Cond;
10335           RHS = I->High;
10336         }
10337 
10338         // If Fallthrough is unreachable, fold away the comparison.
10339         if (FallthroughUnreachable)
10340           CC = ISD::SETTRUE;
10341 
10342         // The false probability is the sum of all unhandled cases.
10343         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10344                      getCurSDLoc(), I->Prob, UnhandledProbs);
10345 
10346         if (CurMBB == SwitchMBB)
10347           visitSwitchCase(CB, SwitchMBB);
10348         else
10349           SL->SwitchCases.push_back(CB);
10350 
10351         break;
10352       }
10353     }
10354     CurMBB = Fallthrough;
10355   }
10356 }
10357 
10358 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10359                                               CaseClusterIt First,
10360                                               CaseClusterIt Last) {
10361   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10362     if (X.Prob != CC.Prob)
10363       return X.Prob > CC.Prob;
10364 
10365     // Ties are broken by comparing the case value.
10366     return X.Low->getValue().slt(CC.Low->getValue());
10367   });
10368 }
10369 
10370 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10371                                         const SwitchWorkListItem &W,
10372                                         Value *Cond,
10373                                         MachineBasicBlock *SwitchMBB) {
10374   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10375          "Clusters not sorted?");
10376 
10377   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10378 
10379   // Balance the tree based on branch probabilities to create a near-optimal (in
10380   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10381   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10382   CaseClusterIt LastLeft = W.FirstCluster;
10383   CaseClusterIt FirstRight = W.LastCluster;
10384   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10385   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10386 
10387   // Move LastLeft and FirstRight towards each other from opposite directions to
10388   // find a partitioning of the clusters which balances the probability on both
10389   // sides. If LeftProb and RightProb are equal, alternate which side is
10390   // taken to ensure 0-probability nodes are distributed evenly.
10391   unsigned I = 0;
10392   while (LastLeft + 1 < FirstRight) {
10393     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10394       LeftProb += (++LastLeft)->Prob;
10395     else
10396       RightProb += (--FirstRight)->Prob;
10397     I++;
10398   }
10399 
10400   while (true) {
10401     // Our binary search tree differs from a typical BST in that ours can have up
10402     // to three values in each leaf. The pivot selection above doesn't take that
10403     // into account, which means the tree might require more nodes and be less
10404     // efficient. We compensate for this here.
10405 
10406     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10407     unsigned NumRight = W.LastCluster - FirstRight + 1;
10408 
10409     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10410       // If one side has less than 3 clusters, and the other has more than 3,
10411       // consider taking a cluster from the other side.
10412 
10413       if (NumLeft < NumRight) {
10414         // Consider moving the first cluster on the right to the left side.
10415         CaseCluster &CC = *FirstRight;
10416         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10417         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10418         if (LeftSideRank <= RightSideRank) {
10419           // Moving the cluster to the left does not demote it.
10420           ++LastLeft;
10421           ++FirstRight;
10422           continue;
10423         }
10424       } else {
10425         assert(NumRight < NumLeft);
10426         // Consider moving the last element on the left to the right side.
10427         CaseCluster &CC = *LastLeft;
10428         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10429         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10430         if (RightSideRank <= LeftSideRank) {
10431           // Moving the cluster to the right does not demot it.
10432           --LastLeft;
10433           --FirstRight;
10434           continue;
10435         }
10436       }
10437     }
10438     break;
10439   }
10440 
10441   assert(LastLeft + 1 == FirstRight);
10442   assert(LastLeft >= W.FirstCluster);
10443   assert(FirstRight <= W.LastCluster);
10444 
10445   // Use the first element on the right as pivot since we will make less-than
10446   // comparisons against it.
10447   CaseClusterIt PivotCluster = FirstRight;
10448   assert(PivotCluster > W.FirstCluster);
10449   assert(PivotCluster <= W.LastCluster);
10450 
10451   CaseClusterIt FirstLeft = W.FirstCluster;
10452   CaseClusterIt LastRight = W.LastCluster;
10453 
10454   const ConstantInt *Pivot = PivotCluster->Low;
10455 
10456   // New blocks will be inserted immediately after the current one.
10457   MachineFunction::iterator BBI(W.MBB);
10458   ++BBI;
10459 
10460   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10461   // we can branch to its destination directly if it's squeezed exactly in
10462   // between the known lower bound and Pivot - 1.
10463   MachineBasicBlock *LeftMBB;
10464   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10465       FirstLeft->Low == W.GE &&
10466       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10467     LeftMBB = FirstLeft->MBB;
10468   } else {
10469     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10470     FuncInfo.MF->insert(BBI, LeftMBB);
10471     WorkList.push_back(
10472         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10473     // Put Cond in a virtual register to make it available from the new blocks.
10474     ExportFromCurrentBlock(Cond);
10475   }
10476 
10477   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10478   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10479   // directly if RHS.High equals the current upper bound.
10480   MachineBasicBlock *RightMBB;
10481   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10482       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10483     RightMBB = FirstRight->MBB;
10484   } else {
10485     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10486     FuncInfo.MF->insert(BBI, RightMBB);
10487     WorkList.push_back(
10488         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10489     // Put Cond in a virtual register to make it available from the new blocks.
10490     ExportFromCurrentBlock(Cond);
10491   }
10492 
10493   // Create the CaseBlock record that will be used to lower the branch.
10494   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10495                getCurSDLoc(), LeftProb, RightProb);
10496 
10497   if (W.MBB == SwitchMBB)
10498     visitSwitchCase(CB, SwitchMBB);
10499   else
10500     SL->SwitchCases.push_back(CB);
10501 }
10502 
10503 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10504 // from the swith statement.
10505 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10506                                             BranchProbability PeeledCaseProb) {
10507   if (PeeledCaseProb == BranchProbability::getOne())
10508     return BranchProbability::getZero();
10509   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10510 
10511   uint32_t Numerator = CaseProb.getNumerator();
10512   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10513   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10514 }
10515 
10516 // Try to peel the top probability case if it exceeds the threshold.
10517 // Return current MachineBasicBlock for the switch statement if the peeling
10518 // does not occur.
10519 // If the peeling is performed, return the newly created MachineBasicBlock
10520 // for the peeled switch statement. Also update Clusters to remove the peeled
10521 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10522 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10523     const SwitchInst &SI, CaseClusterVector &Clusters,
10524     BranchProbability &PeeledCaseProb) {
10525   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10526   // Don't perform if there is only one cluster or optimizing for size.
10527   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10528       TM.getOptLevel() == CodeGenOpt::None ||
10529       SwitchMBB->getParent()->getFunction().hasMinSize())
10530     return SwitchMBB;
10531 
10532   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10533   unsigned PeeledCaseIndex = 0;
10534   bool SwitchPeeled = false;
10535   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10536     CaseCluster &CC = Clusters[Index];
10537     if (CC.Prob < TopCaseProb)
10538       continue;
10539     TopCaseProb = CC.Prob;
10540     PeeledCaseIndex = Index;
10541     SwitchPeeled = true;
10542   }
10543   if (!SwitchPeeled)
10544     return SwitchMBB;
10545 
10546   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10547                     << TopCaseProb << "\n");
10548 
10549   // Record the MBB for the peeled switch statement.
10550   MachineFunction::iterator BBI(SwitchMBB);
10551   ++BBI;
10552   MachineBasicBlock *PeeledSwitchMBB =
10553       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10554   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10555 
10556   ExportFromCurrentBlock(SI.getCondition());
10557   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10558   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10559                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10560   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10561 
10562   Clusters.erase(PeeledCaseIt);
10563   for (CaseCluster &CC : Clusters) {
10564     LLVM_DEBUG(
10565         dbgs() << "Scale the probablity for one cluster, before scaling: "
10566                << CC.Prob << "\n");
10567     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10568     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10569   }
10570   PeeledCaseProb = TopCaseProb;
10571   return PeeledSwitchMBB;
10572 }
10573 
10574 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10575   // Extract cases from the switch.
10576   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10577   CaseClusterVector Clusters;
10578   Clusters.reserve(SI.getNumCases());
10579   for (auto I : SI.cases()) {
10580     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10581     const ConstantInt *CaseVal = I.getCaseValue();
10582     BranchProbability Prob =
10583         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10584             : BranchProbability(1, SI.getNumCases() + 1);
10585     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10586   }
10587 
10588   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10589 
10590   // Cluster adjacent cases with the same destination. We do this at all
10591   // optimization levels because it's cheap to do and will make codegen faster
10592   // if there are many clusters.
10593   sortAndRangeify(Clusters);
10594 
10595   // The branch probablity of the peeled case.
10596   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10597   MachineBasicBlock *PeeledSwitchMBB =
10598       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10599 
10600   // If there is only the default destination, jump there directly.
10601   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10602   if (Clusters.empty()) {
10603     assert(PeeledSwitchMBB == SwitchMBB);
10604     SwitchMBB->addSuccessor(DefaultMBB);
10605     if (DefaultMBB != NextBlock(SwitchMBB)) {
10606       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10607                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10608     }
10609     return;
10610   }
10611 
10612   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
10613   SL->findBitTestClusters(Clusters, &SI);
10614 
10615   LLVM_DEBUG({
10616     dbgs() << "Case clusters: ";
10617     for (const CaseCluster &C : Clusters) {
10618       if (C.Kind == CC_JumpTable)
10619         dbgs() << "JT:";
10620       if (C.Kind == CC_BitTests)
10621         dbgs() << "BT:";
10622 
10623       C.Low->getValue().print(dbgs(), true);
10624       if (C.Low != C.High) {
10625         dbgs() << '-';
10626         C.High->getValue().print(dbgs(), true);
10627       }
10628       dbgs() << ' ';
10629     }
10630     dbgs() << '\n';
10631   });
10632 
10633   assert(!Clusters.empty());
10634   SwitchWorkList WorkList;
10635   CaseClusterIt First = Clusters.begin();
10636   CaseClusterIt Last = Clusters.end() - 1;
10637   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10638   // Scale the branchprobability for DefaultMBB if the peel occurs and
10639   // DefaultMBB is not replaced.
10640   if (PeeledCaseProb != BranchProbability::getZero() &&
10641       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10642     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10643   WorkList.push_back(
10644       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10645 
10646   while (!WorkList.empty()) {
10647     SwitchWorkListItem W = WorkList.back();
10648     WorkList.pop_back();
10649     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10650 
10651     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10652         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
10653       // For optimized builds, lower large range as a balanced binary tree.
10654       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10655       continue;
10656     }
10657 
10658     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10659   }
10660 }
10661 
10662 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
10663   SDValue N = getValue(I.getOperand(0));
10664   setValue(&I, N);
10665 }
10666