xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision ae76dfb74701e05e5ab4be194e20e49f10768e46)
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/BitVector.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/Analysis/BranchProbabilityInfo.h"
25 #include "llvm/Analysis/ConstantFolding.h"
26 #include "llvm/Analysis/Loads.h"
27 #include "llvm/Analysis/MemoryLocation.h"
28 #include "llvm/Analysis/TargetLibraryInfo.h"
29 #include "llvm/Analysis/TargetTransformInfo.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/Analysis/VectorUtils.h"
32 #include "llvm/CodeGen/Analysis.h"
33 #include "llvm/CodeGen/AssignmentTrackingAnalysis.h"
34 #include "llvm/CodeGen/CodeGenCommonISel.h"
35 #include "llvm/CodeGen/FunctionLoweringInfo.h"
36 #include "llvm/CodeGen/GCMetadata.h"
37 #include "llvm/CodeGen/ISDOpcodes.h"
38 #include "llvm/CodeGen/MachineBasicBlock.h"
39 #include "llvm/CodeGen/MachineFrameInfo.h"
40 #include "llvm/CodeGen/MachineFunction.h"
41 #include "llvm/CodeGen/MachineInstrBuilder.h"
42 #include "llvm/CodeGen/MachineInstrBundleIterator.h"
43 #include "llvm/CodeGen/MachineMemOperand.h"
44 #include "llvm/CodeGen/MachineModuleInfo.h"
45 #include "llvm/CodeGen/MachineOperand.h"
46 #include "llvm/CodeGen/MachineRegisterInfo.h"
47 #include "llvm/CodeGen/RuntimeLibcalls.h"
48 #include "llvm/CodeGen/SelectionDAG.h"
49 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
50 #include "llvm/CodeGen/StackMaps.h"
51 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
52 #include "llvm/CodeGen/TargetFrameLowering.h"
53 #include "llvm/CodeGen/TargetInstrInfo.h"
54 #include "llvm/CodeGen/TargetOpcodes.h"
55 #include "llvm/CodeGen/TargetRegisterInfo.h"
56 #include "llvm/CodeGen/TargetSubtargetInfo.h"
57 #include "llvm/CodeGen/WinEHFuncInfo.h"
58 #include "llvm/IR/Argument.h"
59 #include "llvm/IR/Attributes.h"
60 #include "llvm/IR/BasicBlock.h"
61 #include "llvm/IR/CFG.h"
62 #include "llvm/IR/CallingConv.h"
63 #include "llvm/IR/Constant.h"
64 #include "llvm/IR/ConstantRange.h"
65 #include "llvm/IR/Constants.h"
66 #include "llvm/IR/DataLayout.h"
67 #include "llvm/IR/DebugInfo.h"
68 #include "llvm/IR/DebugInfoMetadata.h"
69 #include "llvm/IR/DerivedTypes.h"
70 #include "llvm/IR/DiagnosticInfo.h"
71 #include "llvm/IR/EHPersonalities.h"
72 #include "llvm/IR/Function.h"
73 #include "llvm/IR/GetElementPtrTypeIterator.h"
74 #include "llvm/IR/InlineAsm.h"
75 #include "llvm/IR/InstrTypes.h"
76 #include "llvm/IR/Instructions.h"
77 #include "llvm/IR/IntrinsicInst.h"
78 #include "llvm/IR/Intrinsics.h"
79 #include "llvm/IR/IntrinsicsAArch64.h"
80 #include "llvm/IR/IntrinsicsAMDGPU.h"
81 #include "llvm/IR/IntrinsicsWebAssembly.h"
82 #include "llvm/IR/LLVMContext.h"
83 #include "llvm/IR/Metadata.h"
84 #include "llvm/IR/Module.h"
85 #include "llvm/IR/Operator.h"
86 #include "llvm/IR/PatternMatch.h"
87 #include "llvm/IR/Statepoint.h"
88 #include "llvm/IR/Type.h"
89 #include "llvm/IR/User.h"
90 #include "llvm/IR/Value.h"
91 #include "llvm/MC/MCContext.h"
92 #include "llvm/Support/AtomicOrdering.h"
93 #include "llvm/Support/Casting.h"
94 #include "llvm/Support/CommandLine.h"
95 #include "llvm/Support/Compiler.h"
96 #include "llvm/Support/Debug.h"
97 #include "llvm/Support/InstructionCost.h"
98 #include "llvm/Support/MathExtras.h"
99 #include "llvm/Support/raw_ostream.h"
100 #include "llvm/Target/TargetIntrinsicInfo.h"
101 #include "llvm/Target/TargetMachine.h"
102 #include "llvm/Target/TargetOptions.h"
103 #include "llvm/TargetParser/Triple.h"
104 #include "llvm/Transforms/Utils/Local.h"
105 #include <cstddef>
106 #include <iterator>
107 #include <limits>
108 #include <optional>
109 #include <tuple>
110 
111 using namespace llvm;
112 using namespace PatternMatch;
113 using namespace SwitchCG;
114 
115 #define DEBUG_TYPE "isel"
116 
117 /// LimitFloatPrecision - Generate low-precision inline sequences for
118 /// some float libcalls (6, 8 or 12 bits).
119 static unsigned LimitFloatPrecision;
120 
121 static cl::opt<bool>
122     InsertAssertAlign("insert-assert-align", cl::init(true),
123                       cl::desc("Insert the experimental `assertalign` node."),
124                       cl::ReallyHidden);
125 
126 static cl::opt<unsigned, true>
127     LimitFPPrecision("limit-float-precision",
128                      cl::desc("Generate low-precision inline sequences "
129                               "for some float libcalls"),
130                      cl::location(LimitFloatPrecision), cl::Hidden,
131                      cl::init(0));
132 
133 static cl::opt<unsigned> SwitchPeelThreshold(
134     "switch-peel-threshold", cl::Hidden, cl::init(66),
135     cl::desc("Set the case probability threshold for peeling the case from a "
136              "switch statement. A value greater than 100 will void this "
137              "optimization"));
138 
139 // Limit the width of DAG chains. This is important in general to prevent
140 // DAG-based analysis from blowing up. For example, alias analysis and
141 // load clustering may not complete in reasonable time. It is difficult to
142 // recognize and avoid this situation within each individual analysis, and
143 // future analyses are likely to have the same behavior. Limiting DAG width is
144 // the safe approach and will be especially important with global DAGs.
145 //
146 // MaxParallelChains default is arbitrarily high to avoid affecting
147 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
148 // sequence over this should have been converted to llvm.memcpy by the
149 // frontend. It is easy to induce this behavior with .ll code such as:
150 // %buffer = alloca [4096 x i8]
151 // %data = load [4096 x i8]* %argPtr
152 // store [4096 x i8] %data, [4096 x i8]* %buffer
153 static const unsigned MaxParallelChains = 64;
154 
155 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
156                                       const SDValue *Parts, unsigned NumParts,
157                                       MVT PartVT, EVT ValueVT, const Value *V,
158                                       SDValue InChain,
159                                       std::optional<CallingConv::ID> CC);
160 
161 /// getCopyFromParts - Create a value that contains the specified legal parts
162 /// combined into the value they represent.  If the parts combine to a type
163 /// larger than ValueVT then AssertOp can be used to specify whether the extra
164 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
165 /// (ISD::AssertSext).
166 static SDValue
167 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts,
168                  unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V,
169                  SDValue InChain,
170                  std::optional<CallingConv::ID> CC = std::nullopt,
171                  std::optional<ISD::NodeType> AssertOp = std::nullopt) {
172   // Let the target assemble the parts if it wants to
173   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
174   if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
175                                                    PartVT, ValueVT, CC))
176     return Val;
177 
178   if (ValueVT.isVector())
179     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
180                                   InChain, CC);
181 
182   assert(NumParts > 0 && "No parts to assemble!");
183   SDValue Val = Parts[0];
184 
185   if (NumParts > 1) {
186     // Assemble the value from multiple parts.
187     if (ValueVT.isInteger()) {
188       unsigned PartBits = PartVT.getSizeInBits();
189       unsigned ValueBits = ValueVT.getSizeInBits();
190 
191       // Assemble the power of 2 part.
192       unsigned RoundParts = llvm::bit_floor(NumParts);
193       unsigned RoundBits = PartBits * RoundParts;
194       EVT RoundVT = RoundBits == ValueBits ?
195         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
196       SDValue Lo, Hi;
197 
198       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
199 
200       if (RoundParts > 2) {
201         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, PartVT, HalfVT, V,
202                               InChain);
203         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, RoundParts / 2,
204                               PartVT, HalfVT, V, InChain);
205       } else {
206         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
207         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
208       }
209 
210       if (DAG.getDataLayout().isBigEndian())
211         std::swap(Lo, Hi);
212 
213       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
214 
215       if (RoundParts < NumParts) {
216         // Assemble the trailing non-power-of-2 part.
217         unsigned OddParts = NumParts - RoundParts;
218         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
219         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
220                               OddVT, V, InChain, CC);
221 
222         // Combine the round and odd parts.
223         Lo = Val;
224         if (DAG.getDataLayout().isBigEndian())
225           std::swap(Lo, Hi);
226         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
227         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
228         Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
229                          DAG.getConstant(Lo.getValueSizeInBits(), DL,
230                                          TLI.getShiftAmountTy(
231                                              TotalVT, DAG.getDataLayout())));
232         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
233         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
234       }
235     } else if (PartVT.isFloatingPoint()) {
236       // FP split into multiple FP parts (for ppcf128)
237       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
238              "Unexpected split");
239       SDValue Lo, Hi;
240       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
241       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
242       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
243         std::swap(Lo, Hi);
244       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
245     } else {
246       // FP split into integer parts (soft fp)
247       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
248              !PartVT.isVector() && "Unexpected split");
249       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
250       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V,
251                              InChain, CC);
252     }
253   }
254 
255   // There is now one part, held in Val.  Correct it to match ValueVT.
256   // PartEVT is the type of the register class that holds the value.
257   // ValueVT is the type of the inline asm operation.
258   EVT PartEVT = Val.getValueType();
259 
260   if (PartEVT == ValueVT)
261     return Val;
262 
263   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
264       ValueVT.bitsLT(PartEVT)) {
265     // For an FP value in an integer part, we need to truncate to the right
266     // width first.
267     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
268     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
269   }
270 
271   // Handle types that have the same size.
272   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
273     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
274 
275   // Handle types with different sizes.
276   if (PartEVT.isInteger() && ValueVT.isInteger()) {
277     if (ValueVT.bitsLT(PartEVT)) {
278       // For a truncate, see if we have any information to
279       // indicate whether the truncated bits will always be
280       // zero or sign-extension.
281       if (AssertOp)
282         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
283                           DAG.getValueType(ValueVT));
284       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
285     }
286     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
287   }
288 
289   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
290     // FP_ROUND's are always exact here.
291     if (ValueVT.bitsLT(Val.getValueType())) {
292 
293       SDValue NoChange =
294           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
295 
296       if (DAG.getMachineFunction().getFunction().getAttributes().hasFnAttr(
297               llvm::Attribute::StrictFP)) {
298         return DAG.getNode(ISD::STRICT_FP_ROUND, DL,
299                            DAG.getVTList(ValueVT, MVT::Other), InChain, Val,
300                            NoChange);
301       }
302 
303       return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val, NoChange);
304     }
305 
306     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
307   }
308 
309   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
310   // then truncating.
311   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
312       ValueVT.bitsLT(PartEVT)) {
313     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
314     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
315   }
316 
317   report_fatal_error("Unknown mismatch in getCopyFromParts!");
318 }
319 
320 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
321                                               const Twine &ErrMsg) {
322   const Instruction *I = dyn_cast_or_null<Instruction>(V);
323   if (!V)
324     return Ctx.emitError(ErrMsg);
325 
326   const char *AsmError = ", possible invalid constraint for vector type";
327   if (const CallInst *CI = dyn_cast<CallInst>(I))
328     if (CI->isInlineAsm())
329       return Ctx.emitError(I, ErrMsg + AsmError);
330 
331   return Ctx.emitError(I, ErrMsg);
332 }
333 
334 /// getCopyFromPartsVector - Create a value that contains the specified legal
335 /// parts combined into the value they represent.  If the parts combine to a
336 /// type larger than ValueVT then AssertOp can be used to specify whether the
337 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
338 /// ValueVT (ISD::AssertSext).
339 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
340                                       const SDValue *Parts, unsigned NumParts,
341                                       MVT PartVT, EVT ValueVT, const Value *V,
342                                       SDValue InChain,
343                                       std::optional<CallingConv::ID> CallConv) {
344   assert(ValueVT.isVector() && "Not a vector value");
345   assert(NumParts > 0 && "No parts to assemble!");
346   const bool IsABIRegCopy = CallConv.has_value();
347 
348   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
349   SDValue Val = Parts[0];
350 
351   // Handle a multi-element vector.
352   if (NumParts > 1) {
353     EVT IntermediateVT;
354     MVT RegisterVT;
355     unsigned NumIntermediates;
356     unsigned NumRegs;
357 
358     if (IsABIRegCopy) {
359       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
360           *DAG.getContext(), *CallConv, ValueVT, IntermediateVT,
361           NumIntermediates, RegisterVT);
362     } else {
363       NumRegs =
364           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
365                                      NumIntermediates, RegisterVT);
366     }
367 
368     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
369     NumParts = NumRegs; // Silence a compiler warning.
370     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
371     assert(RegisterVT.getSizeInBits() ==
372            Parts[0].getSimpleValueType().getSizeInBits() &&
373            "Part type sizes don't match!");
374 
375     // Assemble the parts into intermediate operands.
376     SmallVector<SDValue, 8> Ops(NumIntermediates);
377     if (NumIntermediates == NumParts) {
378       // If the register was not expanded, truncate or copy the value,
379       // as appropriate.
380       for (unsigned i = 0; i != NumParts; ++i)
381         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, PartVT, IntermediateVT,
382                                   V, InChain, CallConv);
383     } else if (NumParts > 0) {
384       // If the intermediate type was expanded, build the intermediate
385       // operands from the parts.
386       assert(NumParts % NumIntermediates == 0 &&
387              "Must expand into a divisible number of parts!");
388       unsigned Factor = NumParts / NumIntermediates;
389       for (unsigned i = 0; i != NumIntermediates; ++i)
390         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, PartVT,
391                                   IntermediateVT, V, InChain, CallConv);
392     }
393 
394     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
395     // intermediate operands.
396     EVT BuiltVectorTy =
397         IntermediateVT.isVector()
398             ? EVT::getVectorVT(
399                   *DAG.getContext(), IntermediateVT.getScalarType(),
400                   IntermediateVT.getVectorElementCount() * NumParts)
401             : EVT::getVectorVT(*DAG.getContext(),
402                                IntermediateVT.getScalarType(),
403                                NumIntermediates);
404     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
405                                                 : ISD::BUILD_VECTOR,
406                       DL, BuiltVectorTy, Ops);
407   }
408 
409   // There is now one part, held in Val.  Correct it to match ValueVT.
410   EVT PartEVT = Val.getValueType();
411 
412   if (PartEVT == ValueVT)
413     return Val;
414 
415   if (PartEVT.isVector()) {
416     // Vector/Vector bitcast.
417     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
418       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
419 
420     // If the parts vector has more elements than the value vector, then we
421     // have a vector widening case (e.g. <2 x float> -> <4 x float>).
422     // Extract the elements we want.
423     if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
424       assert((PartEVT.getVectorElementCount().getKnownMinValue() >
425               ValueVT.getVectorElementCount().getKnownMinValue()) &&
426              (PartEVT.getVectorElementCount().isScalable() ==
427               ValueVT.getVectorElementCount().isScalable()) &&
428              "Cannot narrow, it would be a lossy transformation");
429       PartEVT =
430           EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(),
431                            ValueVT.getVectorElementCount());
432       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val,
433                         DAG.getVectorIdxConstant(0, DL));
434       if (PartEVT == ValueVT)
435         return Val;
436       if (PartEVT.isInteger() && ValueVT.isFloatingPoint())
437         return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
438 
439       // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>).
440       if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
441         return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
442     }
443 
444     // Promoted vector extract
445     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
446   }
447 
448   // Trivial bitcast if the types are the same size and the destination
449   // vector type is legal.
450   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
451       TLI.isTypeLegal(ValueVT))
452     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
453 
454   if (ValueVT.getVectorNumElements() != 1) {
455      // Certain ABIs require that vectors are passed as integers. For vectors
456      // are the same size, this is an obvious bitcast.
457      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
458        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
459      } else if (ValueVT.bitsLT(PartEVT)) {
460        const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
461        EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
462        // Drop the extra bits.
463        Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
464        return DAG.getBitcast(ValueVT, Val);
465      }
466 
467      diagnosePossiblyInvalidConstraint(
468          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
469      return DAG.getUNDEF(ValueVT);
470   }
471 
472   // Handle cases such as i8 -> <1 x i1>
473   EVT ValueSVT = ValueVT.getVectorElementType();
474   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
475     unsigned ValueSize = ValueSVT.getSizeInBits();
476     if (ValueSize == PartEVT.getSizeInBits()) {
477       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
478     } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) {
479       // It's possible a scalar floating point type gets softened to integer and
480       // then promoted to a larger integer. If PartEVT is the larger integer
481       // we need to truncate it and then bitcast to the FP type.
482       assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types");
483       EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
484       Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
485       Val = DAG.getBitcast(ValueSVT, Val);
486     } else {
487       Val = ValueVT.isFloatingPoint()
488                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
489                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
490     }
491   }
492 
493   return DAG.getBuildVector(ValueVT, DL, Val);
494 }
495 
496 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
497                                  SDValue Val, SDValue *Parts, unsigned NumParts,
498                                  MVT PartVT, const Value *V,
499                                  std::optional<CallingConv::ID> CallConv);
500 
501 /// getCopyToParts - Create a series of nodes that contain the specified value
502 /// split into legal parts.  If the parts contain more bits than Val, then, for
503 /// integers, ExtendKind can be used to specify how to generate the extra bits.
504 static void
505 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
506                unsigned NumParts, MVT PartVT, const Value *V,
507                std::optional<CallingConv::ID> CallConv = std::nullopt,
508                ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
509   // Let the target split the parts if it wants to
510   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
511   if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
512                                       CallConv))
513     return;
514   EVT ValueVT = Val.getValueType();
515 
516   // Handle the vector case separately.
517   if (ValueVT.isVector())
518     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
519                                 CallConv);
520 
521   unsigned OrigNumParts = NumParts;
522   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
523          "Copying to an illegal type!");
524 
525   if (NumParts == 0)
526     return;
527 
528   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
529   EVT PartEVT = PartVT;
530   if (PartEVT == ValueVT) {
531     assert(NumParts == 1 && "No-op copy with multiple parts!");
532     Parts[0] = Val;
533     return;
534   }
535 
536   unsigned PartBits = PartVT.getSizeInBits();
537   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
538     // If the parts cover more bits than the value has, promote the value.
539     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
540       assert(NumParts == 1 && "Do not know what to promote to!");
541       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
542     } else {
543       if (ValueVT.isFloatingPoint()) {
544         // FP values need to be bitcast, then extended if they are being put
545         // into a larger container.
546         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
547         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
548       }
549       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
550              ValueVT.isInteger() &&
551              "Unknown mismatch!");
552       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
553       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
554       if (PartVT == MVT::x86mmx)
555         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
556     }
557   } else if (PartBits == ValueVT.getSizeInBits()) {
558     // Different types of the same size.
559     assert(NumParts == 1 && PartEVT != ValueVT);
560     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
561   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
562     // If the parts cover less bits than value has, truncate the value.
563     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
564            ValueVT.isInteger() &&
565            "Unknown mismatch!");
566     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
567     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
568     if (PartVT == MVT::x86mmx)
569       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
570   }
571 
572   // The value may have changed - recompute ValueVT.
573   ValueVT = Val.getValueType();
574   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
575          "Failed to tile the value with PartVT!");
576 
577   if (NumParts == 1) {
578     if (PartEVT != ValueVT) {
579       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
580                                         "scalar-to-vector conversion failed");
581       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
582     }
583 
584     Parts[0] = Val;
585     return;
586   }
587 
588   // Expand the value into multiple parts.
589   if (NumParts & (NumParts - 1)) {
590     // The number of parts is not a power of 2.  Split off and copy the tail.
591     assert(PartVT.isInteger() && ValueVT.isInteger() &&
592            "Do not know what to expand to!");
593     unsigned RoundParts = llvm::bit_floor(NumParts);
594     unsigned RoundBits = RoundParts * PartBits;
595     unsigned OddParts = NumParts - RoundParts;
596     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
597       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL));
598 
599     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
600                    CallConv);
601 
602     if (DAG.getDataLayout().isBigEndian())
603       // The odd parts were reversed by getCopyToParts - unreverse them.
604       std::reverse(Parts + RoundParts, Parts + NumParts);
605 
606     NumParts = RoundParts;
607     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
608     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
609   }
610 
611   // The number of parts is a power of 2.  Repeatedly bisect the value using
612   // EXTRACT_ELEMENT.
613   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
614                          EVT::getIntegerVT(*DAG.getContext(),
615                                            ValueVT.getSizeInBits()),
616                          Val);
617 
618   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
619     for (unsigned i = 0; i < NumParts; i += StepSize) {
620       unsigned ThisBits = StepSize * PartBits / 2;
621       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
622       SDValue &Part0 = Parts[i];
623       SDValue &Part1 = Parts[i+StepSize/2];
624 
625       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
626                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
627       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
628                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
629 
630       if (ThisBits == PartBits && ThisVT != PartVT) {
631         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
632         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
633       }
634     }
635   }
636 
637   if (DAG.getDataLayout().isBigEndian())
638     std::reverse(Parts, Parts + OrigNumParts);
639 }
640 
641 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val,
642                                      const SDLoc &DL, EVT PartVT) {
643   if (!PartVT.isVector())
644     return SDValue();
645 
646   EVT ValueVT = Val.getValueType();
647   EVT PartEVT = PartVT.getVectorElementType();
648   EVT ValueEVT = ValueVT.getVectorElementType();
649   ElementCount PartNumElts = PartVT.getVectorElementCount();
650   ElementCount ValueNumElts = ValueVT.getVectorElementCount();
651 
652   // We only support widening vectors with equivalent element types and
653   // fixed/scalable properties. If a target needs to widen a fixed-length type
654   // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
655   if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
656       PartNumElts.isScalable() != ValueNumElts.isScalable())
657     return SDValue();
658 
659   // Have a try for bf16 because some targets share its ABI with fp16.
660   if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) {
661     assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
662            "Cannot widen to illegal type");
663     Val = DAG.getNode(ISD::BITCAST, DL,
664                       ValueVT.changeVectorElementType(MVT::f16), Val);
665   } else if (PartEVT != ValueEVT) {
666     return SDValue();
667   }
668 
669   // Widening a scalable vector to another scalable vector is done by inserting
670   // the vector into a larger undef one.
671   if (PartNumElts.isScalable())
672     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
673                        Val, DAG.getVectorIdxConstant(0, DL));
674 
675   // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
676   // undef elements.
677   SmallVector<SDValue, 16> Ops;
678   DAG.ExtractVectorElements(Val, Ops);
679   SDValue EltUndef = DAG.getUNDEF(PartEVT);
680   Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
681 
682   // FIXME: Use CONCAT for 2x -> 4x.
683   return DAG.getBuildVector(PartVT, DL, Ops);
684 }
685 
686 /// getCopyToPartsVector - Create a series of nodes that contain the specified
687 /// value split into legal parts.
688 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
689                                  SDValue Val, SDValue *Parts, unsigned NumParts,
690                                  MVT PartVT, const Value *V,
691                                  std::optional<CallingConv::ID> CallConv) {
692   EVT ValueVT = Val.getValueType();
693   assert(ValueVT.isVector() && "Not a vector");
694   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
695   const bool IsABIRegCopy = CallConv.has_value();
696 
697   if (NumParts == 1) {
698     EVT PartEVT = PartVT;
699     if (PartEVT == ValueVT) {
700       // Nothing to do.
701     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
702       // Bitconvert vector->vector case.
703       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
704     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
705       Val = Widened;
706     } else if (PartVT.isVector() &&
707                PartEVT.getVectorElementType().bitsGE(
708                    ValueVT.getVectorElementType()) &&
709                PartEVT.getVectorElementCount() ==
710                    ValueVT.getVectorElementCount()) {
711 
712       // Promoted vector extract
713       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
714     } else if (PartEVT.isVector() &&
715                PartEVT.getVectorElementType() !=
716                    ValueVT.getVectorElementType() &&
717                TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
718                    TargetLowering::TypeWidenVector) {
719       // Combination of widening and promotion.
720       EVT WidenVT =
721           EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(),
722                            PartVT.getVectorElementCount());
723       SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
724       Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
725     } else {
726       // Don't extract an integer from a float vector. This can happen if the
727       // FP type gets softened to integer and then promoted. The promotion
728       // prevents it from being picked up by the earlier bitcast case.
729       if (ValueVT.getVectorElementCount().isScalar() &&
730           (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) {
731         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
732                           DAG.getVectorIdxConstant(0, DL));
733       } else {
734         uint64_t ValueSize = ValueVT.getFixedSizeInBits();
735         assert(PartVT.getFixedSizeInBits() > ValueSize &&
736                "lossy conversion of vector to scalar type");
737         EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
738         Val = DAG.getBitcast(IntermediateType, Val);
739         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
740       }
741     }
742 
743     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
744     Parts[0] = Val;
745     return;
746   }
747 
748   // Handle a multi-element vector.
749   EVT IntermediateVT;
750   MVT RegisterVT;
751   unsigned NumIntermediates;
752   unsigned NumRegs;
753   if (IsABIRegCopy) {
754     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
755         *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates,
756         RegisterVT);
757   } else {
758     NumRegs =
759         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
760                                    NumIntermediates, RegisterVT);
761   }
762 
763   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
764   NumParts = NumRegs; // Silence a compiler warning.
765   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
766 
767   assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
768          "Mixing scalable and fixed vectors when copying in parts");
769 
770   std::optional<ElementCount> DestEltCnt;
771 
772   if (IntermediateVT.isVector())
773     DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
774   else
775     DestEltCnt = ElementCount::getFixed(NumIntermediates);
776 
777   EVT BuiltVectorTy = EVT::getVectorVT(
778       *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt);
779 
780   if (ValueVT == BuiltVectorTy) {
781     // Nothing to do.
782   } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
783     // Bitconvert vector->vector case.
784     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
785   } else {
786     if (BuiltVectorTy.getVectorElementType().bitsGT(
787             ValueVT.getVectorElementType())) {
788       // Integer promotion.
789       ValueVT = EVT::getVectorVT(*DAG.getContext(),
790                                  BuiltVectorTy.getVectorElementType(),
791                                  ValueVT.getVectorElementCount());
792       Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
793     }
794 
795     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
796       Val = Widened;
797     }
798   }
799 
800   assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
801 
802   // Split the vector into intermediate operands.
803   SmallVector<SDValue, 8> Ops(NumIntermediates);
804   for (unsigned i = 0; i != NumIntermediates; ++i) {
805     if (IntermediateVT.isVector()) {
806       // This does something sensible for scalable vectors - see the
807       // definition of EXTRACT_SUBVECTOR for further details.
808       unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
809       Ops[i] =
810           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
811                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
812     } else {
813       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
814                            DAG.getVectorIdxConstant(i, DL));
815     }
816   }
817 
818   // Split the intermediate operands into legal parts.
819   if (NumParts == NumIntermediates) {
820     // If the register was not expanded, promote or copy the value,
821     // as appropriate.
822     for (unsigned i = 0; i != NumParts; ++i)
823       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
824   } else if (NumParts > 0) {
825     // If the intermediate type was expanded, split each the value into
826     // legal parts.
827     assert(NumIntermediates != 0 && "division by zero");
828     assert(NumParts % NumIntermediates == 0 &&
829            "Must expand into a divisible number of parts!");
830     unsigned Factor = NumParts / NumIntermediates;
831     for (unsigned i = 0; i != NumIntermediates; ++i)
832       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
833                      CallConv);
834   }
835 }
836 
837 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
838                            EVT valuevt, std::optional<CallingConv::ID> CC)
839     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
840       RegCount(1, regs.size()), CallConv(CC) {}
841 
842 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
843                            const DataLayout &DL, unsigned Reg, Type *Ty,
844                            std::optional<CallingConv::ID> CC) {
845   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
846 
847   CallConv = CC;
848 
849   for (EVT ValueVT : ValueVTs) {
850     unsigned NumRegs =
851         isABIMangled()
852             ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT)
853             : TLI.getNumRegisters(Context, ValueVT);
854     MVT RegisterVT =
855         isABIMangled()
856             ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT)
857             : TLI.getRegisterType(Context, ValueVT);
858     for (unsigned i = 0; i != NumRegs; ++i)
859       Regs.push_back(Reg + i);
860     RegVTs.push_back(RegisterVT);
861     RegCount.push_back(NumRegs);
862     Reg += NumRegs;
863   }
864 }
865 
866 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
867                                       FunctionLoweringInfo &FuncInfo,
868                                       const SDLoc &dl, SDValue &Chain,
869                                       SDValue *Glue, const Value *V) const {
870   // A Value with type {} or [0 x %t] needs no registers.
871   if (ValueVTs.empty())
872     return SDValue();
873 
874   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
875 
876   // Assemble the legal parts into the final values.
877   SmallVector<SDValue, 4> Values(ValueVTs.size());
878   SmallVector<SDValue, 8> Parts;
879   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
880     // Copy the legal parts from the registers.
881     EVT ValueVT = ValueVTs[Value];
882     unsigned NumRegs = RegCount[Value];
883     MVT RegisterVT = isABIMangled()
884                          ? TLI.getRegisterTypeForCallingConv(
885                                *DAG.getContext(), *CallConv, RegVTs[Value])
886                          : RegVTs[Value];
887 
888     Parts.resize(NumRegs);
889     for (unsigned i = 0; i != NumRegs; ++i) {
890       SDValue P;
891       if (!Glue) {
892         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
893       } else {
894         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue);
895         *Glue = P.getValue(2);
896       }
897 
898       Chain = P.getValue(1);
899       Parts[i] = P;
900 
901       // If the source register was virtual and if we know something about it,
902       // add an assert node.
903       if (!Register::isVirtualRegister(Regs[Part + i]) ||
904           !RegisterVT.isInteger())
905         continue;
906 
907       const FunctionLoweringInfo::LiveOutInfo *LOI =
908         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
909       if (!LOI)
910         continue;
911 
912       unsigned RegSize = RegisterVT.getScalarSizeInBits();
913       unsigned NumSignBits = LOI->NumSignBits;
914       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
915 
916       if (NumZeroBits == RegSize) {
917         // The current value is a zero.
918         // Explicitly express that as it would be easier for
919         // optimizations to kick in.
920         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
921         continue;
922       }
923 
924       // FIXME: We capture more information than the dag can represent.  For
925       // now, just use the tightest assertzext/assertsext possible.
926       bool isSExt;
927       EVT FromVT(MVT::Other);
928       if (NumZeroBits) {
929         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
930         isSExt = false;
931       } else if (NumSignBits > 1) {
932         FromVT =
933             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
934         isSExt = true;
935       } else {
936         continue;
937       }
938       // Add an assertion node.
939       assert(FromVT != MVT::Other);
940       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
941                              RegisterVT, P, DAG.getValueType(FromVT));
942     }
943 
944     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
945                                      RegisterVT, ValueVT, V, Chain, CallConv);
946     Part += NumRegs;
947     Parts.clear();
948   }
949 
950   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
951 }
952 
953 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
954                                  const SDLoc &dl, SDValue &Chain, SDValue *Glue,
955                                  const Value *V,
956                                  ISD::NodeType PreferredExtendType) const {
957   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
958   ISD::NodeType ExtendKind = PreferredExtendType;
959 
960   // Get the list of the values's legal parts.
961   unsigned NumRegs = Regs.size();
962   SmallVector<SDValue, 8> Parts(NumRegs);
963   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
964     unsigned NumParts = RegCount[Value];
965 
966     MVT RegisterVT = isABIMangled()
967                          ? TLI.getRegisterTypeForCallingConv(
968                                *DAG.getContext(), *CallConv, RegVTs[Value])
969                          : RegVTs[Value];
970 
971     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
972       ExtendKind = ISD::ZERO_EXTEND;
973 
974     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
975                    NumParts, RegisterVT, V, CallConv, ExtendKind);
976     Part += NumParts;
977   }
978 
979   // Copy the parts into the registers.
980   SmallVector<SDValue, 8> Chains(NumRegs);
981   for (unsigned i = 0; i != NumRegs; ++i) {
982     SDValue Part;
983     if (!Glue) {
984       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
985     } else {
986       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue);
987       *Glue = Part.getValue(1);
988     }
989 
990     Chains[i] = Part.getValue(0);
991   }
992 
993   if (NumRegs == 1 || Glue)
994     // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is
995     // flagged to it. That is the CopyToReg nodes and the user are considered
996     // a single scheduling unit. If we create a TokenFactor and return it as
997     // chain, then the TokenFactor is both a predecessor (operand) of the
998     // user as well as a successor (the TF operands are flagged to the user).
999     // c1, f1 = CopyToReg
1000     // c2, f2 = CopyToReg
1001     // c3     = TokenFactor c1, c2
1002     // ...
1003     //        = op c3, ..., f2
1004     Chain = Chains[NumRegs-1];
1005   else
1006     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
1007 }
1008 
1009 void RegsForValue::AddInlineAsmOperands(InlineAsm::Kind Code, bool HasMatching,
1010                                         unsigned MatchingIdx, const SDLoc &dl,
1011                                         SelectionDAG &DAG,
1012                                         std::vector<SDValue> &Ops) const {
1013   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1014 
1015   InlineAsm::Flag Flag(Code, Regs.size());
1016   if (HasMatching)
1017     Flag.setMatchingOp(MatchingIdx);
1018   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
1019     // Put the register class of the virtual registers in the flag word.  That
1020     // way, later passes can recompute register class constraints for inline
1021     // assembly as well as normal instructions.
1022     // Don't do this for tied operands that can use the regclass information
1023     // from the def.
1024     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1025     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
1026     Flag.setRegClass(RC->getID());
1027   }
1028 
1029   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
1030   Ops.push_back(Res);
1031 
1032   if (Code == InlineAsm::Kind::Clobber) {
1033     // Clobbers should always have a 1:1 mapping with registers, and may
1034     // reference registers that have illegal (e.g. vector) types. Hence, we
1035     // shouldn't try to apply any sort of splitting logic to them.
1036     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
1037            "No 1:1 mapping from clobbers to regs?");
1038     Register SP = TLI.getStackPointerRegisterToSaveRestore();
1039     (void)SP;
1040     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
1041       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
1042       assert(
1043           (Regs[I] != SP ||
1044            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
1045           "If we clobbered the stack pointer, MFI should know about it.");
1046     }
1047     return;
1048   }
1049 
1050   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1051     MVT RegisterVT = RegVTs[Value];
1052     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
1053                                            RegisterVT);
1054     for (unsigned i = 0; i != NumRegs; ++i) {
1055       assert(Reg < Regs.size() && "Mismatch in # registers expected");
1056       unsigned TheReg = Regs[Reg++];
1057       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1058     }
1059   }
1060 }
1061 
1062 SmallVector<std::pair<unsigned, TypeSize>, 4>
1063 RegsForValue::getRegsAndSizes() const {
1064   SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec;
1065   unsigned I = 0;
1066   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1067     unsigned RegCount = std::get<0>(CountAndVT);
1068     MVT RegisterVT = std::get<1>(CountAndVT);
1069     TypeSize RegisterSize = RegisterVT.getSizeInBits();
1070     for (unsigned E = I + RegCount; I != E; ++I)
1071       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1072   }
1073   return OutVec;
1074 }
1075 
1076 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1077                                AssumptionCache *ac,
1078                                const TargetLibraryInfo *li) {
1079   AA = aa;
1080   AC = ac;
1081   GFI = gfi;
1082   LibInfo = li;
1083   Context = DAG.getContext();
1084   LPadToCallSiteMap.clear();
1085   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1086   AssignmentTrackingEnabled = isAssignmentTrackingEnabled(
1087       *DAG.getMachineFunction().getFunction().getParent());
1088 }
1089 
1090 void SelectionDAGBuilder::clear() {
1091   NodeMap.clear();
1092   UnusedArgNodeMap.clear();
1093   PendingLoads.clear();
1094   PendingExports.clear();
1095   PendingConstrainedFP.clear();
1096   PendingConstrainedFPStrict.clear();
1097   CurInst = nullptr;
1098   HasTailCall = false;
1099   SDNodeOrder = LowestSDNodeOrder;
1100   StatepointLowering.clear();
1101 }
1102 
1103 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1104   DanglingDebugInfoMap.clear();
1105 }
1106 
1107 // Update DAG root to include dependencies on Pending chains.
1108 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1109   SDValue Root = DAG.getRoot();
1110 
1111   if (Pending.empty())
1112     return Root;
1113 
1114   // Add current root to PendingChains, unless we already indirectly
1115   // depend on it.
1116   if (Root.getOpcode() != ISD::EntryToken) {
1117     unsigned i = 0, e = Pending.size();
1118     for (; i != e; ++i) {
1119       assert(Pending[i].getNode()->getNumOperands() > 1);
1120       if (Pending[i].getNode()->getOperand(0) == Root)
1121         break;  // Don't add the root if we already indirectly depend on it.
1122     }
1123 
1124     if (i == e)
1125       Pending.push_back(Root);
1126   }
1127 
1128   if (Pending.size() == 1)
1129     Root = Pending[0];
1130   else
1131     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1132 
1133   DAG.setRoot(Root);
1134   Pending.clear();
1135   return Root;
1136 }
1137 
1138 SDValue SelectionDAGBuilder::getMemoryRoot() {
1139   return updateRoot(PendingLoads);
1140 }
1141 
1142 SDValue SelectionDAGBuilder::getRoot() {
1143   // Chain up all pending constrained intrinsics together with all
1144   // pending loads, by simply appending them to PendingLoads and
1145   // then calling getMemoryRoot().
1146   PendingLoads.reserve(PendingLoads.size() +
1147                        PendingConstrainedFP.size() +
1148                        PendingConstrainedFPStrict.size());
1149   PendingLoads.append(PendingConstrainedFP.begin(),
1150                       PendingConstrainedFP.end());
1151   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1152                       PendingConstrainedFPStrict.end());
1153   PendingConstrainedFP.clear();
1154   PendingConstrainedFPStrict.clear();
1155   return getMemoryRoot();
1156 }
1157 
1158 SDValue SelectionDAGBuilder::getControlRoot() {
1159   // We need to emit pending fpexcept.strict constrained intrinsics,
1160   // so append them to the PendingExports list.
1161   PendingExports.append(PendingConstrainedFPStrict.begin(),
1162                         PendingConstrainedFPStrict.end());
1163   PendingConstrainedFPStrict.clear();
1164   return updateRoot(PendingExports);
1165 }
1166 
1167 void SelectionDAGBuilder::handleDebugDeclare(Value *Address,
1168                                              DILocalVariable *Variable,
1169                                              DIExpression *Expression,
1170                                              DebugLoc DL) {
1171   assert(Variable && "Missing variable");
1172 
1173   // Check if address has undef value.
1174   if (!Address || isa<UndefValue>(Address) ||
1175       (Address->use_empty() && !isa<Argument>(Address))) {
1176     LLVM_DEBUG(
1177         dbgs()
1178         << "dbg_declare: Dropping debug info (bad/undef/unused-arg address)\n");
1179     return;
1180   }
1181 
1182   bool IsParameter = Variable->isParameter() || isa<Argument>(Address);
1183 
1184   SDValue &N = NodeMap[Address];
1185   if (!N.getNode() && isa<Argument>(Address))
1186     // Check unused arguments map.
1187     N = UnusedArgNodeMap[Address];
1188   SDDbgValue *SDV;
1189   if (N.getNode()) {
1190     if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
1191       Address = BCI->getOperand(0);
1192     // Parameters are handled specially.
1193     auto *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
1194     if (IsParameter && FINode) {
1195       // Byval parameter. We have a frame index at this point.
1196       SDV = DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
1197                                       /*IsIndirect*/ true, DL, SDNodeOrder);
1198     } else if (isa<Argument>(Address)) {
1199       // Address is an argument, so try to emit its dbg value using
1200       // virtual register info from the FuncInfo.ValueMap.
1201       EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1202                                FuncArgumentDbgValueKind::Declare, N);
1203       return;
1204     } else {
1205       SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
1206                             true, DL, SDNodeOrder);
1207     }
1208     DAG.AddDbgValue(SDV, IsParameter);
1209   } else {
1210     // If Address is an argument then try to emit its dbg value using
1211     // virtual register info from the FuncInfo.ValueMap.
1212     if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1213                                   FuncArgumentDbgValueKind::Declare, N)) {
1214       LLVM_DEBUG(dbgs() << "dbg_declare: Dropping debug info"
1215                         << " (could not emit func-arg dbg_value)\n");
1216     }
1217   }
1218   return;
1219 }
1220 
1221 void SelectionDAGBuilder::visitDbgInfo(const Instruction &I) {
1222   // Add SDDbgValue nodes for any var locs here. Do so before updating
1223   // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1224   if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) {
1225     // Add SDDbgValue nodes for any var locs here. Do so before updating
1226     // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1227     for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I);
1228          It != End; ++It) {
1229       auto *Var = FnVarLocs->getDILocalVariable(It->VariableID);
1230       dropDanglingDebugInfo(Var, It->Expr);
1231       if (It->Values.isKillLocation(It->Expr)) {
1232         handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder);
1233         continue;
1234       }
1235       SmallVector<Value *> Values(It->Values.location_ops());
1236       if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder,
1237                             It->Values.hasArgList())) {
1238         SmallVector<Value *, 4> Vals;
1239         for (Value *V : It->Values.location_ops())
1240           Vals.push_back(V);
1241         addDanglingDebugInfo(Vals,
1242                              FnVarLocs->getDILocalVariable(It->VariableID),
1243                              It->Expr, Vals.size() > 1, It->DL, SDNodeOrder);
1244       }
1245     }
1246   }
1247 
1248   // We must skip DPValues if they've already been processed above as we
1249   // have just emitted the debug values resulting from assignment tracking
1250   // analysis, making any existing DPValues redundant (and probably less
1251   // correct). We still need to process DPLabels. This does sink DPLabels
1252   // to the bottom of the group of debug records. That sholdn't be important
1253   // as it does so deterministcally and ordering between DPLabels and DPValues
1254   // is immaterial (other than for MIR/IR printing).
1255   bool SkipDPValues = DAG.getFunctionVarLocs();
1256   // Is there is any debug-info attached to this instruction, in the form of
1257   // DbgRecord non-instruction debug-info records.
1258   for (DbgRecord &DR : I.getDbgValueRange()) {
1259     if (DPLabel *DPL = dyn_cast<DPLabel>(&DR)) {
1260       assert(DPL->getLabel() && "Missing label");
1261       SDDbgLabel *SDV =
1262           DAG.getDbgLabel(DPL->getLabel(), DPL->getDebugLoc(), SDNodeOrder);
1263       DAG.AddDbgLabel(SDV);
1264       continue;
1265     }
1266 
1267     if (SkipDPValues)
1268       continue;
1269     DPValue &DPV = cast<DPValue>(DR);
1270     DILocalVariable *Variable = DPV.getVariable();
1271     DIExpression *Expression = DPV.getExpression();
1272     dropDanglingDebugInfo(Variable, Expression);
1273 
1274     if (DPV.getType() == DPValue::LocationType::Declare) {
1275       if (FuncInfo.PreprocessedDPVDeclares.contains(&DPV))
1276         continue;
1277       LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DPV
1278                         << "\n");
1279       handleDebugDeclare(DPV.getVariableLocationOp(0), Variable, Expression,
1280                          DPV.getDebugLoc());
1281       continue;
1282     }
1283 
1284     // A DPValue with no locations is a kill location.
1285     SmallVector<Value *, 4> Values(DPV.location_ops());
1286     if (Values.empty()) {
1287       handleKillDebugValue(Variable, Expression, DPV.getDebugLoc(),
1288                            SDNodeOrder);
1289       continue;
1290     }
1291 
1292     // A DPValue with an undef or absent location is also a kill location.
1293     if (llvm::any_of(Values,
1294                      [](Value *V) { return !V || isa<UndefValue>(V); })) {
1295       handleKillDebugValue(Variable, Expression, DPV.getDebugLoc(),
1296                            SDNodeOrder);
1297       continue;
1298     }
1299 
1300     bool IsVariadic = DPV.hasArgList();
1301     if (!handleDebugValue(Values, Variable, Expression, DPV.getDebugLoc(),
1302                           SDNodeOrder, IsVariadic)) {
1303       addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
1304                            DPV.getDebugLoc(), SDNodeOrder);
1305     }
1306   }
1307 }
1308 
1309 void SelectionDAGBuilder::visit(const Instruction &I) {
1310   visitDbgInfo(I);
1311 
1312   // Set up outgoing PHI node register values before emitting the terminator.
1313   if (I.isTerminator()) {
1314     HandlePHINodesInSuccessorBlocks(I.getParent());
1315   }
1316 
1317   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1318   if (!isa<DbgInfoIntrinsic>(I))
1319     ++SDNodeOrder;
1320 
1321   CurInst = &I;
1322 
1323   // Set inserted listener only if required.
1324   bool NodeInserted = false;
1325   std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener;
1326   MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections);
1327   if (PCSectionsMD) {
1328     InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>(
1329         DAG, [&](SDNode *) { NodeInserted = true; });
1330   }
1331 
1332   visit(I.getOpcode(), I);
1333 
1334   if (!I.isTerminator() && !HasTailCall &&
1335       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1336     CopyToExportRegsIfNeeded(&I);
1337 
1338   // Handle metadata.
1339   if (PCSectionsMD) {
1340     auto It = NodeMap.find(&I);
1341     if (It != NodeMap.end()) {
1342       DAG.addPCSections(It->second.getNode(), PCSectionsMD);
1343     } else if (NodeInserted) {
1344       // This should not happen; if it does, don't let it go unnoticed so we can
1345       // fix it. Relevant visit*() function is probably missing a setValue().
1346       errs() << "warning: loosing !pcsections metadata ["
1347              << I.getModule()->getName() << "]\n";
1348       LLVM_DEBUG(I.dump());
1349       assert(false);
1350     }
1351   }
1352 
1353   CurInst = nullptr;
1354 }
1355 
1356 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1357   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1358 }
1359 
1360 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1361   // Note: this doesn't use InstVisitor, because it has to work with
1362   // ConstantExpr's in addition to instructions.
1363   switch (Opcode) {
1364   default: llvm_unreachable("Unknown instruction type encountered!");
1365     // Build the switch statement using the Instruction.def file.
1366 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1367     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1368 #include "llvm/IR/Instruction.def"
1369   }
1370 }
1371 
1372 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG,
1373                                             DILocalVariable *Variable,
1374                                             DebugLoc DL, unsigned Order,
1375                                             SmallVectorImpl<Value *> &Values,
1376                                             DIExpression *Expression) {
1377   // For variadic dbg_values we will now insert an undef.
1378   // FIXME: We can potentially recover these!
1379   SmallVector<SDDbgOperand, 2> Locs;
1380   for (const Value *V : Values) {
1381     auto *Undef = UndefValue::get(V->getType());
1382     Locs.push_back(SDDbgOperand::fromConst(Undef));
1383   }
1384   SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {},
1385                                         /*IsIndirect=*/false, DL, Order,
1386                                         /*IsVariadic=*/true);
1387   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1388   return true;
1389 }
1390 
1391 void SelectionDAGBuilder::addDanglingDebugInfo(SmallVectorImpl<Value *> &Values,
1392                                                DILocalVariable *Var,
1393                                                DIExpression *Expr,
1394                                                bool IsVariadic, DebugLoc DL,
1395                                                unsigned Order) {
1396   if (IsVariadic) {
1397     handleDanglingVariadicDebugInfo(DAG, Var, DL, Order, Values, Expr);
1398     return;
1399   }
1400   // TODO: Dangling debug info will eventually either be resolved or produce
1401   // an Undef DBG_VALUE. However in the resolution case, a gap may appear
1402   // between the original dbg.value location and its resolved DBG_VALUE,
1403   // which we should ideally fill with an extra Undef DBG_VALUE.
1404   assert(Values.size() == 1);
1405   DanglingDebugInfoMap[Values[0]].emplace_back(Var, Expr, DL, Order);
1406 }
1407 
1408 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1409                                                 const DIExpression *Expr) {
1410   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1411     DIVariable *DanglingVariable = DDI.getVariable();
1412     DIExpression *DanglingExpr = DDI.getExpression();
1413     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1414       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for "
1415                         << printDDI(nullptr, DDI) << "\n");
1416       return true;
1417     }
1418     return false;
1419   };
1420 
1421   for (auto &DDIMI : DanglingDebugInfoMap) {
1422     DanglingDebugInfoVector &DDIV = DDIMI.second;
1423 
1424     // If debug info is to be dropped, run it through final checks to see
1425     // whether it can be salvaged.
1426     for (auto &DDI : DDIV)
1427       if (isMatchingDbgValue(DDI))
1428         salvageUnresolvedDbgValue(DDIMI.first, DDI);
1429 
1430     erase_if(DDIV, isMatchingDbgValue);
1431   }
1432 }
1433 
1434 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1435 // generate the debug data structures now that we've seen its definition.
1436 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1437                                                    SDValue Val) {
1438   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1439   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1440     return;
1441 
1442   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1443   for (auto &DDI : DDIV) {
1444     DebugLoc DL = DDI.getDebugLoc();
1445     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1446     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1447     DILocalVariable *Variable = DDI.getVariable();
1448     DIExpression *Expr = DDI.getExpression();
1449     assert(Variable->isValidLocationForIntrinsic(DL) &&
1450            "Expected inlined-at fields to agree");
1451     SDDbgValue *SDV;
1452     if (Val.getNode()) {
1453       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1454       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1455       // we couldn't resolve it directly when examining the DbgValue intrinsic
1456       // in the first place we should not be more successful here). Unless we
1457       // have some test case that prove this to be correct we should avoid
1458       // calling EmitFuncArgumentDbgValue here.
1459       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL,
1460                                     FuncArgumentDbgValueKind::Value, Val)) {
1461         LLVM_DEBUG(dbgs() << "Resolve dangling debug info for "
1462                           << printDDI(V, DDI) << "\n");
1463         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1464         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1465         // inserted after the definition of Val when emitting the instructions
1466         // after ISel. An alternative could be to teach
1467         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1468         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1469                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1470                    << ValSDNodeOrder << "\n");
1471         SDV = getDbgValue(Val, Variable, Expr, DL,
1472                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1473         DAG.AddDbgValue(SDV, false);
1474       } else
1475         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for "
1476                           << printDDI(V, DDI)
1477                           << " in EmitFuncArgumentDbgValue\n");
1478     } else {
1479       LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(V, DDI)
1480                         << "\n");
1481       auto Undef = UndefValue::get(V->getType());
1482       auto SDV =
1483           DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder);
1484       DAG.AddDbgValue(SDV, false);
1485     }
1486   }
1487   DDIV.clear();
1488 }
1489 
1490 void SelectionDAGBuilder::salvageUnresolvedDbgValue(const Value *V,
1491                                                     DanglingDebugInfo &DDI) {
1492   // TODO: For the variadic implementation, instead of only checking the fail
1493   // state of `handleDebugValue`, we need know specifically which values were
1494   // invalid, so that we attempt to salvage only those values when processing
1495   // a DIArgList.
1496   const Value *OrigV = V;
1497   DILocalVariable *Var = DDI.getVariable();
1498   DIExpression *Expr = DDI.getExpression();
1499   DebugLoc DL = DDI.getDebugLoc();
1500   unsigned SDOrder = DDI.getSDNodeOrder();
1501 
1502   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1503   // that DW_OP_stack_value is desired.
1504   bool StackValue = true;
1505 
1506   // Can this Value can be encoded without any further work?
1507   if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false))
1508     return;
1509 
1510   // Attempt to salvage back through as many instructions as possible. Bail if
1511   // a non-instruction is seen, such as a constant expression or global
1512   // variable. FIXME: Further work could recover those too.
1513   while (isa<Instruction>(V)) {
1514     const Instruction &VAsInst = *cast<const Instruction>(V);
1515     // Temporary "0", awaiting real implementation.
1516     SmallVector<uint64_t, 16> Ops;
1517     SmallVector<Value *, 4> AdditionalValues;
1518     V = salvageDebugInfoImpl(const_cast<Instruction &>(VAsInst),
1519                              Expr->getNumLocationOperands(), Ops,
1520                              AdditionalValues);
1521     // If we cannot salvage any further, and haven't yet found a suitable debug
1522     // expression, bail out.
1523     if (!V)
1524       break;
1525 
1526     // TODO: If AdditionalValues isn't empty, then the salvage can only be
1527     // represented with a DBG_VALUE_LIST, so we give up. When we have support
1528     // here for variadic dbg_values, remove that condition.
1529     if (!AdditionalValues.empty())
1530       break;
1531 
1532     // New value and expr now represent this debuginfo.
1533     Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue);
1534 
1535     // Some kind of simplification occurred: check whether the operand of the
1536     // salvaged debug expression can be encoded in this DAG.
1537     if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) {
1538       LLVM_DEBUG(
1539           dbgs() << "Salvaged debug location info for:\n  " << *Var << "\n"
1540                  << *OrigV << "\nBy stripping back to:\n  " << *V << "\n");
1541       return;
1542     }
1543   }
1544 
1545   // This was the final opportunity to salvage this debug information, and it
1546   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1547   // any earlier variable location.
1548   assert(OrigV && "V shouldn't be null");
1549   auto *Undef = UndefValue::get(OrigV->getType());
1550   auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1551   DAG.AddDbgValue(SDV, false);
1552   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  "
1553                     << printDDI(OrigV, DDI) << "\n");
1554 }
1555 
1556 void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var,
1557                                                DIExpression *Expr,
1558                                                DebugLoc DbgLoc,
1559                                                unsigned Order) {
1560   Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context));
1561   DIExpression *NewExpr =
1562       const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr));
1563   handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order,
1564                    /*IsVariadic*/ false);
1565 }
1566 
1567 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1568                                            DILocalVariable *Var,
1569                                            DIExpression *Expr, DebugLoc DbgLoc,
1570                                            unsigned Order, bool IsVariadic) {
1571   if (Values.empty())
1572     return true;
1573 
1574   // Filter EntryValue locations out early.
1575   if (visitEntryValueDbgValue(Values, Var, Expr, DbgLoc))
1576     return true;
1577 
1578   SmallVector<SDDbgOperand> LocationOps;
1579   SmallVector<SDNode *> Dependencies;
1580   for (const Value *V : Values) {
1581     // Constant value.
1582     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1583         isa<ConstantPointerNull>(V)) {
1584       LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1585       continue;
1586     }
1587 
1588     // Look through IntToPtr constants.
1589     if (auto *CE = dyn_cast<ConstantExpr>(V))
1590       if (CE->getOpcode() == Instruction::IntToPtr) {
1591         LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0)));
1592         continue;
1593       }
1594 
1595     // If the Value is a frame index, we can create a FrameIndex debug value
1596     // without relying on the DAG at all.
1597     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1598       auto SI = FuncInfo.StaticAllocaMap.find(AI);
1599       if (SI != FuncInfo.StaticAllocaMap.end()) {
1600         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1601         continue;
1602       }
1603     }
1604 
1605     // Do not use getValue() in here; we don't want to generate code at
1606     // this point if it hasn't been done yet.
1607     SDValue N = NodeMap[V];
1608     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1609       N = UnusedArgNodeMap[V];
1610     if (N.getNode()) {
1611       // Only emit func arg dbg value for non-variadic dbg.values for now.
1612       if (!IsVariadic &&
1613           EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc,
1614                                    FuncArgumentDbgValueKind::Value, N))
1615         return true;
1616       if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1617         // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1618         // describe stack slot locations.
1619         //
1620         // Consider "int x = 0; int *px = &x;". There are two kinds of
1621         // interesting debug values here after optimization:
1622         //
1623         //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
1624         //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1625         //
1626         // Both describe the direct values of their associated variables.
1627         Dependencies.push_back(N.getNode());
1628         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1629         continue;
1630       }
1631       LocationOps.emplace_back(
1632           SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1633       continue;
1634     }
1635 
1636     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1637     // Special rules apply for the first dbg.values of parameter variables in a
1638     // function. Identify them by the fact they reference Argument Values, that
1639     // they're parameters, and they are parameters of the current function. We
1640     // need to let them dangle until they get an SDNode.
1641     bool IsParamOfFunc =
1642         isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt();
1643     if (IsParamOfFunc)
1644       return false;
1645 
1646     // The value is not used in this block yet (or it would have an SDNode).
1647     // We still want the value to appear for the user if possible -- if it has
1648     // an associated VReg, we can refer to that instead.
1649     auto VMI = FuncInfo.ValueMap.find(V);
1650     if (VMI != FuncInfo.ValueMap.end()) {
1651       unsigned Reg = VMI->second;
1652       // If this is a PHI node, it may be split up into several MI PHI nodes
1653       // (in FunctionLoweringInfo::set).
1654       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1655                        V->getType(), std::nullopt);
1656       if (RFV.occupiesMultipleRegs()) {
1657         // FIXME: We could potentially support variadic dbg_values here.
1658         if (IsVariadic)
1659           return false;
1660         unsigned Offset = 0;
1661         unsigned BitsToDescribe = 0;
1662         if (auto VarSize = Var->getSizeInBits())
1663           BitsToDescribe = *VarSize;
1664         if (auto Fragment = Expr->getFragmentInfo())
1665           BitsToDescribe = Fragment->SizeInBits;
1666         for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1667           // Bail out if all bits are described already.
1668           if (Offset >= BitsToDescribe)
1669             break;
1670           // TODO: handle scalable vectors.
1671           unsigned RegisterSize = RegAndSize.second;
1672           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1673                                       ? BitsToDescribe - Offset
1674                                       : RegisterSize;
1675           auto FragmentExpr = DIExpression::createFragmentExpression(
1676               Expr, Offset, FragmentSize);
1677           if (!FragmentExpr)
1678             continue;
1679           SDDbgValue *SDV = DAG.getVRegDbgValue(
1680               Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, SDNodeOrder);
1681           DAG.AddDbgValue(SDV, false);
1682           Offset += RegisterSize;
1683         }
1684         return true;
1685       }
1686       // We can use simple vreg locations for variadic dbg_values as well.
1687       LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1688       continue;
1689     }
1690     // We failed to create a SDDbgOperand for V.
1691     return false;
1692   }
1693 
1694   // We have created a SDDbgOperand for each Value in Values.
1695   // Should use Order instead of SDNodeOrder?
1696   assert(!LocationOps.empty());
1697   SDDbgValue *SDV = DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1698                                         /*IsIndirect=*/false, DbgLoc,
1699                                         SDNodeOrder, IsVariadic);
1700   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1701   return true;
1702 }
1703 
1704 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1705   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1706   for (auto &Pair : DanglingDebugInfoMap)
1707     for (auto &DDI : Pair.second)
1708       salvageUnresolvedDbgValue(const_cast<Value *>(Pair.first), DDI);
1709   clearDanglingDebugInfo();
1710 }
1711 
1712 /// getCopyFromRegs - If there was virtual register allocated for the value V
1713 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1714 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1715   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1716   SDValue Result;
1717 
1718   if (It != FuncInfo.ValueMap.end()) {
1719     Register InReg = It->second;
1720 
1721     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1722                      DAG.getDataLayout(), InReg, Ty,
1723                      std::nullopt); // This is not an ABI copy.
1724     SDValue Chain = DAG.getEntryNode();
1725     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1726                                  V);
1727     resolveDanglingDebugInfo(V, Result);
1728   }
1729 
1730   return Result;
1731 }
1732 
1733 /// getValue - Return an SDValue for the given Value.
1734 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1735   // If we already have an SDValue for this value, use it. It's important
1736   // to do this first, so that we don't create a CopyFromReg if we already
1737   // have a regular SDValue.
1738   SDValue &N = NodeMap[V];
1739   if (N.getNode()) return N;
1740 
1741   // If there's a virtual register allocated and initialized for this
1742   // value, use it.
1743   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1744     return copyFromReg;
1745 
1746   // Otherwise create a new SDValue and remember it.
1747   SDValue Val = getValueImpl(V);
1748   NodeMap[V] = Val;
1749   resolveDanglingDebugInfo(V, Val);
1750   return Val;
1751 }
1752 
1753 /// getNonRegisterValue - Return an SDValue for the given Value, but
1754 /// don't look in FuncInfo.ValueMap for a virtual register.
1755 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1756   // If we already have an SDValue for this value, use it.
1757   SDValue &N = NodeMap[V];
1758   if (N.getNode()) {
1759     if (isIntOrFPConstant(N)) {
1760       // Remove the debug location from the node as the node is about to be used
1761       // in a location which may differ from the original debug location.  This
1762       // is relevant to Constant and ConstantFP nodes because they can appear
1763       // as constant expressions inside PHI nodes.
1764       N->setDebugLoc(DebugLoc());
1765     }
1766     return N;
1767   }
1768 
1769   // Otherwise create a new SDValue and remember it.
1770   SDValue Val = getValueImpl(V);
1771   NodeMap[V] = Val;
1772   resolveDanglingDebugInfo(V, Val);
1773   return Val;
1774 }
1775 
1776 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1777 /// Create an SDValue for the given value.
1778 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1779   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1780 
1781   if (const Constant *C = dyn_cast<Constant>(V)) {
1782     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1783 
1784     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1785       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1786 
1787     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1788       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1789 
1790     if (isa<ConstantPointerNull>(C)) {
1791       unsigned AS = V->getType()->getPointerAddressSpace();
1792       return DAG.getConstant(0, getCurSDLoc(),
1793                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1794     }
1795 
1796     if (match(C, m_VScale()))
1797       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1798 
1799     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1800       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1801 
1802     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1803       return DAG.getUNDEF(VT);
1804 
1805     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1806       visit(CE->getOpcode(), *CE);
1807       SDValue N1 = NodeMap[V];
1808       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1809       return N1;
1810     }
1811 
1812     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1813       SmallVector<SDValue, 4> Constants;
1814       for (const Use &U : C->operands()) {
1815         SDNode *Val = getValue(U).getNode();
1816         // If the operand is an empty aggregate, there are no values.
1817         if (!Val) continue;
1818         // Add each leaf value from the operand to the Constants list
1819         // to form a flattened list of all the values.
1820         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1821           Constants.push_back(SDValue(Val, i));
1822       }
1823 
1824       return DAG.getMergeValues(Constants, getCurSDLoc());
1825     }
1826 
1827     if (const ConstantDataSequential *CDS =
1828           dyn_cast<ConstantDataSequential>(C)) {
1829       SmallVector<SDValue, 4> Ops;
1830       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1831         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1832         // Add each leaf value from the operand to the Constants list
1833         // to form a flattened list of all the values.
1834         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1835           Ops.push_back(SDValue(Val, i));
1836       }
1837 
1838       if (isa<ArrayType>(CDS->getType()))
1839         return DAG.getMergeValues(Ops, getCurSDLoc());
1840       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1841     }
1842 
1843     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1844       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1845              "Unknown struct or array constant!");
1846 
1847       SmallVector<EVT, 4> ValueVTs;
1848       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1849       unsigned NumElts = ValueVTs.size();
1850       if (NumElts == 0)
1851         return SDValue(); // empty struct
1852       SmallVector<SDValue, 4> Constants(NumElts);
1853       for (unsigned i = 0; i != NumElts; ++i) {
1854         EVT EltVT = ValueVTs[i];
1855         if (isa<UndefValue>(C))
1856           Constants[i] = DAG.getUNDEF(EltVT);
1857         else if (EltVT.isFloatingPoint())
1858           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1859         else
1860           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1861       }
1862 
1863       return DAG.getMergeValues(Constants, getCurSDLoc());
1864     }
1865 
1866     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1867       return DAG.getBlockAddress(BA, VT);
1868 
1869     if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1870       return getValue(Equiv->getGlobalValue());
1871 
1872     if (const auto *NC = dyn_cast<NoCFIValue>(C))
1873       return getValue(NC->getGlobalValue());
1874 
1875     if (VT == MVT::aarch64svcount) {
1876       assert(C->isNullValue() && "Can only zero this target type!");
1877       return DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT,
1878                          DAG.getConstant(0, getCurSDLoc(), MVT::nxv16i1));
1879     }
1880 
1881     VectorType *VecTy = cast<VectorType>(V->getType());
1882 
1883     // Now that we know the number and type of the elements, get that number of
1884     // elements into the Ops array based on what kind of constant it is.
1885     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1886       SmallVector<SDValue, 16> Ops;
1887       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1888       for (unsigned i = 0; i != NumElements; ++i)
1889         Ops.push_back(getValue(CV->getOperand(i)));
1890 
1891       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1892     }
1893 
1894     if (isa<ConstantAggregateZero>(C)) {
1895       EVT EltVT =
1896           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1897 
1898       SDValue Op;
1899       if (EltVT.isFloatingPoint())
1900         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1901       else
1902         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1903 
1904       return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op);
1905     }
1906 
1907     llvm_unreachable("Unknown vector constant");
1908   }
1909 
1910   // If this is a static alloca, generate it as the frameindex instead of
1911   // computation.
1912   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1913     DenseMap<const AllocaInst*, int>::iterator SI =
1914       FuncInfo.StaticAllocaMap.find(AI);
1915     if (SI != FuncInfo.StaticAllocaMap.end())
1916       return DAG.getFrameIndex(
1917           SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType()));
1918   }
1919 
1920   // If this is an instruction which fast-isel has deferred, select it now.
1921   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1922     Register InReg = FuncInfo.InitializeRegForValue(Inst);
1923 
1924     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1925                      Inst->getType(), std::nullopt);
1926     SDValue Chain = DAG.getEntryNode();
1927     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1928   }
1929 
1930   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V))
1931     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1932 
1933   if (const auto *BB = dyn_cast<BasicBlock>(V))
1934     return DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
1935 
1936   llvm_unreachable("Can't get register for value!");
1937 }
1938 
1939 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1940   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1941   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1942   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1943   bool IsSEH = isAsynchronousEHPersonality(Pers);
1944   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1945   if (!IsSEH)
1946     CatchPadMBB->setIsEHScopeEntry();
1947   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1948   if (IsMSVCCXX || IsCoreCLR)
1949     CatchPadMBB->setIsEHFuncletEntry();
1950 }
1951 
1952 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1953   // Update machine-CFG edge.
1954   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1955   FuncInfo.MBB->addSuccessor(TargetMBB);
1956   TargetMBB->setIsEHCatchretTarget(true);
1957   DAG.getMachineFunction().setHasEHCatchret(true);
1958 
1959   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1960   bool IsSEH = isAsynchronousEHPersonality(Pers);
1961   if (IsSEH) {
1962     // If this is not a fall-through branch or optimizations are switched off,
1963     // emit the branch.
1964     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1965         TM.getOptLevel() == CodeGenOptLevel::None)
1966       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1967                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1968     return;
1969   }
1970 
1971   // Figure out the funclet membership for the catchret's successor.
1972   // This will be used by the FuncletLayout pass to determine how to order the
1973   // BB's.
1974   // A 'catchret' returns to the outer scope's color.
1975   Value *ParentPad = I.getCatchSwitchParentPad();
1976   const BasicBlock *SuccessorColor;
1977   if (isa<ConstantTokenNone>(ParentPad))
1978     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1979   else
1980     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1981   assert(SuccessorColor && "No parent funclet for catchret!");
1982   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1983   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1984 
1985   // Create the terminator node.
1986   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1987                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1988                             DAG.getBasicBlock(SuccessorColorMBB));
1989   DAG.setRoot(Ret);
1990 }
1991 
1992 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1993   // Don't emit any special code for the cleanuppad instruction. It just marks
1994   // the start of an EH scope/funclet.
1995   FuncInfo.MBB->setIsEHScopeEntry();
1996   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1997   if (Pers != EHPersonality::Wasm_CXX) {
1998     FuncInfo.MBB->setIsEHFuncletEntry();
1999     FuncInfo.MBB->setIsCleanupFuncletEntry();
2000   }
2001 }
2002 
2003 // In wasm EH, even though a catchpad may not catch an exception if a tag does
2004 // not match, it is OK to add only the first unwind destination catchpad to the
2005 // successors, because there will be at least one invoke instruction within the
2006 // catch scope that points to the next unwind destination, if one exists, so
2007 // CFGSort cannot mess up with BB sorting order.
2008 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
2009 // call within them, and catchpads only consisting of 'catch (...)' have a
2010 // '__cxa_end_catch' call within them, both of which generate invokes in case
2011 // the next unwind destination exists, i.e., the next unwind destination is not
2012 // the caller.)
2013 //
2014 // Having at most one EH pad successor is also simpler and helps later
2015 // transformations.
2016 //
2017 // For example,
2018 // current:
2019 //   invoke void @foo to ... unwind label %catch.dispatch
2020 // catch.dispatch:
2021 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
2022 // catch.start:
2023 //   ...
2024 //   ... in this BB or some other child BB dominated by this BB there will be an
2025 //   invoke that points to 'next' BB as an unwind destination
2026 //
2027 // next: ; We don't need to add this to 'current' BB's successor
2028 //   ...
2029 static void findWasmUnwindDestinations(
2030     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2031     BranchProbability Prob,
2032     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2033         &UnwindDests) {
2034   while (EHPadBB) {
2035     const Instruction *Pad = EHPadBB->getFirstNonPHI();
2036     if (isa<CleanupPadInst>(Pad)) {
2037       // Stop on cleanup pads.
2038       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
2039       UnwindDests.back().first->setIsEHScopeEntry();
2040       break;
2041     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
2042       // Add the catchpad handlers to the possible destinations. We don't
2043       // continue to the unwind destination of the catchswitch for wasm.
2044       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2045         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
2046         UnwindDests.back().first->setIsEHScopeEntry();
2047       }
2048       break;
2049     } else {
2050       continue;
2051     }
2052   }
2053 }
2054 
2055 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
2056 /// many places it could ultimately go. In the IR, we have a single unwind
2057 /// destination, but in the machine CFG, we enumerate all the possible blocks.
2058 /// This function skips over imaginary basic blocks that hold catchswitch
2059 /// instructions, and finds all the "real" machine
2060 /// basic block destinations. As those destinations may not be successors of
2061 /// EHPadBB, here we also calculate the edge probability to those destinations.
2062 /// The passed-in Prob is the edge probability to EHPadBB.
2063 static void findUnwindDestinations(
2064     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2065     BranchProbability Prob,
2066     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2067         &UnwindDests) {
2068   EHPersonality Personality =
2069     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
2070   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
2071   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
2072   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
2073   bool IsSEH = isAsynchronousEHPersonality(Personality);
2074 
2075   if (IsWasmCXX) {
2076     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
2077     assert(UnwindDests.size() <= 1 &&
2078            "There should be at most one unwind destination for wasm");
2079     return;
2080   }
2081 
2082   while (EHPadBB) {
2083     const Instruction *Pad = EHPadBB->getFirstNonPHI();
2084     BasicBlock *NewEHPadBB = nullptr;
2085     if (isa<LandingPadInst>(Pad)) {
2086       // Stop on landingpads. They are not funclets.
2087       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
2088       break;
2089     } else if (isa<CleanupPadInst>(Pad)) {
2090       // Stop on cleanup pads. Cleanups are always funclet entries for all known
2091       // personalities.
2092       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
2093       UnwindDests.back().first->setIsEHScopeEntry();
2094       UnwindDests.back().first->setIsEHFuncletEntry();
2095       break;
2096     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
2097       // Add the catchpad handlers to the possible destinations.
2098       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2099         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
2100         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
2101         if (IsMSVCCXX || IsCoreCLR)
2102           UnwindDests.back().first->setIsEHFuncletEntry();
2103         if (!IsSEH)
2104           UnwindDests.back().first->setIsEHScopeEntry();
2105       }
2106       NewEHPadBB = CatchSwitch->getUnwindDest();
2107     } else {
2108       continue;
2109     }
2110 
2111     BranchProbabilityInfo *BPI = FuncInfo.BPI;
2112     if (BPI && NewEHPadBB)
2113       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
2114     EHPadBB = NewEHPadBB;
2115   }
2116 }
2117 
2118 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
2119   // Update successor info.
2120   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2121   auto UnwindDest = I.getUnwindDest();
2122   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2123   BranchProbability UnwindDestProb =
2124       (BPI && UnwindDest)
2125           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
2126           : BranchProbability::getZero();
2127   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
2128   for (auto &UnwindDest : UnwindDests) {
2129     UnwindDest.first->setIsEHPad();
2130     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
2131   }
2132   FuncInfo.MBB->normalizeSuccProbs();
2133 
2134   // Create the terminator node.
2135   SDValue Ret =
2136       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
2137   DAG.setRoot(Ret);
2138 }
2139 
2140 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
2141   report_fatal_error("visitCatchSwitch not yet implemented!");
2142 }
2143 
2144 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
2145   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2146   auto &DL = DAG.getDataLayout();
2147   SDValue Chain = getControlRoot();
2148   SmallVector<ISD::OutputArg, 8> Outs;
2149   SmallVector<SDValue, 8> OutVals;
2150 
2151   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
2152   // lower
2153   //
2154   //   %val = call <ty> @llvm.experimental.deoptimize()
2155   //   ret <ty> %val
2156   //
2157   // differently.
2158   if (I.getParent()->getTerminatingDeoptimizeCall()) {
2159     LowerDeoptimizingReturn();
2160     return;
2161   }
2162 
2163   if (!FuncInfo.CanLowerReturn) {
2164     unsigned DemoteReg = FuncInfo.DemoteRegister;
2165     const Function *F = I.getParent()->getParent();
2166 
2167     // Emit a store of the return value through the virtual register.
2168     // Leave Outs empty so that LowerReturn won't try to load return
2169     // registers the usual way.
2170     SmallVector<EVT, 1> PtrValueVTs;
2171     ComputeValueVTs(TLI, DL,
2172                     PointerType::get(F->getContext(),
2173                                      DAG.getDataLayout().getAllocaAddrSpace()),
2174                     PtrValueVTs);
2175 
2176     SDValue RetPtr =
2177         DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]);
2178     SDValue RetOp = getValue(I.getOperand(0));
2179 
2180     SmallVector<EVT, 4> ValueVTs, MemVTs;
2181     SmallVector<uint64_t, 4> Offsets;
2182     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
2183                     &Offsets, 0);
2184     unsigned NumValues = ValueVTs.size();
2185 
2186     SmallVector<SDValue, 4> Chains(NumValues);
2187     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
2188     for (unsigned i = 0; i != NumValues; ++i) {
2189       // An aggregate return value cannot wrap around the address space, so
2190       // offsets to its parts don't wrap either.
2191       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
2192                                            TypeSize::getFixed(Offsets[i]));
2193 
2194       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
2195       if (MemVTs[i] != ValueVTs[i])
2196         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
2197       Chains[i] = DAG.getStore(
2198           Chain, getCurSDLoc(), Val,
2199           // FIXME: better loc info would be nice.
2200           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
2201           commonAlignment(BaseAlign, Offsets[i]));
2202     }
2203 
2204     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
2205                         MVT::Other, Chains);
2206   } else if (I.getNumOperands() != 0) {
2207     SmallVector<EVT, 4> ValueVTs;
2208     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
2209     unsigned NumValues = ValueVTs.size();
2210     if (NumValues) {
2211       SDValue RetOp = getValue(I.getOperand(0));
2212 
2213       const Function *F = I.getParent()->getParent();
2214 
2215       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
2216           I.getOperand(0)->getType(), F->getCallingConv(),
2217           /*IsVarArg*/ false, DL);
2218 
2219       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
2220       if (F->getAttributes().hasRetAttr(Attribute::SExt))
2221         ExtendKind = ISD::SIGN_EXTEND;
2222       else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
2223         ExtendKind = ISD::ZERO_EXTEND;
2224 
2225       LLVMContext &Context = F->getContext();
2226       bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
2227 
2228       for (unsigned j = 0; j != NumValues; ++j) {
2229         EVT VT = ValueVTs[j];
2230 
2231         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2232           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
2233 
2234         CallingConv::ID CC = F->getCallingConv();
2235 
2236         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
2237         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2238         SmallVector<SDValue, 4> Parts(NumParts);
2239         getCopyToParts(DAG, getCurSDLoc(),
2240                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2241                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
2242 
2243         // 'inreg' on function refers to return value
2244         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2245         if (RetInReg)
2246           Flags.setInReg();
2247 
2248         if (I.getOperand(0)->getType()->isPointerTy()) {
2249           Flags.setPointer();
2250           Flags.setPointerAddrSpace(
2251               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2252         }
2253 
2254         if (NeedsRegBlock) {
2255           Flags.setInConsecutiveRegs();
2256           if (j == NumValues - 1)
2257             Flags.setInConsecutiveRegsLast();
2258         }
2259 
2260         // Propagate extension type if any
2261         if (ExtendKind == ISD::SIGN_EXTEND)
2262           Flags.setSExt();
2263         else if (ExtendKind == ISD::ZERO_EXTEND)
2264           Flags.setZExt();
2265 
2266         for (unsigned i = 0; i < NumParts; ++i) {
2267           Outs.push_back(ISD::OutputArg(Flags,
2268                                         Parts[i].getValueType().getSimpleVT(),
2269                                         VT, /*isfixed=*/true, 0, 0));
2270           OutVals.push_back(Parts[i]);
2271         }
2272       }
2273     }
2274   }
2275 
2276   // Push in swifterror virtual register as the last element of Outs. This makes
2277   // sure swifterror virtual register will be returned in the swifterror
2278   // physical register.
2279   const Function *F = I.getParent()->getParent();
2280   if (TLI.supportSwiftError() &&
2281       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2282     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2283     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2284     Flags.setSwiftError();
2285     Outs.push_back(ISD::OutputArg(
2286         Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
2287         /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
2288     // Create SDNode for the swifterror virtual register.
2289     OutVals.push_back(
2290         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2291                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2292                         EVT(TLI.getPointerTy(DL))));
2293   }
2294 
2295   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2296   CallingConv::ID CallConv =
2297     DAG.getMachineFunction().getFunction().getCallingConv();
2298   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2299       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2300 
2301   // Verify that the target's LowerReturn behaved as expected.
2302   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2303          "LowerReturn didn't return a valid chain!");
2304 
2305   // Update the DAG with the new chain value resulting from return lowering.
2306   DAG.setRoot(Chain);
2307 }
2308 
2309 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2310 /// created for it, emit nodes to copy the value into the virtual
2311 /// registers.
2312 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2313   // Skip empty types
2314   if (V->getType()->isEmptyTy())
2315     return;
2316 
2317   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2318   if (VMI != FuncInfo.ValueMap.end()) {
2319     assert((!V->use_empty() || isa<CallBrInst>(V)) &&
2320            "Unused value assigned virtual registers!");
2321     CopyValueToVirtualRegister(V, VMI->second);
2322   }
2323 }
2324 
2325 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2326 /// the current basic block, add it to ValueMap now so that we'll get a
2327 /// CopyTo/FromReg.
2328 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2329   // No need to export constants.
2330   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2331 
2332   // Already exported?
2333   if (FuncInfo.isExportedInst(V)) return;
2334 
2335   Register Reg = FuncInfo.InitializeRegForValue(V);
2336   CopyValueToVirtualRegister(V, Reg);
2337 }
2338 
2339 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2340                                                      const BasicBlock *FromBB) {
2341   // The operands of the setcc have to be in this block.  We don't know
2342   // how to export them from some other block.
2343   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2344     // Can export from current BB.
2345     if (VI->getParent() == FromBB)
2346       return true;
2347 
2348     // Is already exported, noop.
2349     return FuncInfo.isExportedInst(V);
2350   }
2351 
2352   // If this is an argument, we can export it if the BB is the entry block or
2353   // if it is already exported.
2354   if (isa<Argument>(V)) {
2355     if (FromBB->isEntryBlock())
2356       return true;
2357 
2358     // Otherwise, can only export this if it is already exported.
2359     return FuncInfo.isExportedInst(V);
2360   }
2361 
2362   // Otherwise, constants can always be exported.
2363   return true;
2364 }
2365 
2366 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2367 BranchProbability
2368 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2369                                         const MachineBasicBlock *Dst) const {
2370   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2371   const BasicBlock *SrcBB = Src->getBasicBlock();
2372   const BasicBlock *DstBB = Dst->getBasicBlock();
2373   if (!BPI) {
2374     // If BPI is not available, set the default probability as 1 / N, where N is
2375     // the number of successors.
2376     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2377     return BranchProbability(1, SuccSize);
2378   }
2379   return BPI->getEdgeProbability(SrcBB, DstBB);
2380 }
2381 
2382 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2383                                                MachineBasicBlock *Dst,
2384                                                BranchProbability Prob) {
2385   if (!FuncInfo.BPI)
2386     Src->addSuccessorWithoutProb(Dst);
2387   else {
2388     if (Prob.isUnknown())
2389       Prob = getEdgeProbability(Src, Dst);
2390     Src->addSuccessor(Dst, Prob);
2391   }
2392 }
2393 
2394 static bool InBlock(const Value *V, const BasicBlock *BB) {
2395   if (const Instruction *I = dyn_cast<Instruction>(V))
2396     return I->getParent() == BB;
2397   return true;
2398 }
2399 
2400 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2401 /// This function emits a branch and is used at the leaves of an OR or an
2402 /// AND operator tree.
2403 void
2404 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2405                                                   MachineBasicBlock *TBB,
2406                                                   MachineBasicBlock *FBB,
2407                                                   MachineBasicBlock *CurBB,
2408                                                   MachineBasicBlock *SwitchBB,
2409                                                   BranchProbability TProb,
2410                                                   BranchProbability FProb,
2411                                                   bool InvertCond) {
2412   const BasicBlock *BB = CurBB->getBasicBlock();
2413 
2414   // If the leaf of the tree is a comparison, merge the condition into
2415   // the caseblock.
2416   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2417     // The operands of the cmp have to be in this block.  We don't know
2418     // how to export them from some other block.  If this is the first block
2419     // of the sequence, no exporting is needed.
2420     if (CurBB == SwitchBB ||
2421         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2422          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2423       ISD::CondCode Condition;
2424       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2425         ICmpInst::Predicate Pred =
2426             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2427         Condition = getICmpCondCode(Pred);
2428       } else {
2429         const FCmpInst *FC = cast<FCmpInst>(Cond);
2430         FCmpInst::Predicate Pred =
2431             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2432         Condition = getFCmpCondCode(Pred);
2433         if (TM.Options.NoNaNsFPMath)
2434           Condition = getFCmpCodeWithoutNaN(Condition);
2435       }
2436 
2437       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2438                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2439       SL->SwitchCases.push_back(CB);
2440       return;
2441     }
2442   }
2443 
2444   // Create a CaseBlock record representing this branch.
2445   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2446   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2447                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2448   SL->SwitchCases.push_back(CB);
2449 }
2450 
2451 // Collect dependencies on V recursively. This is used for the cost analysis in
2452 // `shouldKeepJumpConditionsTogether`.
2453 static bool
2454 collectInstructionDeps(SmallPtrSet<const Instruction *, 8> *Deps,
2455                        const Value *V,
2456                        SmallPtrSet<const Instruction *, 8> *Necessary = nullptr,
2457                        unsigned Depth = 0) {
2458   // Return false if we have an incomplete count.
2459   if (Depth >= SelectionDAG::MaxRecursionDepth)
2460     return false;
2461 
2462   auto *I = dyn_cast<Instruction>(V);
2463   if (I == nullptr)
2464     return true;
2465 
2466   if (Necessary != nullptr) {
2467     // This instruction is necessary for the other side of the condition so
2468     // don't count it.
2469     if (Necessary->contains(I))
2470       return true;
2471   }
2472 
2473   // Already added this dep.
2474   if (!Deps->insert(I).second)
2475     return true;
2476 
2477   for (unsigned OpIdx = 0, E = I->getNumOperands(); OpIdx < E; ++OpIdx)
2478     if (!collectInstructionDeps(Deps, I->getOperand(OpIdx), Necessary,
2479                                 Depth + 1))
2480       return false;
2481   return true;
2482 }
2483 
2484 bool SelectionDAGBuilder::shouldKeepJumpConditionsTogether(
2485     const FunctionLoweringInfo &FuncInfo, const BranchInst &I,
2486     Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs,
2487     TargetLoweringBase::CondMergingParams Params) const {
2488   if (I.getNumSuccessors() != 2)
2489     return false;
2490 
2491   if (Params.BaseCost < 0)
2492     return false;
2493 
2494   // Baseline cost.
2495   InstructionCost CostThresh = Params.BaseCost;
2496 
2497   BranchProbabilityInfo *BPI = nullptr;
2498   if (Params.LikelyBias || Params.UnlikelyBias)
2499     BPI = FuncInfo.BPI;
2500   if (BPI != nullptr) {
2501     // See if we are either likely to get an early out or compute both lhs/rhs
2502     // of the condition.
2503     BasicBlock *IfFalse = I.getSuccessor(0);
2504     BasicBlock *IfTrue = I.getSuccessor(1);
2505 
2506     std::optional<bool> Likely;
2507     if (BPI->isEdgeHot(I.getParent(), IfTrue))
2508       Likely = true;
2509     else if (BPI->isEdgeHot(I.getParent(), IfFalse))
2510       Likely = false;
2511 
2512     if (Likely) {
2513       if (Opc == (*Likely ? Instruction::And : Instruction::Or))
2514         // Its likely we will have to compute both lhs and rhs of condition
2515         CostThresh += Params.LikelyBias;
2516       else {
2517         if (Params.UnlikelyBias < 0)
2518           return false;
2519         // Its likely we will get an early out.
2520         CostThresh -= Params.UnlikelyBias;
2521       }
2522     }
2523   }
2524 
2525   if (CostThresh <= 0)
2526     return false;
2527 
2528   // Collect "all" instructions that lhs condition is dependent on.
2529   SmallPtrSet<const Instruction *, 8> LhsDeps, RhsDeps;
2530   collectInstructionDeps(&LhsDeps, Lhs);
2531   // Collect "all" instructions that rhs condition is dependent on AND are
2532   // dependencies of lhs. This gives us an estimate on which instructions we
2533   // stand to save by splitting the condition.
2534   if (!collectInstructionDeps(&RhsDeps, Rhs, &LhsDeps))
2535     return false;
2536   // Add the compare instruction itself unless its a dependency on the LHS.
2537   if (const auto *RhsI = dyn_cast<Instruction>(Rhs))
2538     if (!LhsDeps.contains(RhsI))
2539       RhsDeps.insert(RhsI);
2540 
2541   const auto &TLI = DAG.getTargetLoweringInfo();
2542   const auto &TTI =
2543       TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction());
2544 
2545   InstructionCost CostOfIncluding = 0;
2546   // See if this instruction will need to computed independently of whether RHS
2547   // is.
2548   auto ShouldCountInsn = [&RhsDeps](const Instruction *Ins) {
2549     for (const auto *U : Ins->users()) {
2550       // If user is independent of RHS calculation we don't need to count it.
2551       if (auto *UIns = dyn_cast<Instruction>(U))
2552         if (!RhsDeps.contains(UIns))
2553           return false;
2554     }
2555     return true;
2556   };
2557 
2558   // Prune instructions from RHS Deps that are dependencies of unrelated
2559   // instructions. The value (SelectionDAG::MaxRecursionDepth) is fairly
2560   // arbitrary and just meant to cap the how much time we spend in the pruning
2561   // loop. Its highly unlikely to come into affect.
2562   const unsigned MaxPruneIters = SelectionDAG::MaxRecursionDepth;
2563   // Stop after a certain point. No incorrectness from including too many
2564   // instructions.
2565   for (unsigned PruneIters = 0; PruneIters < MaxPruneIters; ++PruneIters) {
2566     const Instruction *ToDrop = nullptr;
2567     for (const auto *Ins : RhsDeps) {
2568       if (!ShouldCountInsn(Ins)) {
2569         ToDrop = Ins;
2570         break;
2571       }
2572     }
2573     if (ToDrop == nullptr)
2574       break;
2575     RhsDeps.erase(ToDrop);
2576   }
2577 
2578   for (const auto *Ins : RhsDeps) {
2579     // Finally accumulate latency that we can only attribute to computing the
2580     // RHS condition. Use latency because we are essentially trying to calculate
2581     // the cost of the dependency chain.
2582     // Possible TODO: We could try to estimate ILP and make this more precise.
2583     CostOfIncluding +=
2584         TTI.getInstructionCost(Ins, TargetTransformInfo::TCK_Latency);
2585 
2586     if (CostOfIncluding > CostThresh)
2587       return false;
2588   }
2589   return true;
2590 }
2591 
2592 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2593                                                MachineBasicBlock *TBB,
2594                                                MachineBasicBlock *FBB,
2595                                                MachineBasicBlock *CurBB,
2596                                                MachineBasicBlock *SwitchBB,
2597                                                Instruction::BinaryOps Opc,
2598                                                BranchProbability TProb,
2599                                                BranchProbability FProb,
2600                                                bool InvertCond) {
2601   // Skip over not part of the tree and remember to invert op and operands at
2602   // next level.
2603   Value *NotCond;
2604   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2605       InBlock(NotCond, CurBB->getBasicBlock())) {
2606     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2607                          !InvertCond);
2608     return;
2609   }
2610 
2611   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2612   const Value *BOpOp0, *BOpOp1;
2613   // Compute the effective opcode for Cond, taking into account whether it needs
2614   // to be inverted, e.g.
2615   //   and (not (or A, B)), C
2616   // gets lowered as
2617   //   and (and (not A, not B), C)
2618   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2619   if (BOp) {
2620     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2621                ? Instruction::And
2622                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2623                       ? Instruction::Or
2624                       : (Instruction::BinaryOps)0);
2625     if (InvertCond) {
2626       if (BOpc == Instruction::And)
2627         BOpc = Instruction::Or;
2628       else if (BOpc == Instruction::Or)
2629         BOpc = Instruction::And;
2630     }
2631   }
2632 
2633   // If this node is not part of the or/and tree, emit it as a branch.
2634   // Note that all nodes in the tree should have same opcode.
2635   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2636   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2637       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2638       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2639     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2640                                  TProb, FProb, InvertCond);
2641     return;
2642   }
2643 
2644   //  Create TmpBB after CurBB.
2645   MachineFunction::iterator BBI(CurBB);
2646   MachineFunction &MF = DAG.getMachineFunction();
2647   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2648   CurBB->getParent()->insert(++BBI, TmpBB);
2649 
2650   if (Opc == Instruction::Or) {
2651     // Codegen X | Y as:
2652     // BB1:
2653     //   jmp_if_X TBB
2654     //   jmp TmpBB
2655     // TmpBB:
2656     //   jmp_if_Y TBB
2657     //   jmp FBB
2658     //
2659 
2660     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2661     // The requirement is that
2662     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2663     //     = TrueProb for original BB.
2664     // Assuming the original probabilities are A and B, one choice is to set
2665     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2666     // A/(1+B) and 2B/(1+B). This choice assumes that
2667     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2668     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2669     // TmpBB, but the math is more complicated.
2670 
2671     auto NewTrueProb = TProb / 2;
2672     auto NewFalseProb = TProb / 2 + FProb;
2673     // Emit the LHS condition.
2674     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2675                          NewFalseProb, InvertCond);
2676 
2677     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2678     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2679     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2680     // Emit the RHS condition into TmpBB.
2681     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2682                          Probs[1], InvertCond);
2683   } else {
2684     assert(Opc == Instruction::And && "Unknown merge op!");
2685     // Codegen X & Y as:
2686     // BB1:
2687     //   jmp_if_X TmpBB
2688     //   jmp FBB
2689     // TmpBB:
2690     //   jmp_if_Y TBB
2691     //   jmp FBB
2692     //
2693     //  This requires creation of TmpBB after CurBB.
2694 
2695     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2696     // The requirement is that
2697     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2698     //     = FalseProb for original BB.
2699     // Assuming the original probabilities are A and B, one choice is to set
2700     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2701     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2702     // TrueProb for BB1 * FalseProb for TmpBB.
2703 
2704     auto NewTrueProb = TProb + FProb / 2;
2705     auto NewFalseProb = FProb / 2;
2706     // Emit the LHS condition.
2707     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2708                          NewFalseProb, InvertCond);
2709 
2710     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2711     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2712     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2713     // Emit the RHS condition into TmpBB.
2714     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2715                          Probs[1], InvertCond);
2716   }
2717 }
2718 
2719 /// If the set of cases should be emitted as a series of branches, return true.
2720 /// If we should emit this as a bunch of and/or'd together conditions, return
2721 /// false.
2722 bool
2723 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2724   if (Cases.size() != 2) return true;
2725 
2726   // If this is two comparisons of the same values or'd or and'd together, they
2727   // will get folded into a single comparison, so don't emit two blocks.
2728   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2729        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2730       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2731        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2732     return false;
2733   }
2734 
2735   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2736   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2737   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2738       Cases[0].CC == Cases[1].CC &&
2739       isa<Constant>(Cases[0].CmpRHS) &&
2740       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2741     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2742       return false;
2743     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2744       return false;
2745   }
2746 
2747   return true;
2748 }
2749 
2750 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2751   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2752 
2753   // Update machine-CFG edges.
2754   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2755 
2756   if (I.isUnconditional()) {
2757     // Update machine-CFG edges.
2758     BrMBB->addSuccessor(Succ0MBB);
2759 
2760     // If this is not a fall-through branch or optimizations are switched off,
2761     // emit the branch.
2762     if (Succ0MBB != NextBlock(BrMBB) ||
2763         TM.getOptLevel() == CodeGenOptLevel::None) {
2764       auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
2765                             getControlRoot(), DAG.getBasicBlock(Succ0MBB));
2766       setValue(&I, Br);
2767       DAG.setRoot(Br);
2768     }
2769 
2770     return;
2771   }
2772 
2773   // If this condition is one of the special cases we handle, do special stuff
2774   // now.
2775   const Value *CondVal = I.getCondition();
2776   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2777 
2778   // If this is a series of conditions that are or'd or and'd together, emit
2779   // this as a sequence of branches instead of setcc's with and/or operations.
2780   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2781   // unpredictable branches, and vector extracts because those jumps are likely
2782   // expensive for any target), this should improve performance.
2783   // For example, instead of something like:
2784   //     cmp A, B
2785   //     C = seteq
2786   //     cmp D, E
2787   //     F = setle
2788   //     or C, F
2789   //     jnz foo
2790   // Emit:
2791   //     cmp A, B
2792   //     je foo
2793   //     cmp D, E
2794   //     jle foo
2795   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2796   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2797       BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2798     Value *Vec;
2799     const Value *BOp0, *BOp1;
2800     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2801     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2802       Opcode = Instruction::And;
2803     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2804       Opcode = Instruction::Or;
2805 
2806     if (Opcode &&
2807         !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2808           match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value()))) &&
2809         !shouldKeepJumpConditionsTogether(
2810             FuncInfo, I, Opcode, BOp0, BOp1,
2811             DAG.getTargetLoweringInfo().getJumpConditionMergingParams(
2812                 Opcode, BOp0, BOp1))) {
2813       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2814                            getEdgeProbability(BrMBB, Succ0MBB),
2815                            getEdgeProbability(BrMBB, Succ1MBB),
2816                            /*InvertCond=*/false);
2817       // If the compares in later blocks need to use values not currently
2818       // exported from this block, export them now.  This block should always
2819       // be the first entry.
2820       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2821 
2822       // Allow some cases to be rejected.
2823       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2824         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2825           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2826           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2827         }
2828 
2829         // Emit the branch for this block.
2830         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2831         SL->SwitchCases.erase(SL->SwitchCases.begin());
2832         return;
2833       }
2834 
2835       // Okay, we decided not to do this, remove any inserted MBB's and clear
2836       // SwitchCases.
2837       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2838         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2839 
2840       SL->SwitchCases.clear();
2841     }
2842   }
2843 
2844   // Create a CaseBlock record representing this branch.
2845   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2846                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2847 
2848   // Use visitSwitchCase to actually insert the fast branch sequence for this
2849   // cond branch.
2850   visitSwitchCase(CB, BrMBB);
2851 }
2852 
2853 /// visitSwitchCase - Emits the necessary code to represent a single node in
2854 /// the binary search tree resulting from lowering a switch instruction.
2855 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2856                                           MachineBasicBlock *SwitchBB) {
2857   SDValue Cond;
2858   SDValue CondLHS = getValue(CB.CmpLHS);
2859   SDLoc dl = CB.DL;
2860 
2861   if (CB.CC == ISD::SETTRUE) {
2862     // Branch or fall through to TrueBB.
2863     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2864     SwitchBB->normalizeSuccProbs();
2865     if (CB.TrueBB != NextBlock(SwitchBB)) {
2866       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2867                               DAG.getBasicBlock(CB.TrueBB)));
2868     }
2869     return;
2870   }
2871 
2872   auto &TLI = DAG.getTargetLoweringInfo();
2873   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2874 
2875   // Build the setcc now.
2876   if (!CB.CmpMHS) {
2877     // Fold "(X == true)" to X and "(X == false)" to !X to
2878     // handle common cases produced by branch lowering.
2879     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2880         CB.CC == ISD::SETEQ)
2881       Cond = CondLHS;
2882     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2883              CB.CC == ISD::SETEQ) {
2884       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2885       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2886     } else {
2887       SDValue CondRHS = getValue(CB.CmpRHS);
2888 
2889       // If a pointer's DAG type is larger than its memory type then the DAG
2890       // values are zero-extended. This breaks signed comparisons so truncate
2891       // back to the underlying type before doing the compare.
2892       if (CondLHS.getValueType() != MemVT) {
2893         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2894         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2895       }
2896       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2897     }
2898   } else {
2899     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2900 
2901     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2902     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2903 
2904     SDValue CmpOp = getValue(CB.CmpMHS);
2905     EVT VT = CmpOp.getValueType();
2906 
2907     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2908       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2909                           ISD::SETLE);
2910     } else {
2911       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2912                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2913       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2914                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2915     }
2916   }
2917 
2918   // Update successor info
2919   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2920   // TrueBB and FalseBB are always different unless the incoming IR is
2921   // degenerate. This only happens when running llc on weird IR.
2922   if (CB.TrueBB != CB.FalseBB)
2923     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2924   SwitchBB->normalizeSuccProbs();
2925 
2926   // If the lhs block is the next block, invert the condition so that we can
2927   // fall through to the lhs instead of the rhs block.
2928   if (CB.TrueBB == NextBlock(SwitchBB)) {
2929     std::swap(CB.TrueBB, CB.FalseBB);
2930     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2931     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2932   }
2933 
2934   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2935                                MVT::Other, getControlRoot(), Cond,
2936                                DAG.getBasicBlock(CB.TrueBB));
2937 
2938   setValue(CurInst, BrCond);
2939 
2940   // Insert the false branch. Do this even if it's a fall through branch,
2941   // this makes it easier to do DAG optimizations which require inverting
2942   // the branch condition.
2943   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2944                        DAG.getBasicBlock(CB.FalseBB));
2945 
2946   DAG.setRoot(BrCond);
2947 }
2948 
2949 /// visitJumpTable - Emit JumpTable node in the current MBB
2950 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2951   // Emit the code for the jump table
2952   assert(JT.SL && "Should set SDLoc for SelectionDAG!");
2953   assert(JT.Reg != -1U && "Should lower JT Header first!");
2954   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2955   SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy);
2956   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2957   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other,
2958                                     Index.getValue(1), Table, Index);
2959   DAG.setRoot(BrJumpTable);
2960 }
2961 
2962 /// visitJumpTableHeader - This function emits necessary code to produce index
2963 /// in the JumpTable from switch case.
2964 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2965                                                JumpTableHeader &JTH,
2966                                                MachineBasicBlock *SwitchBB) {
2967   assert(JT.SL && "Should set SDLoc for SelectionDAG!");
2968   const SDLoc &dl = *JT.SL;
2969 
2970   // Subtract the lowest switch case value from the value being switched on.
2971   SDValue SwitchOp = getValue(JTH.SValue);
2972   EVT VT = SwitchOp.getValueType();
2973   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2974                             DAG.getConstant(JTH.First, dl, VT));
2975 
2976   // The SDNode we just created, which holds the value being switched on minus
2977   // the smallest case value, needs to be copied to a virtual register so it
2978   // can be used as an index into the jump table in a subsequent basic block.
2979   // This value may be smaller or larger than the target's pointer type, and
2980   // therefore require extension or truncating.
2981   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2982   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2983 
2984   unsigned JumpTableReg =
2985       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2986   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2987                                     JumpTableReg, SwitchOp);
2988   JT.Reg = JumpTableReg;
2989 
2990   if (!JTH.FallthroughUnreachable) {
2991     // Emit the range check for the jump table, and branch to the default block
2992     // for the switch statement if the value being switched on exceeds the
2993     // largest case in the switch.
2994     SDValue CMP = DAG.getSetCC(
2995         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2996                                    Sub.getValueType()),
2997         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2998 
2999     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
3000                                  MVT::Other, CopyTo, CMP,
3001                                  DAG.getBasicBlock(JT.Default));
3002 
3003     // Avoid emitting unnecessary branches to the next block.
3004     if (JT.MBB != NextBlock(SwitchBB))
3005       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
3006                            DAG.getBasicBlock(JT.MBB));
3007 
3008     DAG.setRoot(BrCond);
3009   } else {
3010     // Avoid emitting unnecessary branches to the next block.
3011     if (JT.MBB != NextBlock(SwitchBB))
3012       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
3013                               DAG.getBasicBlock(JT.MBB)));
3014     else
3015       DAG.setRoot(CopyTo);
3016   }
3017 }
3018 
3019 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
3020 /// variable if there exists one.
3021 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
3022                                  SDValue &Chain) {
3023   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3024   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
3025   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
3026   MachineFunction &MF = DAG.getMachineFunction();
3027   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
3028   MachineSDNode *Node =
3029       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
3030   if (Global) {
3031     MachinePointerInfo MPInfo(Global);
3032     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
3033                  MachineMemOperand::MODereferenceable;
3034     MachineMemOperand *MemRef = MF.getMachineMemOperand(
3035         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
3036     DAG.setNodeMemRefs(Node, {MemRef});
3037   }
3038   if (PtrTy != PtrMemTy)
3039     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
3040   return SDValue(Node, 0);
3041 }
3042 
3043 /// Codegen a new tail for a stack protector check ParentMBB which has had its
3044 /// tail spliced into a stack protector check success bb.
3045 ///
3046 /// For a high level explanation of how this fits into the stack protector
3047 /// generation see the comment on the declaration of class
3048 /// StackProtectorDescriptor.
3049 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
3050                                                   MachineBasicBlock *ParentBB) {
3051 
3052   // First create the loads to the guard/stack slot for the comparison.
3053   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3054   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
3055   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
3056 
3057   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3058   int FI = MFI.getStackProtectorIndex();
3059 
3060   SDValue Guard;
3061   SDLoc dl = getCurSDLoc();
3062   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
3063   const Module &M = *ParentBB->getParent()->getFunction().getParent();
3064   Align Align =
3065       DAG.getDataLayout().getPrefTypeAlign(PointerType::get(M.getContext(), 0));
3066 
3067   // Generate code to load the content of the guard slot.
3068   SDValue GuardVal = DAG.getLoad(
3069       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
3070       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
3071       MachineMemOperand::MOVolatile);
3072 
3073   if (TLI.useStackGuardXorFP())
3074     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
3075 
3076   // Retrieve guard check function, nullptr if instrumentation is inlined.
3077   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
3078     // The target provides a guard check function to validate the guard value.
3079     // Generate a call to that function with the content of the guard slot as
3080     // argument.
3081     FunctionType *FnTy = GuardCheckFn->getFunctionType();
3082     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3083 
3084     TargetLowering::ArgListTy Args;
3085     TargetLowering::ArgListEntry Entry;
3086     Entry.Node = GuardVal;
3087     Entry.Ty = FnTy->getParamType(0);
3088     if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
3089       Entry.IsInReg = true;
3090     Args.push_back(Entry);
3091 
3092     TargetLowering::CallLoweringInfo CLI(DAG);
3093     CLI.setDebugLoc(getCurSDLoc())
3094         .setChain(DAG.getEntryNode())
3095         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
3096                    getValue(GuardCheckFn), std::move(Args));
3097 
3098     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
3099     DAG.setRoot(Result.second);
3100     return;
3101   }
3102 
3103   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
3104   // Otherwise, emit a volatile load to retrieve the stack guard value.
3105   SDValue Chain = DAG.getEntryNode();
3106   if (TLI.useLoadStackGuardNode()) {
3107     Guard = getLoadStackGuard(DAG, dl, Chain);
3108   } else {
3109     const Value *IRGuard = TLI.getSDagStackGuard(M);
3110     SDValue GuardPtr = getValue(IRGuard);
3111 
3112     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
3113                         MachinePointerInfo(IRGuard, 0), Align,
3114                         MachineMemOperand::MOVolatile);
3115   }
3116 
3117   // Perform the comparison via a getsetcc.
3118   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
3119                                                         *DAG.getContext(),
3120                                                         Guard.getValueType()),
3121                              Guard, GuardVal, ISD::SETNE);
3122 
3123   // If the guard/stackslot do not equal, branch to failure MBB.
3124   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
3125                                MVT::Other, GuardVal.getOperand(0),
3126                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
3127   // Otherwise branch to success MBB.
3128   SDValue Br = DAG.getNode(ISD::BR, dl,
3129                            MVT::Other, BrCond,
3130                            DAG.getBasicBlock(SPD.getSuccessMBB()));
3131 
3132   DAG.setRoot(Br);
3133 }
3134 
3135 /// Codegen the failure basic block for a stack protector check.
3136 ///
3137 /// A failure stack protector machine basic block consists simply of a call to
3138 /// __stack_chk_fail().
3139 ///
3140 /// For a high level explanation of how this fits into the stack protector
3141 /// generation see the comment on the declaration of class
3142 /// StackProtectorDescriptor.
3143 void
3144 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
3145   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3146   TargetLowering::MakeLibCallOptions CallOptions;
3147   CallOptions.setDiscardResult(true);
3148   SDValue Chain =
3149       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
3150                       std::nullopt, CallOptions, getCurSDLoc())
3151           .second;
3152   // On PS4/PS5, the "return address" must still be within the calling
3153   // function, even if it's at the very end, so emit an explicit TRAP here.
3154   // Passing 'true' for doesNotReturn above won't generate the trap for us.
3155   if (TM.getTargetTriple().isPS())
3156     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
3157   // WebAssembly needs an unreachable instruction after a non-returning call,
3158   // because the function return type can be different from __stack_chk_fail's
3159   // return type (void).
3160   if (TM.getTargetTriple().isWasm())
3161     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
3162 
3163   DAG.setRoot(Chain);
3164 }
3165 
3166 /// visitBitTestHeader - This function emits necessary code to produce value
3167 /// suitable for "bit tests"
3168 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
3169                                              MachineBasicBlock *SwitchBB) {
3170   SDLoc dl = getCurSDLoc();
3171 
3172   // Subtract the minimum value.
3173   SDValue SwitchOp = getValue(B.SValue);
3174   EVT VT = SwitchOp.getValueType();
3175   SDValue RangeSub =
3176       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
3177 
3178   // Determine the type of the test operands.
3179   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3180   bool UsePtrType = false;
3181   if (!TLI.isTypeLegal(VT)) {
3182     UsePtrType = true;
3183   } else {
3184     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
3185       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
3186         // Switch table case range are encoded into series of masks.
3187         // Just use pointer type, it's guaranteed to fit.
3188         UsePtrType = true;
3189         break;
3190       }
3191   }
3192   SDValue Sub = RangeSub;
3193   if (UsePtrType) {
3194     VT = TLI.getPointerTy(DAG.getDataLayout());
3195     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
3196   }
3197 
3198   B.RegVT = VT.getSimpleVT();
3199   B.Reg = FuncInfo.CreateReg(B.RegVT);
3200   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
3201 
3202   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
3203 
3204   if (!B.FallthroughUnreachable)
3205     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
3206   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
3207   SwitchBB->normalizeSuccProbs();
3208 
3209   SDValue Root = CopyTo;
3210   if (!B.FallthroughUnreachable) {
3211     // Conditional branch to the default block.
3212     SDValue RangeCmp = DAG.getSetCC(dl,
3213         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3214                                RangeSub.getValueType()),
3215         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
3216         ISD::SETUGT);
3217 
3218     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
3219                        DAG.getBasicBlock(B.Default));
3220   }
3221 
3222   // Avoid emitting unnecessary branches to the next block.
3223   if (MBB != NextBlock(SwitchBB))
3224     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
3225 
3226   DAG.setRoot(Root);
3227 }
3228 
3229 /// visitBitTestCase - this function produces one "bit test"
3230 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
3231                                            MachineBasicBlock* NextMBB,
3232                                            BranchProbability BranchProbToNext,
3233                                            unsigned Reg,
3234                                            BitTestCase &B,
3235                                            MachineBasicBlock *SwitchBB) {
3236   SDLoc dl = getCurSDLoc();
3237   MVT VT = BB.RegVT;
3238   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
3239   SDValue Cmp;
3240   unsigned PopCount = llvm::popcount(B.Mask);
3241   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3242   if (PopCount == 1) {
3243     // Testing for a single bit; just compare the shift count with what it
3244     // would need to be to shift a 1 bit in that position.
3245     Cmp = DAG.getSetCC(
3246         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3247         ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT),
3248         ISD::SETEQ);
3249   } else if (PopCount == BB.Range) {
3250     // There is only one zero bit in the range, test for it directly.
3251     Cmp = DAG.getSetCC(
3252         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3253         ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE);
3254   } else {
3255     // Make desired shift
3256     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
3257                                     DAG.getConstant(1, dl, VT), ShiftOp);
3258 
3259     // Emit bit tests and jumps
3260     SDValue AndOp = DAG.getNode(ISD::AND, dl,
3261                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
3262     Cmp = DAG.getSetCC(
3263         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3264         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
3265   }
3266 
3267   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
3268   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
3269   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
3270   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
3271   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
3272   // one as they are relative probabilities (and thus work more like weights),
3273   // and hence we need to normalize them to let the sum of them become one.
3274   SwitchBB->normalizeSuccProbs();
3275 
3276   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
3277                               MVT::Other, getControlRoot(),
3278                               Cmp, DAG.getBasicBlock(B.TargetBB));
3279 
3280   // Avoid emitting unnecessary branches to the next block.
3281   if (NextMBB != NextBlock(SwitchBB))
3282     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
3283                         DAG.getBasicBlock(NextMBB));
3284 
3285   DAG.setRoot(BrAnd);
3286 }
3287 
3288 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
3289   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
3290 
3291   // Retrieve successors. Look through artificial IR level blocks like
3292   // catchswitch for successors.
3293   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
3294   const BasicBlock *EHPadBB = I.getSuccessor(1);
3295   MachineBasicBlock *EHPadMBB = FuncInfo.MBBMap[EHPadBB];
3296 
3297   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3298   // have to do anything here to lower funclet bundles.
3299   assert(!I.hasOperandBundlesOtherThan(
3300              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
3301               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
3302               LLVMContext::OB_cfguardtarget,
3303               LLVMContext::OB_clang_arc_attachedcall}) &&
3304          "Cannot lower invokes with arbitrary operand bundles yet!");
3305 
3306   const Value *Callee(I.getCalledOperand());
3307   const Function *Fn = dyn_cast<Function>(Callee);
3308   if (isa<InlineAsm>(Callee))
3309     visitInlineAsm(I, EHPadBB);
3310   else if (Fn && Fn->isIntrinsic()) {
3311     switch (Fn->getIntrinsicID()) {
3312     default:
3313       llvm_unreachable("Cannot invoke this intrinsic");
3314     case Intrinsic::donothing:
3315       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
3316     case Intrinsic::seh_try_begin:
3317     case Intrinsic::seh_scope_begin:
3318     case Intrinsic::seh_try_end:
3319     case Intrinsic::seh_scope_end:
3320       if (EHPadMBB)
3321           // a block referenced by EH table
3322           // so dtor-funclet not removed by opts
3323           EHPadMBB->setMachineBlockAddressTaken();
3324       break;
3325     case Intrinsic::experimental_patchpoint_void:
3326     case Intrinsic::experimental_patchpoint_i64:
3327       visitPatchpoint(I, EHPadBB);
3328       break;
3329     case Intrinsic::experimental_gc_statepoint:
3330       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
3331       break;
3332     case Intrinsic::wasm_rethrow: {
3333       // This is usually done in visitTargetIntrinsic, but this intrinsic is
3334       // special because it can be invoked, so we manually lower it to a DAG
3335       // node here.
3336       SmallVector<SDValue, 8> Ops;
3337       Ops.push_back(getRoot()); // inchain
3338       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3339       Ops.push_back(
3340           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
3341                                 TLI.getPointerTy(DAG.getDataLayout())));
3342       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3343       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3344       break;
3345     }
3346     }
3347   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
3348     // Currently we do not lower any intrinsic calls with deopt operand bundles.
3349     // Eventually we will support lowering the @llvm.experimental.deoptimize
3350     // intrinsic, and right now there are no plans to support other intrinsics
3351     // with deopt state.
3352     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
3353   } else {
3354     LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
3355   }
3356 
3357   // If the value of the invoke is used outside of its defining block, make it
3358   // available as a virtual register.
3359   // We already took care of the exported value for the statepoint instruction
3360   // during call to the LowerStatepoint.
3361   if (!isa<GCStatepointInst>(I)) {
3362     CopyToExportRegsIfNeeded(&I);
3363   }
3364 
3365   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
3366   BranchProbabilityInfo *BPI = FuncInfo.BPI;
3367   BranchProbability EHPadBBProb =
3368       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3369           : BranchProbability::getZero();
3370   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
3371 
3372   // Update successor info.
3373   addSuccessorWithProb(InvokeMBB, Return);
3374   for (auto &UnwindDest : UnwindDests) {
3375     UnwindDest.first->setIsEHPad();
3376     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3377   }
3378   InvokeMBB->normalizeSuccProbs();
3379 
3380   // Drop into normal successor.
3381   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
3382                           DAG.getBasicBlock(Return)));
3383 }
3384 
3385 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3386   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3387 
3388   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3389   // have to do anything here to lower funclet bundles.
3390   assert(!I.hasOperandBundlesOtherThan(
3391              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
3392          "Cannot lower callbrs with arbitrary operand bundles yet!");
3393 
3394   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
3395   visitInlineAsm(I);
3396   CopyToExportRegsIfNeeded(&I);
3397 
3398   // Retrieve successors.
3399   SmallPtrSet<BasicBlock *, 8> Dests;
3400   Dests.insert(I.getDefaultDest());
3401   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
3402 
3403   // Update successor info.
3404   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3405   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
3406     BasicBlock *Dest = I.getIndirectDest(i);
3407     MachineBasicBlock *Target = FuncInfo.MBBMap[Dest];
3408     Target->setIsInlineAsmBrIndirectTarget();
3409     Target->setMachineBlockAddressTaken();
3410     Target->setLabelMustBeEmitted();
3411     // Don't add duplicate machine successors.
3412     if (Dests.insert(Dest).second)
3413       addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3414   }
3415   CallBrMBB->normalizeSuccProbs();
3416 
3417   // Drop into default successor.
3418   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3419                           MVT::Other, getControlRoot(),
3420                           DAG.getBasicBlock(Return)));
3421 }
3422 
3423 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3424   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3425 }
3426 
3427 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3428   assert(FuncInfo.MBB->isEHPad() &&
3429          "Call to landingpad not in landing pad!");
3430 
3431   // If there aren't registers to copy the values into (e.g., during SjLj
3432   // exceptions), then don't bother to create these DAG nodes.
3433   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3434   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3435   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3436       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3437     return;
3438 
3439   // If landingpad's return type is token type, we don't create DAG nodes
3440   // for its exception pointer and selector value. The extraction of exception
3441   // pointer or selector value from token type landingpads is not currently
3442   // supported.
3443   if (LP.getType()->isTokenTy())
3444     return;
3445 
3446   SmallVector<EVT, 2> ValueVTs;
3447   SDLoc dl = getCurSDLoc();
3448   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3449   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3450 
3451   // Get the two live-in registers as SDValues. The physregs have already been
3452   // copied into virtual registers.
3453   SDValue Ops[2];
3454   if (FuncInfo.ExceptionPointerVirtReg) {
3455     Ops[0] = DAG.getZExtOrTrunc(
3456         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3457                            FuncInfo.ExceptionPointerVirtReg,
3458                            TLI.getPointerTy(DAG.getDataLayout())),
3459         dl, ValueVTs[0]);
3460   } else {
3461     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3462   }
3463   Ops[1] = DAG.getZExtOrTrunc(
3464       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3465                          FuncInfo.ExceptionSelectorVirtReg,
3466                          TLI.getPointerTy(DAG.getDataLayout())),
3467       dl, ValueVTs[1]);
3468 
3469   // Merge into one.
3470   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3471                             DAG.getVTList(ValueVTs), Ops);
3472   setValue(&LP, Res);
3473 }
3474 
3475 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3476                                            MachineBasicBlock *Last) {
3477   // Update JTCases.
3478   for (JumpTableBlock &JTB : SL->JTCases)
3479     if (JTB.first.HeaderBB == First)
3480       JTB.first.HeaderBB = Last;
3481 
3482   // Update BitTestCases.
3483   for (BitTestBlock &BTB : SL->BitTestCases)
3484     if (BTB.Parent == First)
3485       BTB.Parent = Last;
3486 }
3487 
3488 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3489   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3490 
3491   // Update machine-CFG edges with unique successors.
3492   SmallSet<BasicBlock*, 32> Done;
3493   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3494     BasicBlock *BB = I.getSuccessor(i);
3495     bool Inserted = Done.insert(BB).second;
3496     if (!Inserted)
3497         continue;
3498 
3499     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
3500     addSuccessorWithProb(IndirectBrMBB, Succ);
3501   }
3502   IndirectBrMBB->normalizeSuccProbs();
3503 
3504   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3505                           MVT::Other, getControlRoot(),
3506                           getValue(I.getAddress())));
3507 }
3508 
3509 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3510   if (!DAG.getTarget().Options.TrapUnreachable)
3511     return;
3512 
3513   // We may be able to ignore unreachable behind a noreturn call.
3514   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
3515     if (const CallInst *Call = dyn_cast_or_null<CallInst>(I.getPrevNode())) {
3516       if (Call->doesNotReturn())
3517         return;
3518     }
3519   }
3520 
3521   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3522 }
3523 
3524 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3525   SDNodeFlags Flags;
3526   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3527     Flags.copyFMF(*FPOp);
3528 
3529   SDValue Op = getValue(I.getOperand(0));
3530   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3531                                     Op, Flags);
3532   setValue(&I, UnNodeValue);
3533 }
3534 
3535 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3536   SDNodeFlags Flags;
3537   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3538     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3539     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3540   }
3541   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3542     Flags.setExact(ExactOp->isExact());
3543   if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&I))
3544     Flags.setDisjoint(DisjointOp->isDisjoint());
3545   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3546     Flags.copyFMF(*FPOp);
3547 
3548   SDValue Op1 = getValue(I.getOperand(0));
3549   SDValue Op2 = getValue(I.getOperand(1));
3550   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3551                                      Op1, Op2, Flags);
3552   setValue(&I, BinNodeValue);
3553 }
3554 
3555 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3556   SDValue Op1 = getValue(I.getOperand(0));
3557   SDValue Op2 = getValue(I.getOperand(1));
3558 
3559   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3560       Op1.getValueType(), DAG.getDataLayout());
3561 
3562   // Coerce the shift amount to the right type if we can. This exposes the
3563   // truncate or zext to optimization early.
3564   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3565     assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) &&
3566            "Unexpected shift type");
3567     Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3568   }
3569 
3570   bool nuw = false;
3571   bool nsw = false;
3572   bool exact = false;
3573 
3574   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3575 
3576     if (const OverflowingBinaryOperator *OFBinOp =
3577             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3578       nuw = OFBinOp->hasNoUnsignedWrap();
3579       nsw = OFBinOp->hasNoSignedWrap();
3580     }
3581     if (const PossiblyExactOperator *ExactOp =
3582             dyn_cast<const PossiblyExactOperator>(&I))
3583       exact = ExactOp->isExact();
3584   }
3585   SDNodeFlags Flags;
3586   Flags.setExact(exact);
3587   Flags.setNoSignedWrap(nsw);
3588   Flags.setNoUnsignedWrap(nuw);
3589   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3590                             Flags);
3591   setValue(&I, Res);
3592 }
3593 
3594 void SelectionDAGBuilder::visitSDiv(const User &I) {
3595   SDValue Op1 = getValue(I.getOperand(0));
3596   SDValue Op2 = getValue(I.getOperand(1));
3597 
3598   SDNodeFlags Flags;
3599   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3600                  cast<PossiblyExactOperator>(&I)->isExact());
3601   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3602                            Op2, Flags));
3603 }
3604 
3605 void SelectionDAGBuilder::visitICmp(const User &I) {
3606   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3607   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3608     predicate = IC->getPredicate();
3609   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3610     predicate = ICmpInst::Predicate(IC->getPredicate());
3611   SDValue Op1 = getValue(I.getOperand(0));
3612   SDValue Op2 = getValue(I.getOperand(1));
3613   ISD::CondCode Opcode = getICmpCondCode(predicate);
3614 
3615   auto &TLI = DAG.getTargetLoweringInfo();
3616   EVT MemVT =
3617       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3618 
3619   // If a pointer's DAG type is larger than its memory type then the DAG values
3620   // are zero-extended. This breaks signed comparisons so truncate back to the
3621   // underlying type before doing the compare.
3622   if (Op1.getValueType() != MemVT) {
3623     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3624     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3625   }
3626 
3627   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3628                                                         I.getType());
3629   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3630 }
3631 
3632 void SelectionDAGBuilder::visitFCmp(const User &I) {
3633   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3634   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3635     predicate = FC->getPredicate();
3636   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3637     predicate = FCmpInst::Predicate(FC->getPredicate());
3638   SDValue Op1 = getValue(I.getOperand(0));
3639   SDValue Op2 = getValue(I.getOperand(1));
3640 
3641   ISD::CondCode Condition = getFCmpCondCode(predicate);
3642   auto *FPMO = cast<FPMathOperator>(&I);
3643   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3644     Condition = getFCmpCodeWithoutNaN(Condition);
3645 
3646   SDNodeFlags Flags;
3647   Flags.copyFMF(*FPMO);
3648   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3649 
3650   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3651                                                         I.getType());
3652   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3653 }
3654 
3655 // Check if the condition of the select has one use or two users that are both
3656 // selects with the same condition.
3657 static bool hasOnlySelectUsers(const Value *Cond) {
3658   return llvm::all_of(Cond->users(), [](const Value *V) {
3659     return isa<SelectInst>(V);
3660   });
3661 }
3662 
3663 void SelectionDAGBuilder::visitSelect(const User &I) {
3664   SmallVector<EVT, 4> ValueVTs;
3665   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3666                   ValueVTs);
3667   unsigned NumValues = ValueVTs.size();
3668   if (NumValues == 0) return;
3669 
3670   SmallVector<SDValue, 4> Values(NumValues);
3671   SDValue Cond     = getValue(I.getOperand(0));
3672   SDValue LHSVal   = getValue(I.getOperand(1));
3673   SDValue RHSVal   = getValue(I.getOperand(2));
3674   SmallVector<SDValue, 1> BaseOps(1, Cond);
3675   ISD::NodeType OpCode =
3676       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3677 
3678   bool IsUnaryAbs = false;
3679   bool Negate = false;
3680 
3681   SDNodeFlags Flags;
3682   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3683     Flags.copyFMF(*FPOp);
3684 
3685   Flags.setUnpredictable(
3686       cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable));
3687 
3688   // Min/max matching is only viable if all output VTs are the same.
3689   if (all_equal(ValueVTs)) {
3690     EVT VT = ValueVTs[0];
3691     LLVMContext &Ctx = *DAG.getContext();
3692     auto &TLI = DAG.getTargetLoweringInfo();
3693 
3694     // We care about the legality of the operation after it has been type
3695     // legalized.
3696     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3697       VT = TLI.getTypeToTransformTo(Ctx, VT);
3698 
3699     // If the vselect is legal, assume we want to leave this as a vector setcc +
3700     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3701     // min/max is legal on the scalar type.
3702     bool UseScalarMinMax = VT.isVector() &&
3703       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3704 
3705     // ValueTracking's select pattern matching does not account for -0.0,
3706     // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that
3707     // -0.0 is less than +0.0.
3708     Value *LHS, *RHS;
3709     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3710     ISD::NodeType Opc = ISD::DELETED_NODE;
3711     switch (SPR.Flavor) {
3712     case SPF_UMAX:    Opc = ISD::UMAX; break;
3713     case SPF_UMIN:    Opc = ISD::UMIN; break;
3714     case SPF_SMAX:    Opc = ISD::SMAX; break;
3715     case SPF_SMIN:    Opc = ISD::SMIN; break;
3716     case SPF_FMINNUM:
3717       switch (SPR.NaNBehavior) {
3718       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3719       case SPNB_RETURNS_NAN: break;
3720       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3721       case SPNB_RETURNS_ANY:
3722         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) ||
3723             (UseScalarMinMax &&
3724              TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType())))
3725           Opc = ISD::FMINNUM;
3726         break;
3727       }
3728       break;
3729     case SPF_FMAXNUM:
3730       switch (SPR.NaNBehavior) {
3731       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3732       case SPNB_RETURNS_NAN: break;
3733       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3734       case SPNB_RETURNS_ANY:
3735         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) ||
3736             (UseScalarMinMax &&
3737              TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType())))
3738           Opc = ISD::FMAXNUM;
3739         break;
3740       }
3741       break;
3742     case SPF_NABS:
3743       Negate = true;
3744       [[fallthrough]];
3745     case SPF_ABS:
3746       IsUnaryAbs = true;
3747       Opc = ISD::ABS;
3748       break;
3749     default: break;
3750     }
3751 
3752     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3753         (TLI.isOperationLegalOrCustomOrPromote(Opc, VT) ||
3754          (UseScalarMinMax &&
3755           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3756         // If the underlying comparison instruction is used by any other
3757         // instruction, the consumed instructions won't be destroyed, so it is
3758         // not profitable to convert to a min/max.
3759         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3760       OpCode = Opc;
3761       LHSVal = getValue(LHS);
3762       RHSVal = getValue(RHS);
3763       BaseOps.clear();
3764     }
3765 
3766     if (IsUnaryAbs) {
3767       OpCode = Opc;
3768       LHSVal = getValue(LHS);
3769       BaseOps.clear();
3770     }
3771   }
3772 
3773   if (IsUnaryAbs) {
3774     for (unsigned i = 0; i != NumValues; ++i) {
3775       SDLoc dl = getCurSDLoc();
3776       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3777       Values[i] =
3778           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3779       if (Negate)
3780         Values[i] = DAG.getNegative(Values[i], dl, VT);
3781     }
3782   } else {
3783     for (unsigned i = 0; i != NumValues; ++i) {
3784       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3785       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3786       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3787       Values[i] = DAG.getNode(
3788           OpCode, getCurSDLoc(),
3789           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3790     }
3791   }
3792 
3793   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3794                            DAG.getVTList(ValueVTs), Values));
3795 }
3796 
3797 void SelectionDAGBuilder::visitTrunc(const User &I) {
3798   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3799   SDValue N = getValue(I.getOperand(0));
3800   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3801                                                         I.getType());
3802   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3803 }
3804 
3805 void SelectionDAGBuilder::visitZExt(const User &I) {
3806   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3807   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3808   SDValue N = getValue(I.getOperand(0));
3809   auto &TLI = DAG.getTargetLoweringInfo();
3810   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3811 
3812   SDNodeFlags Flags;
3813   if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
3814     Flags.setNonNeg(PNI->hasNonNeg());
3815 
3816   // Eagerly use nonneg information to canonicalize towards sign_extend if
3817   // that is the target's preference.
3818   // TODO: Let the target do this later.
3819   if (Flags.hasNonNeg() &&
3820       TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) {
3821     setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3822     return;
3823   }
3824 
3825   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags));
3826 }
3827 
3828 void SelectionDAGBuilder::visitSExt(const User &I) {
3829   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3830   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3831   SDValue N = getValue(I.getOperand(0));
3832   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3833                                                         I.getType());
3834   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3835 }
3836 
3837 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3838   // FPTrunc is never a no-op cast, no need to check
3839   SDValue N = getValue(I.getOperand(0));
3840   SDLoc dl = getCurSDLoc();
3841   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3842   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3843   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3844                            DAG.getTargetConstant(
3845                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3846 }
3847 
3848 void SelectionDAGBuilder::visitFPExt(const User &I) {
3849   // FPExt is never a no-op cast, no need to check
3850   SDValue N = getValue(I.getOperand(0));
3851   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3852                                                         I.getType());
3853   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3854 }
3855 
3856 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3857   // FPToUI is never a no-op cast, no need to check
3858   SDValue N = getValue(I.getOperand(0));
3859   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3860                                                         I.getType());
3861   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3862 }
3863 
3864 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3865   // FPToSI is never a no-op cast, no need to check
3866   SDValue N = getValue(I.getOperand(0));
3867   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3868                                                         I.getType());
3869   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3870 }
3871 
3872 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3873   // UIToFP is never a no-op cast, no need to check
3874   SDValue N = getValue(I.getOperand(0));
3875   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3876                                                         I.getType());
3877   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3878 }
3879 
3880 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3881   // SIToFP is never a no-op cast, no need to check
3882   SDValue N = getValue(I.getOperand(0));
3883   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3884                                                         I.getType());
3885   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3886 }
3887 
3888 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3889   // What to do depends on the size of the integer and the size of the pointer.
3890   // We can either truncate, zero extend, or no-op, accordingly.
3891   SDValue N = getValue(I.getOperand(0));
3892   auto &TLI = DAG.getTargetLoweringInfo();
3893   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3894                                                         I.getType());
3895   EVT PtrMemVT =
3896       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3897   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3898   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3899   setValue(&I, N);
3900 }
3901 
3902 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3903   // What to do depends on the size of the integer and the size of the pointer.
3904   // We can either truncate, zero extend, or no-op, accordingly.
3905   SDValue N = getValue(I.getOperand(0));
3906   auto &TLI = DAG.getTargetLoweringInfo();
3907   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3908   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3909   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3910   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3911   setValue(&I, N);
3912 }
3913 
3914 void SelectionDAGBuilder::visitBitCast(const User &I) {
3915   SDValue N = getValue(I.getOperand(0));
3916   SDLoc dl = getCurSDLoc();
3917   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3918                                                         I.getType());
3919 
3920   // BitCast assures us that source and destination are the same size so this is
3921   // either a BITCAST or a no-op.
3922   if (DestVT != N.getValueType())
3923     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3924                              DestVT, N)); // convert types.
3925   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3926   // might fold any kind of constant expression to an integer constant and that
3927   // is not what we are looking for. Only recognize a bitcast of a genuine
3928   // constant integer as an opaque constant.
3929   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3930     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3931                                  /*isOpaque*/true));
3932   else
3933     setValue(&I, N);            // noop cast.
3934 }
3935 
3936 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3937   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3938   const Value *SV = I.getOperand(0);
3939   SDValue N = getValue(SV);
3940   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3941 
3942   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3943   unsigned DestAS = I.getType()->getPointerAddressSpace();
3944 
3945   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3946     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3947 
3948   setValue(&I, N);
3949 }
3950 
3951 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3952   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3953   SDValue InVec = getValue(I.getOperand(0));
3954   SDValue InVal = getValue(I.getOperand(1));
3955   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3956                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3957   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3958                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3959                            InVec, InVal, InIdx));
3960 }
3961 
3962 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3963   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3964   SDValue InVec = getValue(I.getOperand(0));
3965   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3966                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3967   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3968                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3969                            InVec, InIdx));
3970 }
3971 
3972 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3973   SDValue Src1 = getValue(I.getOperand(0));
3974   SDValue Src2 = getValue(I.getOperand(1));
3975   ArrayRef<int> Mask;
3976   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3977     Mask = SVI->getShuffleMask();
3978   else
3979     Mask = cast<ConstantExpr>(I).getShuffleMask();
3980   SDLoc DL = getCurSDLoc();
3981   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3982   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3983   EVT SrcVT = Src1.getValueType();
3984 
3985   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3986       VT.isScalableVector()) {
3987     // Canonical splat form of first element of first input vector.
3988     SDValue FirstElt =
3989         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3990                     DAG.getVectorIdxConstant(0, DL));
3991     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3992     return;
3993   }
3994 
3995   // For now, we only handle splats for scalable vectors.
3996   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3997   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3998   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3999 
4000   unsigned SrcNumElts = SrcVT.getVectorNumElements();
4001   unsigned MaskNumElts = Mask.size();
4002 
4003   if (SrcNumElts == MaskNumElts) {
4004     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
4005     return;
4006   }
4007 
4008   // Normalize the shuffle vector since mask and vector length don't match.
4009   if (SrcNumElts < MaskNumElts) {
4010     // Mask is longer than the source vectors. We can use concatenate vector to
4011     // make the mask and vectors lengths match.
4012 
4013     if (MaskNumElts % SrcNumElts == 0) {
4014       // Mask length is a multiple of the source vector length.
4015       // Check if the shuffle is some kind of concatenation of the input
4016       // vectors.
4017       unsigned NumConcat = MaskNumElts / SrcNumElts;
4018       bool IsConcat = true;
4019       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
4020       for (unsigned i = 0; i != MaskNumElts; ++i) {
4021         int Idx = Mask[i];
4022         if (Idx < 0)
4023           continue;
4024         // Ensure the indices in each SrcVT sized piece are sequential and that
4025         // the same source is used for the whole piece.
4026         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
4027             (ConcatSrcs[i / SrcNumElts] >= 0 &&
4028              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
4029           IsConcat = false;
4030           break;
4031         }
4032         // Remember which source this index came from.
4033         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
4034       }
4035 
4036       // The shuffle is concatenating multiple vectors together. Just emit
4037       // a CONCAT_VECTORS operation.
4038       if (IsConcat) {
4039         SmallVector<SDValue, 8> ConcatOps;
4040         for (auto Src : ConcatSrcs) {
4041           if (Src < 0)
4042             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
4043           else if (Src == 0)
4044             ConcatOps.push_back(Src1);
4045           else
4046             ConcatOps.push_back(Src2);
4047         }
4048         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
4049         return;
4050       }
4051     }
4052 
4053     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
4054     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
4055     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
4056                                     PaddedMaskNumElts);
4057 
4058     // Pad both vectors with undefs to make them the same length as the mask.
4059     SDValue UndefVal = DAG.getUNDEF(SrcVT);
4060 
4061     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
4062     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
4063     MOps1[0] = Src1;
4064     MOps2[0] = Src2;
4065 
4066     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
4067     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
4068 
4069     // Readjust mask for new input vector length.
4070     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
4071     for (unsigned i = 0; i != MaskNumElts; ++i) {
4072       int Idx = Mask[i];
4073       if (Idx >= (int)SrcNumElts)
4074         Idx -= SrcNumElts - PaddedMaskNumElts;
4075       MappedOps[i] = Idx;
4076     }
4077 
4078     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
4079 
4080     // If the concatenated vector was padded, extract a subvector with the
4081     // correct number of elements.
4082     if (MaskNumElts != PaddedMaskNumElts)
4083       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
4084                            DAG.getVectorIdxConstant(0, DL));
4085 
4086     setValue(&I, Result);
4087     return;
4088   }
4089 
4090   if (SrcNumElts > MaskNumElts) {
4091     // Analyze the access pattern of the vector to see if we can extract
4092     // two subvectors and do the shuffle.
4093     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
4094     bool CanExtract = true;
4095     for (int Idx : Mask) {
4096       unsigned Input = 0;
4097       if (Idx < 0)
4098         continue;
4099 
4100       if (Idx >= (int)SrcNumElts) {
4101         Input = 1;
4102         Idx -= SrcNumElts;
4103       }
4104 
4105       // If all the indices come from the same MaskNumElts sized portion of
4106       // the sources we can use extract. Also make sure the extract wouldn't
4107       // extract past the end of the source.
4108       int NewStartIdx = alignDown(Idx, MaskNumElts);
4109       if (NewStartIdx + MaskNumElts > SrcNumElts ||
4110           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
4111         CanExtract = false;
4112       // Make sure we always update StartIdx as we use it to track if all
4113       // elements are undef.
4114       StartIdx[Input] = NewStartIdx;
4115     }
4116 
4117     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
4118       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
4119       return;
4120     }
4121     if (CanExtract) {
4122       // Extract appropriate subvector and generate a vector shuffle
4123       for (unsigned Input = 0; Input < 2; ++Input) {
4124         SDValue &Src = Input == 0 ? Src1 : Src2;
4125         if (StartIdx[Input] < 0)
4126           Src = DAG.getUNDEF(VT);
4127         else {
4128           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
4129                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
4130         }
4131       }
4132 
4133       // Calculate new mask.
4134       SmallVector<int, 8> MappedOps(Mask);
4135       for (int &Idx : MappedOps) {
4136         if (Idx >= (int)SrcNumElts)
4137           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
4138         else if (Idx >= 0)
4139           Idx -= StartIdx[0];
4140       }
4141 
4142       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
4143       return;
4144     }
4145   }
4146 
4147   // We can't use either concat vectors or extract subvectors so fall back to
4148   // replacing the shuffle with extract and build vector.
4149   // to insert and build vector.
4150   EVT EltVT = VT.getVectorElementType();
4151   SmallVector<SDValue,8> Ops;
4152   for (int Idx : Mask) {
4153     SDValue Res;
4154 
4155     if (Idx < 0) {
4156       Res = DAG.getUNDEF(EltVT);
4157     } else {
4158       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
4159       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
4160 
4161       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
4162                         DAG.getVectorIdxConstant(Idx, DL));
4163     }
4164 
4165     Ops.push_back(Res);
4166   }
4167 
4168   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
4169 }
4170 
4171 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
4172   ArrayRef<unsigned> Indices = I.getIndices();
4173   const Value *Op0 = I.getOperand(0);
4174   const Value *Op1 = I.getOperand(1);
4175   Type *AggTy = I.getType();
4176   Type *ValTy = Op1->getType();
4177   bool IntoUndef = isa<UndefValue>(Op0);
4178   bool FromUndef = isa<UndefValue>(Op1);
4179 
4180   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4181 
4182   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4183   SmallVector<EVT, 4> AggValueVTs;
4184   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
4185   SmallVector<EVT, 4> ValValueVTs;
4186   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4187 
4188   unsigned NumAggValues = AggValueVTs.size();
4189   unsigned NumValValues = ValValueVTs.size();
4190   SmallVector<SDValue, 4> Values(NumAggValues);
4191 
4192   // Ignore an insertvalue that produces an empty object
4193   if (!NumAggValues) {
4194     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4195     return;
4196   }
4197 
4198   SDValue Agg = getValue(Op0);
4199   unsigned i = 0;
4200   // Copy the beginning value(s) from the original aggregate.
4201   for (; i != LinearIndex; ++i)
4202     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4203                 SDValue(Agg.getNode(), Agg.getResNo() + i);
4204   // Copy values from the inserted value(s).
4205   if (NumValValues) {
4206     SDValue Val = getValue(Op1);
4207     for (; i != LinearIndex + NumValValues; ++i)
4208       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4209                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
4210   }
4211   // Copy remaining value(s) from the original aggregate.
4212   for (; i != NumAggValues; ++i)
4213     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4214                 SDValue(Agg.getNode(), Agg.getResNo() + i);
4215 
4216   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
4217                            DAG.getVTList(AggValueVTs), Values));
4218 }
4219 
4220 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
4221   ArrayRef<unsigned> Indices = I.getIndices();
4222   const Value *Op0 = I.getOperand(0);
4223   Type *AggTy = Op0->getType();
4224   Type *ValTy = I.getType();
4225   bool OutOfUndef = isa<UndefValue>(Op0);
4226 
4227   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4228 
4229   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4230   SmallVector<EVT, 4> ValValueVTs;
4231   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4232 
4233   unsigned NumValValues = ValValueVTs.size();
4234 
4235   // Ignore a extractvalue that produces an empty object
4236   if (!NumValValues) {
4237     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4238     return;
4239   }
4240 
4241   SmallVector<SDValue, 4> Values(NumValValues);
4242 
4243   SDValue Agg = getValue(Op0);
4244   // Copy out the selected value(s).
4245   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
4246     Values[i - LinearIndex] =
4247       OutOfUndef ?
4248         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
4249         SDValue(Agg.getNode(), Agg.getResNo() + i);
4250 
4251   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
4252                            DAG.getVTList(ValValueVTs), Values));
4253 }
4254 
4255 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
4256   Value *Op0 = I.getOperand(0);
4257   // Note that the pointer operand may be a vector of pointers. Take the scalar
4258   // element which holds a pointer.
4259   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
4260   SDValue N = getValue(Op0);
4261   SDLoc dl = getCurSDLoc();
4262   auto &TLI = DAG.getTargetLoweringInfo();
4263 
4264   // Normalize Vector GEP - all scalar operands should be converted to the
4265   // splat vector.
4266   bool IsVectorGEP = I.getType()->isVectorTy();
4267   ElementCount VectorElementCount =
4268       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
4269                   : ElementCount::getFixed(0);
4270 
4271   if (IsVectorGEP && !N.getValueType().isVector()) {
4272     LLVMContext &Context = *DAG.getContext();
4273     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
4274     N = DAG.getSplat(VT, dl, N);
4275   }
4276 
4277   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
4278        GTI != E; ++GTI) {
4279     const Value *Idx = GTI.getOperand();
4280     if (StructType *StTy = GTI.getStructTypeOrNull()) {
4281       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
4282       if (Field) {
4283         // N = N + Offset
4284         uint64_t Offset =
4285             DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
4286 
4287         // In an inbounds GEP with an offset that is nonnegative even when
4288         // interpreted as signed, assume there is no unsigned overflow.
4289         SDNodeFlags Flags;
4290         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
4291           Flags.setNoUnsignedWrap(true);
4292 
4293         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
4294                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
4295       }
4296     } else {
4297       // IdxSize is the width of the arithmetic according to IR semantics.
4298       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
4299       // (and fix up the result later).
4300       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
4301       MVT IdxTy = MVT::getIntegerVT(IdxSize);
4302       TypeSize ElementSize =
4303           GTI.getSequentialElementStride(DAG.getDataLayout());
4304       // We intentionally mask away the high bits here; ElementSize may not
4305       // fit in IdxTy.
4306       APInt ElementMul(IdxSize, ElementSize.getKnownMinValue());
4307       bool ElementScalable = ElementSize.isScalable();
4308 
4309       // If this is a scalar constant or a splat vector of constants,
4310       // handle it quickly.
4311       const auto *C = dyn_cast<Constant>(Idx);
4312       if (C && isa<VectorType>(C->getType()))
4313         C = C->getSplatValue();
4314 
4315       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
4316       if (CI && CI->isZero())
4317         continue;
4318       if (CI && !ElementScalable) {
4319         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
4320         LLVMContext &Context = *DAG.getContext();
4321         SDValue OffsVal;
4322         if (IsVectorGEP)
4323           OffsVal = DAG.getConstant(
4324               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
4325         else
4326           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
4327 
4328         // In an inbounds GEP with an offset that is nonnegative even when
4329         // interpreted as signed, assume there is no unsigned overflow.
4330         SDNodeFlags Flags;
4331         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
4332           Flags.setNoUnsignedWrap(true);
4333 
4334         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
4335 
4336         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
4337         continue;
4338       }
4339 
4340       // N = N + Idx * ElementMul;
4341       SDValue IdxN = getValue(Idx);
4342 
4343       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
4344         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
4345                                   VectorElementCount);
4346         IdxN = DAG.getSplat(VT, dl, IdxN);
4347       }
4348 
4349       // If the index is smaller or larger than intptr_t, truncate or extend
4350       // it.
4351       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
4352 
4353       if (ElementScalable) {
4354         EVT VScaleTy = N.getValueType().getScalarType();
4355         SDValue VScale = DAG.getNode(
4356             ISD::VSCALE, dl, VScaleTy,
4357             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
4358         if (IsVectorGEP)
4359           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
4360         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
4361       } else {
4362         // If this is a multiply by a power of two, turn it into a shl
4363         // immediately.  This is a very common case.
4364         if (ElementMul != 1) {
4365           if (ElementMul.isPowerOf2()) {
4366             unsigned Amt = ElementMul.logBase2();
4367             IdxN = DAG.getNode(ISD::SHL, dl,
4368                                N.getValueType(), IdxN,
4369                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
4370           } else {
4371             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
4372                                             IdxN.getValueType());
4373             IdxN = DAG.getNode(ISD::MUL, dl,
4374                                N.getValueType(), IdxN, Scale);
4375           }
4376         }
4377       }
4378 
4379       N = DAG.getNode(ISD::ADD, dl,
4380                       N.getValueType(), N, IdxN);
4381     }
4382   }
4383 
4384   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4385   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4386   if (IsVectorGEP) {
4387     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4388     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4389   }
4390 
4391   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4392     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4393 
4394   setValue(&I, N);
4395 }
4396 
4397 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4398   // If this is a fixed sized alloca in the entry block of the function,
4399   // allocate it statically on the stack.
4400   if (FuncInfo.StaticAllocaMap.count(&I))
4401     return;   // getValue will auto-populate this.
4402 
4403   SDLoc dl = getCurSDLoc();
4404   Type *Ty = I.getAllocatedType();
4405   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4406   auto &DL = DAG.getDataLayout();
4407   TypeSize TySize = DL.getTypeAllocSize(Ty);
4408   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4409 
4410   SDValue AllocSize = getValue(I.getArraySize());
4411 
4412   EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace());
4413   if (AllocSize.getValueType() != IntPtr)
4414     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4415 
4416   if (TySize.isScalable())
4417     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4418                             DAG.getVScale(dl, IntPtr,
4419                                           APInt(IntPtr.getScalarSizeInBits(),
4420                                                 TySize.getKnownMinValue())));
4421   else {
4422     SDValue TySizeValue =
4423         DAG.getConstant(TySize.getFixedValue(), dl, MVT::getIntegerVT(64));
4424     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4425                             DAG.getZExtOrTrunc(TySizeValue, dl, IntPtr));
4426   }
4427 
4428   // Handle alignment.  If the requested alignment is less than or equal to
4429   // the stack alignment, ignore it.  If the size is greater than or equal to
4430   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4431   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4432   if (*Alignment <= StackAlign)
4433     Alignment = std::nullopt;
4434 
4435   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4436   // Round the size of the allocation up to the stack alignment size
4437   // by add SA-1 to the size. This doesn't overflow because we're computing
4438   // an address inside an alloca.
4439   SDNodeFlags Flags;
4440   Flags.setNoUnsignedWrap(true);
4441   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4442                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4443 
4444   // Mask out the low bits for alignment purposes.
4445   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4446                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
4447 
4448   SDValue Ops[] = {
4449       getRoot(), AllocSize,
4450       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4451   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4452   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4453   setValue(&I, DSA);
4454   DAG.setRoot(DSA.getValue(1));
4455 
4456   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4457 }
4458 
4459 static const MDNode *getRangeMetadata(const Instruction &I) {
4460   // If !noundef is not present, then !range violation results in a poison
4461   // value rather than immediate undefined behavior. In theory, transferring
4462   // these annotations to SDAG is fine, but in practice there are key SDAG
4463   // transforms that are known not to be poison-safe, such as folding logical
4464   // and/or to bitwise and/or. For now, only transfer !range if !noundef is
4465   // also present.
4466   if (!I.hasMetadata(LLVMContext::MD_noundef))
4467     return nullptr;
4468   return I.getMetadata(LLVMContext::MD_range);
4469 }
4470 
4471 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4472   if (I.isAtomic())
4473     return visitAtomicLoad(I);
4474 
4475   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4476   const Value *SV = I.getOperand(0);
4477   if (TLI.supportSwiftError()) {
4478     // Swifterror values can come from either a function parameter with
4479     // swifterror attribute or an alloca with swifterror attribute.
4480     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4481       if (Arg->hasSwiftErrorAttr())
4482         return visitLoadFromSwiftError(I);
4483     }
4484 
4485     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4486       if (Alloca->isSwiftError())
4487         return visitLoadFromSwiftError(I);
4488     }
4489   }
4490 
4491   SDValue Ptr = getValue(SV);
4492 
4493   Type *Ty = I.getType();
4494   SmallVector<EVT, 4> ValueVTs, MemVTs;
4495   SmallVector<TypeSize, 4> Offsets;
4496   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4497   unsigned NumValues = ValueVTs.size();
4498   if (NumValues == 0)
4499     return;
4500 
4501   Align Alignment = I.getAlign();
4502   AAMDNodes AAInfo = I.getAAMetadata();
4503   const MDNode *Ranges = getRangeMetadata(I);
4504   bool isVolatile = I.isVolatile();
4505   MachineMemOperand::Flags MMOFlags =
4506       TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4507 
4508   SDValue Root;
4509   bool ConstantMemory = false;
4510   if (isVolatile)
4511     // Serialize volatile loads with other side effects.
4512     Root = getRoot();
4513   else if (NumValues > MaxParallelChains)
4514     Root = getMemoryRoot();
4515   else if (AA &&
4516            AA->pointsToConstantMemory(MemoryLocation(
4517                SV,
4518                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4519                AAInfo))) {
4520     // Do not serialize (non-volatile) loads of constant memory with anything.
4521     Root = DAG.getEntryNode();
4522     ConstantMemory = true;
4523     MMOFlags |= MachineMemOperand::MOInvariant;
4524   } else {
4525     // Do not serialize non-volatile loads against each other.
4526     Root = DAG.getRoot();
4527   }
4528 
4529   SDLoc dl = getCurSDLoc();
4530 
4531   if (isVolatile)
4532     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4533 
4534   SmallVector<SDValue, 4> Values(NumValues);
4535   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4536 
4537   unsigned ChainI = 0;
4538   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4539     // Serializing loads here may result in excessive register pressure, and
4540     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4541     // could recover a bit by hoisting nodes upward in the chain by recognizing
4542     // they are side-effect free or do not alias. The optimizer should really
4543     // avoid this case by converting large object/array copies to llvm.memcpy
4544     // (MaxParallelChains should always remain as failsafe).
4545     if (ChainI == MaxParallelChains) {
4546       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4547       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4548                                   ArrayRef(Chains.data(), ChainI));
4549       Root = Chain;
4550       ChainI = 0;
4551     }
4552 
4553     // TODO: MachinePointerInfo only supports a fixed length offset.
4554     MachinePointerInfo PtrInfo =
4555         !Offsets[i].isScalable() || Offsets[i].isZero()
4556             ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue())
4557             : MachinePointerInfo();
4558 
4559     SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4560     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment,
4561                             MMOFlags, AAInfo, Ranges);
4562     Chains[ChainI] = L.getValue(1);
4563 
4564     if (MemVTs[i] != ValueVTs[i])
4565       L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]);
4566 
4567     Values[i] = L;
4568   }
4569 
4570   if (!ConstantMemory) {
4571     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4572                                 ArrayRef(Chains.data(), ChainI));
4573     if (isVolatile)
4574       DAG.setRoot(Chain);
4575     else
4576       PendingLoads.push_back(Chain);
4577   }
4578 
4579   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4580                            DAG.getVTList(ValueVTs), Values));
4581 }
4582 
4583 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4584   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4585          "call visitStoreToSwiftError when backend supports swifterror");
4586 
4587   SmallVector<EVT, 4> ValueVTs;
4588   SmallVector<uint64_t, 4> Offsets;
4589   const Value *SrcV = I.getOperand(0);
4590   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4591                   SrcV->getType(), ValueVTs, &Offsets, 0);
4592   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4593          "expect a single EVT for swifterror");
4594 
4595   SDValue Src = getValue(SrcV);
4596   // Create a virtual register, then update the virtual register.
4597   Register VReg =
4598       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4599   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4600   // Chain can be getRoot or getControlRoot.
4601   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4602                                       SDValue(Src.getNode(), Src.getResNo()));
4603   DAG.setRoot(CopyNode);
4604 }
4605 
4606 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4607   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4608          "call visitLoadFromSwiftError when backend supports swifterror");
4609 
4610   assert(!I.isVolatile() &&
4611          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4612          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4613          "Support volatile, non temporal, invariant for load_from_swift_error");
4614 
4615   const Value *SV = I.getOperand(0);
4616   Type *Ty = I.getType();
4617   assert(
4618       (!AA ||
4619        !AA->pointsToConstantMemory(MemoryLocation(
4620            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4621            I.getAAMetadata()))) &&
4622       "load_from_swift_error should not be constant memory");
4623 
4624   SmallVector<EVT, 4> ValueVTs;
4625   SmallVector<uint64_t, 4> Offsets;
4626   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4627                   ValueVTs, &Offsets, 0);
4628   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4629          "expect a single EVT for swifterror");
4630 
4631   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4632   SDValue L = DAG.getCopyFromReg(
4633       getRoot(), getCurSDLoc(),
4634       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4635 
4636   setValue(&I, L);
4637 }
4638 
4639 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4640   if (I.isAtomic())
4641     return visitAtomicStore(I);
4642 
4643   const Value *SrcV = I.getOperand(0);
4644   const Value *PtrV = I.getOperand(1);
4645 
4646   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4647   if (TLI.supportSwiftError()) {
4648     // Swifterror values can come from either a function parameter with
4649     // swifterror attribute or an alloca with swifterror attribute.
4650     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4651       if (Arg->hasSwiftErrorAttr())
4652         return visitStoreToSwiftError(I);
4653     }
4654 
4655     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4656       if (Alloca->isSwiftError())
4657         return visitStoreToSwiftError(I);
4658     }
4659   }
4660 
4661   SmallVector<EVT, 4> ValueVTs, MemVTs;
4662   SmallVector<TypeSize, 4> Offsets;
4663   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4664                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4665   unsigned NumValues = ValueVTs.size();
4666   if (NumValues == 0)
4667     return;
4668 
4669   // Get the lowered operands. Note that we do this after
4670   // checking if NumResults is zero, because with zero results
4671   // the operands won't have values in the map.
4672   SDValue Src = getValue(SrcV);
4673   SDValue Ptr = getValue(PtrV);
4674 
4675   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4676   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4677   SDLoc dl = getCurSDLoc();
4678   Align Alignment = I.getAlign();
4679   AAMDNodes AAInfo = I.getAAMetadata();
4680 
4681   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4682 
4683   unsigned ChainI = 0;
4684   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4685     // See visitLoad comments.
4686     if (ChainI == MaxParallelChains) {
4687       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4688                                   ArrayRef(Chains.data(), ChainI));
4689       Root = Chain;
4690       ChainI = 0;
4691     }
4692 
4693     // TODO: MachinePointerInfo only supports a fixed length offset.
4694     MachinePointerInfo PtrInfo =
4695         !Offsets[i].isScalable() || Offsets[i].isZero()
4696             ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue())
4697             : MachinePointerInfo();
4698 
4699     SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4700     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4701     if (MemVTs[i] != ValueVTs[i])
4702       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4703     SDValue St =
4704         DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags, AAInfo);
4705     Chains[ChainI] = St;
4706   }
4707 
4708   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4709                                   ArrayRef(Chains.data(), ChainI));
4710   setValue(&I, StoreNode);
4711   DAG.setRoot(StoreNode);
4712 }
4713 
4714 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4715                                            bool IsCompressing) {
4716   SDLoc sdl = getCurSDLoc();
4717 
4718   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4719                                MaybeAlign &Alignment) {
4720     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4721     Src0 = I.getArgOperand(0);
4722     Ptr = I.getArgOperand(1);
4723     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
4724     Mask = I.getArgOperand(3);
4725   };
4726   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4727                                     MaybeAlign &Alignment) {
4728     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4729     Src0 = I.getArgOperand(0);
4730     Ptr = I.getArgOperand(1);
4731     Mask = I.getArgOperand(2);
4732     Alignment = std::nullopt;
4733   };
4734 
4735   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4736   MaybeAlign Alignment;
4737   if (IsCompressing)
4738     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4739   else
4740     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4741 
4742   SDValue Ptr = getValue(PtrOperand);
4743   SDValue Src0 = getValue(Src0Operand);
4744   SDValue Mask = getValue(MaskOperand);
4745   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4746 
4747   EVT VT = Src0.getValueType();
4748   if (!Alignment)
4749     Alignment = DAG.getEVTAlign(VT);
4750 
4751   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4752       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4753       MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata());
4754   SDValue StoreNode =
4755       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4756                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4757   DAG.setRoot(StoreNode);
4758   setValue(&I, StoreNode);
4759 }
4760 
4761 // Get a uniform base for the Gather/Scatter intrinsic.
4762 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4763 // We try to represent it as a base pointer + vector of indices.
4764 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4765 // The first operand of the GEP may be a single pointer or a vector of pointers
4766 // Example:
4767 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4768 //  or
4769 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4770 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4771 //
4772 // When the first GEP operand is a single pointer - it is the uniform base we
4773 // are looking for. If first operand of the GEP is a splat vector - we
4774 // extract the splat value and use it as a uniform base.
4775 // In all other cases the function returns 'false'.
4776 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4777                            ISD::MemIndexType &IndexType, SDValue &Scale,
4778                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB,
4779                            uint64_t ElemSize) {
4780   SelectionDAG& DAG = SDB->DAG;
4781   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4782   const DataLayout &DL = DAG.getDataLayout();
4783 
4784   assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4785 
4786   // Handle splat constant pointer.
4787   if (auto *C = dyn_cast<Constant>(Ptr)) {
4788     C = C->getSplatValue();
4789     if (!C)
4790       return false;
4791 
4792     Base = SDB->getValue(C);
4793 
4794     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4795     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4796     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4797     IndexType = ISD::SIGNED_SCALED;
4798     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4799     return true;
4800   }
4801 
4802   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4803   if (!GEP || GEP->getParent() != CurBB)
4804     return false;
4805 
4806   if (GEP->getNumOperands() != 2)
4807     return false;
4808 
4809   const Value *BasePtr = GEP->getPointerOperand();
4810   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4811 
4812   // Make sure the base is scalar and the index is a vector.
4813   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4814     return false;
4815 
4816   TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
4817   if (ScaleVal.isScalable())
4818     return false;
4819 
4820   // Target may not support the required addressing mode.
4821   if (ScaleVal != 1 &&
4822       !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize))
4823     return false;
4824 
4825   Base = SDB->getValue(BasePtr);
4826   Index = SDB->getValue(IndexVal);
4827   IndexType = ISD::SIGNED_SCALED;
4828 
4829   Scale =
4830       DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4831   return true;
4832 }
4833 
4834 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4835   SDLoc sdl = getCurSDLoc();
4836 
4837   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4838   const Value *Ptr = I.getArgOperand(1);
4839   SDValue Src0 = getValue(I.getArgOperand(0));
4840   SDValue Mask = getValue(I.getArgOperand(3));
4841   EVT VT = Src0.getValueType();
4842   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4843                         ->getMaybeAlignValue()
4844                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4845   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4846 
4847   SDValue Base;
4848   SDValue Index;
4849   ISD::MemIndexType IndexType;
4850   SDValue Scale;
4851   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4852                                     I.getParent(), VT.getScalarStoreSize());
4853 
4854   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4855   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4856       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4857       // TODO: Make MachineMemOperands aware of scalable
4858       // vectors.
4859       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata());
4860   if (!UniformBase) {
4861     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4862     Index = getValue(Ptr);
4863     IndexType = ISD::SIGNED_SCALED;
4864     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4865   }
4866 
4867   EVT IdxVT = Index.getValueType();
4868   EVT EltTy = IdxVT.getVectorElementType();
4869   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4870     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4871     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4872   }
4873 
4874   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4875   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4876                                          Ops, MMO, IndexType, false);
4877   DAG.setRoot(Scatter);
4878   setValue(&I, Scatter);
4879 }
4880 
4881 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4882   SDLoc sdl = getCurSDLoc();
4883 
4884   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4885                               MaybeAlign &Alignment) {
4886     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4887     Ptr = I.getArgOperand(0);
4888     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4889     Mask = I.getArgOperand(2);
4890     Src0 = I.getArgOperand(3);
4891   };
4892   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4893                                  MaybeAlign &Alignment) {
4894     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4895     Ptr = I.getArgOperand(0);
4896     Alignment = std::nullopt;
4897     Mask = I.getArgOperand(1);
4898     Src0 = I.getArgOperand(2);
4899   };
4900 
4901   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4902   MaybeAlign Alignment;
4903   if (IsExpanding)
4904     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4905   else
4906     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4907 
4908   SDValue Ptr = getValue(PtrOperand);
4909   SDValue Src0 = getValue(Src0Operand);
4910   SDValue Mask = getValue(MaskOperand);
4911   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4912 
4913   EVT VT = Src0.getValueType();
4914   if (!Alignment)
4915     Alignment = DAG.getEVTAlign(VT);
4916 
4917   AAMDNodes AAInfo = I.getAAMetadata();
4918   const MDNode *Ranges = getRangeMetadata(I);
4919 
4920   // Do not serialize masked loads of constant memory with anything.
4921   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
4922   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4923 
4924   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4925 
4926   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4927       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4928       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
4929 
4930   SDValue Load =
4931       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4932                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4933   if (AddToChain)
4934     PendingLoads.push_back(Load.getValue(1));
4935   setValue(&I, Load);
4936 }
4937 
4938 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4939   SDLoc sdl = getCurSDLoc();
4940 
4941   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4942   const Value *Ptr = I.getArgOperand(0);
4943   SDValue Src0 = getValue(I.getArgOperand(3));
4944   SDValue Mask = getValue(I.getArgOperand(2));
4945 
4946   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4947   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4948   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4949                         ->getMaybeAlignValue()
4950                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4951 
4952   const MDNode *Ranges = getRangeMetadata(I);
4953 
4954   SDValue Root = DAG.getRoot();
4955   SDValue Base;
4956   SDValue Index;
4957   ISD::MemIndexType IndexType;
4958   SDValue Scale;
4959   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4960                                     I.getParent(), VT.getScalarStoreSize());
4961   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4962   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4963       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4964       // TODO: Make MachineMemOperands aware of scalable
4965       // vectors.
4966       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
4967 
4968   if (!UniformBase) {
4969     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4970     Index = getValue(Ptr);
4971     IndexType = ISD::SIGNED_SCALED;
4972     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4973   }
4974 
4975   EVT IdxVT = Index.getValueType();
4976   EVT EltTy = IdxVT.getVectorElementType();
4977   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4978     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4979     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4980   }
4981 
4982   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4983   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4984                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
4985 
4986   PendingLoads.push_back(Gather.getValue(1));
4987   setValue(&I, Gather);
4988 }
4989 
4990 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4991   SDLoc dl = getCurSDLoc();
4992   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4993   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4994   SyncScope::ID SSID = I.getSyncScopeID();
4995 
4996   SDValue InChain = getRoot();
4997 
4998   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4999   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
5000 
5001   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5002   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5003 
5004   MachineFunction &MF = DAG.getMachineFunction();
5005   MachineMemOperand *MMO = MF.getMachineMemOperand(
5006       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
5007       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
5008       FailureOrdering);
5009 
5010   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
5011                                    dl, MemVT, VTs, InChain,
5012                                    getValue(I.getPointerOperand()),
5013                                    getValue(I.getCompareOperand()),
5014                                    getValue(I.getNewValOperand()), MMO);
5015 
5016   SDValue OutChain = L.getValue(2);
5017 
5018   setValue(&I, L);
5019   DAG.setRoot(OutChain);
5020 }
5021 
5022 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
5023   SDLoc dl = getCurSDLoc();
5024   ISD::NodeType NT;
5025   switch (I.getOperation()) {
5026   default: llvm_unreachable("Unknown atomicrmw operation");
5027   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
5028   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
5029   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
5030   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
5031   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
5032   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
5033   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
5034   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
5035   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
5036   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
5037   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
5038   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
5039   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
5040   case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break;
5041   case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break;
5042   case AtomicRMWInst::UIncWrap:
5043     NT = ISD::ATOMIC_LOAD_UINC_WRAP;
5044     break;
5045   case AtomicRMWInst::UDecWrap:
5046     NT = ISD::ATOMIC_LOAD_UDEC_WRAP;
5047     break;
5048   }
5049   AtomicOrdering Ordering = I.getOrdering();
5050   SyncScope::ID SSID = I.getSyncScopeID();
5051 
5052   SDValue InChain = getRoot();
5053 
5054   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
5055   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5056   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5057 
5058   MachineFunction &MF = DAG.getMachineFunction();
5059   MachineMemOperand *MMO = MF.getMachineMemOperand(
5060       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
5061       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
5062 
5063   SDValue L =
5064     DAG.getAtomic(NT, dl, MemVT, InChain,
5065                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
5066                   MMO);
5067 
5068   SDValue OutChain = L.getValue(1);
5069 
5070   setValue(&I, L);
5071   DAG.setRoot(OutChain);
5072 }
5073 
5074 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
5075   SDLoc dl = getCurSDLoc();
5076   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5077   SDValue Ops[3];
5078   Ops[0] = getRoot();
5079   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
5080                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
5081   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
5082                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
5083   SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
5084   setValue(&I, N);
5085   DAG.setRoot(N);
5086 }
5087 
5088 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
5089   SDLoc dl = getCurSDLoc();
5090   AtomicOrdering Order = I.getOrdering();
5091   SyncScope::ID SSID = I.getSyncScopeID();
5092 
5093   SDValue InChain = getRoot();
5094 
5095   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5096   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5097   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
5098 
5099   if (!TLI.supportsUnalignedAtomics() &&
5100       I.getAlign().value() < MemVT.getSizeInBits() / 8)
5101     report_fatal_error("Cannot generate unaligned atomic load");
5102 
5103   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
5104 
5105   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5106       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
5107       I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
5108 
5109   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
5110 
5111   SDValue Ptr = getValue(I.getPointerOperand());
5112   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
5113                             Ptr, MMO);
5114 
5115   SDValue OutChain = L.getValue(1);
5116   if (MemVT != VT)
5117     L = DAG.getPtrExtOrTrunc(L, dl, VT);
5118 
5119   setValue(&I, L);
5120   DAG.setRoot(OutChain);
5121 }
5122 
5123 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
5124   SDLoc dl = getCurSDLoc();
5125 
5126   AtomicOrdering Ordering = I.getOrdering();
5127   SyncScope::ID SSID = I.getSyncScopeID();
5128 
5129   SDValue InChain = getRoot();
5130 
5131   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5132   EVT MemVT =
5133       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
5134 
5135   if (!TLI.supportsUnalignedAtomics() &&
5136       I.getAlign().value() < MemVT.getSizeInBits() / 8)
5137     report_fatal_error("Cannot generate unaligned atomic store");
5138 
5139   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
5140 
5141   MachineFunction &MF = DAG.getMachineFunction();
5142   MachineMemOperand *MMO = MF.getMachineMemOperand(
5143       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
5144       I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
5145 
5146   SDValue Val = getValue(I.getValueOperand());
5147   if (Val.getValueType() != MemVT)
5148     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
5149   SDValue Ptr = getValue(I.getPointerOperand());
5150 
5151   SDValue OutChain =
5152       DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO);
5153 
5154   setValue(&I, OutChain);
5155   DAG.setRoot(OutChain);
5156 }
5157 
5158 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
5159 /// node.
5160 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
5161                                                unsigned Intrinsic) {
5162   // Ignore the callsite's attributes. A specific call site may be marked with
5163   // readnone, but the lowering code will expect the chain based on the
5164   // definition.
5165   const Function *F = I.getCalledFunction();
5166   bool HasChain = !F->doesNotAccessMemory();
5167   bool OnlyLoad = HasChain && F->onlyReadsMemory();
5168 
5169   // Build the operand list.
5170   SmallVector<SDValue, 8> Ops;
5171   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
5172     if (OnlyLoad) {
5173       // We don't need to serialize loads against other loads.
5174       Ops.push_back(DAG.getRoot());
5175     } else {
5176       Ops.push_back(getRoot());
5177     }
5178   }
5179 
5180   // Info is set by getTgtMemIntrinsic
5181   TargetLowering::IntrinsicInfo Info;
5182   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5183   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
5184                                                DAG.getMachineFunction(),
5185                                                Intrinsic);
5186 
5187   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
5188   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
5189       Info.opc == ISD::INTRINSIC_W_CHAIN)
5190     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
5191                                         TLI.getPointerTy(DAG.getDataLayout())));
5192 
5193   // Add all operands of the call to the operand list.
5194   for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
5195     const Value *Arg = I.getArgOperand(i);
5196     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
5197       Ops.push_back(getValue(Arg));
5198       continue;
5199     }
5200 
5201     // Use TargetConstant instead of a regular constant for immarg.
5202     EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
5203     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
5204       assert(CI->getBitWidth() <= 64 &&
5205              "large intrinsic immediates not handled");
5206       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
5207     } else {
5208       Ops.push_back(
5209           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
5210     }
5211   }
5212 
5213   SmallVector<EVT, 4> ValueVTs;
5214   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
5215 
5216   if (HasChain)
5217     ValueVTs.push_back(MVT::Other);
5218 
5219   SDVTList VTs = DAG.getVTList(ValueVTs);
5220 
5221   // Propagate fast-math-flags from IR to node(s).
5222   SDNodeFlags Flags;
5223   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
5224     Flags.copyFMF(*FPMO);
5225   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
5226 
5227   // Create the node.
5228   SDValue Result;
5229   // In some cases, custom collection of operands from CallInst I may be needed.
5230   TLI.CollectTargetIntrinsicOperands(I, Ops, DAG);
5231   if (IsTgtIntrinsic) {
5232     // This is target intrinsic that touches memory
5233     //
5234     // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic
5235     //       didn't yield anything useful.
5236     MachinePointerInfo MPI;
5237     if (Info.ptrVal)
5238       MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
5239     else if (Info.fallbackAddressSpace)
5240       MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
5241     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops,
5242                                      Info.memVT, MPI, Info.align, Info.flags,
5243                                      Info.size, I.getAAMetadata());
5244   } else if (!HasChain) {
5245     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
5246   } else if (!I.getType()->isVoidTy()) {
5247     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
5248   } else {
5249     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
5250   }
5251 
5252   if (HasChain) {
5253     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
5254     if (OnlyLoad)
5255       PendingLoads.push_back(Chain);
5256     else
5257       DAG.setRoot(Chain);
5258   }
5259 
5260   if (!I.getType()->isVoidTy()) {
5261     if (!isa<VectorType>(I.getType()))
5262       Result = lowerRangeToAssertZExt(DAG, I, Result);
5263 
5264     MaybeAlign Alignment = I.getRetAlign();
5265 
5266     // Insert `assertalign` node if there's an alignment.
5267     if (InsertAssertAlign && Alignment) {
5268       Result =
5269           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
5270     }
5271 
5272     setValue(&I, Result);
5273   }
5274 }
5275 
5276 /// GetSignificand - Get the significand and build it into a floating-point
5277 /// number with exponent of 1:
5278 ///
5279 ///   Op = (Op & 0x007fffff) | 0x3f800000;
5280 ///
5281 /// where Op is the hexadecimal representation of floating point value.
5282 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
5283   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5284                            DAG.getConstant(0x007fffff, dl, MVT::i32));
5285   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
5286                            DAG.getConstant(0x3f800000, dl, MVT::i32));
5287   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
5288 }
5289 
5290 /// GetExponent - Get the exponent:
5291 ///
5292 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
5293 ///
5294 /// where Op is the hexadecimal representation of floating point value.
5295 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
5296                            const TargetLowering &TLI, const SDLoc &dl) {
5297   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5298                            DAG.getConstant(0x7f800000, dl, MVT::i32));
5299   SDValue t1 = DAG.getNode(
5300       ISD::SRL, dl, MVT::i32, t0,
5301       DAG.getConstant(23, dl,
5302                       TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout())));
5303   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
5304                            DAG.getConstant(127, dl, MVT::i32));
5305   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
5306 }
5307 
5308 /// getF32Constant - Get 32-bit floating point constant.
5309 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
5310                               const SDLoc &dl) {
5311   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
5312                            MVT::f32);
5313 }
5314 
5315 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
5316                                        SelectionDAG &DAG) {
5317   // TODO: What fast-math-flags should be set on the floating-point nodes?
5318 
5319   //   IntegerPartOfX = ((int32_t)(t0);
5320   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
5321 
5322   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
5323   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
5324   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
5325 
5326   //   IntegerPartOfX <<= 23;
5327   IntegerPartOfX =
5328       DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
5329                   DAG.getConstant(23, dl,
5330                                   DAG.getTargetLoweringInfo().getShiftAmountTy(
5331                                       MVT::i32, DAG.getDataLayout())));
5332 
5333   SDValue TwoToFractionalPartOfX;
5334   if (LimitFloatPrecision <= 6) {
5335     // For floating-point precision of 6:
5336     //
5337     //   TwoToFractionalPartOfX =
5338     //     0.997535578f +
5339     //       (0.735607626f + 0.252464424f * x) * x;
5340     //
5341     // error 0.0144103317, which is 6 bits
5342     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5343                              getF32Constant(DAG, 0x3e814304, dl));
5344     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5345                              getF32Constant(DAG, 0x3f3c50c8, dl));
5346     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5347     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5348                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
5349   } else if (LimitFloatPrecision <= 12) {
5350     // For floating-point precision of 12:
5351     //
5352     //   TwoToFractionalPartOfX =
5353     //     0.999892986f +
5354     //       (0.696457318f +
5355     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
5356     //
5357     // error 0.000107046256, which is 13 to 14 bits
5358     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5359                              getF32Constant(DAG, 0x3da235e3, dl));
5360     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5361                              getF32Constant(DAG, 0x3e65b8f3, dl));
5362     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5363     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5364                              getF32Constant(DAG, 0x3f324b07, dl));
5365     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5366     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5367                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
5368   } else { // LimitFloatPrecision <= 18
5369     // For floating-point precision of 18:
5370     //
5371     //   TwoToFractionalPartOfX =
5372     //     0.999999982f +
5373     //       (0.693148872f +
5374     //         (0.240227044f +
5375     //           (0.554906021e-1f +
5376     //             (0.961591928e-2f +
5377     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5378     // error 2.47208000*10^(-7), which is better than 18 bits
5379     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5380                              getF32Constant(DAG, 0x3924b03e, dl));
5381     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5382                              getF32Constant(DAG, 0x3ab24b87, dl));
5383     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5384     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5385                              getF32Constant(DAG, 0x3c1d8c17, dl));
5386     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5387     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5388                              getF32Constant(DAG, 0x3d634a1d, dl));
5389     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5390     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5391                              getF32Constant(DAG, 0x3e75fe14, dl));
5392     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5393     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5394                               getF32Constant(DAG, 0x3f317234, dl));
5395     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5396     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5397                                          getF32Constant(DAG, 0x3f800000, dl));
5398   }
5399 
5400   // Add the exponent into the result in integer domain.
5401   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5402   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5403                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5404 }
5405 
5406 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5407 /// limited-precision mode.
5408 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5409                          const TargetLowering &TLI, SDNodeFlags Flags) {
5410   if (Op.getValueType() == MVT::f32 &&
5411       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5412 
5413     // Put the exponent in the right bit position for later addition to the
5414     // final result:
5415     //
5416     // t0 = Op * log2(e)
5417 
5418     // TODO: What fast-math-flags should be set here?
5419     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5420                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5421     return getLimitedPrecisionExp2(t0, dl, DAG);
5422   }
5423 
5424   // No special expansion.
5425   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5426 }
5427 
5428 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5429 /// limited-precision mode.
5430 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5431                          const TargetLowering &TLI, SDNodeFlags Flags) {
5432   // TODO: What fast-math-flags should be set on the floating-point nodes?
5433 
5434   if (Op.getValueType() == MVT::f32 &&
5435       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5436     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5437 
5438     // Scale the exponent by log(2).
5439     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5440     SDValue LogOfExponent =
5441         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5442                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5443 
5444     // Get the significand and build it into a floating-point number with
5445     // exponent of 1.
5446     SDValue X = GetSignificand(DAG, Op1, dl);
5447 
5448     SDValue LogOfMantissa;
5449     if (LimitFloatPrecision <= 6) {
5450       // For floating-point precision of 6:
5451       //
5452       //   LogofMantissa =
5453       //     -1.1609546f +
5454       //       (1.4034025f - 0.23903021f * x) * x;
5455       //
5456       // error 0.0034276066, which is better than 8 bits
5457       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5458                                getF32Constant(DAG, 0xbe74c456, dl));
5459       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5460                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5461       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5462       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5463                                   getF32Constant(DAG, 0x3f949a29, dl));
5464     } else if (LimitFloatPrecision <= 12) {
5465       // For floating-point precision of 12:
5466       //
5467       //   LogOfMantissa =
5468       //     -1.7417939f +
5469       //       (2.8212026f +
5470       //         (-1.4699568f +
5471       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5472       //
5473       // error 0.000061011436, which is 14 bits
5474       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5475                                getF32Constant(DAG, 0xbd67b6d6, dl));
5476       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5477                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5478       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5479       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5480                                getF32Constant(DAG, 0x3fbc278b, dl));
5481       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5482       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5483                                getF32Constant(DAG, 0x40348e95, dl));
5484       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5485       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5486                                   getF32Constant(DAG, 0x3fdef31a, dl));
5487     } else { // LimitFloatPrecision <= 18
5488       // For floating-point precision of 18:
5489       //
5490       //   LogOfMantissa =
5491       //     -2.1072184f +
5492       //       (4.2372794f +
5493       //         (-3.7029485f +
5494       //           (2.2781945f +
5495       //             (-0.87823314f +
5496       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5497       //
5498       // error 0.0000023660568, which is better than 18 bits
5499       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5500                                getF32Constant(DAG, 0xbc91e5ac, dl));
5501       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5502                                getF32Constant(DAG, 0x3e4350aa, dl));
5503       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5504       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5505                                getF32Constant(DAG, 0x3f60d3e3, dl));
5506       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5507       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5508                                getF32Constant(DAG, 0x4011cdf0, dl));
5509       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5510       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5511                                getF32Constant(DAG, 0x406cfd1c, dl));
5512       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5513       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5514                                getF32Constant(DAG, 0x408797cb, dl));
5515       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5516       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5517                                   getF32Constant(DAG, 0x4006dcab, dl));
5518     }
5519 
5520     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5521   }
5522 
5523   // No special expansion.
5524   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5525 }
5526 
5527 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5528 /// limited-precision mode.
5529 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5530                           const TargetLowering &TLI, SDNodeFlags Flags) {
5531   // TODO: What fast-math-flags should be set on the floating-point nodes?
5532 
5533   if (Op.getValueType() == MVT::f32 &&
5534       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5535     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5536 
5537     // Get the exponent.
5538     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5539 
5540     // Get the significand and build it into a floating-point number with
5541     // exponent of 1.
5542     SDValue X = GetSignificand(DAG, Op1, dl);
5543 
5544     // Different possible minimax approximations of significand in
5545     // floating-point for various degrees of accuracy over [1,2].
5546     SDValue Log2ofMantissa;
5547     if (LimitFloatPrecision <= 6) {
5548       // For floating-point precision of 6:
5549       //
5550       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5551       //
5552       // error 0.0049451742, which is more than 7 bits
5553       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5554                                getF32Constant(DAG, 0xbeb08fe0, dl));
5555       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5556                                getF32Constant(DAG, 0x40019463, dl));
5557       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5558       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5559                                    getF32Constant(DAG, 0x3fd6633d, dl));
5560     } else if (LimitFloatPrecision <= 12) {
5561       // For floating-point precision of 12:
5562       //
5563       //   Log2ofMantissa =
5564       //     -2.51285454f +
5565       //       (4.07009056f +
5566       //         (-2.12067489f +
5567       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5568       //
5569       // error 0.0000876136000, which is better than 13 bits
5570       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5571                                getF32Constant(DAG, 0xbda7262e, dl));
5572       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5573                                getF32Constant(DAG, 0x3f25280b, dl));
5574       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5575       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5576                                getF32Constant(DAG, 0x4007b923, dl));
5577       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5578       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5579                                getF32Constant(DAG, 0x40823e2f, dl));
5580       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5581       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5582                                    getF32Constant(DAG, 0x4020d29c, dl));
5583     } else { // LimitFloatPrecision <= 18
5584       // For floating-point precision of 18:
5585       //
5586       //   Log2ofMantissa =
5587       //     -3.0400495f +
5588       //       (6.1129976f +
5589       //         (-5.3420409f +
5590       //           (3.2865683f +
5591       //             (-1.2669343f +
5592       //               (0.27515199f -
5593       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5594       //
5595       // error 0.0000018516, which is better than 18 bits
5596       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5597                                getF32Constant(DAG, 0xbcd2769e, dl));
5598       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5599                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5600       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5601       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5602                                getF32Constant(DAG, 0x3fa22ae7, dl));
5603       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5604       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5605                                getF32Constant(DAG, 0x40525723, dl));
5606       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5607       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5608                                getF32Constant(DAG, 0x40aaf200, dl));
5609       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5610       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5611                                getF32Constant(DAG, 0x40c39dad, dl));
5612       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5613       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5614                                    getF32Constant(DAG, 0x4042902c, dl));
5615     }
5616 
5617     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5618   }
5619 
5620   // No special expansion.
5621   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5622 }
5623 
5624 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5625 /// limited-precision mode.
5626 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5627                            const TargetLowering &TLI, SDNodeFlags Flags) {
5628   // TODO: What fast-math-flags should be set on the floating-point nodes?
5629 
5630   if (Op.getValueType() == MVT::f32 &&
5631       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5632     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5633 
5634     // Scale the exponent by log10(2) [0.30102999f].
5635     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5636     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5637                                         getF32Constant(DAG, 0x3e9a209a, dl));
5638 
5639     // Get the significand and build it into a floating-point number with
5640     // exponent of 1.
5641     SDValue X = GetSignificand(DAG, Op1, dl);
5642 
5643     SDValue Log10ofMantissa;
5644     if (LimitFloatPrecision <= 6) {
5645       // For floating-point precision of 6:
5646       //
5647       //   Log10ofMantissa =
5648       //     -0.50419619f +
5649       //       (0.60948995f - 0.10380950f * x) * x;
5650       //
5651       // error 0.0014886165, which is 6 bits
5652       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5653                                getF32Constant(DAG, 0xbdd49a13, dl));
5654       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5655                                getF32Constant(DAG, 0x3f1c0789, dl));
5656       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5657       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5658                                     getF32Constant(DAG, 0x3f011300, dl));
5659     } else if (LimitFloatPrecision <= 12) {
5660       // For floating-point precision of 12:
5661       //
5662       //   Log10ofMantissa =
5663       //     -0.64831180f +
5664       //       (0.91751397f +
5665       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5666       //
5667       // error 0.00019228036, which is better than 12 bits
5668       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5669                                getF32Constant(DAG, 0x3d431f31, dl));
5670       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5671                                getF32Constant(DAG, 0x3ea21fb2, dl));
5672       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5673       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5674                                getF32Constant(DAG, 0x3f6ae232, dl));
5675       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5676       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5677                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5678     } else { // LimitFloatPrecision <= 18
5679       // For floating-point precision of 18:
5680       //
5681       //   Log10ofMantissa =
5682       //     -0.84299375f +
5683       //       (1.5327582f +
5684       //         (-1.0688956f +
5685       //           (0.49102474f +
5686       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5687       //
5688       // error 0.0000037995730, which is better than 18 bits
5689       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5690                                getF32Constant(DAG, 0x3c5d51ce, dl));
5691       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5692                                getF32Constant(DAG, 0x3e00685a, dl));
5693       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5694       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5695                                getF32Constant(DAG, 0x3efb6798, dl));
5696       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5697       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5698                                getF32Constant(DAG, 0x3f88d192, dl));
5699       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5700       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5701                                getF32Constant(DAG, 0x3fc4316c, dl));
5702       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5703       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5704                                     getF32Constant(DAG, 0x3f57ce70, dl));
5705     }
5706 
5707     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5708   }
5709 
5710   // No special expansion.
5711   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5712 }
5713 
5714 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5715 /// limited-precision mode.
5716 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5717                           const TargetLowering &TLI, SDNodeFlags Flags) {
5718   if (Op.getValueType() == MVT::f32 &&
5719       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5720     return getLimitedPrecisionExp2(Op, dl, DAG);
5721 
5722   // No special expansion.
5723   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5724 }
5725 
5726 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5727 /// limited-precision mode with x == 10.0f.
5728 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5729                          SelectionDAG &DAG, const TargetLowering &TLI,
5730                          SDNodeFlags Flags) {
5731   bool IsExp10 = false;
5732   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5733       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5734     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5735       APFloat Ten(10.0f);
5736       IsExp10 = LHSC->isExactlyValue(Ten);
5737     }
5738   }
5739 
5740   // TODO: What fast-math-flags should be set on the FMUL node?
5741   if (IsExp10) {
5742     // Put the exponent in the right bit position for later addition to the
5743     // final result:
5744     //
5745     //   #define LOG2OF10 3.3219281f
5746     //   t0 = Op * LOG2OF10;
5747     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5748                              getF32Constant(DAG, 0x40549a78, dl));
5749     return getLimitedPrecisionExp2(t0, dl, DAG);
5750   }
5751 
5752   // No special expansion.
5753   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5754 }
5755 
5756 /// ExpandPowI - Expand a llvm.powi intrinsic.
5757 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5758                           SelectionDAG &DAG) {
5759   // If RHS is a constant, we can expand this out to a multiplication tree if
5760   // it's beneficial on the target, otherwise we end up lowering to a call to
5761   // __powidf2 (for example).
5762   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5763     unsigned Val = RHSC->getSExtValue();
5764 
5765     // powi(x, 0) -> 1.0
5766     if (Val == 0)
5767       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5768 
5769     if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI(
5770             Val, DAG.shouldOptForSize())) {
5771       // Get the exponent as a positive value.
5772       if ((int)Val < 0)
5773         Val = -Val;
5774       // We use the simple binary decomposition method to generate the multiply
5775       // sequence.  There are more optimal ways to do this (for example,
5776       // powi(x,15) generates one more multiply than it should), but this has
5777       // the benefit of being both really simple and much better than a libcall.
5778       SDValue Res; // Logically starts equal to 1.0
5779       SDValue CurSquare = LHS;
5780       // TODO: Intrinsics should have fast-math-flags that propagate to these
5781       // nodes.
5782       while (Val) {
5783         if (Val & 1) {
5784           if (Res.getNode())
5785             Res =
5786                 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
5787           else
5788             Res = CurSquare; // 1.0*CurSquare.
5789         }
5790 
5791         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5792                                 CurSquare, CurSquare);
5793         Val >>= 1;
5794       }
5795 
5796       // If the original was negative, invert the result, producing 1/(x*x*x).
5797       if (RHSC->getSExtValue() < 0)
5798         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5799                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5800       return Res;
5801     }
5802   }
5803 
5804   // Otherwise, expand to a libcall.
5805   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5806 }
5807 
5808 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5809                             SDValue LHS, SDValue RHS, SDValue Scale,
5810                             SelectionDAG &DAG, const TargetLowering &TLI) {
5811   EVT VT = LHS.getValueType();
5812   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5813   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5814   LLVMContext &Ctx = *DAG.getContext();
5815 
5816   // If the type is legal but the operation isn't, this node might survive all
5817   // the way to operation legalization. If we end up there and we do not have
5818   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5819   // node.
5820 
5821   // Coax the legalizer into expanding the node during type legalization instead
5822   // by bumping the size by one bit. This will force it to Promote, enabling the
5823   // early expansion and avoiding the need to expand later.
5824 
5825   // We don't have to do this if Scale is 0; that can always be expanded, unless
5826   // it's a saturating signed operation. Those can experience true integer
5827   // division overflow, a case which we must avoid.
5828 
5829   // FIXME: We wouldn't have to do this (or any of the early
5830   // expansion/promotion) if it was possible to expand a libcall of an
5831   // illegal type during operation legalization. But it's not, so things
5832   // get a bit hacky.
5833   unsigned ScaleInt = Scale->getAsZExtVal();
5834   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5835       (TLI.isTypeLegal(VT) ||
5836        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5837     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5838         Opcode, VT, ScaleInt);
5839     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5840       EVT PromVT;
5841       if (VT.isScalarInteger())
5842         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5843       else if (VT.isVector()) {
5844         PromVT = VT.getVectorElementType();
5845         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5846         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5847       } else
5848         llvm_unreachable("Wrong VT for DIVFIX?");
5849       LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT);
5850       RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT);
5851       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5852       // For saturating operations, we need to shift up the LHS to get the
5853       // proper saturation width, and then shift down again afterwards.
5854       if (Saturating)
5855         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5856                           DAG.getConstant(1, DL, ShiftTy));
5857       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5858       if (Saturating)
5859         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5860                           DAG.getConstant(1, DL, ShiftTy));
5861       return DAG.getZExtOrTrunc(Res, DL, VT);
5862     }
5863   }
5864 
5865   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5866 }
5867 
5868 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5869 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5870 static void
5871 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5872                      const SDValue &N) {
5873   switch (N.getOpcode()) {
5874   case ISD::CopyFromReg: {
5875     SDValue Op = N.getOperand(1);
5876     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5877                       Op.getValueType().getSizeInBits());
5878     return;
5879   }
5880   case ISD::BITCAST:
5881   case ISD::AssertZext:
5882   case ISD::AssertSext:
5883   case ISD::TRUNCATE:
5884     getUnderlyingArgRegs(Regs, N.getOperand(0));
5885     return;
5886   case ISD::BUILD_PAIR:
5887   case ISD::BUILD_VECTOR:
5888   case ISD::CONCAT_VECTORS:
5889     for (SDValue Op : N->op_values())
5890       getUnderlyingArgRegs(Regs, Op);
5891     return;
5892   default:
5893     return;
5894   }
5895 }
5896 
5897 /// If the DbgValueInst is a dbg_value of a function argument, create the
5898 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5899 /// instruction selection, they will be inserted to the entry BB.
5900 /// We don't currently support this for variadic dbg_values, as they shouldn't
5901 /// appear for function arguments or in the prologue.
5902 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5903     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5904     DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
5905   const Argument *Arg = dyn_cast<Argument>(V);
5906   if (!Arg)
5907     return false;
5908 
5909   MachineFunction &MF = DAG.getMachineFunction();
5910   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5911 
5912   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
5913   // we've been asked to pursue.
5914   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
5915                               bool Indirect) {
5916     if (Reg.isVirtual() && MF.useDebugInstrRef()) {
5917       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
5918       // pointing at the VReg, which will be patched up later.
5919       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
5920       SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg(
5921           /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
5922           /* isKill */ false, /* isDead */ false,
5923           /* isUndef */ false, /* isEarlyClobber */ false,
5924           /* SubReg */ 0, /* isDebug */ true)});
5925 
5926       auto *NewDIExpr = FragExpr;
5927       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
5928       // the DIExpression.
5929       if (Indirect)
5930         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
5931       SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0});
5932       NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops);
5933       return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr);
5934     } else {
5935       // Create a completely standard DBG_VALUE.
5936       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
5937       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
5938     }
5939   };
5940 
5941   if (Kind == FuncArgumentDbgValueKind::Value) {
5942     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5943     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5944     // the entry block.
5945     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5946     if (!IsInEntryBlock)
5947       return false;
5948 
5949     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5950     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5951     // variable that also is a param.
5952     //
5953     // Although, if we are at the top of the entry block already, we can still
5954     // emit using ArgDbgValue. This might catch some situations when the
5955     // dbg.value refers to an argument that isn't used in the entry block, so
5956     // any CopyToReg node would be optimized out and the only way to express
5957     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5958     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5959     // we should only emit as ArgDbgValue if the Variable is an argument to the
5960     // current function, and the dbg.value intrinsic is found in the entry
5961     // block.
5962     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5963         !DL->getInlinedAt();
5964     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5965     if (!IsInPrologue && !VariableIsFunctionInputArg)
5966       return false;
5967 
5968     // Here we assume that a function argument on IR level only can be used to
5969     // describe one input parameter on source level. If we for example have
5970     // source code like this
5971     //
5972     //    struct A { long x, y; };
5973     //    void foo(struct A a, long b) {
5974     //      ...
5975     //      b = a.x;
5976     //      ...
5977     //    }
5978     //
5979     // and IR like this
5980     //
5981     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5982     //  entry:
5983     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5984     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5985     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5986     //    ...
5987     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5988     //    ...
5989     //
5990     // then the last dbg.value is describing a parameter "b" using a value that
5991     // is an argument. But since we already has used %a1 to describe a parameter
5992     // we should not handle that last dbg.value here (that would result in an
5993     // incorrect hoisting of the DBG_VALUE to the function entry).
5994     // Notice that we allow one dbg.value per IR level argument, to accommodate
5995     // for the situation with fragments above.
5996     if (VariableIsFunctionInputArg) {
5997       unsigned ArgNo = Arg->getArgNo();
5998       if (ArgNo >= FuncInfo.DescribedArgs.size())
5999         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
6000       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
6001         return false;
6002       FuncInfo.DescribedArgs.set(ArgNo);
6003     }
6004   }
6005 
6006   bool IsIndirect = false;
6007   std::optional<MachineOperand> Op;
6008   // Some arguments' frame index is recorded during argument lowering.
6009   int FI = FuncInfo.getArgumentFrameIndex(Arg);
6010   if (FI != std::numeric_limits<int>::max())
6011     Op = MachineOperand::CreateFI(FI);
6012 
6013   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
6014   if (!Op && N.getNode()) {
6015     getUnderlyingArgRegs(ArgRegsAndSizes, N);
6016     Register Reg;
6017     if (ArgRegsAndSizes.size() == 1)
6018       Reg = ArgRegsAndSizes.front().first;
6019 
6020     if (Reg && Reg.isVirtual()) {
6021       MachineRegisterInfo &RegInfo = MF.getRegInfo();
6022       Register PR = RegInfo.getLiveInPhysReg(Reg);
6023       if (PR)
6024         Reg = PR;
6025     }
6026     if (Reg) {
6027       Op = MachineOperand::CreateReg(Reg, false);
6028       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6029     }
6030   }
6031 
6032   if (!Op && N.getNode()) {
6033     // Check if frame index is available.
6034     SDValue LCandidate = peekThroughBitcasts(N);
6035     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
6036       if (FrameIndexSDNode *FINode =
6037           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
6038         Op = MachineOperand::CreateFI(FINode->getIndex());
6039   }
6040 
6041   if (!Op) {
6042     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
6043     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
6044                                          SplitRegs) {
6045       unsigned Offset = 0;
6046       for (const auto &RegAndSize : SplitRegs) {
6047         // If the expression is already a fragment, the current register
6048         // offset+size might extend beyond the fragment. In this case, only
6049         // the register bits that are inside the fragment are relevant.
6050         int RegFragmentSizeInBits = RegAndSize.second;
6051         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
6052           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
6053           // The register is entirely outside the expression fragment,
6054           // so is irrelevant for debug info.
6055           if (Offset >= ExprFragmentSizeInBits)
6056             break;
6057           // The register is partially outside the expression fragment, only
6058           // the low bits within the fragment are relevant for debug info.
6059           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
6060             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
6061           }
6062         }
6063 
6064         auto FragmentExpr = DIExpression::createFragmentExpression(
6065             Expr, Offset, RegFragmentSizeInBits);
6066         Offset += RegAndSize.second;
6067         // If a valid fragment expression cannot be created, the variable's
6068         // correct value cannot be determined and so it is set as Undef.
6069         if (!FragmentExpr) {
6070           SDDbgValue *SDV = DAG.getConstantDbgValue(
6071               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
6072           DAG.AddDbgValue(SDV, false);
6073           continue;
6074         }
6075         MachineInstr *NewMI =
6076             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr,
6077                              Kind != FuncArgumentDbgValueKind::Value);
6078         FuncInfo.ArgDbgValues.push_back(NewMI);
6079       }
6080     };
6081 
6082     // Check if ValueMap has reg number.
6083     DenseMap<const Value *, Register>::const_iterator
6084       VMI = FuncInfo.ValueMap.find(V);
6085     if (VMI != FuncInfo.ValueMap.end()) {
6086       const auto &TLI = DAG.getTargetLoweringInfo();
6087       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
6088                        V->getType(), std::nullopt);
6089       if (RFV.occupiesMultipleRegs()) {
6090         splitMultiRegDbgValue(RFV.getRegsAndSizes());
6091         return true;
6092       }
6093 
6094       Op = MachineOperand::CreateReg(VMI->second, false);
6095       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6096     } else if (ArgRegsAndSizes.size() > 1) {
6097       // This was split due to the calling convention, and no virtual register
6098       // mapping exists for the value.
6099       splitMultiRegDbgValue(ArgRegsAndSizes);
6100       return true;
6101     }
6102   }
6103 
6104   if (!Op)
6105     return false;
6106 
6107   assert(Variable->isValidLocationForIntrinsic(DL) &&
6108          "Expected inlined-at fields to agree");
6109   MachineInstr *NewMI = nullptr;
6110 
6111   if (Op->isReg())
6112     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
6113   else
6114     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
6115                     Variable, Expr);
6116 
6117   // Otherwise, use ArgDbgValues.
6118   FuncInfo.ArgDbgValues.push_back(NewMI);
6119   return true;
6120 }
6121 
6122 /// Return the appropriate SDDbgValue based on N.
6123 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
6124                                              DILocalVariable *Variable,
6125                                              DIExpression *Expr,
6126                                              const DebugLoc &dl,
6127                                              unsigned DbgSDNodeOrder) {
6128   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
6129     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
6130     // stack slot locations.
6131     //
6132     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
6133     // debug values here after optimization:
6134     //
6135     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
6136     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
6137     //
6138     // Both describe the direct values of their associated variables.
6139     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
6140                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6141   }
6142   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
6143                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6144 }
6145 
6146 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
6147   switch (Intrinsic) {
6148   case Intrinsic::smul_fix:
6149     return ISD::SMULFIX;
6150   case Intrinsic::umul_fix:
6151     return ISD::UMULFIX;
6152   case Intrinsic::smul_fix_sat:
6153     return ISD::SMULFIXSAT;
6154   case Intrinsic::umul_fix_sat:
6155     return ISD::UMULFIXSAT;
6156   case Intrinsic::sdiv_fix:
6157     return ISD::SDIVFIX;
6158   case Intrinsic::udiv_fix:
6159     return ISD::UDIVFIX;
6160   case Intrinsic::sdiv_fix_sat:
6161     return ISD::SDIVFIXSAT;
6162   case Intrinsic::udiv_fix_sat:
6163     return ISD::UDIVFIXSAT;
6164   default:
6165     llvm_unreachable("Unhandled fixed point intrinsic");
6166   }
6167 }
6168 
6169 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
6170                                            const char *FunctionName) {
6171   assert(FunctionName && "FunctionName must not be nullptr");
6172   SDValue Callee = DAG.getExternalSymbol(
6173       FunctionName,
6174       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6175   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
6176 }
6177 
6178 /// Given a @llvm.call.preallocated.setup, return the corresponding
6179 /// preallocated call.
6180 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
6181   assert(cast<CallBase>(PreallocatedSetup)
6182                  ->getCalledFunction()
6183                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
6184          "expected call_preallocated_setup Value");
6185   for (const auto *U : PreallocatedSetup->users()) {
6186     auto *UseCall = cast<CallBase>(U);
6187     const Function *Fn = UseCall->getCalledFunction();
6188     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
6189       return UseCall;
6190     }
6191   }
6192   llvm_unreachable("expected corresponding call to preallocated setup/arg");
6193 }
6194 
6195 /// If DI is a debug value with an EntryValue expression, lower it using the
6196 /// corresponding physical register of the associated Argument value
6197 /// (guaranteed to exist by the verifier).
6198 bool SelectionDAGBuilder::visitEntryValueDbgValue(
6199     ArrayRef<const Value *> Values, DILocalVariable *Variable,
6200     DIExpression *Expr, DebugLoc DbgLoc) {
6201   if (!Expr->isEntryValue() || !hasSingleElement(Values))
6202     return false;
6203 
6204   // These properties are guaranteed by the verifier.
6205   const Argument *Arg = cast<Argument>(Values[0]);
6206   assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync));
6207 
6208   auto ArgIt = FuncInfo.ValueMap.find(Arg);
6209   if (ArgIt == FuncInfo.ValueMap.end()) {
6210     LLVM_DEBUG(
6211         dbgs() << "Dropping dbg.value: expression is entry_value but "
6212                   "couldn't find an associated register for the Argument\n");
6213     return true;
6214   }
6215   Register ArgVReg = ArgIt->getSecond();
6216 
6217   for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
6218     if (ArgVReg == VirtReg || ArgVReg == PhysReg) {
6219       SDDbgValue *SDV = DAG.getVRegDbgValue(
6220           Variable, Expr, PhysReg, false /*IsIndidrect*/, DbgLoc, SDNodeOrder);
6221       DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/);
6222       return true;
6223     }
6224   LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but "
6225                        "couldn't find a physical register\n");
6226   return true;
6227 }
6228 
6229 /// Lower the call to the specified intrinsic function.
6230 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
6231                                              unsigned Intrinsic) {
6232   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6233   SDLoc sdl = getCurSDLoc();
6234   DebugLoc dl = getCurDebugLoc();
6235   SDValue Res;
6236 
6237   SDNodeFlags Flags;
6238   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
6239     Flags.copyFMF(*FPOp);
6240 
6241   switch (Intrinsic) {
6242   default:
6243     // By default, turn this into a target intrinsic node.
6244     visitTargetIntrinsic(I, Intrinsic);
6245     return;
6246   case Intrinsic::vscale: {
6247     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6248     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
6249     return;
6250   }
6251   case Intrinsic::vastart:  visitVAStart(I); return;
6252   case Intrinsic::vaend:    visitVAEnd(I); return;
6253   case Intrinsic::vacopy:   visitVACopy(I); return;
6254   case Intrinsic::returnaddress:
6255     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
6256                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6257                              getValue(I.getArgOperand(0))));
6258     return;
6259   case Intrinsic::addressofreturnaddress:
6260     setValue(&I,
6261              DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
6262                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6263     return;
6264   case Intrinsic::sponentry:
6265     setValue(&I,
6266              DAG.getNode(ISD::SPONENTRY, sdl,
6267                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6268     return;
6269   case Intrinsic::frameaddress:
6270     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
6271                              TLI.getFrameIndexTy(DAG.getDataLayout()),
6272                              getValue(I.getArgOperand(0))));
6273     return;
6274   case Intrinsic::read_volatile_register:
6275   case Intrinsic::read_register: {
6276     Value *Reg = I.getArgOperand(0);
6277     SDValue Chain = getRoot();
6278     SDValue RegName =
6279         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6280     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6281     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
6282       DAG.getVTList(VT, MVT::Other), Chain, RegName);
6283     setValue(&I, Res);
6284     DAG.setRoot(Res.getValue(1));
6285     return;
6286   }
6287   case Intrinsic::write_register: {
6288     Value *Reg = I.getArgOperand(0);
6289     Value *RegValue = I.getArgOperand(1);
6290     SDValue Chain = getRoot();
6291     SDValue RegName =
6292         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6293     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
6294                             RegName, getValue(RegValue)));
6295     return;
6296   }
6297   case Intrinsic::memcpy: {
6298     const auto &MCI = cast<MemCpyInst>(I);
6299     SDValue Op1 = getValue(I.getArgOperand(0));
6300     SDValue Op2 = getValue(I.getArgOperand(1));
6301     SDValue Op3 = getValue(I.getArgOperand(2));
6302     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
6303     Align DstAlign = MCI.getDestAlign().valueOrOne();
6304     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6305     Align Alignment = std::min(DstAlign, SrcAlign);
6306     bool isVol = MCI.isVolatile();
6307     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6308     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6309     // node.
6310     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6311     SDValue MC = DAG.getMemcpy(
6312         Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6313         /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)),
6314         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
6315     updateDAGForMaybeTailCall(MC);
6316     return;
6317   }
6318   case Intrinsic::memcpy_inline: {
6319     const auto &MCI = cast<MemCpyInlineInst>(I);
6320     SDValue Dst = getValue(I.getArgOperand(0));
6321     SDValue Src = getValue(I.getArgOperand(1));
6322     SDValue Size = getValue(I.getArgOperand(2));
6323     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
6324     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
6325     Align DstAlign = MCI.getDestAlign().valueOrOne();
6326     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6327     Align Alignment = std::min(DstAlign, SrcAlign);
6328     bool isVol = MCI.isVolatile();
6329     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6330     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6331     // node.
6332     SDValue MC = DAG.getMemcpy(
6333         getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
6334         /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)),
6335         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
6336     updateDAGForMaybeTailCall(MC);
6337     return;
6338   }
6339   case Intrinsic::memset: {
6340     const auto &MSI = cast<MemSetInst>(I);
6341     SDValue Op1 = getValue(I.getArgOperand(0));
6342     SDValue Op2 = getValue(I.getArgOperand(1));
6343     SDValue Op3 = getValue(I.getArgOperand(2));
6344     // @llvm.memset defines 0 and 1 to both mean no alignment.
6345     Align Alignment = MSI.getDestAlign().valueOrOne();
6346     bool isVol = MSI.isVolatile();
6347     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6348     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6349     SDValue MS = DAG.getMemset(
6350         Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false,
6351         isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
6352     updateDAGForMaybeTailCall(MS);
6353     return;
6354   }
6355   case Intrinsic::memset_inline: {
6356     const auto &MSII = cast<MemSetInlineInst>(I);
6357     SDValue Dst = getValue(I.getArgOperand(0));
6358     SDValue Value = getValue(I.getArgOperand(1));
6359     SDValue Size = getValue(I.getArgOperand(2));
6360     assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size");
6361     // @llvm.memset defines 0 and 1 to both mean no alignment.
6362     Align DstAlign = MSII.getDestAlign().valueOrOne();
6363     bool isVol = MSII.isVolatile();
6364     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6365     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6366     SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol,
6367                                /* AlwaysInline */ true, isTC,
6368                                MachinePointerInfo(I.getArgOperand(0)),
6369                                I.getAAMetadata());
6370     updateDAGForMaybeTailCall(MC);
6371     return;
6372   }
6373   case Intrinsic::memmove: {
6374     const auto &MMI = cast<MemMoveInst>(I);
6375     SDValue Op1 = getValue(I.getArgOperand(0));
6376     SDValue Op2 = getValue(I.getArgOperand(1));
6377     SDValue Op3 = getValue(I.getArgOperand(2));
6378     // @llvm.memmove defines 0 and 1 to both mean no alignment.
6379     Align DstAlign = MMI.getDestAlign().valueOrOne();
6380     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
6381     Align Alignment = std::min(DstAlign, SrcAlign);
6382     bool isVol = MMI.isVolatile();
6383     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6384     // FIXME: Support passing different dest/src alignments to the memmove DAG
6385     // node.
6386     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6387     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6388                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
6389                                 MachinePointerInfo(I.getArgOperand(1)),
6390                                 I.getAAMetadata(), AA);
6391     updateDAGForMaybeTailCall(MM);
6392     return;
6393   }
6394   case Intrinsic::memcpy_element_unordered_atomic: {
6395     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
6396     SDValue Dst = getValue(MI.getRawDest());
6397     SDValue Src = getValue(MI.getRawSource());
6398     SDValue Length = getValue(MI.getLength());
6399 
6400     Type *LengthTy = MI.getLength()->getType();
6401     unsigned ElemSz = MI.getElementSizeInBytes();
6402     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6403     SDValue MC =
6404         DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6405                             isTC, MachinePointerInfo(MI.getRawDest()),
6406                             MachinePointerInfo(MI.getRawSource()));
6407     updateDAGForMaybeTailCall(MC);
6408     return;
6409   }
6410   case Intrinsic::memmove_element_unordered_atomic: {
6411     auto &MI = cast<AtomicMemMoveInst>(I);
6412     SDValue Dst = getValue(MI.getRawDest());
6413     SDValue Src = getValue(MI.getRawSource());
6414     SDValue Length = getValue(MI.getLength());
6415 
6416     Type *LengthTy = MI.getLength()->getType();
6417     unsigned ElemSz = MI.getElementSizeInBytes();
6418     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6419     SDValue MC =
6420         DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6421                              isTC, MachinePointerInfo(MI.getRawDest()),
6422                              MachinePointerInfo(MI.getRawSource()));
6423     updateDAGForMaybeTailCall(MC);
6424     return;
6425   }
6426   case Intrinsic::memset_element_unordered_atomic: {
6427     auto &MI = cast<AtomicMemSetInst>(I);
6428     SDValue Dst = getValue(MI.getRawDest());
6429     SDValue Val = getValue(MI.getValue());
6430     SDValue Length = getValue(MI.getLength());
6431 
6432     Type *LengthTy = MI.getLength()->getType();
6433     unsigned ElemSz = MI.getElementSizeInBytes();
6434     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6435     SDValue MC =
6436         DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
6437                             isTC, MachinePointerInfo(MI.getRawDest()));
6438     updateDAGForMaybeTailCall(MC);
6439     return;
6440   }
6441   case Intrinsic::call_preallocated_setup: {
6442     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
6443     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6444     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
6445                               getRoot(), SrcValue);
6446     setValue(&I, Res);
6447     DAG.setRoot(Res);
6448     return;
6449   }
6450   case Intrinsic::call_preallocated_arg: {
6451     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6452     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6453     SDValue Ops[3];
6454     Ops[0] = getRoot();
6455     Ops[1] = SrcValue;
6456     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6457                                    MVT::i32); // arg index
6458     SDValue Res = DAG.getNode(
6459         ISD::PREALLOCATED_ARG, sdl,
6460         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6461     setValue(&I, Res);
6462     DAG.setRoot(Res.getValue(1));
6463     return;
6464   }
6465   case Intrinsic::dbg_declare: {
6466     const auto &DI = cast<DbgDeclareInst>(I);
6467     // Debug intrinsics are handled separately in assignment tracking mode.
6468     // Some intrinsics are handled right after Argument lowering.
6469     if (AssignmentTrackingEnabled ||
6470         FuncInfo.PreprocessedDbgDeclares.count(&DI))
6471       return;
6472     LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DI << "\n");
6473     DILocalVariable *Variable = DI.getVariable();
6474     DIExpression *Expression = DI.getExpression();
6475     dropDanglingDebugInfo(Variable, Expression);
6476     // Assume dbg.declare can not currently use DIArgList, i.e.
6477     // it is non-variadic.
6478     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6479     handleDebugDeclare(DI.getVariableLocationOp(0), Variable, Expression,
6480                        DI.getDebugLoc());
6481     return;
6482   }
6483   case Intrinsic::dbg_label: {
6484     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6485     DILabel *Label = DI.getLabel();
6486     assert(Label && "Missing label");
6487 
6488     SDDbgLabel *SDV;
6489     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6490     DAG.AddDbgLabel(SDV);
6491     return;
6492   }
6493   case Intrinsic::dbg_assign: {
6494     // Debug intrinsics are handled seperately in assignment tracking mode.
6495     if (AssignmentTrackingEnabled)
6496       return;
6497     // If assignment tracking hasn't been enabled then fall through and treat
6498     // the dbg.assign as a dbg.value.
6499     [[fallthrough]];
6500   }
6501   case Intrinsic::dbg_value: {
6502     // Debug intrinsics are handled seperately in assignment tracking mode.
6503     if (AssignmentTrackingEnabled)
6504       return;
6505     const DbgValueInst &DI = cast<DbgValueInst>(I);
6506     assert(DI.getVariable() && "Missing variable");
6507 
6508     DILocalVariable *Variable = DI.getVariable();
6509     DIExpression *Expression = DI.getExpression();
6510     dropDanglingDebugInfo(Variable, Expression);
6511 
6512     if (DI.isKillLocation()) {
6513       handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder);
6514       return;
6515     }
6516 
6517     SmallVector<Value *, 4> Values(DI.getValues());
6518     if (Values.empty())
6519       return;
6520 
6521     bool IsVariadic = DI.hasArgList();
6522     if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(),
6523                           SDNodeOrder, IsVariadic))
6524       addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
6525                            DI.getDebugLoc(), SDNodeOrder);
6526     return;
6527   }
6528 
6529   case Intrinsic::eh_typeid_for: {
6530     // Find the type id for the given typeinfo.
6531     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6532     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6533     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6534     setValue(&I, Res);
6535     return;
6536   }
6537 
6538   case Intrinsic::eh_return_i32:
6539   case Intrinsic::eh_return_i64:
6540     DAG.getMachineFunction().setCallsEHReturn(true);
6541     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6542                             MVT::Other,
6543                             getControlRoot(),
6544                             getValue(I.getArgOperand(0)),
6545                             getValue(I.getArgOperand(1))));
6546     return;
6547   case Intrinsic::eh_unwind_init:
6548     DAG.getMachineFunction().setCallsUnwindInit(true);
6549     return;
6550   case Intrinsic::eh_dwarf_cfa:
6551     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6552                              TLI.getPointerTy(DAG.getDataLayout()),
6553                              getValue(I.getArgOperand(0))));
6554     return;
6555   case Intrinsic::eh_sjlj_callsite: {
6556     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6557     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
6558     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6559 
6560     MMI.setCurrentCallSite(CI->getZExtValue());
6561     return;
6562   }
6563   case Intrinsic::eh_sjlj_functioncontext: {
6564     // Get and store the index of the function context.
6565     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6566     AllocaInst *FnCtx =
6567       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6568     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6569     MFI.setFunctionContextIndex(FI);
6570     return;
6571   }
6572   case Intrinsic::eh_sjlj_setjmp: {
6573     SDValue Ops[2];
6574     Ops[0] = getRoot();
6575     Ops[1] = getValue(I.getArgOperand(0));
6576     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6577                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6578     setValue(&I, Op.getValue(0));
6579     DAG.setRoot(Op.getValue(1));
6580     return;
6581   }
6582   case Intrinsic::eh_sjlj_longjmp:
6583     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6584                             getRoot(), getValue(I.getArgOperand(0))));
6585     return;
6586   case Intrinsic::eh_sjlj_setup_dispatch:
6587     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6588                             getRoot()));
6589     return;
6590   case Intrinsic::masked_gather:
6591     visitMaskedGather(I);
6592     return;
6593   case Intrinsic::masked_load:
6594     visitMaskedLoad(I);
6595     return;
6596   case Intrinsic::masked_scatter:
6597     visitMaskedScatter(I);
6598     return;
6599   case Intrinsic::masked_store:
6600     visitMaskedStore(I);
6601     return;
6602   case Intrinsic::masked_expandload:
6603     visitMaskedLoad(I, true /* IsExpanding */);
6604     return;
6605   case Intrinsic::masked_compressstore:
6606     visitMaskedStore(I, true /* IsCompressing */);
6607     return;
6608   case Intrinsic::powi:
6609     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6610                             getValue(I.getArgOperand(1)), DAG));
6611     return;
6612   case Intrinsic::log:
6613     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6614     return;
6615   case Intrinsic::log2:
6616     setValue(&I,
6617              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6618     return;
6619   case Intrinsic::log10:
6620     setValue(&I,
6621              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6622     return;
6623   case Intrinsic::exp:
6624     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6625     return;
6626   case Intrinsic::exp2:
6627     setValue(&I,
6628              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6629     return;
6630   case Intrinsic::pow:
6631     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6632                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6633     return;
6634   case Intrinsic::sqrt:
6635   case Intrinsic::fabs:
6636   case Intrinsic::sin:
6637   case Intrinsic::cos:
6638   case Intrinsic::exp10:
6639   case Intrinsic::floor:
6640   case Intrinsic::ceil:
6641   case Intrinsic::trunc:
6642   case Intrinsic::rint:
6643   case Intrinsic::nearbyint:
6644   case Intrinsic::round:
6645   case Intrinsic::roundeven:
6646   case Intrinsic::canonicalize: {
6647     unsigned Opcode;
6648     switch (Intrinsic) {
6649     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6650     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6651     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6652     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6653     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6654     case Intrinsic::exp10:     Opcode = ISD::FEXP10;     break;
6655     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6656     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6657     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6658     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6659     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6660     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6661     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6662     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6663     }
6664 
6665     setValue(&I, DAG.getNode(Opcode, sdl,
6666                              getValue(I.getArgOperand(0)).getValueType(),
6667                              getValue(I.getArgOperand(0)), Flags));
6668     return;
6669   }
6670   case Intrinsic::lround:
6671   case Intrinsic::llround:
6672   case Intrinsic::lrint:
6673   case Intrinsic::llrint: {
6674     unsigned Opcode;
6675     switch (Intrinsic) {
6676     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6677     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6678     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6679     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6680     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6681     }
6682 
6683     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6684     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6685                              getValue(I.getArgOperand(0))));
6686     return;
6687   }
6688   case Intrinsic::minnum:
6689     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6690                              getValue(I.getArgOperand(0)).getValueType(),
6691                              getValue(I.getArgOperand(0)),
6692                              getValue(I.getArgOperand(1)), Flags));
6693     return;
6694   case Intrinsic::maxnum:
6695     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6696                              getValue(I.getArgOperand(0)).getValueType(),
6697                              getValue(I.getArgOperand(0)),
6698                              getValue(I.getArgOperand(1)), Flags));
6699     return;
6700   case Intrinsic::minimum:
6701     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6702                              getValue(I.getArgOperand(0)).getValueType(),
6703                              getValue(I.getArgOperand(0)),
6704                              getValue(I.getArgOperand(1)), Flags));
6705     return;
6706   case Intrinsic::maximum:
6707     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6708                              getValue(I.getArgOperand(0)).getValueType(),
6709                              getValue(I.getArgOperand(0)),
6710                              getValue(I.getArgOperand(1)), Flags));
6711     return;
6712   case Intrinsic::copysign:
6713     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6714                              getValue(I.getArgOperand(0)).getValueType(),
6715                              getValue(I.getArgOperand(0)),
6716                              getValue(I.getArgOperand(1)), Flags));
6717     return;
6718   case Intrinsic::ldexp:
6719     setValue(&I, DAG.getNode(ISD::FLDEXP, sdl,
6720                              getValue(I.getArgOperand(0)).getValueType(),
6721                              getValue(I.getArgOperand(0)),
6722                              getValue(I.getArgOperand(1)), Flags));
6723     return;
6724   case Intrinsic::frexp: {
6725     SmallVector<EVT, 2> ValueVTs;
6726     ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
6727     SDVTList VTs = DAG.getVTList(ValueVTs);
6728     setValue(&I,
6729              DAG.getNode(ISD::FFREXP, sdl, VTs, getValue(I.getArgOperand(0))));
6730     return;
6731   }
6732   case Intrinsic::arithmetic_fence: {
6733     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6734                              getValue(I.getArgOperand(0)).getValueType(),
6735                              getValue(I.getArgOperand(0)), Flags));
6736     return;
6737   }
6738   case Intrinsic::fma:
6739     setValue(&I, DAG.getNode(
6740                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6741                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6742                      getValue(I.getArgOperand(2)), Flags));
6743     return;
6744 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6745   case Intrinsic::INTRINSIC:
6746 #include "llvm/IR/ConstrainedOps.def"
6747     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6748     return;
6749 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6750 #include "llvm/IR/VPIntrinsics.def"
6751     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6752     return;
6753   case Intrinsic::fptrunc_round: {
6754     // Get the last argument, the metadata and convert it to an integer in the
6755     // call
6756     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
6757     std::optional<RoundingMode> RoundMode =
6758         convertStrToRoundingMode(cast<MDString>(MD)->getString());
6759 
6760     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6761 
6762     // Propagate fast-math-flags from IR to node(s).
6763     SDNodeFlags Flags;
6764     Flags.copyFMF(*cast<FPMathOperator>(&I));
6765     SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
6766 
6767     SDValue Result;
6768     Result = DAG.getNode(
6769         ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
6770         DAG.getTargetConstant((int)*RoundMode, sdl,
6771                               TLI.getPointerTy(DAG.getDataLayout())));
6772     setValue(&I, Result);
6773 
6774     return;
6775   }
6776   case Intrinsic::fmuladd: {
6777     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6778     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6779         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6780       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6781                                getValue(I.getArgOperand(0)).getValueType(),
6782                                getValue(I.getArgOperand(0)),
6783                                getValue(I.getArgOperand(1)),
6784                                getValue(I.getArgOperand(2)), Flags));
6785     } else {
6786       // TODO: Intrinsic calls should have fast-math-flags.
6787       SDValue Mul = DAG.getNode(
6788           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6789           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6790       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6791                                 getValue(I.getArgOperand(0)).getValueType(),
6792                                 Mul, getValue(I.getArgOperand(2)), Flags);
6793       setValue(&I, Add);
6794     }
6795     return;
6796   }
6797   case Intrinsic::convert_to_fp16:
6798     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6799                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6800                                          getValue(I.getArgOperand(0)),
6801                                          DAG.getTargetConstant(0, sdl,
6802                                                                MVT::i32))));
6803     return;
6804   case Intrinsic::convert_from_fp16:
6805     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6806                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6807                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6808                                          getValue(I.getArgOperand(0)))));
6809     return;
6810   case Intrinsic::fptosi_sat: {
6811     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6812     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
6813                              getValue(I.getArgOperand(0)),
6814                              DAG.getValueType(VT.getScalarType())));
6815     return;
6816   }
6817   case Intrinsic::fptoui_sat: {
6818     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6819     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
6820                              getValue(I.getArgOperand(0)),
6821                              DAG.getValueType(VT.getScalarType())));
6822     return;
6823   }
6824   case Intrinsic::set_rounding:
6825     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6826                       {getRoot(), getValue(I.getArgOperand(0))});
6827     setValue(&I, Res);
6828     DAG.setRoot(Res.getValue(0));
6829     return;
6830   case Intrinsic::is_fpclass: {
6831     const DataLayout DLayout = DAG.getDataLayout();
6832     EVT DestVT = TLI.getValueType(DLayout, I.getType());
6833     EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
6834     FPClassTest Test = static_cast<FPClassTest>(
6835         cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
6836     MachineFunction &MF = DAG.getMachineFunction();
6837     const Function &F = MF.getFunction();
6838     SDValue Op = getValue(I.getArgOperand(0));
6839     SDNodeFlags Flags;
6840     Flags.setNoFPExcept(
6841         !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
6842     // If ISD::IS_FPCLASS should be expanded, do it right now, because the
6843     // expansion can use illegal types. Making expansion early allows
6844     // legalizing these types prior to selection.
6845     if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) {
6846       SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
6847       setValue(&I, Result);
6848       return;
6849     }
6850 
6851     SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
6852     SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
6853     setValue(&I, V);
6854     return;
6855   }
6856   case Intrinsic::get_fpenv: {
6857     const DataLayout DLayout = DAG.getDataLayout();
6858     EVT EnvVT = TLI.getValueType(DLayout, I.getType());
6859     Align TempAlign = DAG.getEVTAlign(EnvVT);
6860     SDValue Chain = getRoot();
6861     // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node
6862     // and temporary storage in stack.
6863     if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) {
6864       Res = DAG.getNode(
6865           ISD::GET_FPENV, sdl,
6866           DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
6867                         MVT::Other),
6868           Chain);
6869     } else {
6870       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
6871       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
6872       auto MPI =
6873           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
6874       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6875           MPI, MachineMemOperand::MOStore, MemoryLocation::UnknownSize,
6876           TempAlign);
6877       Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
6878       Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI);
6879     }
6880     setValue(&I, Res);
6881     DAG.setRoot(Res.getValue(1));
6882     return;
6883   }
6884   case Intrinsic::set_fpenv: {
6885     const DataLayout DLayout = DAG.getDataLayout();
6886     SDValue Env = getValue(I.getArgOperand(0));
6887     EVT EnvVT = Env.getValueType();
6888     Align TempAlign = DAG.getEVTAlign(EnvVT);
6889     SDValue Chain = getRoot();
6890     // If SET_FPENV is custom or legal, use it. Otherwise use loading
6891     // environment from memory.
6892     if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) {
6893       Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env);
6894     } else {
6895       // Allocate space in stack, copy environment bits into it and use this
6896       // memory in SET_FPENV_MEM.
6897       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
6898       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
6899       auto MPI =
6900           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
6901       Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign,
6902                            MachineMemOperand::MOStore);
6903       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6904           MPI, MachineMemOperand::MOLoad, MemoryLocation::UnknownSize,
6905           TempAlign);
6906       Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
6907     }
6908     DAG.setRoot(Chain);
6909     return;
6910   }
6911   case Intrinsic::reset_fpenv:
6912     DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot()));
6913     return;
6914   case Intrinsic::get_fpmode:
6915     Res = DAG.getNode(
6916         ISD::GET_FPMODE, sdl,
6917         DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
6918                       MVT::Other),
6919         DAG.getRoot());
6920     setValue(&I, Res);
6921     DAG.setRoot(Res.getValue(1));
6922     return;
6923   case Intrinsic::set_fpmode:
6924     Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()},
6925                       getValue(I.getArgOperand(0)));
6926     DAG.setRoot(Res);
6927     return;
6928   case Intrinsic::reset_fpmode: {
6929     Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot());
6930     DAG.setRoot(Res);
6931     return;
6932   }
6933   case Intrinsic::pcmarker: {
6934     SDValue Tmp = getValue(I.getArgOperand(0));
6935     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6936     return;
6937   }
6938   case Intrinsic::readcyclecounter: {
6939     SDValue Op = getRoot();
6940     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6941                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6942     setValue(&I, Res);
6943     DAG.setRoot(Res.getValue(1));
6944     return;
6945   }
6946   case Intrinsic::readsteadycounter: {
6947     SDValue Op = getRoot();
6948     Res = DAG.getNode(ISD::READSTEADYCOUNTER, sdl,
6949                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6950     setValue(&I, Res);
6951     DAG.setRoot(Res.getValue(1));
6952     return;
6953   }
6954   case Intrinsic::bitreverse:
6955     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6956                              getValue(I.getArgOperand(0)).getValueType(),
6957                              getValue(I.getArgOperand(0))));
6958     return;
6959   case Intrinsic::bswap:
6960     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6961                              getValue(I.getArgOperand(0)).getValueType(),
6962                              getValue(I.getArgOperand(0))));
6963     return;
6964   case Intrinsic::cttz: {
6965     SDValue Arg = getValue(I.getArgOperand(0));
6966     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6967     EVT Ty = Arg.getValueType();
6968     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6969                              sdl, Ty, Arg));
6970     return;
6971   }
6972   case Intrinsic::ctlz: {
6973     SDValue Arg = getValue(I.getArgOperand(0));
6974     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6975     EVT Ty = Arg.getValueType();
6976     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6977                              sdl, Ty, Arg));
6978     return;
6979   }
6980   case Intrinsic::ctpop: {
6981     SDValue Arg = getValue(I.getArgOperand(0));
6982     EVT Ty = Arg.getValueType();
6983     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6984     return;
6985   }
6986   case Intrinsic::fshl:
6987   case Intrinsic::fshr: {
6988     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6989     SDValue X = getValue(I.getArgOperand(0));
6990     SDValue Y = getValue(I.getArgOperand(1));
6991     SDValue Z = getValue(I.getArgOperand(2));
6992     EVT VT = X.getValueType();
6993 
6994     if (X == Y) {
6995       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6996       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6997     } else {
6998       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6999       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
7000     }
7001     return;
7002   }
7003   case Intrinsic::sadd_sat: {
7004     SDValue Op1 = getValue(I.getArgOperand(0));
7005     SDValue Op2 = getValue(I.getArgOperand(1));
7006     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7007     return;
7008   }
7009   case Intrinsic::uadd_sat: {
7010     SDValue Op1 = getValue(I.getArgOperand(0));
7011     SDValue Op2 = getValue(I.getArgOperand(1));
7012     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7013     return;
7014   }
7015   case Intrinsic::ssub_sat: {
7016     SDValue Op1 = getValue(I.getArgOperand(0));
7017     SDValue Op2 = getValue(I.getArgOperand(1));
7018     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7019     return;
7020   }
7021   case Intrinsic::usub_sat: {
7022     SDValue Op1 = getValue(I.getArgOperand(0));
7023     SDValue Op2 = getValue(I.getArgOperand(1));
7024     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7025     return;
7026   }
7027   case Intrinsic::sshl_sat: {
7028     SDValue Op1 = getValue(I.getArgOperand(0));
7029     SDValue Op2 = getValue(I.getArgOperand(1));
7030     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
7031     return;
7032   }
7033   case Intrinsic::ushl_sat: {
7034     SDValue Op1 = getValue(I.getArgOperand(0));
7035     SDValue Op2 = getValue(I.getArgOperand(1));
7036     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
7037     return;
7038   }
7039   case Intrinsic::smul_fix:
7040   case Intrinsic::umul_fix:
7041   case Intrinsic::smul_fix_sat:
7042   case Intrinsic::umul_fix_sat: {
7043     SDValue Op1 = getValue(I.getArgOperand(0));
7044     SDValue Op2 = getValue(I.getArgOperand(1));
7045     SDValue Op3 = getValue(I.getArgOperand(2));
7046     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7047                              Op1.getValueType(), Op1, Op2, Op3));
7048     return;
7049   }
7050   case Intrinsic::sdiv_fix:
7051   case Intrinsic::udiv_fix:
7052   case Intrinsic::sdiv_fix_sat:
7053   case Intrinsic::udiv_fix_sat: {
7054     SDValue Op1 = getValue(I.getArgOperand(0));
7055     SDValue Op2 = getValue(I.getArgOperand(1));
7056     SDValue Op3 = getValue(I.getArgOperand(2));
7057     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7058                               Op1, Op2, Op3, DAG, TLI));
7059     return;
7060   }
7061   case Intrinsic::smax: {
7062     SDValue Op1 = getValue(I.getArgOperand(0));
7063     SDValue Op2 = getValue(I.getArgOperand(1));
7064     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
7065     return;
7066   }
7067   case Intrinsic::smin: {
7068     SDValue Op1 = getValue(I.getArgOperand(0));
7069     SDValue Op2 = getValue(I.getArgOperand(1));
7070     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
7071     return;
7072   }
7073   case Intrinsic::umax: {
7074     SDValue Op1 = getValue(I.getArgOperand(0));
7075     SDValue Op2 = getValue(I.getArgOperand(1));
7076     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
7077     return;
7078   }
7079   case Intrinsic::umin: {
7080     SDValue Op1 = getValue(I.getArgOperand(0));
7081     SDValue Op2 = getValue(I.getArgOperand(1));
7082     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
7083     return;
7084   }
7085   case Intrinsic::abs: {
7086     // TODO: Preserve "int min is poison" arg in SDAG?
7087     SDValue Op1 = getValue(I.getArgOperand(0));
7088     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
7089     return;
7090   }
7091   case Intrinsic::stacksave: {
7092     SDValue Op = getRoot();
7093     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7094     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
7095     setValue(&I, Res);
7096     DAG.setRoot(Res.getValue(1));
7097     return;
7098   }
7099   case Intrinsic::stackrestore:
7100     Res = getValue(I.getArgOperand(0));
7101     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
7102     return;
7103   case Intrinsic::get_dynamic_area_offset: {
7104     SDValue Op = getRoot();
7105     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7106     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7107     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
7108     // target.
7109     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
7110       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
7111                          " intrinsic!");
7112     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
7113                       Op);
7114     DAG.setRoot(Op);
7115     setValue(&I, Res);
7116     return;
7117   }
7118   case Intrinsic::stackguard: {
7119     MachineFunction &MF = DAG.getMachineFunction();
7120     const Module &M = *MF.getFunction().getParent();
7121     EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7122     SDValue Chain = getRoot();
7123     if (TLI.useLoadStackGuardNode()) {
7124       Res = getLoadStackGuard(DAG, sdl, Chain);
7125       Res = DAG.getPtrExtOrTrunc(Res, sdl, PtrTy);
7126     } else {
7127       const Value *Global = TLI.getSDagStackGuard(M);
7128       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
7129       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
7130                         MachinePointerInfo(Global, 0), Align,
7131                         MachineMemOperand::MOVolatile);
7132     }
7133     if (TLI.useStackGuardXorFP())
7134       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
7135     DAG.setRoot(Chain);
7136     setValue(&I, Res);
7137     return;
7138   }
7139   case Intrinsic::stackprotector: {
7140     // Emit code into the DAG to store the stack guard onto the stack.
7141     MachineFunction &MF = DAG.getMachineFunction();
7142     MachineFrameInfo &MFI = MF.getFrameInfo();
7143     SDValue Src, Chain = getRoot();
7144 
7145     if (TLI.useLoadStackGuardNode())
7146       Src = getLoadStackGuard(DAG, sdl, Chain);
7147     else
7148       Src = getValue(I.getArgOperand(0));   // The guard's value.
7149 
7150     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
7151 
7152     int FI = FuncInfo.StaticAllocaMap[Slot];
7153     MFI.setStackProtectorIndex(FI);
7154     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7155 
7156     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
7157 
7158     // Store the stack protector onto the stack.
7159     Res = DAG.getStore(
7160         Chain, sdl, Src, FIN,
7161         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
7162         MaybeAlign(), MachineMemOperand::MOVolatile);
7163     setValue(&I, Res);
7164     DAG.setRoot(Res);
7165     return;
7166   }
7167   case Intrinsic::objectsize:
7168     llvm_unreachable("llvm.objectsize.* should have been lowered already");
7169 
7170   case Intrinsic::is_constant:
7171     llvm_unreachable("llvm.is.constant.* should have been lowered already");
7172 
7173   case Intrinsic::annotation:
7174   case Intrinsic::ptr_annotation:
7175   case Intrinsic::launder_invariant_group:
7176   case Intrinsic::strip_invariant_group:
7177     // Drop the intrinsic, but forward the value
7178     setValue(&I, getValue(I.getOperand(0)));
7179     return;
7180 
7181   case Intrinsic::assume:
7182   case Intrinsic::experimental_noalias_scope_decl:
7183   case Intrinsic::var_annotation:
7184   case Intrinsic::sideeffect:
7185     // Discard annotate attributes, noalias scope declarations, assumptions, and
7186     // artificial side-effects.
7187     return;
7188 
7189   case Intrinsic::codeview_annotation: {
7190     // Emit a label associated with this metadata.
7191     MachineFunction &MF = DAG.getMachineFunction();
7192     MCSymbol *Label =
7193         MF.getMMI().getContext().createTempSymbol("annotation", true);
7194     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
7195     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
7196     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
7197     DAG.setRoot(Res);
7198     return;
7199   }
7200 
7201   case Intrinsic::init_trampoline: {
7202     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
7203 
7204     SDValue Ops[6];
7205     Ops[0] = getRoot();
7206     Ops[1] = getValue(I.getArgOperand(0));
7207     Ops[2] = getValue(I.getArgOperand(1));
7208     Ops[3] = getValue(I.getArgOperand(2));
7209     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
7210     Ops[5] = DAG.getSrcValue(F);
7211 
7212     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
7213 
7214     DAG.setRoot(Res);
7215     return;
7216   }
7217   case Intrinsic::adjust_trampoline:
7218     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
7219                              TLI.getPointerTy(DAG.getDataLayout()),
7220                              getValue(I.getArgOperand(0))));
7221     return;
7222   case Intrinsic::gcroot: {
7223     assert(DAG.getMachineFunction().getFunction().hasGC() &&
7224            "only valid in functions with gc specified, enforced by Verifier");
7225     assert(GFI && "implied by previous");
7226     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
7227     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
7228 
7229     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
7230     GFI->addStackRoot(FI->getIndex(), TypeMap);
7231     return;
7232   }
7233   case Intrinsic::gcread:
7234   case Intrinsic::gcwrite:
7235     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
7236   case Intrinsic::get_rounding:
7237     Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot());
7238     setValue(&I, Res);
7239     DAG.setRoot(Res.getValue(1));
7240     return;
7241 
7242   case Intrinsic::expect:
7243     // Just replace __builtin_expect(exp, c) with EXP.
7244     setValue(&I, getValue(I.getArgOperand(0)));
7245     return;
7246 
7247   case Intrinsic::ubsantrap:
7248   case Intrinsic::debugtrap:
7249   case Intrinsic::trap: {
7250     StringRef TrapFuncName =
7251         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
7252     if (TrapFuncName.empty()) {
7253       switch (Intrinsic) {
7254       case Intrinsic::trap:
7255         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
7256         break;
7257       case Intrinsic::debugtrap:
7258         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
7259         break;
7260       case Intrinsic::ubsantrap:
7261         DAG.setRoot(DAG.getNode(
7262             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
7263             DAG.getTargetConstant(
7264                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
7265                 MVT::i32)));
7266         break;
7267       default: llvm_unreachable("unknown trap intrinsic");
7268       }
7269       return;
7270     }
7271     TargetLowering::ArgListTy Args;
7272     if (Intrinsic == Intrinsic::ubsantrap) {
7273       Args.push_back(TargetLoweringBase::ArgListEntry());
7274       Args[0].Val = I.getArgOperand(0);
7275       Args[0].Node = getValue(Args[0].Val);
7276       Args[0].Ty = Args[0].Val->getType();
7277     }
7278 
7279     TargetLowering::CallLoweringInfo CLI(DAG);
7280     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
7281         CallingConv::C, I.getType(),
7282         DAG.getExternalSymbol(TrapFuncName.data(),
7283                               TLI.getPointerTy(DAG.getDataLayout())),
7284         std::move(Args));
7285 
7286     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7287     DAG.setRoot(Result.second);
7288     return;
7289   }
7290 
7291   case Intrinsic::uadd_with_overflow:
7292   case Intrinsic::sadd_with_overflow:
7293   case Intrinsic::usub_with_overflow:
7294   case Intrinsic::ssub_with_overflow:
7295   case Intrinsic::umul_with_overflow:
7296   case Intrinsic::smul_with_overflow: {
7297     ISD::NodeType Op;
7298     switch (Intrinsic) {
7299     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7300     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
7301     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
7302     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
7303     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
7304     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
7305     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
7306     }
7307     SDValue Op1 = getValue(I.getArgOperand(0));
7308     SDValue Op2 = getValue(I.getArgOperand(1));
7309 
7310     EVT ResultVT = Op1.getValueType();
7311     EVT OverflowVT = MVT::i1;
7312     if (ResultVT.isVector())
7313       OverflowVT = EVT::getVectorVT(
7314           *Context, OverflowVT, ResultVT.getVectorElementCount());
7315 
7316     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
7317     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
7318     return;
7319   }
7320   case Intrinsic::prefetch: {
7321     SDValue Ops[5];
7322     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7323     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
7324     Ops[0] = DAG.getRoot();
7325     Ops[1] = getValue(I.getArgOperand(0));
7326     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
7327                                    MVT::i32);
7328     Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl,
7329                                    MVT::i32);
7330     Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl,
7331                                    MVT::i32);
7332     SDValue Result = DAG.getMemIntrinsicNode(
7333         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
7334         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
7335         /* align */ std::nullopt, Flags);
7336 
7337     // Chain the prefetch in parallel with any pending loads, to stay out of
7338     // the way of later optimizations.
7339     PendingLoads.push_back(Result);
7340     Result = getRoot();
7341     DAG.setRoot(Result);
7342     return;
7343   }
7344   case Intrinsic::lifetime_start:
7345   case Intrinsic::lifetime_end: {
7346     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
7347     // Stack coloring is not enabled in O0, discard region information.
7348     if (TM.getOptLevel() == CodeGenOptLevel::None)
7349       return;
7350 
7351     const int64_t ObjectSize =
7352         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
7353     Value *const ObjectPtr = I.getArgOperand(1);
7354     SmallVector<const Value *, 4> Allocas;
7355     getUnderlyingObjects(ObjectPtr, Allocas);
7356 
7357     for (const Value *Alloca : Allocas) {
7358       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
7359 
7360       // Could not find an Alloca.
7361       if (!LifetimeObject)
7362         continue;
7363 
7364       // First check that the Alloca is static, otherwise it won't have a
7365       // valid frame index.
7366       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
7367       if (SI == FuncInfo.StaticAllocaMap.end())
7368         return;
7369 
7370       const int FrameIndex = SI->second;
7371       int64_t Offset;
7372       if (GetPointerBaseWithConstantOffset(
7373               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
7374         Offset = -1; // Cannot determine offset from alloca to lifetime object.
7375       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
7376                                 Offset);
7377       DAG.setRoot(Res);
7378     }
7379     return;
7380   }
7381   case Intrinsic::pseudoprobe: {
7382     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
7383     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7384     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
7385     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
7386     DAG.setRoot(Res);
7387     return;
7388   }
7389   case Intrinsic::invariant_start:
7390     // Discard region information.
7391     setValue(&I,
7392              DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
7393     return;
7394   case Intrinsic::invariant_end:
7395     // Discard region information.
7396     return;
7397   case Intrinsic::clear_cache:
7398     /// FunctionName may be null.
7399     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
7400       lowerCallToExternalSymbol(I, FunctionName);
7401     return;
7402   case Intrinsic::donothing:
7403   case Intrinsic::seh_try_begin:
7404   case Intrinsic::seh_scope_begin:
7405   case Intrinsic::seh_try_end:
7406   case Intrinsic::seh_scope_end:
7407     // ignore
7408     return;
7409   case Intrinsic::experimental_stackmap:
7410     visitStackmap(I);
7411     return;
7412   case Intrinsic::experimental_patchpoint_void:
7413   case Intrinsic::experimental_patchpoint_i64:
7414     visitPatchpoint(I);
7415     return;
7416   case Intrinsic::experimental_gc_statepoint:
7417     LowerStatepoint(cast<GCStatepointInst>(I));
7418     return;
7419   case Intrinsic::experimental_gc_result:
7420     visitGCResult(cast<GCResultInst>(I));
7421     return;
7422   case Intrinsic::experimental_gc_relocate:
7423     visitGCRelocate(cast<GCRelocateInst>(I));
7424     return;
7425   case Intrinsic::instrprof_cover:
7426     llvm_unreachable("instrprof failed to lower a cover");
7427   case Intrinsic::instrprof_increment:
7428     llvm_unreachable("instrprof failed to lower an increment");
7429   case Intrinsic::instrprof_timestamp:
7430     llvm_unreachable("instrprof failed to lower a timestamp");
7431   case Intrinsic::instrprof_value_profile:
7432     llvm_unreachable("instrprof failed to lower a value profiling call");
7433   case Intrinsic::instrprof_mcdc_parameters:
7434     llvm_unreachable("instrprof failed to lower mcdc parameters");
7435   case Intrinsic::instrprof_mcdc_tvbitmap_update:
7436     llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update");
7437   case Intrinsic::instrprof_mcdc_condbitmap_update:
7438     llvm_unreachable("instrprof failed to lower an mcdc condbitmap update");
7439   case Intrinsic::localescape: {
7440     MachineFunction &MF = DAG.getMachineFunction();
7441     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
7442 
7443     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
7444     // is the same on all targets.
7445     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
7446       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
7447       if (isa<ConstantPointerNull>(Arg))
7448         continue; // Skip null pointers. They represent a hole in index space.
7449       AllocaInst *Slot = cast<AllocaInst>(Arg);
7450       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
7451              "can only escape static allocas");
7452       int FI = FuncInfo.StaticAllocaMap[Slot];
7453       MCSymbol *FrameAllocSym =
7454           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7455               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
7456       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
7457               TII->get(TargetOpcode::LOCAL_ESCAPE))
7458           .addSym(FrameAllocSym)
7459           .addFrameIndex(FI);
7460     }
7461 
7462     return;
7463   }
7464 
7465   case Intrinsic::localrecover: {
7466     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
7467     MachineFunction &MF = DAG.getMachineFunction();
7468 
7469     // Get the symbol that defines the frame offset.
7470     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
7471     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
7472     unsigned IdxVal =
7473         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
7474     MCSymbol *FrameAllocSym =
7475         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7476             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
7477 
7478     Value *FP = I.getArgOperand(1);
7479     SDValue FPVal = getValue(FP);
7480     EVT PtrVT = FPVal.getValueType();
7481 
7482     // Create a MCSymbol for the label to avoid any target lowering
7483     // that would make this PC relative.
7484     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
7485     SDValue OffsetVal =
7486         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
7487 
7488     // Add the offset to the FP.
7489     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
7490     setValue(&I, Add);
7491 
7492     return;
7493   }
7494 
7495   case Intrinsic::eh_exceptionpointer:
7496   case Intrinsic::eh_exceptioncode: {
7497     // Get the exception pointer vreg, copy from it, and resize it to fit.
7498     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
7499     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
7500     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
7501     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
7502     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
7503     if (Intrinsic == Intrinsic::eh_exceptioncode)
7504       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
7505     setValue(&I, N);
7506     return;
7507   }
7508   case Intrinsic::xray_customevent: {
7509     // Here we want to make sure that the intrinsic behaves as if it has a
7510     // specific calling convention.
7511     const auto &Triple = DAG.getTarget().getTargetTriple();
7512     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7513       return;
7514 
7515     SmallVector<SDValue, 8> Ops;
7516 
7517     // We want to say that we always want the arguments in registers.
7518     SDValue LogEntryVal = getValue(I.getArgOperand(0));
7519     SDValue StrSizeVal = getValue(I.getArgOperand(1));
7520     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7521     SDValue Chain = getRoot();
7522     Ops.push_back(LogEntryVal);
7523     Ops.push_back(StrSizeVal);
7524     Ops.push_back(Chain);
7525 
7526     // We need to enforce the calling convention for the callsite, so that
7527     // argument ordering is enforced correctly, and that register allocation can
7528     // see that some registers may be assumed clobbered and have to preserve
7529     // them across calls to the intrinsic.
7530     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
7531                                            sdl, NodeTys, Ops);
7532     SDValue patchableNode = SDValue(MN, 0);
7533     DAG.setRoot(patchableNode);
7534     setValue(&I, patchableNode);
7535     return;
7536   }
7537   case Intrinsic::xray_typedevent: {
7538     // Here we want to make sure that the intrinsic behaves as if it has a
7539     // specific calling convention.
7540     const auto &Triple = DAG.getTarget().getTargetTriple();
7541     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7542       return;
7543 
7544     SmallVector<SDValue, 8> Ops;
7545 
7546     // We want to say that we always want the arguments in registers.
7547     // It's unclear to me how manipulating the selection DAG here forces callers
7548     // to provide arguments in registers instead of on the stack.
7549     SDValue LogTypeId = getValue(I.getArgOperand(0));
7550     SDValue LogEntryVal = getValue(I.getArgOperand(1));
7551     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7552     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7553     SDValue Chain = getRoot();
7554     Ops.push_back(LogTypeId);
7555     Ops.push_back(LogEntryVal);
7556     Ops.push_back(StrSizeVal);
7557     Ops.push_back(Chain);
7558 
7559     // We need to enforce the calling convention for the callsite, so that
7560     // argument ordering is enforced correctly, and that register allocation can
7561     // see that some registers may be assumed clobbered and have to preserve
7562     // them across calls to the intrinsic.
7563     MachineSDNode *MN = DAG.getMachineNode(
7564         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7565     SDValue patchableNode = SDValue(MN, 0);
7566     DAG.setRoot(patchableNode);
7567     setValue(&I, patchableNode);
7568     return;
7569   }
7570   case Intrinsic::experimental_deoptimize:
7571     LowerDeoptimizeCall(&I);
7572     return;
7573   case Intrinsic::experimental_stepvector:
7574     visitStepVector(I);
7575     return;
7576   case Intrinsic::vector_reduce_fadd:
7577   case Intrinsic::vector_reduce_fmul:
7578   case Intrinsic::vector_reduce_add:
7579   case Intrinsic::vector_reduce_mul:
7580   case Intrinsic::vector_reduce_and:
7581   case Intrinsic::vector_reduce_or:
7582   case Intrinsic::vector_reduce_xor:
7583   case Intrinsic::vector_reduce_smax:
7584   case Intrinsic::vector_reduce_smin:
7585   case Intrinsic::vector_reduce_umax:
7586   case Intrinsic::vector_reduce_umin:
7587   case Intrinsic::vector_reduce_fmax:
7588   case Intrinsic::vector_reduce_fmin:
7589   case Intrinsic::vector_reduce_fmaximum:
7590   case Intrinsic::vector_reduce_fminimum:
7591     visitVectorReduce(I, Intrinsic);
7592     return;
7593 
7594   case Intrinsic::icall_branch_funnel: {
7595     SmallVector<SDValue, 16> Ops;
7596     Ops.push_back(getValue(I.getArgOperand(0)));
7597 
7598     int64_t Offset;
7599     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7600         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7601     if (!Base)
7602       report_fatal_error(
7603           "llvm.icall.branch.funnel operand must be a GlobalValue");
7604     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7605 
7606     struct BranchFunnelTarget {
7607       int64_t Offset;
7608       SDValue Target;
7609     };
7610     SmallVector<BranchFunnelTarget, 8> Targets;
7611 
7612     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7613       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7614           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7615       if (ElemBase != Base)
7616         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7617                            "to the same GlobalValue");
7618 
7619       SDValue Val = getValue(I.getArgOperand(Op + 1));
7620       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7621       if (!GA)
7622         report_fatal_error(
7623             "llvm.icall.branch.funnel operand must be a GlobalValue");
7624       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7625                                      GA->getGlobal(), sdl, Val.getValueType(),
7626                                      GA->getOffset())});
7627     }
7628     llvm::sort(Targets,
7629                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7630                  return T1.Offset < T2.Offset;
7631                });
7632 
7633     for (auto &T : Targets) {
7634       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7635       Ops.push_back(T.Target);
7636     }
7637 
7638     Ops.push_back(DAG.getRoot()); // Chain
7639     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7640                                  MVT::Other, Ops),
7641               0);
7642     DAG.setRoot(N);
7643     setValue(&I, N);
7644     HasTailCall = true;
7645     return;
7646   }
7647 
7648   case Intrinsic::wasm_landingpad_index:
7649     // Information this intrinsic contained has been transferred to
7650     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7651     // delete it now.
7652     return;
7653 
7654   case Intrinsic::aarch64_settag:
7655   case Intrinsic::aarch64_settag_zero: {
7656     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7657     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7658     SDValue Val = TSI.EmitTargetCodeForSetTag(
7659         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7660         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7661         ZeroMemory);
7662     DAG.setRoot(Val);
7663     setValue(&I, Val);
7664     return;
7665   }
7666   case Intrinsic::amdgcn_cs_chain: {
7667     assert(I.arg_size() == 5 && "Additional args not supported yet");
7668     assert(cast<ConstantInt>(I.getOperand(4))->isZero() &&
7669            "Non-zero flags not supported yet");
7670 
7671     // At this point we don't care if it's amdgpu_cs_chain or
7672     // amdgpu_cs_chain_preserve.
7673     CallingConv::ID CC = CallingConv::AMDGPU_CS_Chain;
7674 
7675     Type *RetTy = I.getType();
7676     assert(RetTy->isVoidTy() && "Should not return");
7677 
7678     SDValue Callee = getValue(I.getOperand(0));
7679 
7680     // We only have 2 actual args: one for the SGPRs and one for the VGPRs.
7681     // We'll also tack the value of the EXEC mask at the end.
7682     TargetLowering::ArgListTy Args;
7683     Args.reserve(3);
7684 
7685     for (unsigned Idx : {2, 3, 1}) {
7686       TargetLowering::ArgListEntry Arg;
7687       Arg.Node = getValue(I.getOperand(Idx));
7688       Arg.Ty = I.getOperand(Idx)->getType();
7689       Arg.setAttributes(&I, Idx);
7690       Args.push_back(Arg);
7691     }
7692 
7693     assert(Args[0].IsInReg && "SGPR args should be marked inreg");
7694     assert(!Args[1].IsInReg && "VGPR args should not be marked inreg");
7695     Args[2].IsInReg = true; // EXEC should be inreg
7696 
7697     TargetLowering::CallLoweringInfo CLI(DAG);
7698     CLI.setDebugLoc(getCurSDLoc())
7699         .setChain(getRoot())
7700         .setCallee(CC, RetTy, Callee, std::move(Args))
7701         .setNoReturn(true)
7702         .setTailCall(true)
7703         .setConvergent(I.isConvergent());
7704     CLI.CB = &I;
7705     std::pair<SDValue, SDValue> Result =
7706         lowerInvokable(CLI, /*EHPadBB*/ nullptr);
7707     (void)Result;
7708     assert(!Result.first.getNode() && !Result.second.getNode() &&
7709            "Should've lowered as tail call");
7710 
7711     HasTailCall = true;
7712     return;
7713   }
7714   case Intrinsic::ptrmask: {
7715     SDValue Ptr = getValue(I.getOperand(0));
7716     SDValue Mask = getValue(I.getOperand(1));
7717 
7718     EVT PtrVT = Ptr.getValueType();
7719     assert(PtrVT == Mask.getValueType() &&
7720            "Pointers with different index type are not supported by SDAG");
7721     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask));
7722     return;
7723   }
7724   case Intrinsic::threadlocal_address: {
7725     setValue(&I, getValue(I.getOperand(0)));
7726     return;
7727   }
7728   case Intrinsic::get_active_lane_mask: {
7729     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7730     SDValue Index = getValue(I.getOperand(0));
7731     EVT ElementVT = Index.getValueType();
7732 
7733     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
7734       visitTargetIntrinsic(I, Intrinsic);
7735       return;
7736     }
7737 
7738     SDValue TripCount = getValue(I.getOperand(1));
7739     EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT,
7740                                  CCVT.getVectorElementCount());
7741 
7742     SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
7743     SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
7744     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
7745     SDValue VectorInduction = DAG.getNode(
7746         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
7747     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
7748                                  VectorTripCount, ISD::CondCode::SETULT);
7749     setValue(&I, SetCC);
7750     return;
7751   }
7752   case Intrinsic::experimental_get_vector_length: {
7753     assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 &&
7754            "Expected positive VF");
7755     unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue();
7756     bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne();
7757 
7758     SDValue Count = getValue(I.getOperand(0));
7759     EVT CountVT = Count.getValueType();
7760 
7761     if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) {
7762       visitTargetIntrinsic(I, Intrinsic);
7763       return;
7764     }
7765 
7766     // Expand to a umin between the trip count and the maximum elements the type
7767     // can hold.
7768     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7769 
7770     // Extend the trip count to at least the result VT.
7771     if (CountVT.bitsLT(VT)) {
7772       Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count);
7773       CountVT = VT;
7774     }
7775 
7776     SDValue MaxEVL = DAG.getElementCount(sdl, CountVT,
7777                                          ElementCount::get(VF, IsScalable));
7778 
7779     SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL);
7780     // Clip to the result type if needed.
7781     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin);
7782 
7783     setValue(&I, Trunc);
7784     return;
7785   }
7786   case Intrinsic::experimental_cttz_elts: {
7787     auto DL = getCurSDLoc();
7788     SDValue Op = getValue(I.getOperand(0));
7789     EVT OpVT = Op.getValueType();
7790 
7791     if (!TLI.shouldExpandCttzElements(OpVT)) {
7792       visitTargetIntrinsic(I, Intrinsic);
7793       return;
7794     }
7795 
7796     if (OpVT.getScalarType() != MVT::i1) {
7797       // Compare the input vector elements to zero & use to count trailing zeros
7798       SDValue AllZero = DAG.getConstant(0, DL, OpVT);
7799       OpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
7800                               OpVT.getVectorElementCount());
7801       Op = DAG.getSetCC(DL, OpVT, Op, AllZero, ISD::SETNE);
7802     }
7803 
7804     // Find the smallest "sensible" element type to use for the expansion.
7805     ConstantRange CR(
7806         APInt(64, OpVT.getVectorElementCount().getKnownMinValue()));
7807     if (OpVT.isScalableVT())
7808       CR = CR.umul_sat(getVScaleRange(I.getCaller(), 64));
7809 
7810     // If the zero-is-poison flag is set, we can assume the upper limit
7811     // of the result is VF-1.
7812     if (!cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero())
7813       CR = CR.subtract(APInt(64, 1));
7814 
7815     unsigned EltWidth = I.getType()->getScalarSizeInBits();
7816     EltWidth = std::min(EltWidth, (unsigned)CR.getActiveBits());
7817     EltWidth = std::max(llvm::bit_ceil(EltWidth), (unsigned)8);
7818 
7819     MVT NewEltTy = MVT::getIntegerVT(EltWidth);
7820 
7821     // Create the new vector type & get the vector length
7822     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), NewEltTy,
7823                                  OpVT.getVectorElementCount());
7824 
7825     SDValue VL =
7826         DAG.getElementCount(DL, NewEltTy, OpVT.getVectorElementCount());
7827 
7828     SDValue StepVec = DAG.getStepVector(DL, NewVT);
7829     SDValue SplatVL = DAG.getSplat(NewVT, DL, VL);
7830     SDValue StepVL = DAG.getNode(ISD::SUB, DL, NewVT, SplatVL, StepVec);
7831     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, Op);
7832     SDValue And = DAG.getNode(ISD::AND, DL, NewVT, StepVL, Ext);
7833     SDValue Max = DAG.getNode(ISD::VECREDUCE_UMAX, DL, NewEltTy, And);
7834     SDValue Sub = DAG.getNode(ISD::SUB, DL, NewEltTy, VL, Max);
7835 
7836     EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7837     SDValue Ret = DAG.getZExtOrTrunc(Sub, DL, RetTy);
7838 
7839     setValue(&I, Ret);
7840     return;
7841   }
7842   case Intrinsic::vector_insert: {
7843     SDValue Vec = getValue(I.getOperand(0));
7844     SDValue SubVec = getValue(I.getOperand(1));
7845     SDValue Index = getValue(I.getOperand(2));
7846 
7847     // The intrinsic's index type is i64, but the SDNode requires an index type
7848     // suitable for the target. Convert the index as required.
7849     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7850     if (Index.getValueType() != VectorIdxTy)
7851       Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
7852 
7853     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7854     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
7855                              Index));
7856     return;
7857   }
7858   case Intrinsic::vector_extract: {
7859     SDValue Vec = getValue(I.getOperand(0));
7860     SDValue Index = getValue(I.getOperand(1));
7861     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7862 
7863     // The intrinsic's index type is i64, but the SDNode requires an index type
7864     // suitable for the target. Convert the index as required.
7865     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7866     if (Index.getValueType() != VectorIdxTy)
7867       Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
7868 
7869     setValue(&I,
7870              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
7871     return;
7872   }
7873   case Intrinsic::experimental_vector_reverse:
7874     visitVectorReverse(I);
7875     return;
7876   case Intrinsic::experimental_vector_splice:
7877     visitVectorSplice(I);
7878     return;
7879   case Intrinsic::callbr_landingpad:
7880     visitCallBrLandingPad(I);
7881     return;
7882   case Intrinsic::experimental_vector_interleave2:
7883     visitVectorInterleave(I);
7884     return;
7885   case Intrinsic::experimental_vector_deinterleave2:
7886     visitVectorDeinterleave(I);
7887     return;
7888   }
7889 }
7890 
7891 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7892     const ConstrainedFPIntrinsic &FPI) {
7893   SDLoc sdl = getCurSDLoc();
7894 
7895   // We do not need to serialize constrained FP intrinsics against
7896   // each other or against (nonvolatile) loads, so they can be
7897   // chained like loads.
7898   SDValue Chain = DAG.getRoot();
7899   SmallVector<SDValue, 4> Opers;
7900   Opers.push_back(Chain);
7901   if (FPI.isUnaryOp()) {
7902     Opers.push_back(getValue(FPI.getArgOperand(0)));
7903   } else if (FPI.isTernaryOp()) {
7904     Opers.push_back(getValue(FPI.getArgOperand(0)));
7905     Opers.push_back(getValue(FPI.getArgOperand(1)));
7906     Opers.push_back(getValue(FPI.getArgOperand(2)));
7907   } else {
7908     Opers.push_back(getValue(FPI.getArgOperand(0)));
7909     Opers.push_back(getValue(FPI.getArgOperand(1)));
7910   }
7911 
7912   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
7913     assert(Result.getNode()->getNumValues() == 2);
7914 
7915     // Push node to the appropriate list so that future instructions can be
7916     // chained up correctly.
7917     SDValue OutChain = Result.getValue(1);
7918     switch (EB) {
7919     case fp::ExceptionBehavior::ebIgnore:
7920       // The only reason why ebIgnore nodes still need to be chained is that
7921       // they might depend on the current rounding mode, and therefore must
7922       // not be moved across instruction that may change that mode.
7923       [[fallthrough]];
7924     case fp::ExceptionBehavior::ebMayTrap:
7925       // These must not be moved across calls or instructions that may change
7926       // floating-point exception masks.
7927       PendingConstrainedFP.push_back(OutChain);
7928       break;
7929     case fp::ExceptionBehavior::ebStrict:
7930       // These must not be moved across calls or instructions that may change
7931       // floating-point exception masks or read floating-point exception flags.
7932       // In addition, they cannot be optimized out even if unused.
7933       PendingConstrainedFPStrict.push_back(OutChain);
7934       break;
7935     }
7936   };
7937 
7938   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7939   EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
7940   SDVTList VTs = DAG.getVTList(VT, MVT::Other);
7941   fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
7942 
7943   SDNodeFlags Flags;
7944   if (EB == fp::ExceptionBehavior::ebIgnore)
7945     Flags.setNoFPExcept(true);
7946 
7947   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
7948     Flags.copyFMF(*FPOp);
7949 
7950   unsigned Opcode;
7951   switch (FPI.getIntrinsicID()) {
7952   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7953 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7954   case Intrinsic::INTRINSIC:                                                   \
7955     Opcode = ISD::STRICT_##DAGN;                                               \
7956     break;
7957 #include "llvm/IR/ConstrainedOps.def"
7958   case Intrinsic::experimental_constrained_fmuladd: {
7959     Opcode = ISD::STRICT_FMA;
7960     // Break fmuladd into fmul and fadd.
7961     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7962         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
7963       Opers.pop_back();
7964       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
7965       pushOutChain(Mul, EB);
7966       Opcode = ISD::STRICT_FADD;
7967       Opers.clear();
7968       Opers.push_back(Mul.getValue(1));
7969       Opers.push_back(Mul.getValue(0));
7970       Opers.push_back(getValue(FPI.getArgOperand(2)));
7971     }
7972     break;
7973   }
7974   }
7975 
7976   // A few strict DAG nodes carry additional operands that are not
7977   // set up by the default code above.
7978   switch (Opcode) {
7979   default: break;
7980   case ISD::STRICT_FP_ROUND:
7981     Opers.push_back(
7982         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7983     break;
7984   case ISD::STRICT_FSETCC:
7985   case ISD::STRICT_FSETCCS: {
7986     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7987     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
7988     if (TM.Options.NoNaNsFPMath)
7989       Condition = getFCmpCodeWithoutNaN(Condition);
7990     Opers.push_back(DAG.getCondCode(Condition));
7991     break;
7992   }
7993   }
7994 
7995   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7996   pushOutChain(Result, EB);
7997 
7998   SDValue FPResult = Result.getValue(0);
7999   setValue(&FPI, FPResult);
8000 }
8001 
8002 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
8003   std::optional<unsigned> ResOPC;
8004   switch (VPIntrin.getIntrinsicID()) {
8005   case Intrinsic::vp_ctlz: {
8006     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8007     ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ;
8008     break;
8009   }
8010   case Intrinsic::vp_cttz: {
8011     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8012     ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ;
8013     break;
8014   }
8015 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD)                                    \
8016   case Intrinsic::VPID:                                                        \
8017     ResOPC = ISD::VPSD;                                                        \
8018     break;
8019 #include "llvm/IR/VPIntrinsics.def"
8020   }
8021 
8022   if (!ResOPC)
8023     llvm_unreachable(
8024         "Inconsistency: no SDNode available for this VPIntrinsic!");
8025 
8026   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
8027       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
8028     if (VPIntrin.getFastMathFlags().allowReassoc())
8029       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
8030                                                 : ISD::VP_REDUCE_FMUL;
8031   }
8032 
8033   return *ResOPC;
8034 }
8035 
8036 void SelectionDAGBuilder::visitVPLoad(
8037     const VPIntrinsic &VPIntrin, EVT VT,
8038     const SmallVectorImpl<SDValue> &OpValues) {
8039   SDLoc DL = getCurSDLoc();
8040   Value *PtrOperand = VPIntrin.getArgOperand(0);
8041   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8042   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8043   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8044   SDValue LD;
8045   // Do not serialize variable-length loads of constant memory with
8046   // anything.
8047   if (!Alignment)
8048     Alignment = DAG.getEVTAlign(VT);
8049   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
8050   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
8051   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8052   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8053       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
8054       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
8055   LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
8056                      MMO, false /*IsExpanding */);
8057   if (AddToChain)
8058     PendingLoads.push_back(LD.getValue(1));
8059   setValue(&VPIntrin, LD);
8060 }
8061 
8062 void SelectionDAGBuilder::visitVPGather(
8063     const VPIntrinsic &VPIntrin, EVT VT,
8064     const SmallVectorImpl<SDValue> &OpValues) {
8065   SDLoc DL = getCurSDLoc();
8066   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8067   Value *PtrOperand = VPIntrin.getArgOperand(0);
8068   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8069   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8070   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8071   SDValue LD;
8072   if (!Alignment)
8073     Alignment = DAG.getEVTAlign(VT.getScalarType());
8074   unsigned AS =
8075     PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8076   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8077      MachinePointerInfo(AS), MachineMemOperand::MOLoad,
8078      MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
8079   SDValue Base, Index, Scale;
8080   ISD::MemIndexType IndexType;
8081   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
8082                                     this, VPIntrin.getParent(),
8083                                     VT.getScalarStoreSize());
8084   if (!UniformBase) {
8085     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
8086     Index = getValue(PtrOperand);
8087     IndexType = ISD::SIGNED_SCALED;
8088     Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
8089   }
8090   EVT IdxVT = Index.getValueType();
8091   EVT EltTy = IdxVT.getVectorElementType();
8092   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
8093     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
8094     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
8095   }
8096   LD = DAG.getGatherVP(
8097       DAG.getVTList(VT, MVT::Other), VT, DL,
8098       {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
8099       IndexType);
8100   PendingLoads.push_back(LD.getValue(1));
8101   setValue(&VPIntrin, LD);
8102 }
8103 
8104 void SelectionDAGBuilder::visitVPStore(
8105     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8106   SDLoc DL = getCurSDLoc();
8107   Value *PtrOperand = VPIntrin.getArgOperand(1);
8108   EVT VT = OpValues[0].getValueType();
8109   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8110   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8111   SDValue ST;
8112   if (!Alignment)
8113     Alignment = DAG.getEVTAlign(VT);
8114   SDValue Ptr = OpValues[1];
8115   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
8116   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8117       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
8118       MemoryLocation::UnknownSize, *Alignment, AAInfo);
8119   ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
8120                       OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
8121                       /* IsTruncating */ false, /*IsCompressing*/ false);
8122   DAG.setRoot(ST);
8123   setValue(&VPIntrin, ST);
8124 }
8125 
8126 void SelectionDAGBuilder::visitVPScatter(
8127     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8128   SDLoc DL = getCurSDLoc();
8129   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8130   Value *PtrOperand = VPIntrin.getArgOperand(1);
8131   EVT VT = OpValues[0].getValueType();
8132   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8133   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8134   SDValue ST;
8135   if (!Alignment)
8136     Alignment = DAG.getEVTAlign(VT.getScalarType());
8137   unsigned AS =
8138       PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8139   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8140       MachinePointerInfo(AS), MachineMemOperand::MOStore,
8141       MemoryLocation::UnknownSize, *Alignment, AAInfo);
8142   SDValue Base, Index, Scale;
8143   ISD::MemIndexType IndexType;
8144   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
8145                                     this, VPIntrin.getParent(),
8146                                     VT.getScalarStoreSize());
8147   if (!UniformBase) {
8148     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
8149     Index = getValue(PtrOperand);
8150     IndexType = ISD::SIGNED_SCALED;
8151     Scale =
8152       DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
8153   }
8154   EVT IdxVT = Index.getValueType();
8155   EVT EltTy = IdxVT.getVectorElementType();
8156   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
8157     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
8158     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
8159   }
8160   ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
8161                         {getMemoryRoot(), OpValues[0], Base, Index, Scale,
8162                          OpValues[2], OpValues[3]},
8163                         MMO, IndexType);
8164   DAG.setRoot(ST);
8165   setValue(&VPIntrin, ST);
8166 }
8167 
8168 void SelectionDAGBuilder::visitVPStridedLoad(
8169     const VPIntrinsic &VPIntrin, EVT VT,
8170     const SmallVectorImpl<SDValue> &OpValues) {
8171   SDLoc DL = getCurSDLoc();
8172   Value *PtrOperand = VPIntrin.getArgOperand(0);
8173   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8174   if (!Alignment)
8175     Alignment = DAG.getEVTAlign(VT.getScalarType());
8176   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8177   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8178   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
8179   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
8180   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8181   unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8182   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8183       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
8184       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
8185 
8186   SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
8187                                     OpValues[2], OpValues[3], MMO,
8188                                     false /*IsExpanding*/);
8189 
8190   if (AddToChain)
8191     PendingLoads.push_back(LD.getValue(1));
8192   setValue(&VPIntrin, LD);
8193 }
8194 
8195 void SelectionDAGBuilder::visitVPStridedStore(
8196     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8197   SDLoc DL = getCurSDLoc();
8198   Value *PtrOperand = VPIntrin.getArgOperand(1);
8199   EVT VT = OpValues[0].getValueType();
8200   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8201   if (!Alignment)
8202     Alignment = DAG.getEVTAlign(VT.getScalarType());
8203   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8204   unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8205   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8206       MachinePointerInfo(AS), MachineMemOperand::MOStore,
8207       MemoryLocation::UnknownSize, *Alignment, AAInfo);
8208 
8209   SDValue ST = DAG.getStridedStoreVP(
8210       getMemoryRoot(), DL, OpValues[0], OpValues[1],
8211       DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3],
8212       OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
8213       /*IsCompressing*/ false);
8214 
8215   DAG.setRoot(ST);
8216   setValue(&VPIntrin, ST);
8217 }
8218 
8219 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) {
8220   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8221   SDLoc DL = getCurSDLoc();
8222 
8223   ISD::CondCode Condition;
8224   CmpInst::Predicate CondCode = VPIntrin.getPredicate();
8225   bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy();
8226   if (IsFP) {
8227     // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan)
8228     // flags, but calls that don't return floating-point types can't be
8229     // FPMathOperators, like vp.fcmp. This affects constrained fcmp too.
8230     Condition = getFCmpCondCode(CondCode);
8231     if (TM.Options.NoNaNsFPMath)
8232       Condition = getFCmpCodeWithoutNaN(Condition);
8233   } else {
8234     Condition = getICmpCondCode(CondCode);
8235   }
8236 
8237   SDValue Op1 = getValue(VPIntrin.getOperand(0));
8238   SDValue Op2 = getValue(VPIntrin.getOperand(1));
8239   // #2 is the condition code
8240   SDValue MaskOp = getValue(VPIntrin.getOperand(3));
8241   SDValue EVL = getValue(VPIntrin.getOperand(4));
8242   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8243   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8244          "Unexpected target EVL type");
8245   EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL);
8246 
8247   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8248                                                         VPIntrin.getType());
8249   setValue(&VPIntrin,
8250            DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL));
8251 }
8252 
8253 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
8254     const VPIntrinsic &VPIntrin) {
8255   SDLoc DL = getCurSDLoc();
8256   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
8257 
8258   auto IID = VPIntrin.getIntrinsicID();
8259 
8260   if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin))
8261     return visitVPCmp(*CmpI);
8262 
8263   SmallVector<EVT, 4> ValueVTs;
8264   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8265   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
8266   SDVTList VTs = DAG.getVTList(ValueVTs);
8267 
8268   auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
8269 
8270   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8271   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8272          "Unexpected target EVL type");
8273 
8274   // Request operands.
8275   SmallVector<SDValue, 7> OpValues;
8276   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
8277     auto Op = getValue(VPIntrin.getArgOperand(I));
8278     if (I == EVLParamPos)
8279       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
8280     OpValues.push_back(Op);
8281   }
8282 
8283   switch (Opcode) {
8284   default: {
8285     SDNodeFlags SDFlags;
8286     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8287       SDFlags.copyFMF(*FPMO);
8288     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
8289     setValue(&VPIntrin, Result);
8290     break;
8291   }
8292   case ISD::VP_LOAD:
8293     visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
8294     break;
8295   case ISD::VP_GATHER:
8296     visitVPGather(VPIntrin, ValueVTs[0], OpValues);
8297     break;
8298   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
8299     visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
8300     break;
8301   case ISD::VP_STORE:
8302     visitVPStore(VPIntrin, OpValues);
8303     break;
8304   case ISD::VP_SCATTER:
8305     visitVPScatter(VPIntrin, OpValues);
8306     break;
8307   case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
8308     visitVPStridedStore(VPIntrin, OpValues);
8309     break;
8310   case ISD::VP_FMULADD: {
8311     assert(OpValues.size() == 5 && "Unexpected number of operands");
8312     SDNodeFlags SDFlags;
8313     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8314       SDFlags.copyFMF(*FPMO);
8315     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
8316         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) {
8317       setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags));
8318     } else {
8319       SDValue Mul = DAG.getNode(
8320           ISD::VP_FMUL, DL, VTs,
8321           {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags);
8322       SDValue Add =
8323           DAG.getNode(ISD::VP_FADD, DL, VTs,
8324                       {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags);
8325       setValue(&VPIntrin, Add);
8326     }
8327     break;
8328   }
8329   case ISD::VP_IS_FPCLASS: {
8330     const DataLayout DLayout = DAG.getDataLayout();
8331     EVT DestVT = TLI.getValueType(DLayout, VPIntrin.getType());
8332     auto Constant = OpValues[1]->getAsZExtVal();
8333     SDValue Check = DAG.getTargetConstant(Constant, DL, MVT::i32);
8334     SDValue V = DAG.getNode(ISD::VP_IS_FPCLASS, DL, DestVT,
8335                             {OpValues[0], Check, OpValues[2], OpValues[3]});
8336     setValue(&VPIntrin, V);
8337     return;
8338   }
8339   case ISD::VP_INTTOPTR: {
8340     SDValue N = OpValues[0];
8341     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType());
8342     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType());
8343     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8344                                OpValues[2]);
8345     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8346                              OpValues[2]);
8347     setValue(&VPIntrin, N);
8348     break;
8349   }
8350   case ISD::VP_PTRTOINT: {
8351     SDValue N = OpValues[0];
8352     EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8353                                                           VPIntrin.getType());
8354     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(),
8355                                        VPIntrin.getOperand(0)->getType());
8356     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8357                                OpValues[2]);
8358     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8359                              OpValues[2]);
8360     setValue(&VPIntrin, N);
8361     break;
8362   }
8363   case ISD::VP_ABS:
8364   case ISD::VP_CTLZ:
8365   case ISD::VP_CTLZ_ZERO_UNDEF:
8366   case ISD::VP_CTTZ:
8367   case ISD::VP_CTTZ_ZERO_UNDEF: {
8368     SDValue Result =
8369         DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]});
8370     setValue(&VPIntrin, Result);
8371     break;
8372   }
8373   }
8374 }
8375 
8376 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
8377                                           const BasicBlock *EHPadBB,
8378                                           MCSymbol *&BeginLabel) {
8379   MachineFunction &MF = DAG.getMachineFunction();
8380   MachineModuleInfo &MMI = MF.getMMI();
8381 
8382   // Insert a label before the invoke call to mark the try range.  This can be
8383   // used to detect deletion of the invoke via the MachineModuleInfo.
8384   BeginLabel = MMI.getContext().createTempSymbol();
8385 
8386   // For SjLj, keep track of which landing pads go with which invokes
8387   // so as to maintain the ordering of pads in the LSDA.
8388   unsigned CallSiteIndex = MMI.getCurrentCallSite();
8389   if (CallSiteIndex) {
8390     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
8391     LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
8392 
8393     // Now that the call site is handled, stop tracking it.
8394     MMI.setCurrentCallSite(0);
8395   }
8396 
8397   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
8398 }
8399 
8400 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
8401                                         const BasicBlock *EHPadBB,
8402                                         MCSymbol *BeginLabel) {
8403   assert(BeginLabel && "BeginLabel should've been set");
8404 
8405   MachineFunction &MF = DAG.getMachineFunction();
8406   MachineModuleInfo &MMI = MF.getMMI();
8407 
8408   // Insert a label at the end of the invoke call to mark the try range.  This
8409   // can be used to detect deletion of the invoke via the MachineModuleInfo.
8410   MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
8411   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
8412 
8413   // Inform MachineModuleInfo of range.
8414   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
8415   // There is a platform (e.g. wasm) that uses funclet style IR but does not
8416   // actually use outlined funclets and their LSDA info style.
8417   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
8418     assert(II && "II should've been set");
8419     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
8420     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
8421   } else if (!isScopedEHPersonality(Pers)) {
8422     assert(EHPadBB);
8423     MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
8424   }
8425 
8426   return Chain;
8427 }
8428 
8429 std::pair<SDValue, SDValue>
8430 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
8431                                     const BasicBlock *EHPadBB) {
8432   MCSymbol *BeginLabel = nullptr;
8433 
8434   if (EHPadBB) {
8435     // Both PendingLoads and PendingExports must be flushed here;
8436     // this call might not return.
8437     (void)getRoot();
8438     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
8439     CLI.setChain(getRoot());
8440   }
8441 
8442   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8443   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
8444 
8445   assert((CLI.IsTailCall || Result.second.getNode()) &&
8446          "Non-null chain expected with non-tail call!");
8447   assert((Result.second.getNode() || !Result.first.getNode()) &&
8448          "Null value expected with tail call!");
8449 
8450   if (!Result.second.getNode()) {
8451     // As a special case, a null chain means that a tail call has been emitted
8452     // and the DAG root is already updated.
8453     HasTailCall = true;
8454 
8455     // Since there's no actual continuation from this block, nothing can be
8456     // relying on us setting vregs for them.
8457     PendingExports.clear();
8458   } else {
8459     DAG.setRoot(Result.second);
8460   }
8461 
8462   if (EHPadBB) {
8463     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
8464                            BeginLabel));
8465   }
8466 
8467   return Result;
8468 }
8469 
8470 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
8471                                       bool isTailCall,
8472                                       bool isMustTailCall,
8473                                       const BasicBlock *EHPadBB) {
8474   auto &DL = DAG.getDataLayout();
8475   FunctionType *FTy = CB.getFunctionType();
8476   Type *RetTy = CB.getType();
8477 
8478   TargetLowering::ArgListTy Args;
8479   Args.reserve(CB.arg_size());
8480 
8481   const Value *SwiftErrorVal = nullptr;
8482   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8483 
8484   if (isTailCall) {
8485     // Avoid emitting tail calls in functions with the disable-tail-calls
8486     // attribute.
8487     auto *Caller = CB.getParent()->getParent();
8488     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
8489         "true" && !isMustTailCall)
8490       isTailCall = false;
8491 
8492     // We can't tail call inside a function with a swifterror argument. Lowering
8493     // does not support this yet. It would have to move into the swifterror
8494     // register before the call.
8495     if (TLI.supportSwiftError() &&
8496         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
8497       isTailCall = false;
8498   }
8499 
8500   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
8501     TargetLowering::ArgListEntry Entry;
8502     const Value *V = *I;
8503 
8504     // Skip empty types
8505     if (V->getType()->isEmptyTy())
8506       continue;
8507 
8508     SDValue ArgNode = getValue(V);
8509     Entry.Node = ArgNode; Entry.Ty = V->getType();
8510 
8511     Entry.setAttributes(&CB, I - CB.arg_begin());
8512 
8513     // Use swifterror virtual register as input to the call.
8514     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
8515       SwiftErrorVal = V;
8516       // We find the virtual register for the actual swifterror argument.
8517       // Instead of using the Value, we use the virtual register instead.
8518       Entry.Node =
8519           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
8520                           EVT(TLI.getPointerTy(DL)));
8521     }
8522 
8523     Args.push_back(Entry);
8524 
8525     // If we have an explicit sret argument that is an Instruction, (i.e., it
8526     // might point to function-local memory), we can't meaningfully tail-call.
8527     if (Entry.IsSRet && isa<Instruction>(V))
8528       isTailCall = false;
8529   }
8530 
8531   // If call site has a cfguardtarget operand bundle, create and add an
8532   // additional ArgListEntry.
8533   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
8534     TargetLowering::ArgListEntry Entry;
8535     Value *V = Bundle->Inputs[0];
8536     SDValue ArgNode = getValue(V);
8537     Entry.Node = ArgNode;
8538     Entry.Ty = V->getType();
8539     Entry.IsCFGuardTarget = true;
8540     Args.push_back(Entry);
8541   }
8542 
8543   // Check if target-independent constraints permit a tail call here.
8544   // Target-dependent constraints are checked within TLI->LowerCallTo.
8545   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
8546     isTailCall = false;
8547 
8548   // Disable tail calls if there is an swifterror argument. Targets have not
8549   // been updated to support tail calls.
8550   if (TLI.supportSwiftError() && SwiftErrorVal)
8551     isTailCall = false;
8552 
8553   ConstantInt *CFIType = nullptr;
8554   if (CB.isIndirectCall()) {
8555     if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
8556       if (!TLI.supportKCFIBundles())
8557         report_fatal_error(
8558             "Target doesn't support calls with kcfi operand bundles.");
8559       CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
8560       assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
8561     }
8562   }
8563 
8564   TargetLowering::CallLoweringInfo CLI(DAG);
8565   CLI.setDebugLoc(getCurSDLoc())
8566       .setChain(getRoot())
8567       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
8568       .setTailCall(isTailCall)
8569       .setConvergent(CB.isConvergent())
8570       .setIsPreallocated(
8571           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
8572       .setCFIType(CFIType);
8573   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8574 
8575   if (Result.first.getNode()) {
8576     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
8577     setValue(&CB, Result.first);
8578   }
8579 
8580   // The last element of CLI.InVals has the SDValue for swifterror return.
8581   // Here we copy it to a virtual register and update SwiftErrorMap for
8582   // book-keeping.
8583   if (SwiftErrorVal && TLI.supportSwiftError()) {
8584     // Get the last element of InVals.
8585     SDValue Src = CLI.InVals.back();
8586     Register VReg =
8587         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
8588     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
8589     DAG.setRoot(CopyNode);
8590   }
8591 }
8592 
8593 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
8594                              SelectionDAGBuilder &Builder) {
8595   // Check to see if this load can be trivially constant folded, e.g. if the
8596   // input is from a string literal.
8597   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
8598     // Cast pointer to the type we really want to load.
8599     Type *LoadTy =
8600         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
8601     if (LoadVT.isVector())
8602       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
8603 
8604     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
8605                                          PointerType::getUnqual(LoadTy));
8606 
8607     if (const Constant *LoadCst =
8608             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
8609                                          LoadTy, Builder.DAG.getDataLayout()))
8610       return Builder.getValue(LoadCst);
8611   }
8612 
8613   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
8614   // still constant memory, the input chain can be the entry node.
8615   SDValue Root;
8616   bool ConstantMemory = false;
8617 
8618   // Do not serialize (non-volatile) loads of constant memory with anything.
8619   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
8620     Root = Builder.DAG.getEntryNode();
8621     ConstantMemory = true;
8622   } else {
8623     // Do not serialize non-volatile loads against each other.
8624     Root = Builder.DAG.getRoot();
8625   }
8626 
8627   SDValue Ptr = Builder.getValue(PtrVal);
8628   SDValue LoadVal =
8629       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
8630                           MachinePointerInfo(PtrVal), Align(1));
8631 
8632   if (!ConstantMemory)
8633     Builder.PendingLoads.push_back(LoadVal.getValue(1));
8634   return LoadVal;
8635 }
8636 
8637 /// Record the value for an instruction that produces an integer result,
8638 /// converting the type where necessary.
8639 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
8640                                                   SDValue Value,
8641                                                   bool IsSigned) {
8642   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8643                                                     I.getType(), true);
8644   Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT);
8645   setValue(&I, Value);
8646 }
8647 
8648 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
8649 /// true and lower it. Otherwise return false, and it will be lowered like a
8650 /// normal call.
8651 /// The caller already checked that \p I calls the appropriate LibFunc with a
8652 /// correct prototype.
8653 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
8654   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
8655   const Value *Size = I.getArgOperand(2);
8656   const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
8657   if (CSize && CSize->getZExtValue() == 0) {
8658     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8659                                                           I.getType(), true);
8660     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
8661     return true;
8662   }
8663 
8664   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8665   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
8666       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
8667       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
8668   if (Res.first.getNode()) {
8669     processIntegerCallValue(I, Res.first, true);
8670     PendingLoads.push_back(Res.second);
8671     return true;
8672   }
8673 
8674   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
8675   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
8676   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
8677     return false;
8678 
8679   // If the target has a fast compare for the given size, it will return a
8680   // preferred load type for that size. Require that the load VT is legal and
8681   // that the target supports unaligned loads of that type. Otherwise, return
8682   // INVALID.
8683   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
8684     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8685     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
8686     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
8687       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
8688       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
8689       // TODO: Check alignment of src and dest ptrs.
8690       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
8691       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
8692       if (!TLI.isTypeLegal(LVT) ||
8693           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
8694           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
8695         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
8696     }
8697 
8698     return LVT;
8699   };
8700 
8701   // This turns into unaligned loads. We only do this if the target natively
8702   // supports the MVT we'll be loading or if it is small enough (<= 4) that
8703   // we'll only produce a small number of byte loads.
8704   MVT LoadVT;
8705   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
8706   switch (NumBitsToCompare) {
8707   default:
8708     return false;
8709   case 16:
8710     LoadVT = MVT::i16;
8711     break;
8712   case 32:
8713     LoadVT = MVT::i32;
8714     break;
8715   case 64:
8716   case 128:
8717   case 256:
8718     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
8719     break;
8720   }
8721 
8722   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
8723     return false;
8724 
8725   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
8726   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
8727 
8728   // Bitcast to a wide integer type if the loads are vectors.
8729   if (LoadVT.isVector()) {
8730     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
8731     LoadL = DAG.getBitcast(CmpVT, LoadL);
8732     LoadR = DAG.getBitcast(CmpVT, LoadR);
8733   }
8734 
8735   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
8736   processIntegerCallValue(I, Cmp, false);
8737   return true;
8738 }
8739 
8740 /// See if we can lower a memchr call into an optimized form. If so, return
8741 /// true and lower it. Otherwise return false, and it will be lowered like a
8742 /// normal call.
8743 /// The caller already checked that \p I calls the appropriate LibFunc with a
8744 /// correct prototype.
8745 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
8746   const Value *Src = I.getArgOperand(0);
8747   const Value *Char = I.getArgOperand(1);
8748   const Value *Length = I.getArgOperand(2);
8749 
8750   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8751   std::pair<SDValue, SDValue> Res =
8752     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
8753                                 getValue(Src), getValue(Char), getValue(Length),
8754                                 MachinePointerInfo(Src));
8755   if (Res.first.getNode()) {
8756     setValue(&I, Res.first);
8757     PendingLoads.push_back(Res.second);
8758     return true;
8759   }
8760 
8761   return false;
8762 }
8763 
8764 /// See if we can lower a mempcpy call into an optimized form. If so, return
8765 /// true and lower it. Otherwise return false, and it will be lowered like a
8766 /// normal call.
8767 /// The caller already checked that \p I calls the appropriate LibFunc with a
8768 /// correct prototype.
8769 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
8770   SDValue Dst = getValue(I.getArgOperand(0));
8771   SDValue Src = getValue(I.getArgOperand(1));
8772   SDValue Size = getValue(I.getArgOperand(2));
8773 
8774   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
8775   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
8776   // DAG::getMemcpy needs Alignment to be defined.
8777   Align Alignment = std::min(DstAlign, SrcAlign);
8778 
8779   SDLoc sdl = getCurSDLoc();
8780 
8781   // In the mempcpy context we need to pass in a false value for isTailCall
8782   // because the return pointer needs to be adjusted by the size of
8783   // the copied memory.
8784   SDValue Root = getMemoryRoot();
8785   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, false, false,
8786                              /*isTailCall=*/false,
8787                              MachinePointerInfo(I.getArgOperand(0)),
8788                              MachinePointerInfo(I.getArgOperand(1)),
8789                              I.getAAMetadata());
8790   assert(MC.getNode() != nullptr &&
8791          "** memcpy should not be lowered as TailCall in mempcpy context **");
8792   DAG.setRoot(MC);
8793 
8794   // Check if Size needs to be truncated or extended.
8795   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
8796 
8797   // Adjust return pointer to point just past the last dst byte.
8798   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
8799                                     Dst, Size);
8800   setValue(&I, DstPlusSize);
8801   return true;
8802 }
8803 
8804 /// See if we can lower a strcpy call into an optimized form.  If so, return
8805 /// true and lower it, otherwise return false and it will be lowered like a
8806 /// normal call.
8807 /// The caller already checked that \p I calls the appropriate LibFunc with a
8808 /// correct prototype.
8809 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
8810   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8811 
8812   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8813   std::pair<SDValue, SDValue> Res =
8814     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
8815                                 getValue(Arg0), getValue(Arg1),
8816                                 MachinePointerInfo(Arg0),
8817                                 MachinePointerInfo(Arg1), isStpcpy);
8818   if (Res.first.getNode()) {
8819     setValue(&I, Res.first);
8820     DAG.setRoot(Res.second);
8821     return true;
8822   }
8823 
8824   return false;
8825 }
8826 
8827 /// See if we can lower a strcmp call into an optimized form.  If so, return
8828 /// true and lower it, otherwise return false and it will be lowered like a
8829 /// normal call.
8830 /// The caller already checked that \p I calls the appropriate LibFunc with a
8831 /// correct prototype.
8832 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
8833   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8834 
8835   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8836   std::pair<SDValue, SDValue> Res =
8837     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
8838                                 getValue(Arg0), getValue(Arg1),
8839                                 MachinePointerInfo(Arg0),
8840                                 MachinePointerInfo(Arg1));
8841   if (Res.first.getNode()) {
8842     processIntegerCallValue(I, Res.first, true);
8843     PendingLoads.push_back(Res.second);
8844     return true;
8845   }
8846 
8847   return false;
8848 }
8849 
8850 /// See if we can lower a strlen call into an optimized form.  If so, return
8851 /// true and lower it, otherwise return false and it will be lowered like a
8852 /// normal call.
8853 /// The caller already checked that \p I calls the appropriate LibFunc with a
8854 /// correct prototype.
8855 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
8856   const Value *Arg0 = I.getArgOperand(0);
8857 
8858   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8859   std::pair<SDValue, SDValue> Res =
8860     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
8861                                 getValue(Arg0), MachinePointerInfo(Arg0));
8862   if (Res.first.getNode()) {
8863     processIntegerCallValue(I, Res.first, false);
8864     PendingLoads.push_back(Res.second);
8865     return true;
8866   }
8867 
8868   return false;
8869 }
8870 
8871 /// See if we can lower a strnlen call into an optimized form.  If so, return
8872 /// true and lower it, otherwise return false and it will be lowered like a
8873 /// normal call.
8874 /// The caller already checked that \p I calls the appropriate LibFunc with a
8875 /// correct prototype.
8876 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
8877   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8878 
8879   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8880   std::pair<SDValue, SDValue> Res =
8881     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
8882                                  getValue(Arg0), getValue(Arg1),
8883                                  MachinePointerInfo(Arg0));
8884   if (Res.first.getNode()) {
8885     processIntegerCallValue(I, Res.first, false);
8886     PendingLoads.push_back(Res.second);
8887     return true;
8888   }
8889 
8890   return false;
8891 }
8892 
8893 /// See if we can lower a unary floating-point operation into an SDNode with
8894 /// the specified Opcode.  If so, return true and lower it, otherwise return
8895 /// false and it will be lowered like a normal call.
8896 /// The caller already checked that \p I calls the appropriate LibFunc with a
8897 /// correct prototype.
8898 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
8899                                               unsigned Opcode) {
8900   // We already checked this call's prototype; verify it doesn't modify errno.
8901   if (!I.onlyReadsMemory())
8902     return false;
8903 
8904   SDNodeFlags Flags;
8905   Flags.copyFMF(cast<FPMathOperator>(I));
8906 
8907   SDValue Tmp = getValue(I.getArgOperand(0));
8908   setValue(&I,
8909            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
8910   return true;
8911 }
8912 
8913 /// See if we can lower a binary floating-point operation into an SDNode with
8914 /// the specified Opcode. If so, return true and lower it. Otherwise return
8915 /// false, and it will be lowered like a normal call.
8916 /// The caller already checked that \p I calls the appropriate LibFunc with a
8917 /// correct prototype.
8918 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
8919                                                unsigned Opcode) {
8920   // We already checked this call's prototype; verify it doesn't modify errno.
8921   if (!I.onlyReadsMemory())
8922     return false;
8923 
8924   SDNodeFlags Flags;
8925   Flags.copyFMF(cast<FPMathOperator>(I));
8926 
8927   SDValue Tmp0 = getValue(I.getArgOperand(0));
8928   SDValue Tmp1 = getValue(I.getArgOperand(1));
8929   EVT VT = Tmp0.getValueType();
8930   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
8931   return true;
8932 }
8933 
8934 void SelectionDAGBuilder::visitCall(const CallInst &I) {
8935   // Handle inline assembly differently.
8936   if (I.isInlineAsm()) {
8937     visitInlineAsm(I);
8938     return;
8939   }
8940 
8941   diagnoseDontCall(I);
8942 
8943   if (Function *F = I.getCalledFunction()) {
8944     if (F->isDeclaration()) {
8945       // Is this an LLVM intrinsic or a target-specific intrinsic?
8946       unsigned IID = F->getIntrinsicID();
8947       if (!IID)
8948         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
8949           IID = II->getIntrinsicID(F);
8950 
8951       if (IID) {
8952         visitIntrinsicCall(I, IID);
8953         return;
8954       }
8955     }
8956 
8957     // Check for well-known libc/libm calls.  If the function is internal, it
8958     // can't be a library call.  Don't do the check if marked as nobuiltin for
8959     // some reason or the call site requires strict floating point semantics.
8960     LibFunc Func;
8961     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
8962         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
8963         LibInfo->hasOptimizedCodeGen(Func)) {
8964       switch (Func) {
8965       default: break;
8966       case LibFunc_bcmp:
8967         if (visitMemCmpBCmpCall(I))
8968           return;
8969         break;
8970       case LibFunc_copysign:
8971       case LibFunc_copysignf:
8972       case LibFunc_copysignl:
8973         // We already checked this call's prototype; verify it doesn't modify
8974         // errno.
8975         if (I.onlyReadsMemory()) {
8976           SDValue LHS = getValue(I.getArgOperand(0));
8977           SDValue RHS = getValue(I.getArgOperand(1));
8978           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
8979                                    LHS.getValueType(), LHS, RHS));
8980           return;
8981         }
8982         break;
8983       case LibFunc_fabs:
8984       case LibFunc_fabsf:
8985       case LibFunc_fabsl:
8986         if (visitUnaryFloatCall(I, ISD::FABS))
8987           return;
8988         break;
8989       case LibFunc_fmin:
8990       case LibFunc_fminf:
8991       case LibFunc_fminl:
8992         if (visitBinaryFloatCall(I, ISD::FMINNUM))
8993           return;
8994         break;
8995       case LibFunc_fmax:
8996       case LibFunc_fmaxf:
8997       case LibFunc_fmaxl:
8998         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
8999           return;
9000         break;
9001       case LibFunc_sin:
9002       case LibFunc_sinf:
9003       case LibFunc_sinl:
9004         if (visitUnaryFloatCall(I, ISD::FSIN))
9005           return;
9006         break;
9007       case LibFunc_cos:
9008       case LibFunc_cosf:
9009       case LibFunc_cosl:
9010         if (visitUnaryFloatCall(I, ISD::FCOS))
9011           return;
9012         break;
9013       case LibFunc_sqrt:
9014       case LibFunc_sqrtf:
9015       case LibFunc_sqrtl:
9016       case LibFunc_sqrt_finite:
9017       case LibFunc_sqrtf_finite:
9018       case LibFunc_sqrtl_finite:
9019         if (visitUnaryFloatCall(I, ISD::FSQRT))
9020           return;
9021         break;
9022       case LibFunc_floor:
9023       case LibFunc_floorf:
9024       case LibFunc_floorl:
9025         if (visitUnaryFloatCall(I, ISD::FFLOOR))
9026           return;
9027         break;
9028       case LibFunc_nearbyint:
9029       case LibFunc_nearbyintf:
9030       case LibFunc_nearbyintl:
9031         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
9032           return;
9033         break;
9034       case LibFunc_ceil:
9035       case LibFunc_ceilf:
9036       case LibFunc_ceill:
9037         if (visitUnaryFloatCall(I, ISD::FCEIL))
9038           return;
9039         break;
9040       case LibFunc_rint:
9041       case LibFunc_rintf:
9042       case LibFunc_rintl:
9043         if (visitUnaryFloatCall(I, ISD::FRINT))
9044           return;
9045         break;
9046       case LibFunc_round:
9047       case LibFunc_roundf:
9048       case LibFunc_roundl:
9049         if (visitUnaryFloatCall(I, ISD::FROUND))
9050           return;
9051         break;
9052       case LibFunc_trunc:
9053       case LibFunc_truncf:
9054       case LibFunc_truncl:
9055         if (visitUnaryFloatCall(I, ISD::FTRUNC))
9056           return;
9057         break;
9058       case LibFunc_log2:
9059       case LibFunc_log2f:
9060       case LibFunc_log2l:
9061         if (visitUnaryFloatCall(I, ISD::FLOG2))
9062           return;
9063         break;
9064       case LibFunc_exp2:
9065       case LibFunc_exp2f:
9066       case LibFunc_exp2l:
9067         if (visitUnaryFloatCall(I, ISD::FEXP2))
9068           return;
9069         break;
9070       case LibFunc_exp10:
9071       case LibFunc_exp10f:
9072       case LibFunc_exp10l:
9073         if (visitUnaryFloatCall(I, ISD::FEXP10))
9074           return;
9075         break;
9076       case LibFunc_ldexp:
9077       case LibFunc_ldexpf:
9078       case LibFunc_ldexpl:
9079         if (visitBinaryFloatCall(I, ISD::FLDEXP))
9080           return;
9081         break;
9082       case LibFunc_memcmp:
9083         if (visitMemCmpBCmpCall(I))
9084           return;
9085         break;
9086       case LibFunc_mempcpy:
9087         if (visitMemPCpyCall(I))
9088           return;
9089         break;
9090       case LibFunc_memchr:
9091         if (visitMemChrCall(I))
9092           return;
9093         break;
9094       case LibFunc_strcpy:
9095         if (visitStrCpyCall(I, false))
9096           return;
9097         break;
9098       case LibFunc_stpcpy:
9099         if (visitStrCpyCall(I, true))
9100           return;
9101         break;
9102       case LibFunc_strcmp:
9103         if (visitStrCmpCall(I))
9104           return;
9105         break;
9106       case LibFunc_strlen:
9107         if (visitStrLenCall(I))
9108           return;
9109         break;
9110       case LibFunc_strnlen:
9111         if (visitStrNLenCall(I))
9112           return;
9113         break;
9114       }
9115     }
9116   }
9117 
9118   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
9119   // have to do anything here to lower funclet bundles.
9120   // CFGuardTarget bundles are lowered in LowerCallTo.
9121   assert(!I.hasOperandBundlesOtherThan(
9122              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
9123               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
9124               LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) &&
9125          "Cannot lower calls with arbitrary operand bundles!");
9126 
9127   SDValue Callee = getValue(I.getCalledOperand());
9128 
9129   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
9130     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
9131   else
9132     // Check if we can potentially perform a tail call. More detailed checking
9133     // is be done within LowerCallTo, after more information about the call is
9134     // known.
9135     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
9136 }
9137 
9138 namespace {
9139 
9140 /// AsmOperandInfo - This contains information for each constraint that we are
9141 /// lowering.
9142 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
9143 public:
9144   /// CallOperand - If this is the result output operand or a clobber
9145   /// this is null, otherwise it is the incoming operand to the CallInst.
9146   /// This gets modified as the asm is processed.
9147   SDValue CallOperand;
9148 
9149   /// AssignedRegs - If this is a register or register class operand, this
9150   /// contains the set of register corresponding to the operand.
9151   RegsForValue AssignedRegs;
9152 
9153   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
9154     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
9155   }
9156 
9157   /// Whether or not this operand accesses memory
9158   bool hasMemory(const TargetLowering &TLI) const {
9159     // Indirect operand accesses access memory.
9160     if (isIndirect)
9161       return true;
9162 
9163     for (const auto &Code : Codes)
9164       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
9165         return true;
9166 
9167     return false;
9168   }
9169 };
9170 
9171 
9172 } // end anonymous namespace
9173 
9174 /// Make sure that the output operand \p OpInfo and its corresponding input
9175 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
9176 /// out).
9177 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
9178                                SDISelAsmOperandInfo &MatchingOpInfo,
9179                                SelectionDAG &DAG) {
9180   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
9181     return;
9182 
9183   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
9184   const auto &TLI = DAG.getTargetLoweringInfo();
9185 
9186   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
9187       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
9188                                        OpInfo.ConstraintVT);
9189   std::pair<unsigned, const TargetRegisterClass *> InputRC =
9190       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
9191                                        MatchingOpInfo.ConstraintVT);
9192   if ((OpInfo.ConstraintVT.isInteger() !=
9193        MatchingOpInfo.ConstraintVT.isInteger()) ||
9194       (MatchRC.second != InputRC.second)) {
9195     // FIXME: error out in a more elegant fashion
9196     report_fatal_error("Unsupported asm: input constraint"
9197                        " with a matching output constraint of"
9198                        " incompatible type!");
9199   }
9200   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
9201 }
9202 
9203 /// Get a direct memory input to behave well as an indirect operand.
9204 /// This may introduce stores, hence the need for a \p Chain.
9205 /// \return The (possibly updated) chain.
9206 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
9207                                         SDISelAsmOperandInfo &OpInfo,
9208                                         SelectionDAG &DAG) {
9209   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9210 
9211   // If we don't have an indirect input, put it in the constpool if we can,
9212   // otherwise spill it to a stack slot.
9213   // TODO: This isn't quite right. We need to handle these according to
9214   // the addressing mode that the constraint wants. Also, this may take
9215   // an additional register for the computation and we don't want that
9216   // either.
9217 
9218   // If the operand is a float, integer, or vector constant, spill to a
9219   // constant pool entry to get its address.
9220   const Value *OpVal = OpInfo.CallOperandVal;
9221   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
9222       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
9223     OpInfo.CallOperand = DAG.getConstantPool(
9224         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
9225     return Chain;
9226   }
9227 
9228   // Otherwise, create a stack slot and emit a store to it before the asm.
9229   Type *Ty = OpVal->getType();
9230   auto &DL = DAG.getDataLayout();
9231   uint64_t TySize = DL.getTypeAllocSize(Ty);
9232   MachineFunction &MF = DAG.getMachineFunction();
9233   int SSFI = MF.getFrameInfo().CreateStackObject(
9234       TySize, DL.getPrefTypeAlign(Ty), false);
9235   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
9236   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
9237                             MachinePointerInfo::getFixedStack(MF, SSFI),
9238                             TLI.getMemValueType(DL, Ty));
9239   OpInfo.CallOperand = StackSlot;
9240 
9241   return Chain;
9242 }
9243 
9244 /// GetRegistersForValue - Assign registers (virtual or physical) for the
9245 /// specified operand.  We prefer to assign virtual registers, to allow the
9246 /// register allocator to handle the assignment process.  However, if the asm
9247 /// uses features that we can't model on machineinstrs, we have SDISel do the
9248 /// allocation.  This produces generally horrible, but correct, code.
9249 ///
9250 ///   OpInfo describes the operand
9251 ///   RefOpInfo describes the matching operand if any, the operand otherwise
9252 static std::optional<unsigned>
9253 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
9254                      SDISelAsmOperandInfo &OpInfo,
9255                      SDISelAsmOperandInfo &RefOpInfo) {
9256   LLVMContext &Context = *DAG.getContext();
9257   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9258 
9259   MachineFunction &MF = DAG.getMachineFunction();
9260   SmallVector<unsigned, 4> Regs;
9261   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9262 
9263   // No work to do for memory/address operands.
9264   if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9265       OpInfo.ConstraintType == TargetLowering::C_Address)
9266     return std::nullopt;
9267 
9268   // If this is a constraint for a single physreg, or a constraint for a
9269   // register class, find it.
9270   unsigned AssignedReg;
9271   const TargetRegisterClass *RC;
9272   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
9273       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
9274   // RC is unset only on failure. Return immediately.
9275   if (!RC)
9276     return std::nullopt;
9277 
9278   // Get the actual register value type.  This is important, because the user
9279   // may have asked for (e.g.) the AX register in i32 type.  We need to
9280   // remember that AX is actually i16 to get the right extension.
9281   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
9282 
9283   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
9284     // If this is an FP operand in an integer register (or visa versa), or more
9285     // generally if the operand value disagrees with the register class we plan
9286     // to stick it in, fix the operand type.
9287     //
9288     // If this is an input value, the bitcast to the new type is done now.
9289     // Bitcast for output value is done at the end of visitInlineAsm().
9290     if ((OpInfo.Type == InlineAsm::isOutput ||
9291          OpInfo.Type == InlineAsm::isInput) &&
9292         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
9293       // Try to convert to the first EVT that the reg class contains.  If the
9294       // types are identical size, use a bitcast to convert (e.g. two differing
9295       // vector types).  Note: output bitcast is done at the end of
9296       // visitInlineAsm().
9297       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
9298         // Exclude indirect inputs while they are unsupported because the code
9299         // to perform the load is missing and thus OpInfo.CallOperand still
9300         // refers to the input address rather than the pointed-to value.
9301         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
9302           OpInfo.CallOperand =
9303               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
9304         OpInfo.ConstraintVT = RegVT;
9305         // If the operand is an FP value and we want it in integer registers,
9306         // use the corresponding integer type. This turns an f64 value into
9307         // i64, which can be passed with two i32 values on a 32-bit machine.
9308       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
9309         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
9310         if (OpInfo.Type == InlineAsm::isInput)
9311           OpInfo.CallOperand =
9312               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
9313         OpInfo.ConstraintVT = VT;
9314       }
9315     }
9316   }
9317 
9318   // No need to allocate a matching input constraint since the constraint it's
9319   // matching to has already been allocated.
9320   if (OpInfo.isMatchingInputConstraint())
9321     return std::nullopt;
9322 
9323   EVT ValueVT = OpInfo.ConstraintVT;
9324   if (OpInfo.ConstraintVT == MVT::Other)
9325     ValueVT = RegVT;
9326 
9327   // Initialize NumRegs.
9328   unsigned NumRegs = 1;
9329   if (OpInfo.ConstraintVT != MVT::Other)
9330     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
9331 
9332   // If this is a constraint for a specific physical register, like {r17},
9333   // assign it now.
9334 
9335   // If this associated to a specific register, initialize iterator to correct
9336   // place. If virtual, make sure we have enough registers
9337 
9338   // Initialize iterator if necessary
9339   TargetRegisterClass::iterator I = RC->begin();
9340   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9341 
9342   // Do not check for single registers.
9343   if (AssignedReg) {
9344     I = std::find(I, RC->end(), AssignedReg);
9345     if (I == RC->end()) {
9346       // RC does not contain the selected register, which indicates a
9347       // mismatch between the register and the required type/bitwidth.
9348       return {AssignedReg};
9349     }
9350   }
9351 
9352   for (; NumRegs; --NumRegs, ++I) {
9353     assert(I != RC->end() && "Ran out of registers to allocate!");
9354     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
9355     Regs.push_back(R);
9356   }
9357 
9358   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
9359   return std::nullopt;
9360 }
9361 
9362 static unsigned
9363 findMatchingInlineAsmOperand(unsigned OperandNo,
9364                              const std::vector<SDValue> &AsmNodeOperands) {
9365   // Scan until we find the definition we already emitted of this operand.
9366   unsigned CurOp = InlineAsm::Op_FirstOperand;
9367   for (; OperandNo; --OperandNo) {
9368     // Advance to the next operand.
9369     unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal();
9370     const InlineAsm::Flag F(OpFlag);
9371     assert(
9372         (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) &&
9373         "Skipped past definitions?");
9374     CurOp += F.getNumOperandRegisters() + 1;
9375   }
9376   return CurOp;
9377 }
9378 
9379 namespace {
9380 
9381 class ExtraFlags {
9382   unsigned Flags = 0;
9383 
9384 public:
9385   explicit ExtraFlags(const CallBase &Call) {
9386     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9387     if (IA->hasSideEffects())
9388       Flags |= InlineAsm::Extra_HasSideEffects;
9389     if (IA->isAlignStack())
9390       Flags |= InlineAsm::Extra_IsAlignStack;
9391     if (Call.isConvergent())
9392       Flags |= InlineAsm::Extra_IsConvergent;
9393     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
9394   }
9395 
9396   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
9397     // Ideally, we would only check against memory constraints.  However, the
9398     // meaning of an Other constraint can be target-specific and we can't easily
9399     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
9400     // for Other constraints as well.
9401     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9402         OpInfo.ConstraintType == TargetLowering::C_Other) {
9403       if (OpInfo.Type == InlineAsm::isInput)
9404         Flags |= InlineAsm::Extra_MayLoad;
9405       else if (OpInfo.Type == InlineAsm::isOutput)
9406         Flags |= InlineAsm::Extra_MayStore;
9407       else if (OpInfo.Type == InlineAsm::isClobber)
9408         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
9409     }
9410   }
9411 
9412   unsigned get() const { return Flags; }
9413 };
9414 
9415 } // end anonymous namespace
9416 
9417 static bool isFunction(SDValue Op) {
9418   if (Op && Op.getOpcode() == ISD::GlobalAddress) {
9419     if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
9420       auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
9421 
9422       // In normal "call dllimport func" instruction (non-inlineasm) it force
9423       // indirect access by specifing call opcode. And usually specially print
9424       // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
9425       // not do in this way now. (In fact, this is similar with "Data Access"
9426       // action). So here we ignore dllimport function.
9427       if (Fn && !Fn->hasDLLImportStorageClass())
9428         return true;
9429     }
9430   }
9431   return false;
9432 }
9433 
9434 /// visitInlineAsm - Handle a call to an InlineAsm object.
9435 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
9436                                          const BasicBlock *EHPadBB) {
9437   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9438 
9439   /// ConstraintOperands - Information about all of the constraints.
9440   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
9441 
9442   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9443   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
9444       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
9445 
9446   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
9447   // AsmDialect, MayLoad, MayStore).
9448   bool HasSideEffect = IA->hasSideEffects();
9449   ExtraFlags ExtraInfo(Call);
9450 
9451   for (auto &T : TargetConstraints) {
9452     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
9453     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
9454 
9455     if (OpInfo.CallOperandVal)
9456       OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
9457 
9458     if (!HasSideEffect)
9459       HasSideEffect = OpInfo.hasMemory(TLI);
9460 
9461     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
9462     // FIXME: Could we compute this on OpInfo rather than T?
9463 
9464     // Compute the constraint code and ConstraintType to use.
9465     TLI.ComputeConstraintToUse(T, SDValue());
9466 
9467     if (T.ConstraintType == TargetLowering::C_Immediate &&
9468         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
9469       // We've delayed emitting a diagnostic like the "n" constraint because
9470       // inlining could cause an integer showing up.
9471       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
9472                                           "' expects an integer constant "
9473                                           "expression");
9474 
9475     ExtraInfo.update(T);
9476   }
9477 
9478   // We won't need to flush pending loads if this asm doesn't touch
9479   // memory and is nonvolatile.
9480   SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
9481 
9482   bool EmitEHLabels = isa<InvokeInst>(Call);
9483   if (EmitEHLabels) {
9484     assert(EHPadBB && "InvokeInst must have an EHPadBB");
9485   }
9486   bool IsCallBr = isa<CallBrInst>(Call);
9487 
9488   if (IsCallBr || EmitEHLabels) {
9489     // If this is a callbr or invoke we need to flush pending exports since
9490     // inlineasm_br and invoke are terminators.
9491     // We need to do this before nodes are glued to the inlineasm_br node.
9492     Chain = getControlRoot();
9493   }
9494 
9495   MCSymbol *BeginLabel = nullptr;
9496   if (EmitEHLabels) {
9497     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
9498   }
9499 
9500   int OpNo = -1;
9501   SmallVector<StringRef> AsmStrs;
9502   IA->collectAsmStrs(AsmStrs);
9503 
9504   // Second pass over the constraints: compute which constraint option to use.
9505   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9506     if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
9507       OpNo++;
9508 
9509     // If this is an output operand with a matching input operand, look up the
9510     // matching input. If their types mismatch, e.g. one is an integer, the
9511     // other is floating point, or their sizes are different, flag it as an
9512     // error.
9513     if (OpInfo.hasMatchingInput()) {
9514       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
9515       patchMatchingInput(OpInfo, Input, DAG);
9516     }
9517 
9518     // Compute the constraint code and ConstraintType to use.
9519     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
9520 
9521     if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
9522          OpInfo.Type == InlineAsm::isClobber) ||
9523         OpInfo.ConstraintType == TargetLowering::C_Address)
9524       continue;
9525 
9526     // In Linux PIC model, there are 4 cases about value/label addressing:
9527     //
9528     // 1: Function call or Label jmp inside the module.
9529     // 2: Data access (such as global variable, static variable) inside module.
9530     // 3: Function call or Label jmp outside the module.
9531     // 4: Data access (such as global variable) outside the module.
9532     //
9533     // Due to current llvm inline asm architecture designed to not "recognize"
9534     // the asm code, there are quite troubles for us to treat mem addressing
9535     // differently for same value/adress used in different instuctions.
9536     // For example, in pic model, call a func may in plt way or direclty
9537     // pc-related, but lea/mov a function adress may use got.
9538     //
9539     // Here we try to "recognize" function call for the case 1 and case 3 in
9540     // inline asm. And try to adjust the constraint for them.
9541     //
9542     // TODO: Due to current inline asm didn't encourage to jmp to the outsider
9543     // label, so here we don't handle jmp function label now, but we need to
9544     // enhance it (especilly in PIC model) if we meet meaningful requirements.
9545     if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
9546         TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
9547         TM.getCodeModel() != CodeModel::Large) {
9548       OpInfo.isIndirect = false;
9549       OpInfo.ConstraintType = TargetLowering::C_Address;
9550     }
9551 
9552     // If this is a memory input, and if the operand is not indirect, do what we
9553     // need to provide an address for the memory input.
9554     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
9555         !OpInfo.isIndirect) {
9556       assert((OpInfo.isMultipleAlternative ||
9557               (OpInfo.Type == InlineAsm::isInput)) &&
9558              "Can only indirectify direct input operands!");
9559 
9560       // Memory operands really want the address of the value.
9561       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
9562 
9563       // There is no longer a Value* corresponding to this operand.
9564       OpInfo.CallOperandVal = nullptr;
9565 
9566       // It is now an indirect operand.
9567       OpInfo.isIndirect = true;
9568     }
9569 
9570   }
9571 
9572   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
9573   std::vector<SDValue> AsmNodeOperands;
9574   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
9575   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
9576       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
9577 
9578   // If we have a !srcloc metadata node associated with it, we want to attach
9579   // this to the ultimately generated inline asm machineinstr.  To do this, we
9580   // pass in the third operand as this (potentially null) inline asm MDNode.
9581   const MDNode *SrcLoc = Call.getMetadata("srcloc");
9582   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
9583 
9584   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
9585   // bits as operand 3.
9586   AsmNodeOperands.push_back(DAG.getTargetConstant(
9587       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9588 
9589   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
9590   // this, assign virtual and physical registers for inputs and otput.
9591   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9592     // Assign Registers.
9593     SDISelAsmOperandInfo &RefOpInfo =
9594         OpInfo.isMatchingInputConstraint()
9595             ? ConstraintOperands[OpInfo.getMatchedOperand()]
9596             : OpInfo;
9597     const auto RegError =
9598         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
9599     if (RegError) {
9600       const MachineFunction &MF = DAG.getMachineFunction();
9601       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9602       const char *RegName = TRI.getName(*RegError);
9603       emitInlineAsmError(Call, "register '" + Twine(RegName) +
9604                                    "' allocated for constraint '" +
9605                                    Twine(OpInfo.ConstraintCode) +
9606                                    "' does not match required type");
9607       return;
9608     }
9609 
9610     auto DetectWriteToReservedRegister = [&]() {
9611       const MachineFunction &MF = DAG.getMachineFunction();
9612       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9613       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
9614         if (Register::isPhysicalRegister(Reg) &&
9615             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
9616           const char *RegName = TRI.getName(Reg);
9617           emitInlineAsmError(Call, "write to reserved register '" +
9618                                        Twine(RegName) + "'");
9619           return true;
9620         }
9621       }
9622       return false;
9623     };
9624     assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
9625             (OpInfo.Type == InlineAsm::isInput &&
9626              !OpInfo.isMatchingInputConstraint())) &&
9627            "Only address as input operand is allowed.");
9628 
9629     switch (OpInfo.Type) {
9630     case InlineAsm::isOutput:
9631       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
9632         const InlineAsm::ConstraintCode ConstraintID =
9633             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9634         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
9635                "Failed to convert memory constraint code to constraint id.");
9636 
9637         // Add information to the INLINEASM node to know about this output.
9638         InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1);
9639         OpFlags.setMemConstraint(ConstraintID);
9640         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
9641                                                         MVT::i32));
9642         AsmNodeOperands.push_back(OpInfo.CallOperand);
9643       } else {
9644         // Otherwise, this outputs to a register (directly for C_Register /
9645         // C_RegisterClass, and a target-defined fashion for
9646         // C_Immediate/C_Other). Find a register that we can use.
9647         if (OpInfo.AssignedRegs.Regs.empty()) {
9648           emitInlineAsmError(
9649               Call, "couldn't allocate output register for constraint '" +
9650                         Twine(OpInfo.ConstraintCode) + "'");
9651           return;
9652         }
9653 
9654         if (DetectWriteToReservedRegister())
9655           return;
9656 
9657         // Add information to the INLINEASM node to know that this register is
9658         // set.
9659         OpInfo.AssignedRegs.AddInlineAsmOperands(
9660             OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber
9661                                   : InlineAsm::Kind::RegDef,
9662             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
9663       }
9664       break;
9665 
9666     case InlineAsm::isInput:
9667     case InlineAsm::isLabel: {
9668       SDValue InOperandVal = OpInfo.CallOperand;
9669 
9670       if (OpInfo.isMatchingInputConstraint()) {
9671         // If this is required to match an output register we have already set,
9672         // just use its register.
9673         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
9674                                                   AsmNodeOperands);
9675         InlineAsm::Flag Flag(AsmNodeOperands[CurOp]->getAsZExtVal());
9676         if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) {
9677           if (OpInfo.isIndirect) {
9678             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
9679             emitInlineAsmError(Call, "inline asm not supported yet: "
9680                                      "don't know how to handle tied "
9681                                      "indirect register inputs");
9682             return;
9683           }
9684 
9685           SmallVector<unsigned, 4> Regs;
9686           MachineFunction &MF = DAG.getMachineFunction();
9687           MachineRegisterInfo &MRI = MF.getRegInfo();
9688           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9689           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
9690           Register TiedReg = R->getReg();
9691           MVT RegVT = R->getSimpleValueType(0);
9692           const TargetRegisterClass *RC =
9693               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
9694               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
9695                                       : TRI.getMinimalPhysRegClass(TiedReg);
9696           for (unsigned i = 0, e = Flag.getNumOperandRegisters(); i != e; ++i)
9697             Regs.push_back(MRI.createVirtualRegister(RC));
9698 
9699           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
9700 
9701           SDLoc dl = getCurSDLoc();
9702           // Use the produced MatchedRegs object to
9703           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call);
9704           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, true,
9705                                            OpInfo.getMatchedOperand(), dl, DAG,
9706                                            AsmNodeOperands);
9707           break;
9708         }
9709 
9710         assert(Flag.isMemKind() && "Unknown matching constraint!");
9711         assert(Flag.getNumOperandRegisters() == 1 &&
9712                "Unexpected number of operands");
9713         // Add information to the INLINEASM node to know about this input.
9714         // See InlineAsm.h isUseOperandTiedToDef.
9715         Flag.clearMemConstraint();
9716         Flag.setMatchingOp(OpInfo.getMatchedOperand());
9717         AsmNodeOperands.push_back(DAG.getTargetConstant(
9718             Flag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9719         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
9720         break;
9721       }
9722 
9723       // Treat indirect 'X' constraint as memory.
9724       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
9725           OpInfo.isIndirect)
9726         OpInfo.ConstraintType = TargetLowering::C_Memory;
9727 
9728       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
9729           OpInfo.ConstraintType == TargetLowering::C_Other) {
9730         std::vector<SDValue> Ops;
9731         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
9732                                           Ops, DAG);
9733         if (Ops.empty()) {
9734           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
9735             if (isa<ConstantSDNode>(InOperandVal)) {
9736               emitInlineAsmError(Call, "value out of range for constraint '" +
9737                                            Twine(OpInfo.ConstraintCode) + "'");
9738               return;
9739             }
9740 
9741           emitInlineAsmError(Call,
9742                              "invalid operand for inline asm constraint '" +
9743                                  Twine(OpInfo.ConstraintCode) + "'");
9744           return;
9745         }
9746 
9747         // Add information to the INLINEASM node to know about this input.
9748         InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size());
9749         AsmNodeOperands.push_back(DAG.getTargetConstant(
9750             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9751         llvm::append_range(AsmNodeOperands, Ops);
9752         break;
9753       }
9754 
9755       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
9756         assert((OpInfo.isIndirect ||
9757                 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
9758                "Operand must be indirect to be a mem!");
9759         assert(InOperandVal.getValueType() ==
9760                    TLI.getPointerTy(DAG.getDataLayout()) &&
9761                "Memory operands expect pointer values");
9762 
9763         const InlineAsm::ConstraintCode ConstraintID =
9764             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9765         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
9766                "Failed to convert memory constraint code to constraint id.");
9767 
9768         // Add information to the INLINEASM node to know about this input.
9769         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
9770         ResOpType.setMemConstraint(ConstraintID);
9771         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
9772                                                         getCurSDLoc(),
9773                                                         MVT::i32));
9774         AsmNodeOperands.push_back(InOperandVal);
9775         break;
9776       }
9777 
9778       if (OpInfo.ConstraintType == TargetLowering::C_Address) {
9779         const InlineAsm::ConstraintCode ConstraintID =
9780             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9781         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
9782                "Failed to convert memory constraint code to constraint id.");
9783 
9784         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
9785 
9786         SDValue AsmOp = InOperandVal;
9787         if (isFunction(InOperandVal)) {
9788           auto *GA = cast<GlobalAddressSDNode>(InOperandVal);
9789           ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1);
9790           AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(),
9791                                              InOperandVal.getValueType(),
9792                                              GA->getOffset());
9793         }
9794 
9795         // Add information to the INLINEASM node to know about this input.
9796         ResOpType.setMemConstraint(ConstraintID);
9797 
9798         AsmNodeOperands.push_back(
9799             DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32));
9800 
9801         AsmNodeOperands.push_back(AsmOp);
9802         break;
9803       }
9804 
9805       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
9806               OpInfo.ConstraintType == TargetLowering::C_Register) &&
9807              "Unknown constraint type!");
9808 
9809       // TODO: Support this.
9810       if (OpInfo.isIndirect) {
9811         emitInlineAsmError(
9812             Call, "Don't know how to handle indirect register inputs yet "
9813                   "for constraint '" +
9814                       Twine(OpInfo.ConstraintCode) + "'");
9815         return;
9816       }
9817 
9818       // Copy the input into the appropriate registers.
9819       if (OpInfo.AssignedRegs.Regs.empty()) {
9820         emitInlineAsmError(Call,
9821                            "couldn't allocate input reg for constraint '" +
9822                                Twine(OpInfo.ConstraintCode) + "'");
9823         return;
9824       }
9825 
9826       if (DetectWriteToReservedRegister())
9827         return;
9828 
9829       SDLoc dl = getCurSDLoc();
9830 
9831       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue,
9832                                         &Call);
9833 
9834       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, false,
9835                                                0, dl, DAG, AsmNodeOperands);
9836       break;
9837     }
9838     case InlineAsm::isClobber:
9839       // Add the clobbered value to the operand list, so that the register
9840       // allocator is aware that the physreg got clobbered.
9841       if (!OpInfo.AssignedRegs.Regs.empty())
9842         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::Clobber,
9843                                                  false, 0, getCurSDLoc(), DAG,
9844                                                  AsmNodeOperands);
9845       break;
9846     }
9847   }
9848 
9849   // Finish up input operands.  Set the input chain and add the flag last.
9850   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
9851   if (Glue.getNode()) AsmNodeOperands.push_back(Glue);
9852 
9853   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
9854   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
9855                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
9856   Glue = Chain.getValue(1);
9857 
9858   // Do additional work to generate outputs.
9859 
9860   SmallVector<EVT, 1> ResultVTs;
9861   SmallVector<SDValue, 1> ResultValues;
9862   SmallVector<SDValue, 8> OutChains;
9863 
9864   llvm::Type *CallResultType = Call.getType();
9865   ArrayRef<Type *> ResultTypes;
9866   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
9867     ResultTypes = StructResult->elements();
9868   else if (!CallResultType->isVoidTy())
9869     ResultTypes = ArrayRef(CallResultType);
9870 
9871   auto CurResultType = ResultTypes.begin();
9872   auto handleRegAssign = [&](SDValue V) {
9873     assert(CurResultType != ResultTypes.end() && "Unexpected value");
9874     assert((*CurResultType)->isSized() && "Unexpected unsized type");
9875     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
9876     ++CurResultType;
9877     // If the type of the inline asm call site return value is different but has
9878     // same size as the type of the asm output bitcast it.  One example of this
9879     // is for vectors with different width / number of elements.  This can
9880     // happen for register classes that can contain multiple different value
9881     // types.  The preg or vreg allocated may not have the same VT as was
9882     // expected.
9883     //
9884     // This can also happen for a return value that disagrees with the register
9885     // class it is put in, eg. a double in a general-purpose register on a
9886     // 32-bit machine.
9887     if (ResultVT != V.getValueType() &&
9888         ResultVT.getSizeInBits() == V.getValueSizeInBits())
9889       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
9890     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
9891              V.getValueType().isInteger()) {
9892       // If a result value was tied to an input value, the computed result
9893       // may have a wider width than the expected result.  Extract the
9894       // relevant portion.
9895       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
9896     }
9897     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
9898     ResultVTs.push_back(ResultVT);
9899     ResultValues.push_back(V);
9900   };
9901 
9902   // Deal with output operands.
9903   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9904     if (OpInfo.Type == InlineAsm::isOutput) {
9905       SDValue Val;
9906       // Skip trivial output operands.
9907       if (OpInfo.AssignedRegs.Regs.empty())
9908         continue;
9909 
9910       switch (OpInfo.ConstraintType) {
9911       case TargetLowering::C_Register:
9912       case TargetLowering::C_RegisterClass:
9913         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
9914                                                   Chain, &Glue, &Call);
9915         break;
9916       case TargetLowering::C_Immediate:
9917       case TargetLowering::C_Other:
9918         Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(),
9919                                               OpInfo, DAG);
9920         break;
9921       case TargetLowering::C_Memory:
9922         break; // Already handled.
9923       case TargetLowering::C_Address:
9924         break; // Silence warning.
9925       case TargetLowering::C_Unknown:
9926         assert(false && "Unexpected unknown constraint");
9927       }
9928 
9929       // Indirect output manifest as stores. Record output chains.
9930       if (OpInfo.isIndirect) {
9931         const Value *Ptr = OpInfo.CallOperandVal;
9932         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
9933         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
9934                                      MachinePointerInfo(Ptr));
9935         OutChains.push_back(Store);
9936       } else {
9937         // generate CopyFromRegs to associated registers.
9938         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
9939         if (Val.getOpcode() == ISD::MERGE_VALUES) {
9940           for (const SDValue &V : Val->op_values())
9941             handleRegAssign(V);
9942         } else
9943           handleRegAssign(Val);
9944       }
9945     }
9946   }
9947 
9948   // Set results.
9949   if (!ResultValues.empty()) {
9950     assert(CurResultType == ResultTypes.end() &&
9951            "Mismatch in number of ResultTypes");
9952     assert(ResultValues.size() == ResultTypes.size() &&
9953            "Mismatch in number of output operands in asm result");
9954 
9955     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
9956                             DAG.getVTList(ResultVTs), ResultValues);
9957     setValue(&Call, V);
9958   }
9959 
9960   // Collect store chains.
9961   if (!OutChains.empty())
9962     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
9963 
9964   if (EmitEHLabels) {
9965     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
9966   }
9967 
9968   // Only Update Root if inline assembly has a memory effect.
9969   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
9970       EmitEHLabels)
9971     DAG.setRoot(Chain);
9972 }
9973 
9974 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
9975                                              const Twine &Message) {
9976   LLVMContext &Ctx = *DAG.getContext();
9977   Ctx.emitError(&Call, Message);
9978 
9979   // Make sure we leave the DAG in a valid state
9980   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9981   SmallVector<EVT, 1> ValueVTs;
9982   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
9983 
9984   if (ValueVTs.empty())
9985     return;
9986 
9987   SmallVector<SDValue, 1> Ops;
9988   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
9989     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
9990 
9991   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
9992 }
9993 
9994 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
9995   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
9996                           MVT::Other, getRoot(),
9997                           getValue(I.getArgOperand(0)),
9998                           DAG.getSrcValue(I.getArgOperand(0))));
9999 }
10000 
10001 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
10002   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10003   const DataLayout &DL = DAG.getDataLayout();
10004   SDValue V = DAG.getVAArg(
10005       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
10006       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
10007       DL.getABITypeAlign(I.getType()).value());
10008   DAG.setRoot(V.getValue(1));
10009 
10010   if (I.getType()->isPointerTy())
10011     V = DAG.getPtrExtOrTrunc(
10012         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
10013   setValue(&I, V);
10014 }
10015 
10016 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
10017   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
10018                           MVT::Other, getRoot(),
10019                           getValue(I.getArgOperand(0)),
10020                           DAG.getSrcValue(I.getArgOperand(0))));
10021 }
10022 
10023 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
10024   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
10025                           MVT::Other, getRoot(),
10026                           getValue(I.getArgOperand(0)),
10027                           getValue(I.getArgOperand(1)),
10028                           DAG.getSrcValue(I.getArgOperand(0)),
10029                           DAG.getSrcValue(I.getArgOperand(1))));
10030 }
10031 
10032 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
10033                                                     const Instruction &I,
10034                                                     SDValue Op) {
10035   const MDNode *Range = getRangeMetadata(I);
10036   if (!Range)
10037     return Op;
10038 
10039   ConstantRange CR = getConstantRangeFromMetadata(*Range);
10040   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
10041     return Op;
10042 
10043   APInt Lo = CR.getUnsignedMin();
10044   if (!Lo.isMinValue())
10045     return Op;
10046 
10047   APInt Hi = CR.getUnsignedMax();
10048   unsigned Bits = std::max(Hi.getActiveBits(),
10049                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
10050 
10051   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
10052 
10053   SDLoc SL = getCurSDLoc();
10054 
10055   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
10056                              DAG.getValueType(SmallVT));
10057   unsigned NumVals = Op.getNode()->getNumValues();
10058   if (NumVals == 1)
10059     return ZExt;
10060 
10061   SmallVector<SDValue, 4> Ops;
10062 
10063   Ops.push_back(ZExt);
10064   for (unsigned I = 1; I != NumVals; ++I)
10065     Ops.push_back(Op.getValue(I));
10066 
10067   return DAG.getMergeValues(Ops, SL);
10068 }
10069 
10070 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
10071 /// the call being lowered.
10072 ///
10073 /// This is a helper for lowering intrinsics that follow a target calling
10074 /// convention or require stack pointer adjustment. Only a subset of the
10075 /// intrinsic's operands need to participate in the calling convention.
10076 void SelectionDAGBuilder::populateCallLoweringInfo(
10077     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
10078     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
10079     AttributeSet RetAttrs, bool IsPatchPoint) {
10080   TargetLowering::ArgListTy Args;
10081   Args.reserve(NumArgs);
10082 
10083   // Populate the argument list.
10084   // Attributes for args start at offset 1, after the return attribute.
10085   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
10086        ArgI != ArgE; ++ArgI) {
10087     const Value *V = Call->getOperand(ArgI);
10088 
10089     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
10090 
10091     TargetLowering::ArgListEntry Entry;
10092     Entry.Node = getValue(V);
10093     Entry.Ty = V->getType();
10094     Entry.setAttributes(Call, ArgI);
10095     Args.push_back(Entry);
10096   }
10097 
10098   CLI.setDebugLoc(getCurSDLoc())
10099       .setChain(getRoot())
10100       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args),
10101                  RetAttrs)
10102       .setDiscardResult(Call->use_empty())
10103       .setIsPatchPoint(IsPatchPoint)
10104       .setIsPreallocated(
10105           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
10106 }
10107 
10108 /// Add a stack map intrinsic call's live variable operands to a stackmap
10109 /// or patchpoint target node's operand list.
10110 ///
10111 /// Constants are converted to TargetConstants purely as an optimization to
10112 /// avoid constant materialization and register allocation.
10113 ///
10114 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
10115 /// generate addess computation nodes, and so FinalizeISel can convert the
10116 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
10117 /// address materialization and register allocation, but may also be required
10118 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
10119 /// alloca in the entry block, then the runtime may assume that the alloca's
10120 /// StackMap location can be read immediately after compilation and that the
10121 /// location is valid at any point during execution (this is similar to the
10122 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
10123 /// only available in a register, then the runtime would need to trap when
10124 /// execution reaches the StackMap in order to read the alloca's location.
10125 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
10126                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
10127                                 SelectionDAGBuilder &Builder) {
10128   SelectionDAG &DAG = Builder.DAG;
10129   for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
10130     SDValue Op = Builder.getValue(Call.getArgOperand(I));
10131 
10132     // Things on the stack are pointer-typed, meaning that they are already
10133     // legal and can be emitted directly to target nodes.
10134     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
10135       Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
10136     } else {
10137       // Otherwise emit a target independent node to be legalised.
10138       Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
10139     }
10140   }
10141 }
10142 
10143 /// Lower llvm.experimental.stackmap.
10144 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
10145   // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
10146   //                                  [live variables...])
10147 
10148   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
10149 
10150   SDValue Chain, InGlue, Callee;
10151   SmallVector<SDValue, 32> Ops;
10152 
10153   SDLoc DL = getCurSDLoc();
10154   Callee = getValue(CI.getCalledOperand());
10155 
10156   // The stackmap intrinsic only records the live variables (the arguments
10157   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
10158   // intrinsic, this won't be lowered to a function call. This means we don't
10159   // have to worry about calling conventions and target specific lowering code.
10160   // Instead we perform the call lowering right here.
10161   //
10162   // chain, flag = CALLSEQ_START(chain, 0, 0)
10163   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
10164   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
10165   //
10166   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
10167   InGlue = Chain.getValue(1);
10168 
10169   // Add the STACKMAP operands, starting with DAG house-keeping.
10170   Ops.push_back(Chain);
10171   Ops.push_back(InGlue);
10172 
10173   // Add the <id>, <numShadowBytes> operands.
10174   //
10175   // These do not require legalisation, and can be emitted directly to target
10176   // constant nodes.
10177   SDValue ID = getValue(CI.getArgOperand(0));
10178   assert(ID.getValueType() == MVT::i64);
10179   SDValue IDConst =
10180       DAG.getTargetConstant(ID->getAsZExtVal(), DL, ID.getValueType());
10181   Ops.push_back(IDConst);
10182 
10183   SDValue Shad = getValue(CI.getArgOperand(1));
10184   assert(Shad.getValueType() == MVT::i32);
10185   SDValue ShadConst =
10186       DAG.getTargetConstant(Shad->getAsZExtVal(), DL, Shad.getValueType());
10187   Ops.push_back(ShadConst);
10188 
10189   // Add the live variables.
10190   addStackMapLiveVars(CI, 2, DL, Ops, *this);
10191 
10192   // Create the STACKMAP node.
10193   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10194   Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
10195   InGlue = Chain.getValue(1);
10196 
10197   Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL);
10198 
10199   // Stackmaps don't generate values, so nothing goes into the NodeMap.
10200 
10201   // Set the root to the target-lowered call chain.
10202   DAG.setRoot(Chain);
10203 
10204   // Inform the Frame Information that we have a stackmap in this function.
10205   FuncInfo.MF->getFrameInfo().setHasStackMap();
10206 }
10207 
10208 /// Lower llvm.experimental.patchpoint directly to its target opcode.
10209 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
10210                                           const BasicBlock *EHPadBB) {
10211   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
10212   //                                                 i32 <numBytes>,
10213   //                                                 i8* <target>,
10214   //                                                 i32 <numArgs>,
10215   //                                                 [Args...],
10216   //                                                 [live variables...])
10217 
10218   CallingConv::ID CC = CB.getCallingConv();
10219   bool IsAnyRegCC = CC == CallingConv::AnyReg;
10220   bool HasDef = !CB.getType()->isVoidTy();
10221   SDLoc dl = getCurSDLoc();
10222   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
10223 
10224   // Handle immediate and symbolic callees.
10225   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
10226     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
10227                                    /*isTarget=*/true);
10228   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
10229     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
10230                                          SDLoc(SymbolicCallee),
10231                                          SymbolicCallee->getValueType(0));
10232 
10233   // Get the real number of arguments participating in the call <numArgs>
10234   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
10235   unsigned NumArgs = NArgVal->getAsZExtVal();
10236 
10237   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
10238   // Intrinsics include all meta-operands up to but not including CC.
10239   unsigned NumMetaOpers = PatchPointOpers::CCPos;
10240   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
10241          "Not enough arguments provided to the patchpoint intrinsic");
10242 
10243   // For AnyRegCC the arguments are lowered later on manually.
10244   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
10245   Type *ReturnTy =
10246       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
10247 
10248   TargetLowering::CallLoweringInfo CLI(DAG);
10249   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
10250                            ReturnTy, CB.getAttributes().getRetAttrs(), true);
10251   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
10252 
10253   SDNode *CallEnd = Result.second.getNode();
10254   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
10255     CallEnd = CallEnd->getOperand(0).getNode();
10256 
10257   /// Get a call instruction from the call sequence chain.
10258   /// Tail calls are not allowed.
10259   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
10260          "Expected a callseq node.");
10261   SDNode *Call = CallEnd->getOperand(0).getNode();
10262   bool HasGlue = Call->getGluedNode();
10263 
10264   // Replace the target specific call node with the patchable intrinsic.
10265   SmallVector<SDValue, 8> Ops;
10266 
10267   // Push the chain.
10268   Ops.push_back(*(Call->op_begin()));
10269 
10270   // Optionally, push the glue (if any).
10271   if (HasGlue)
10272     Ops.push_back(*(Call->op_end() - 1));
10273 
10274   // Push the register mask info.
10275   if (HasGlue)
10276     Ops.push_back(*(Call->op_end() - 2));
10277   else
10278     Ops.push_back(*(Call->op_end() - 1));
10279 
10280   // Add the <id> and <numBytes> constants.
10281   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
10282   Ops.push_back(DAG.getTargetConstant(IDVal->getAsZExtVal(), dl, MVT::i64));
10283   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
10284   Ops.push_back(DAG.getTargetConstant(NBytesVal->getAsZExtVal(), dl, MVT::i32));
10285 
10286   // Add the callee.
10287   Ops.push_back(Callee);
10288 
10289   // Adjust <numArgs> to account for any arguments that have been passed on the
10290   // stack instead.
10291   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
10292   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
10293   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
10294   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
10295 
10296   // Add the calling convention
10297   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
10298 
10299   // Add the arguments we omitted previously. The register allocator should
10300   // place these in any free register.
10301   if (IsAnyRegCC)
10302     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
10303       Ops.push_back(getValue(CB.getArgOperand(i)));
10304 
10305   // Push the arguments from the call instruction.
10306   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
10307   Ops.append(Call->op_begin() + 2, e);
10308 
10309   // Push live variables for the stack map.
10310   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
10311 
10312   SDVTList NodeTys;
10313   if (IsAnyRegCC && HasDef) {
10314     // Create the return types based on the intrinsic definition
10315     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10316     SmallVector<EVT, 3> ValueVTs;
10317     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
10318     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
10319 
10320     // There is always a chain and a glue type at the end
10321     ValueVTs.push_back(MVT::Other);
10322     ValueVTs.push_back(MVT::Glue);
10323     NodeTys = DAG.getVTList(ValueVTs);
10324   } else
10325     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10326 
10327   // Replace the target specific call node with a PATCHPOINT node.
10328   SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
10329 
10330   // Update the NodeMap.
10331   if (HasDef) {
10332     if (IsAnyRegCC)
10333       setValue(&CB, SDValue(PPV.getNode(), 0));
10334     else
10335       setValue(&CB, Result.first);
10336   }
10337 
10338   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
10339   // call sequence. Furthermore the location of the chain and glue can change
10340   // when the AnyReg calling convention is used and the intrinsic returns a
10341   // value.
10342   if (IsAnyRegCC && HasDef) {
10343     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
10344     SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
10345     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10346   } else
10347     DAG.ReplaceAllUsesWith(Call, PPV.getNode());
10348   DAG.DeleteNode(Call);
10349 
10350   // Inform the Frame Information that we have a patchpoint in this function.
10351   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
10352 }
10353 
10354 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
10355                                             unsigned Intrinsic) {
10356   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10357   SDValue Op1 = getValue(I.getArgOperand(0));
10358   SDValue Op2;
10359   if (I.arg_size() > 1)
10360     Op2 = getValue(I.getArgOperand(1));
10361   SDLoc dl = getCurSDLoc();
10362   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
10363   SDValue Res;
10364   SDNodeFlags SDFlags;
10365   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
10366     SDFlags.copyFMF(*FPMO);
10367 
10368   switch (Intrinsic) {
10369   case Intrinsic::vector_reduce_fadd:
10370     if (SDFlags.hasAllowReassociation())
10371       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
10372                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
10373                         SDFlags);
10374     else
10375       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
10376     break;
10377   case Intrinsic::vector_reduce_fmul:
10378     if (SDFlags.hasAllowReassociation())
10379       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
10380                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
10381                         SDFlags);
10382     else
10383       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
10384     break;
10385   case Intrinsic::vector_reduce_add:
10386     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
10387     break;
10388   case Intrinsic::vector_reduce_mul:
10389     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
10390     break;
10391   case Intrinsic::vector_reduce_and:
10392     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
10393     break;
10394   case Intrinsic::vector_reduce_or:
10395     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
10396     break;
10397   case Intrinsic::vector_reduce_xor:
10398     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
10399     break;
10400   case Intrinsic::vector_reduce_smax:
10401     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
10402     break;
10403   case Intrinsic::vector_reduce_smin:
10404     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
10405     break;
10406   case Intrinsic::vector_reduce_umax:
10407     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
10408     break;
10409   case Intrinsic::vector_reduce_umin:
10410     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
10411     break;
10412   case Intrinsic::vector_reduce_fmax:
10413     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
10414     break;
10415   case Intrinsic::vector_reduce_fmin:
10416     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
10417     break;
10418   case Intrinsic::vector_reduce_fmaximum:
10419     Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags);
10420     break;
10421   case Intrinsic::vector_reduce_fminimum:
10422     Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags);
10423     break;
10424   default:
10425     llvm_unreachable("Unhandled vector reduce intrinsic");
10426   }
10427   setValue(&I, Res);
10428 }
10429 
10430 /// Returns an AttributeList representing the attributes applied to the return
10431 /// value of the given call.
10432 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
10433   SmallVector<Attribute::AttrKind, 2> Attrs;
10434   if (CLI.RetSExt)
10435     Attrs.push_back(Attribute::SExt);
10436   if (CLI.RetZExt)
10437     Attrs.push_back(Attribute::ZExt);
10438   if (CLI.IsInReg)
10439     Attrs.push_back(Attribute::InReg);
10440 
10441   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
10442                             Attrs);
10443 }
10444 
10445 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
10446 /// implementation, which just calls LowerCall.
10447 /// FIXME: When all targets are
10448 /// migrated to using LowerCall, this hook should be integrated into SDISel.
10449 std::pair<SDValue, SDValue>
10450 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
10451   // Handle the incoming return values from the call.
10452   CLI.Ins.clear();
10453   Type *OrigRetTy = CLI.RetTy;
10454   SmallVector<EVT, 4> RetTys;
10455   SmallVector<uint64_t, 4> Offsets;
10456   auto &DL = CLI.DAG.getDataLayout();
10457   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets, 0);
10458 
10459   if (CLI.IsPostTypeLegalization) {
10460     // If we are lowering a libcall after legalization, split the return type.
10461     SmallVector<EVT, 4> OldRetTys;
10462     SmallVector<uint64_t, 4> OldOffsets;
10463     RetTys.swap(OldRetTys);
10464     Offsets.swap(OldOffsets);
10465 
10466     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
10467       EVT RetVT = OldRetTys[i];
10468       uint64_t Offset = OldOffsets[i];
10469       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
10470       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
10471       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
10472       RetTys.append(NumRegs, RegisterVT);
10473       for (unsigned j = 0; j != NumRegs; ++j)
10474         Offsets.push_back(Offset + j * RegisterVTByteSZ);
10475     }
10476   }
10477 
10478   SmallVector<ISD::OutputArg, 4> Outs;
10479   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
10480 
10481   bool CanLowerReturn =
10482       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
10483                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
10484 
10485   SDValue DemoteStackSlot;
10486   int DemoteStackIdx = -100;
10487   if (!CanLowerReturn) {
10488     // FIXME: equivalent assert?
10489     // assert(!CS.hasInAllocaArgument() &&
10490     //        "sret demotion is incompatible with inalloca");
10491     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
10492     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
10493     MachineFunction &MF = CLI.DAG.getMachineFunction();
10494     DemoteStackIdx =
10495         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
10496     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
10497                                               DL.getAllocaAddrSpace());
10498 
10499     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
10500     ArgListEntry Entry;
10501     Entry.Node = DemoteStackSlot;
10502     Entry.Ty = StackSlotPtrType;
10503     Entry.IsSExt = false;
10504     Entry.IsZExt = false;
10505     Entry.IsInReg = false;
10506     Entry.IsSRet = true;
10507     Entry.IsNest = false;
10508     Entry.IsByVal = false;
10509     Entry.IsByRef = false;
10510     Entry.IsReturned = false;
10511     Entry.IsSwiftSelf = false;
10512     Entry.IsSwiftAsync = false;
10513     Entry.IsSwiftError = false;
10514     Entry.IsCFGuardTarget = false;
10515     Entry.Alignment = Alignment;
10516     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
10517     CLI.NumFixedArgs += 1;
10518     CLI.getArgs()[0].IndirectType = CLI.RetTy;
10519     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
10520 
10521     // sret demotion isn't compatible with tail-calls, since the sret argument
10522     // points into the callers stack frame.
10523     CLI.IsTailCall = false;
10524   } else {
10525     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10526         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
10527     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
10528       ISD::ArgFlagsTy Flags;
10529       if (NeedsRegBlock) {
10530         Flags.setInConsecutiveRegs();
10531         if (I == RetTys.size() - 1)
10532           Flags.setInConsecutiveRegsLast();
10533       }
10534       EVT VT = RetTys[I];
10535       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10536                                                      CLI.CallConv, VT);
10537       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10538                                                        CLI.CallConv, VT);
10539       for (unsigned i = 0; i != NumRegs; ++i) {
10540         ISD::InputArg MyFlags;
10541         MyFlags.Flags = Flags;
10542         MyFlags.VT = RegisterVT;
10543         MyFlags.ArgVT = VT;
10544         MyFlags.Used = CLI.IsReturnValueUsed;
10545         if (CLI.RetTy->isPointerTy()) {
10546           MyFlags.Flags.setPointer();
10547           MyFlags.Flags.setPointerAddrSpace(
10548               cast<PointerType>(CLI.RetTy)->getAddressSpace());
10549         }
10550         if (CLI.RetSExt)
10551           MyFlags.Flags.setSExt();
10552         if (CLI.RetZExt)
10553           MyFlags.Flags.setZExt();
10554         if (CLI.IsInReg)
10555           MyFlags.Flags.setInReg();
10556         CLI.Ins.push_back(MyFlags);
10557       }
10558     }
10559   }
10560 
10561   // We push in swifterror return as the last element of CLI.Ins.
10562   ArgListTy &Args = CLI.getArgs();
10563   if (supportSwiftError()) {
10564     for (const ArgListEntry &Arg : Args) {
10565       if (Arg.IsSwiftError) {
10566         ISD::InputArg MyFlags;
10567         MyFlags.VT = getPointerTy(DL);
10568         MyFlags.ArgVT = EVT(getPointerTy(DL));
10569         MyFlags.Flags.setSwiftError();
10570         CLI.Ins.push_back(MyFlags);
10571       }
10572     }
10573   }
10574 
10575   // Handle all of the outgoing arguments.
10576   CLI.Outs.clear();
10577   CLI.OutVals.clear();
10578   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
10579     SmallVector<EVT, 4> ValueVTs;
10580     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
10581     // FIXME: Split arguments if CLI.IsPostTypeLegalization
10582     Type *FinalType = Args[i].Ty;
10583     if (Args[i].IsByVal)
10584       FinalType = Args[i].IndirectType;
10585     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10586         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
10587     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
10588          ++Value) {
10589       EVT VT = ValueVTs[Value];
10590       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
10591       SDValue Op = SDValue(Args[i].Node.getNode(),
10592                            Args[i].Node.getResNo() + Value);
10593       ISD::ArgFlagsTy Flags;
10594 
10595       // Certain targets (such as MIPS), may have a different ABI alignment
10596       // for a type depending on the context. Give the target a chance to
10597       // specify the alignment it wants.
10598       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
10599       Flags.setOrigAlign(OriginalAlignment);
10600 
10601       if (Args[i].Ty->isPointerTy()) {
10602         Flags.setPointer();
10603         Flags.setPointerAddrSpace(
10604             cast<PointerType>(Args[i].Ty)->getAddressSpace());
10605       }
10606       if (Args[i].IsZExt)
10607         Flags.setZExt();
10608       if (Args[i].IsSExt)
10609         Flags.setSExt();
10610       if (Args[i].IsInReg) {
10611         // If we are using vectorcall calling convention, a structure that is
10612         // passed InReg - is surely an HVA
10613         if (CLI.CallConv == CallingConv::X86_VectorCall &&
10614             isa<StructType>(FinalType)) {
10615           // The first value of a structure is marked
10616           if (0 == Value)
10617             Flags.setHvaStart();
10618           Flags.setHva();
10619         }
10620         // Set InReg Flag
10621         Flags.setInReg();
10622       }
10623       if (Args[i].IsSRet)
10624         Flags.setSRet();
10625       if (Args[i].IsSwiftSelf)
10626         Flags.setSwiftSelf();
10627       if (Args[i].IsSwiftAsync)
10628         Flags.setSwiftAsync();
10629       if (Args[i].IsSwiftError)
10630         Flags.setSwiftError();
10631       if (Args[i].IsCFGuardTarget)
10632         Flags.setCFGuardTarget();
10633       if (Args[i].IsByVal)
10634         Flags.setByVal();
10635       if (Args[i].IsByRef)
10636         Flags.setByRef();
10637       if (Args[i].IsPreallocated) {
10638         Flags.setPreallocated();
10639         // Set the byval flag for CCAssignFn callbacks that don't know about
10640         // preallocated.  This way we can know how many bytes we should've
10641         // allocated and how many bytes a callee cleanup function will pop.  If
10642         // we port preallocated to more targets, we'll have to add custom
10643         // preallocated handling in the various CC lowering callbacks.
10644         Flags.setByVal();
10645       }
10646       if (Args[i].IsInAlloca) {
10647         Flags.setInAlloca();
10648         // Set the byval flag for CCAssignFn callbacks that don't know about
10649         // inalloca.  This way we can know how many bytes we should've allocated
10650         // and how many bytes a callee cleanup function will pop.  If we port
10651         // inalloca to more targets, we'll have to add custom inalloca handling
10652         // in the various CC lowering callbacks.
10653         Flags.setByVal();
10654       }
10655       Align MemAlign;
10656       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
10657         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
10658         Flags.setByValSize(FrameSize);
10659 
10660         // info is not there but there are cases it cannot get right.
10661         if (auto MA = Args[i].Alignment)
10662           MemAlign = *MA;
10663         else
10664           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
10665       } else if (auto MA = Args[i].Alignment) {
10666         MemAlign = *MA;
10667       } else {
10668         MemAlign = OriginalAlignment;
10669       }
10670       Flags.setMemAlign(MemAlign);
10671       if (Args[i].IsNest)
10672         Flags.setNest();
10673       if (NeedsRegBlock)
10674         Flags.setInConsecutiveRegs();
10675 
10676       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10677                                                  CLI.CallConv, VT);
10678       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10679                                                         CLI.CallConv, VT);
10680       SmallVector<SDValue, 4> Parts(NumParts);
10681       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
10682 
10683       if (Args[i].IsSExt)
10684         ExtendKind = ISD::SIGN_EXTEND;
10685       else if (Args[i].IsZExt)
10686         ExtendKind = ISD::ZERO_EXTEND;
10687 
10688       // Conservatively only handle 'returned' on non-vectors that can be lowered,
10689       // for now.
10690       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
10691           CanLowerReturn) {
10692         assert((CLI.RetTy == Args[i].Ty ||
10693                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
10694                  CLI.RetTy->getPointerAddressSpace() ==
10695                      Args[i].Ty->getPointerAddressSpace())) &&
10696                RetTys.size() == NumValues && "unexpected use of 'returned'");
10697         // Before passing 'returned' to the target lowering code, ensure that
10698         // either the register MVT and the actual EVT are the same size or that
10699         // the return value and argument are extended in the same way; in these
10700         // cases it's safe to pass the argument register value unchanged as the
10701         // return register value (although it's at the target's option whether
10702         // to do so)
10703         // TODO: allow code generation to take advantage of partially preserved
10704         // registers rather than clobbering the entire register when the
10705         // parameter extension method is not compatible with the return
10706         // extension method
10707         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
10708             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
10709              CLI.RetZExt == Args[i].IsZExt))
10710           Flags.setReturned();
10711       }
10712 
10713       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
10714                      CLI.CallConv, ExtendKind);
10715 
10716       for (unsigned j = 0; j != NumParts; ++j) {
10717         // if it isn't first piece, alignment must be 1
10718         // For scalable vectors the scalable part is currently handled
10719         // by individual targets, so we just use the known minimum size here.
10720         ISD::OutputArg MyFlags(
10721             Flags, Parts[j].getValueType().getSimpleVT(), VT,
10722             i < CLI.NumFixedArgs, i,
10723             j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
10724         if (NumParts > 1 && j == 0)
10725           MyFlags.Flags.setSplit();
10726         else if (j != 0) {
10727           MyFlags.Flags.setOrigAlign(Align(1));
10728           if (j == NumParts - 1)
10729             MyFlags.Flags.setSplitEnd();
10730         }
10731 
10732         CLI.Outs.push_back(MyFlags);
10733         CLI.OutVals.push_back(Parts[j]);
10734       }
10735 
10736       if (NeedsRegBlock && Value == NumValues - 1)
10737         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
10738     }
10739   }
10740 
10741   SmallVector<SDValue, 4> InVals;
10742   CLI.Chain = LowerCall(CLI, InVals);
10743 
10744   // Update CLI.InVals to use outside of this function.
10745   CLI.InVals = InVals;
10746 
10747   // Verify that the target's LowerCall behaved as expected.
10748   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
10749          "LowerCall didn't return a valid chain!");
10750   assert((!CLI.IsTailCall || InVals.empty()) &&
10751          "LowerCall emitted a return value for a tail call!");
10752   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
10753          "LowerCall didn't emit the correct number of values!");
10754 
10755   // For a tail call, the return value is merely live-out and there aren't
10756   // any nodes in the DAG representing it. Return a special value to
10757   // indicate that a tail call has been emitted and no more Instructions
10758   // should be processed in the current block.
10759   if (CLI.IsTailCall) {
10760     CLI.DAG.setRoot(CLI.Chain);
10761     return std::make_pair(SDValue(), SDValue());
10762   }
10763 
10764 #ifndef NDEBUG
10765   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
10766     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
10767     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
10768            "LowerCall emitted a value with the wrong type!");
10769   }
10770 #endif
10771 
10772   SmallVector<SDValue, 4> ReturnValues;
10773   if (!CanLowerReturn) {
10774     // The instruction result is the result of loading from the
10775     // hidden sret parameter.
10776     SmallVector<EVT, 1> PVTs;
10777     Type *PtrRetTy =
10778         PointerType::get(OrigRetTy->getContext(), DL.getAllocaAddrSpace());
10779 
10780     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
10781     assert(PVTs.size() == 1 && "Pointers should fit in one register");
10782     EVT PtrVT = PVTs[0];
10783 
10784     unsigned NumValues = RetTys.size();
10785     ReturnValues.resize(NumValues);
10786     SmallVector<SDValue, 4> Chains(NumValues);
10787 
10788     // An aggregate return value cannot wrap around the address space, so
10789     // offsets to its parts don't wrap either.
10790     SDNodeFlags Flags;
10791     Flags.setNoUnsignedWrap(true);
10792 
10793     MachineFunction &MF = CLI.DAG.getMachineFunction();
10794     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
10795     for (unsigned i = 0; i < NumValues; ++i) {
10796       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
10797                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
10798                                                         PtrVT), Flags);
10799       SDValue L = CLI.DAG.getLoad(
10800           RetTys[i], CLI.DL, CLI.Chain, Add,
10801           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
10802                                             DemoteStackIdx, Offsets[i]),
10803           HiddenSRetAlign);
10804       ReturnValues[i] = L;
10805       Chains[i] = L.getValue(1);
10806     }
10807 
10808     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
10809   } else {
10810     // Collect the legal value parts into potentially illegal values
10811     // that correspond to the original function's return values.
10812     std::optional<ISD::NodeType> AssertOp;
10813     if (CLI.RetSExt)
10814       AssertOp = ISD::AssertSext;
10815     else if (CLI.RetZExt)
10816       AssertOp = ISD::AssertZext;
10817     unsigned CurReg = 0;
10818     for (EVT VT : RetTys) {
10819       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10820                                                      CLI.CallConv, VT);
10821       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10822                                                        CLI.CallConv, VT);
10823 
10824       ReturnValues.push_back(getCopyFromParts(
10825           CLI.DAG, CLI.DL, &InVals[CurReg], NumRegs, RegisterVT, VT, nullptr,
10826           CLI.Chain, CLI.CallConv, AssertOp));
10827       CurReg += NumRegs;
10828     }
10829 
10830     // For a function returning void, there is no return value. We can't create
10831     // such a node, so we just return a null return value in that case. In
10832     // that case, nothing will actually look at the value.
10833     if (ReturnValues.empty())
10834       return std::make_pair(SDValue(), CLI.Chain);
10835   }
10836 
10837   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
10838                                 CLI.DAG.getVTList(RetTys), ReturnValues);
10839   return std::make_pair(Res, CLI.Chain);
10840 }
10841 
10842 /// Places new result values for the node in Results (their number
10843 /// and types must exactly match those of the original return values of
10844 /// the node), or leaves Results empty, which indicates that the node is not
10845 /// to be custom lowered after all.
10846 void TargetLowering::LowerOperationWrapper(SDNode *N,
10847                                            SmallVectorImpl<SDValue> &Results,
10848                                            SelectionDAG &DAG) const {
10849   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
10850 
10851   if (!Res.getNode())
10852     return;
10853 
10854   // If the original node has one result, take the return value from
10855   // LowerOperation as is. It might not be result number 0.
10856   if (N->getNumValues() == 1) {
10857     Results.push_back(Res);
10858     return;
10859   }
10860 
10861   // If the original node has multiple results, then the return node should
10862   // have the same number of results.
10863   assert((N->getNumValues() == Res->getNumValues()) &&
10864       "Lowering returned the wrong number of results!");
10865 
10866   // Places new result values base on N result number.
10867   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
10868     Results.push_back(Res.getValue(I));
10869 }
10870 
10871 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10872   llvm_unreachable("LowerOperation not implemented for this target!");
10873 }
10874 
10875 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
10876                                                      unsigned Reg,
10877                                                      ISD::NodeType ExtendType) {
10878   SDValue Op = getNonRegisterValue(V);
10879   assert((Op.getOpcode() != ISD::CopyFromReg ||
10880           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
10881          "Copy from a reg to the same reg!");
10882   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
10883 
10884   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10885   // If this is an InlineAsm we have to match the registers required, not the
10886   // notional registers required by the type.
10887 
10888   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
10889                    std::nullopt); // This is not an ABI copy.
10890   SDValue Chain = DAG.getEntryNode();
10891 
10892   if (ExtendType == ISD::ANY_EXTEND) {
10893     auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
10894     if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
10895       ExtendType = PreferredExtendIt->second;
10896   }
10897   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
10898   PendingExports.push_back(Chain);
10899 }
10900 
10901 #include "llvm/CodeGen/SelectionDAGISel.h"
10902 
10903 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
10904 /// entry block, return true.  This includes arguments used by switches, since
10905 /// the switch may expand into multiple basic blocks.
10906 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
10907   // With FastISel active, we may be splitting blocks, so force creation
10908   // of virtual registers for all non-dead arguments.
10909   if (FastISel)
10910     return A->use_empty();
10911 
10912   const BasicBlock &Entry = A->getParent()->front();
10913   for (const User *U : A->users())
10914     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
10915       return false;  // Use not in entry block.
10916 
10917   return true;
10918 }
10919 
10920 using ArgCopyElisionMapTy =
10921     DenseMap<const Argument *,
10922              std::pair<const AllocaInst *, const StoreInst *>>;
10923 
10924 /// Scan the entry block of the function in FuncInfo for arguments that look
10925 /// like copies into a local alloca. Record any copied arguments in
10926 /// ArgCopyElisionCandidates.
10927 static void
10928 findArgumentCopyElisionCandidates(const DataLayout &DL,
10929                                   FunctionLoweringInfo *FuncInfo,
10930                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
10931   // Record the state of every static alloca used in the entry block. Argument
10932   // allocas are all used in the entry block, so we need approximately as many
10933   // entries as we have arguments.
10934   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
10935   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
10936   unsigned NumArgs = FuncInfo->Fn->arg_size();
10937   StaticAllocas.reserve(NumArgs * 2);
10938 
10939   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
10940     if (!V)
10941       return nullptr;
10942     V = V->stripPointerCasts();
10943     const auto *AI = dyn_cast<AllocaInst>(V);
10944     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
10945       return nullptr;
10946     auto Iter = StaticAllocas.insert({AI, Unknown});
10947     return &Iter.first->second;
10948   };
10949 
10950   // Look for stores of arguments to static allocas. Look through bitcasts and
10951   // GEPs to handle type coercions, as long as the alloca is fully initialized
10952   // by the store. Any non-store use of an alloca escapes it and any subsequent
10953   // unanalyzed store might write it.
10954   // FIXME: Handle structs initialized with multiple stores.
10955   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
10956     // Look for stores, and handle non-store uses conservatively.
10957     const auto *SI = dyn_cast<StoreInst>(&I);
10958     if (!SI) {
10959       // We will look through cast uses, so ignore them completely.
10960       if (I.isCast())
10961         continue;
10962       // Ignore debug info and pseudo op intrinsics, they don't escape or store
10963       // to allocas.
10964       if (I.isDebugOrPseudoInst())
10965         continue;
10966       // This is an unknown instruction. Assume it escapes or writes to all
10967       // static alloca operands.
10968       for (const Use &U : I.operands()) {
10969         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
10970           *Info = StaticAllocaInfo::Clobbered;
10971       }
10972       continue;
10973     }
10974 
10975     // If the stored value is a static alloca, mark it as escaped.
10976     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
10977       *Info = StaticAllocaInfo::Clobbered;
10978 
10979     // Check if the destination is a static alloca.
10980     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
10981     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
10982     if (!Info)
10983       continue;
10984     const AllocaInst *AI = cast<AllocaInst>(Dst);
10985 
10986     // Skip allocas that have been initialized or clobbered.
10987     if (*Info != StaticAllocaInfo::Unknown)
10988       continue;
10989 
10990     // Check if the stored value is an argument, and that this store fully
10991     // initializes the alloca.
10992     // If the argument type has padding bits we can't directly forward a pointer
10993     // as the upper bits may contain garbage.
10994     // Don't elide copies from the same argument twice.
10995     const Value *Val = SI->getValueOperand()->stripPointerCasts();
10996     const auto *Arg = dyn_cast<Argument>(Val);
10997     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
10998         Arg->getType()->isEmptyTy() ||
10999         DL.getTypeStoreSize(Arg->getType()) !=
11000             DL.getTypeAllocSize(AI->getAllocatedType()) ||
11001         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
11002         ArgCopyElisionCandidates.count(Arg)) {
11003       *Info = StaticAllocaInfo::Clobbered;
11004       continue;
11005     }
11006 
11007     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
11008                       << '\n');
11009 
11010     // Mark this alloca and store for argument copy elision.
11011     *Info = StaticAllocaInfo::Elidable;
11012     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
11013 
11014     // Stop scanning if we've seen all arguments. This will happen early in -O0
11015     // builds, which is useful, because -O0 builds have large entry blocks and
11016     // many allocas.
11017     if (ArgCopyElisionCandidates.size() == NumArgs)
11018       break;
11019   }
11020 }
11021 
11022 /// Try to elide argument copies from memory into a local alloca. Succeeds if
11023 /// ArgVal is a load from a suitable fixed stack object.
11024 static void tryToElideArgumentCopy(
11025     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
11026     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
11027     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
11028     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
11029     ArrayRef<SDValue> ArgVals, bool &ArgHasUses) {
11030   // Check if this is a load from a fixed stack object.
11031   auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]);
11032   if (!LNode)
11033     return;
11034   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
11035   if (!FINode)
11036     return;
11037 
11038   // Check that the fixed stack object is the right size and alignment.
11039   // Look at the alignment that the user wrote on the alloca instead of looking
11040   // at the stack object.
11041   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
11042   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
11043   const AllocaInst *AI = ArgCopyIter->second.first;
11044   int FixedIndex = FINode->getIndex();
11045   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
11046   int OldIndex = AllocaIndex;
11047   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
11048   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
11049     LLVM_DEBUG(
11050         dbgs() << "  argument copy elision failed due to bad fixed stack "
11051                   "object size\n");
11052     return;
11053   }
11054   Align RequiredAlignment = AI->getAlign();
11055   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
11056     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
11057                          "greater than stack argument alignment ("
11058                       << DebugStr(RequiredAlignment) << " vs "
11059                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
11060     return;
11061   }
11062 
11063   // Perform the elision. Delete the old stack object and replace its only use
11064   // in the variable info map. Mark the stack object as mutable.
11065   LLVM_DEBUG({
11066     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
11067            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
11068            << '\n';
11069   });
11070   MFI.RemoveStackObject(OldIndex);
11071   MFI.setIsImmutableObjectIndex(FixedIndex, false);
11072   AllocaIndex = FixedIndex;
11073   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
11074   for (SDValue ArgVal : ArgVals)
11075     Chains.push_back(ArgVal.getValue(1));
11076 
11077   // Avoid emitting code for the store implementing the copy.
11078   const StoreInst *SI = ArgCopyIter->second.second;
11079   ElidedArgCopyInstrs.insert(SI);
11080 
11081   // Check for uses of the argument again so that we can avoid exporting ArgVal
11082   // if it is't used by anything other than the store.
11083   for (const Value *U : Arg.users()) {
11084     if (U != SI) {
11085       ArgHasUses = true;
11086       break;
11087     }
11088   }
11089 }
11090 
11091 void SelectionDAGISel::LowerArguments(const Function &F) {
11092   SelectionDAG &DAG = SDB->DAG;
11093   SDLoc dl = SDB->getCurSDLoc();
11094   const DataLayout &DL = DAG.getDataLayout();
11095   SmallVector<ISD::InputArg, 16> Ins;
11096 
11097   // In Naked functions we aren't going to save any registers.
11098   if (F.hasFnAttribute(Attribute::Naked))
11099     return;
11100 
11101   if (!FuncInfo->CanLowerReturn) {
11102     // Put in an sret pointer parameter before all the other parameters.
11103     SmallVector<EVT, 1> ValueVTs;
11104     ComputeValueVTs(*TLI, DAG.getDataLayout(),
11105                     PointerType::get(F.getContext(),
11106                                      DAG.getDataLayout().getAllocaAddrSpace()),
11107                     ValueVTs);
11108 
11109     // NOTE: Assuming that a pointer will never break down to more than one VT
11110     // or one register.
11111     ISD::ArgFlagsTy Flags;
11112     Flags.setSRet();
11113     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
11114     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
11115                          ISD::InputArg::NoArgIndex, 0);
11116     Ins.push_back(RetArg);
11117   }
11118 
11119   // Look for stores of arguments to static allocas. Mark such arguments with a
11120   // flag to ask the target to give us the memory location of that argument if
11121   // available.
11122   ArgCopyElisionMapTy ArgCopyElisionCandidates;
11123   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
11124                                     ArgCopyElisionCandidates);
11125 
11126   // Set up the incoming argument description vector.
11127   for (const Argument &Arg : F.args()) {
11128     unsigned ArgNo = Arg.getArgNo();
11129     SmallVector<EVT, 4> ValueVTs;
11130     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
11131     bool isArgValueUsed = !Arg.use_empty();
11132     unsigned PartBase = 0;
11133     Type *FinalType = Arg.getType();
11134     if (Arg.hasAttribute(Attribute::ByVal))
11135       FinalType = Arg.getParamByValType();
11136     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
11137         FinalType, F.getCallingConv(), F.isVarArg(), DL);
11138     for (unsigned Value = 0, NumValues = ValueVTs.size();
11139          Value != NumValues; ++Value) {
11140       EVT VT = ValueVTs[Value];
11141       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
11142       ISD::ArgFlagsTy Flags;
11143 
11144 
11145       if (Arg.getType()->isPointerTy()) {
11146         Flags.setPointer();
11147         Flags.setPointerAddrSpace(
11148             cast<PointerType>(Arg.getType())->getAddressSpace());
11149       }
11150       if (Arg.hasAttribute(Attribute::ZExt))
11151         Flags.setZExt();
11152       if (Arg.hasAttribute(Attribute::SExt))
11153         Flags.setSExt();
11154       if (Arg.hasAttribute(Attribute::InReg)) {
11155         // If we are using vectorcall calling convention, a structure that is
11156         // passed InReg - is surely an HVA
11157         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
11158             isa<StructType>(Arg.getType())) {
11159           // The first value of a structure is marked
11160           if (0 == Value)
11161             Flags.setHvaStart();
11162           Flags.setHva();
11163         }
11164         // Set InReg Flag
11165         Flags.setInReg();
11166       }
11167       if (Arg.hasAttribute(Attribute::StructRet))
11168         Flags.setSRet();
11169       if (Arg.hasAttribute(Attribute::SwiftSelf))
11170         Flags.setSwiftSelf();
11171       if (Arg.hasAttribute(Attribute::SwiftAsync))
11172         Flags.setSwiftAsync();
11173       if (Arg.hasAttribute(Attribute::SwiftError))
11174         Flags.setSwiftError();
11175       if (Arg.hasAttribute(Attribute::ByVal))
11176         Flags.setByVal();
11177       if (Arg.hasAttribute(Attribute::ByRef))
11178         Flags.setByRef();
11179       if (Arg.hasAttribute(Attribute::InAlloca)) {
11180         Flags.setInAlloca();
11181         // Set the byval flag for CCAssignFn callbacks that don't know about
11182         // inalloca.  This way we can know how many bytes we should've allocated
11183         // and how many bytes a callee cleanup function will pop.  If we port
11184         // inalloca to more targets, we'll have to add custom inalloca handling
11185         // in the various CC lowering callbacks.
11186         Flags.setByVal();
11187       }
11188       if (Arg.hasAttribute(Attribute::Preallocated)) {
11189         Flags.setPreallocated();
11190         // Set the byval flag for CCAssignFn callbacks that don't know about
11191         // preallocated.  This way we can know how many bytes we should've
11192         // allocated and how many bytes a callee cleanup function will pop.  If
11193         // we port preallocated to more targets, we'll have to add custom
11194         // preallocated handling in the various CC lowering callbacks.
11195         Flags.setByVal();
11196       }
11197 
11198       // Certain targets (such as MIPS), may have a different ABI alignment
11199       // for a type depending on the context. Give the target a chance to
11200       // specify the alignment it wants.
11201       const Align OriginalAlignment(
11202           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
11203       Flags.setOrigAlign(OriginalAlignment);
11204 
11205       Align MemAlign;
11206       Type *ArgMemTy = nullptr;
11207       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
11208           Flags.isByRef()) {
11209         if (!ArgMemTy)
11210           ArgMemTy = Arg.getPointeeInMemoryValueType();
11211 
11212         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
11213 
11214         // For in-memory arguments, size and alignment should be passed from FE.
11215         // BE will guess if this info is not there but there are cases it cannot
11216         // get right.
11217         if (auto ParamAlign = Arg.getParamStackAlign())
11218           MemAlign = *ParamAlign;
11219         else if ((ParamAlign = Arg.getParamAlign()))
11220           MemAlign = *ParamAlign;
11221         else
11222           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
11223         if (Flags.isByRef())
11224           Flags.setByRefSize(MemSize);
11225         else
11226           Flags.setByValSize(MemSize);
11227       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
11228         MemAlign = *ParamAlign;
11229       } else {
11230         MemAlign = OriginalAlignment;
11231       }
11232       Flags.setMemAlign(MemAlign);
11233 
11234       if (Arg.hasAttribute(Attribute::Nest))
11235         Flags.setNest();
11236       if (NeedsRegBlock)
11237         Flags.setInConsecutiveRegs();
11238       if (ArgCopyElisionCandidates.count(&Arg))
11239         Flags.setCopyElisionCandidate();
11240       if (Arg.hasAttribute(Attribute::Returned))
11241         Flags.setReturned();
11242 
11243       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
11244           *CurDAG->getContext(), F.getCallingConv(), VT);
11245       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
11246           *CurDAG->getContext(), F.getCallingConv(), VT);
11247       for (unsigned i = 0; i != NumRegs; ++i) {
11248         // For scalable vectors, use the minimum size; individual targets
11249         // are responsible for handling scalable vector arguments and
11250         // return values.
11251         ISD::InputArg MyFlags(
11252             Flags, RegisterVT, VT, isArgValueUsed, ArgNo,
11253             PartBase + i * RegisterVT.getStoreSize().getKnownMinValue());
11254         if (NumRegs > 1 && i == 0)
11255           MyFlags.Flags.setSplit();
11256         // if it isn't first piece, alignment must be 1
11257         else if (i > 0) {
11258           MyFlags.Flags.setOrigAlign(Align(1));
11259           if (i == NumRegs - 1)
11260             MyFlags.Flags.setSplitEnd();
11261         }
11262         Ins.push_back(MyFlags);
11263       }
11264       if (NeedsRegBlock && Value == NumValues - 1)
11265         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
11266       PartBase += VT.getStoreSize().getKnownMinValue();
11267     }
11268   }
11269 
11270   // Call the target to set up the argument values.
11271   SmallVector<SDValue, 8> InVals;
11272   SDValue NewRoot = TLI->LowerFormalArguments(
11273       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
11274 
11275   // Verify that the target's LowerFormalArguments behaved as expected.
11276   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
11277          "LowerFormalArguments didn't return a valid chain!");
11278   assert(InVals.size() == Ins.size() &&
11279          "LowerFormalArguments didn't emit the correct number of values!");
11280   LLVM_DEBUG({
11281     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
11282       assert(InVals[i].getNode() &&
11283              "LowerFormalArguments emitted a null value!");
11284       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
11285              "LowerFormalArguments emitted a value with the wrong type!");
11286     }
11287   });
11288 
11289   // Update the DAG with the new chain value resulting from argument lowering.
11290   DAG.setRoot(NewRoot);
11291 
11292   // Set up the argument values.
11293   unsigned i = 0;
11294   if (!FuncInfo->CanLowerReturn) {
11295     // Create a virtual register for the sret pointer, and put in a copy
11296     // from the sret argument into it.
11297     SmallVector<EVT, 1> ValueVTs;
11298     ComputeValueVTs(*TLI, DAG.getDataLayout(),
11299                     PointerType::get(F.getContext(),
11300                                      DAG.getDataLayout().getAllocaAddrSpace()),
11301                     ValueVTs);
11302     MVT VT = ValueVTs[0].getSimpleVT();
11303     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
11304     std::optional<ISD::NodeType> AssertOp;
11305     SDValue ArgValue =
11306         getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, nullptr, NewRoot,
11307                          F.getCallingConv(), AssertOp);
11308 
11309     MachineFunction& MF = SDB->DAG.getMachineFunction();
11310     MachineRegisterInfo& RegInfo = MF.getRegInfo();
11311     Register SRetReg =
11312         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
11313     FuncInfo->DemoteRegister = SRetReg;
11314     NewRoot =
11315         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
11316     DAG.setRoot(NewRoot);
11317 
11318     // i indexes lowered arguments.  Bump it past the hidden sret argument.
11319     ++i;
11320   }
11321 
11322   SmallVector<SDValue, 4> Chains;
11323   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
11324   for (const Argument &Arg : F.args()) {
11325     SmallVector<SDValue, 4> ArgValues;
11326     SmallVector<EVT, 4> ValueVTs;
11327     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
11328     unsigned NumValues = ValueVTs.size();
11329     if (NumValues == 0)
11330       continue;
11331 
11332     bool ArgHasUses = !Arg.use_empty();
11333 
11334     // Elide the copying store if the target loaded this argument from a
11335     // suitable fixed stack object.
11336     if (Ins[i].Flags.isCopyElisionCandidate()) {
11337       unsigned NumParts = 0;
11338       for (EVT VT : ValueVTs)
11339         NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(),
11340                                                        F.getCallingConv(), VT);
11341 
11342       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
11343                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
11344                              ArrayRef(&InVals[i], NumParts), ArgHasUses);
11345     }
11346 
11347     // If this argument is unused then remember its value. It is used to generate
11348     // debugging information.
11349     bool isSwiftErrorArg =
11350         TLI->supportSwiftError() &&
11351         Arg.hasAttribute(Attribute::SwiftError);
11352     if (!ArgHasUses && !isSwiftErrorArg) {
11353       SDB->setUnusedArgValue(&Arg, InVals[i]);
11354 
11355       // Also remember any frame index for use in FastISel.
11356       if (FrameIndexSDNode *FI =
11357           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
11358         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11359     }
11360 
11361     for (unsigned Val = 0; Val != NumValues; ++Val) {
11362       EVT VT = ValueVTs[Val];
11363       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
11364                                                       F.getCallingConv(), VT);
11365       unsigned NumParts = TLI->getNumRegistersForCallingConv(
11366           *CurDAG->getContext(), F.getCallingConv(), VT);
11367 
11368       // Even an apparent 'unused' swifterror argument needs to be returned. So
11369       // we do generate a copy for it that can be used on return from the
11370       // function.
11371       if (ArgHasUses || isSwiftErrorArg) {
11372         std::optional<ISD::NodeType> AssertOp;
11373         if (Arg.hasAttribute(Attribute::SExt))
11374           AssertOp = ISD::AssertSext;
11375         else if (Arg.hasAttribute(Attribute::ZExt))
11376           AssertOp = ISD::AssertZext;
11377 
11378         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
11379                                              PartVT, VT, nullptr, NewRoot,
11380                                              F.getCallingConv(), AssertOp));
11381       }
11382 
11383       i += NumParts;
11384     }
11385 
11386     // We don't need to do anything else for unused arguments.
11387     if (ArgValues.empty())
11388       continue;
11389 
11390     // Note down frame index.
11391     if (FrameIndexSDNode *FI =
11392         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
11393       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11394 
11395     SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues),
11396                                      SDB->getCurSDLoc());
11397 
11398     SDB->setValue(&Arg, Res);
11399     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
11400       // We want to associate the argument with the frame index, among
11401       // involved operands, that correspond to the lowest address. The
11402       // getCopyFromParts function, called earlier, is swapping the order of
11403       // the operands to BUILD_PAIR depending on endianness. The result of
11404       // that swapping is that the least significant bits of the argument will
11405       // be in the first operand of the BUILD_PAIR node, and the most
11406       // significant bits will be in the second operand.
11407       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
11408       if (LoadSDNode *LNode =
11409           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
11410         if (FrameIndexSDNode *FI =
11411             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
11412           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11413     }
11414 
11415     // Analyses past this point are naive and don't expect an assertion.
11416     if (Res.getOpcode() == ISD::AssertZext)
11417       Res = Res.getOperand(0);
11418 
11419     // Update the SwiftErrorVRegDefMap.
11420     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
11421       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11422       if (Register::isVirtualRegister(Reg))
11423         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
11424                                    Reg);
11425     }
11426 
11427     // If this argument is live outside of the entry block, insert a copy from
11428     // wherever we got it to the vreg that other BB's will reference it as.
11429     if (Res.getOpcode() == ISD::CopyFromReg) {
11430       // If we can, though, try to skip creating an unnecessary vreg.
11431       // FIXME: This isn't very clean... it would be nice to make this more
11432       // general.
11433       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11434       if (Register::isVirtualRegister(Reg)) {
11435         FuncInfo->ValueMap[&Arg] = Reg;
11436         continue;
11437       }
11438     }
11439     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
11440       FuncInfo->InitializeRegForValue(&Arg);
11441       SDB->CopyToExportRegsIfNeeded(&Arg);
11442     }
11443   }
11444 
11445   if (!Chains.empty()) {
11446     Chains.push_back(NewRoot);
11447     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
11448   }
11449 
11450   DAG.setRoot(NewRoot);
11451 
11452   assert(i == InVals.size() && "Argument register count mismatch!");
11453 
11454   // If any argument copy elisions occurred and we have debug info, update the
11455   // stale frame indices used in the dbg.declare variable info table.
11456   if (!ArgCopyElisionFrameIndexMap.empty()) {
11457     for (MachineFunction::VariableDbgInfo &VI :
11458          MF->getInStackSlotVariableDbgInfo()) {
11459       auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot());
11460       if (I != ArgCopyElisionFrameIndexMap.end())
11461         VI.updateStackSlot(I->second);
11462     }
11463   }
11464 
11465   // Finally, if the target has anything special to do, allow it to do so.
11466   emitFunctionEntryCode();
11467 }
11468 
11469 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
11470 /// ensure constants are generated when needed.  Remember the virtual registers
11471 /// that need to be added to the Machine PHI nodes as input.  We cannot just
11472 /// directly add them, because expansion might result in multiple MBB's for one
11473 /// BB.  As such, the start of the BB might correspond to a different MBB than
11474 /// the end.
11475 void
11476 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
11477   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11478 
11479   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
11480 
11481   // Check PHI nodes in successors that expect a value to be available from this
11482   // block.
11483   for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
11484     if (!isa<PHINode>(SuccBB->begin())) continue;
11485     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
11486 
11487     // If this terminator has multiple identical successors (common for
11488     // switches), only handle each succ once.
11489     if (!SuccsHandled.insert(SuccMBB).second)
11490       continue;
11491 
11492     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
11493 
11494     // At this point we know that there is a 1-1 correspondence between LLVM PHI
11495     // nodes and Machine PHI nodes, but the incoming operands have not been
11496     // emitted yet.
11497     for (const PHINode &PN : SuccBB->phis()) {
11498       // Ignore dead phi's.
11499       if (PN.use_empty())
11500         continue;
11501 
11502       // Skip empty types
11503       if (PN.getType()->isEmptyTy())
11504         continue;
11505 
11506       unsigned Reg;
11507       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
11508 
11509       if (const auto *C = dyn_cast<Constant>(PHIOp)) {
11510         unsigned &RegOut = ConstantsOut[C];
11511         if (RegOut == 0) {
11512           RegOut = FuncInfo.CreateRegs(C);
11513           // We need to zero/sign extend ConstantInt phi operands to match
11514           // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
11515           ISD::NodeType ExtendType = ISD::ANY_EXTEND;
11516           if (auto *CI = dyn_cast<ConstantInt>(C))
11517             ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
11518                                                     : ISD::ZERO_EXTEND;
11519           CopyValueToVirtualRegister(C, RegOut, ExtendType);
11520         }
11521         Reg = RegOut;
11522       } else {
11523         DenseMap<const Value *, Register>::iterator I =
11524           FuncInfo.ValueMap.find(PHIOp);
11525         if (I != FuncInfo.ValueMap.end())
11526           Reg = I->second;
11527         else {
11528           assert(isa<AllocaInst>(PHIOp) &&
11529                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
11530                  "Didn't codegen value into a register!??");
11531           Reg = FuncInfo.CreateRegs(PHIOp);
11532           CopyValueToVirtualRegister(PHIOp, Reg);
11533         }
11534       }
11535 
11536       // Remember that this register needs to added to the machine PHI node as
11537       // the input for this MBB.
11538       SmallVector<EVT, 4> ValueVTs;
11539       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
11540       for (EVT VT : ValueVTs) {
11541         const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
11542         for (unsigned i = 0; i != NumRegisters; ++i)
11543           FuncInfo.PHINodesToUpdate.push_back(
11544               std::make_pair(&*MBBI++, Reg + i));
11545         Reg += NumRegisters;
11546       }
11547     }
11548   }
11549 
11550   ConstantsOut.clear();
11551 }
11552 
11553 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
11554   MachineFunction::iterator I(MBB);
11555   if (++I == FuncInfo.MF->end())
11556     return nullptr;
11557   return &*I;
11558 }
11559 
11560 /// During lowering new call nodes can be created (such as memset, etc.).
11561 /// Those will become new roots of the current DAG, but complications arise
11562 /// when they are tail calls. In such cases, the call lowering will update
11563 /// the root, but the builder still needs to know that a tail call has been
11564 /// lowered in order to avoid generating an additional return.
11565 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
11566   // If the node is null, we do have a tail call.
11567   if (MaybeTC.getNode() != nullptr)
11568     DAG.setRoot(MaybeTC);
11569   else
11570     HasTailCall = true;
11571 }
11572 
11573 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
11574                                         MachineBasicBlock *SwitchMBB,
11575                                         MachineBasicBlock *DefaultMBB) {
11576   MachineFunction *CurMF = FuncInfo.MF;
11577   MachineBasicBlock *NextMBB = nullptr;
11578   MachineFunction::iterator BBI(W.MBB);
11579   if (++BBI != FuncInfo.MF->end())
11580     NextMBB = &*BBI;
11581 
11582   unsigned Size = W.LastCluster - W.FirstCluster + 1;
11583 
11584   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11585 
11586   if (Size == 2 && W.MBB == SwitchMBB) {
11587     // If any two of the cases has the same destination, and if one value
11588     // is the same as the other, but has one bit unset that the other has set,
11589     // use bit manipulation to do two compares at once.  For example:
11590     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
11591     // TODO: This could be extended to merge any 2 cases in switches with 3
11592     // cases.
11593     // TODO: Handle cases where W.CaseBB != SwitchBB.
11594     CaseCluster &Small = *W.FirstCluster;
11595     CaseCluster &Big = *W.LastCluster;
11596 
11597     if (Small.Low == Small.High && Big.Low == Big.High &&
11598         Small.MBB == Big.MBB) {
11599       const APInt &SmallValue = Small.Low->getValue();
11600       const APInt &BigValue = Big.Low->getValue();
11601 
11602       // Check that there is only one bit different.
11603       APInt CommonBit = BigValue ^ SmallValue;
11604       if (CommonBit.isPowerOf2()) {
11605         SDValue CondLHS = getValue(Cond);
11606         EVT VT = CondLHS.getValueType();
11607         SDLoc DL = getCurSDLoc();
11608 
11609         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
11610                                  DAG.getConstant(CommonBit, DL, VT));
11611         SDValue Cond = DAG.getSetCC(
11612             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
11613             ISD::SETEQ);
11614 
11615         // Update successor info.
11616         // Both Small and Big will jump to Small.BB, so we sum up the
11617         // probabilities.
11618         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
11619         if (BPI)
11620           addSuccessorWithProb(
11621               SwitchMBB, DefaultMBB,
11622               // The default destination is the first successor in IR.
11623               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
11624         else
11625           addSuccessorWithProb(SwitchMBB, DefaultMBB);
11626 
11627         // Insert the true branch.
11628         SDValue BrCond =
11629             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
11630                         DAG.getBasicBlock(Small.MBB));
11631         // Insert the false branch.
11632         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
11633                              DAG.getBasicBlock(DefaultMBB));
11634 
11635         DAG.setRoot(BrCond);
11636         return;
11637       }
11638     }
11639   }
11640 
11641   if (TM.getOptLevel() != CodeGenOptLevel::None) {
11642     // Here, we order cases by probability so the most likely case will be
11643     // checked first. However, two clusters can have the same probability in
11644     // which case their relative ordering is non-deterministic. So we use Low
11645     // as a tie-breaker as clusters are guaranteed to never overlap.
11646     llvm::sort(W.FirstCluster, W.LastCluster + 1,
11647                [](const CaseCluster &a, const CaseCluster &b) {
11648       return a.Prob != b.Prob ?
11649              a.Prob > b.Prob :
11650              a.Low->getValue().slt(b.Low->getValue());
11651     });
11652 
11653     // Rearrange the case blocks so that the last one falls through if possible
11654     // without changing the order of probabilities.
11655     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
11656       --I;
11657       if (I->Prob > W.LastCluster->Prob)
11658         break;
11659       if (I->Kind == CC_Range && I->MBB == NextMBB) {
11660         std::swap(*I, *W.LastCluster);
11661         break;
11662       }
11663     }
11664   }
11665 
11666   // Compute total probability.
11667   BranchProbability DefaultProb = W.DefaultProb;
11668   BranchProbability UnhandledProbs = DefaultProb;
11669   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
11670     UnhandledProbs += I->Prob;
11671 
11672   MachineBasicBlock *CurMBB = W.MBB;
11673   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
11674     bool FallthroughUnreachable = false;
11675     MachineBasicBlock *Fallthrough;
11676     if (I == W.LastCluster) {
11677       // For the last cluster, fall through to the default destination.
11678       Fallthrough = DefaultMBB;
11679       FallthroughUnreachable = isa<UnreachableInst>(
11680           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
11681     } else {
11682       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
11683       CurMF->insert(BBI, Fallthrough);
11684       // Put Cond in a virtual register to make it available from the new blocks.
11685       ExportFromCurrentBlock(Cond);
11686     }
11687     UnhandledProbs -= I->Prob;
11688 
11689     switch (I->Kind) {
11690       case CC_JumpTable: {
11691         // FIXME: Optimize away range check based on pivot comparisons.
11692         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
11693         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
11694 
11695         // The jump block hasn't been inserted yet; insert it here.
11696         MachineBasicBlock *JumpMBB = JT->MBB;
11697         CurMF->insert(BBI, JumpMBB);
11698 
11699         auto JumpProb = I->Prob;
11700         auto FallthroughProb = UnhandledProbs;
11701 
11702         // If the default statement is a target of the jump table, we evenly
11703         // distribute the default probability to successors of CurMBB. Also
11704         // update the probability on the edge from JumpMBB to Fallthrough.
11705         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
11706                                               SE = JumpMBB->succ_end();
11707              SI != SE; ++SI) {
11708           if (*SI == DefaultMBB) {
11709             JumpProb += DefaultProb / 2;
11710             FallthroughProb -= DefaultProb / 2;
11711             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
11712             JumpMBB->normalizeSuccProbs();
11713             break;
11714           }
11715         }
11716 
11717         // If the default clause is unreachable, propagate that knowledge into
11718         // JTH->FallthroughUnreachable which will use it to suppress the range
11719         // check.
11720         //
11721         // However, don't do this if we're doing branch target enforcement,
11722         // because a table branch _without_ a range check can be a tempting JOP
11723         // gadget - out-of-bounds inputs that are impossible in correct
11724         // execution become possible again if an attacker can influence the
11725         // control flow. So if an attacker doesn't already have a BTI bypass
11726         // available, we don't want them to be able to get one out of this
11727         // table branch.
11728         if (FallthroughUnreachable) {
11729           Function &CurFunc = CurMF->getFunction();
11730           bool HasBranchTargetEnforcement = false;
11731           if (CurFunc.hasFnAttribute("branch-target-enforcement")) {
11732             HasBranchTargetEnforcement =
11733                 CurFunc.getFnAttribute("branch-target-enforcement")
11734                     .getValueAsBool();
11735           } else {
11736             HasBranchTargetEnforcement =
11737                 CurMF->getMMI().getModule()->getModuleFlag(
11738                     "branch-target-enforcement");
11739           }
11740           if (!HasBranchTargetEnforcement)
11741             JTH->FallthroughUnreachable = true;
11742         }
11743 
11744         if (!JTH->FallthroughUnreachable)
11745           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
11746         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
11747         CurMBB->normalizeSuccProbs();
11748 
11749         // The jump table header will be inserted in our current block, do the
11750         // range check, and fall through to our fallthrough block.
11751         JTH->HeaderBB = CurMBB;
11752         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
11753 
11754         // If we're in the right place, emit the jump table header right now.
11755         if (CurMBB == SwitchMBB) {
11756           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
11757           JTH->Emitted = true;
11758         }
11759         break;
11760       }
11761       case CC_BitTests: {
11762         // FIXME: Optimize away range check based on pivot comparisons.
11763         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
11764 
11765         // The bit test blocks haven't been inserted yet; insert them here.
11766         for (BitTestCase &BTC : BTB->Cases)
11767           CurMF->insert(BBI, BTC.ThisBB);
11768 
11769         // Fill in fields of the BitTestBlock.
11770         BTB->Parent = CurMBB;
11771         BTB->Default = Fallthrough;
11772 
11773         BTB->DefaultProb = UnhandledProbs;
11774         // If the cases in bit test don't form a contiguous range, we evenly
11775         // distribute the probability on the edge to Fallthrough to two
11776         // successors of CurMBB.
11777         if (!BTB->ContiguousRange) {
11778           BTB->Prob += DefaultProb / 2;
11779           BTB->DefaultProb -= DefaultProb / 2;
11780         }
11781 
11782         if (FallthroughUnreachable)
11783           BTB->FallthroughUnreachable = true;
11784 
11785         // If we're in the right place, emit the bit test header right now.
11786         if (CurMBB == SwitchMBB) {
11787           visitBitTestHeader(*BTB, SwitchMBB);
11788           BTB->Emitted = true;
11789         }
11790         break;
11791       }
11792       case CC_Range: {
11793         const Value *RHS, *LHS, *MHS;
11794         ISD::CondCode CC;
11795         if (I->Low == I->High) {
11796           // Check Cond == I->Low.
11797           CC = ISD::SETEQ;
11798           LHS = Cond;
11799           RHS=I->Low;
11800           MHS = nullptr;
11801         } else {
11802           // Check I->Low <= Cond <= I->High.
11803           CC = ISD::SETLE;
11804           LHS = I->Low;
11805           MHS = Cond;
11806           RHS = I->High;
11807         }
11808 
11809         // If Fallthrough is unreachable, fold away the comparison.
11810         if (FallthroughUnreachable)
11811           CC = ISD::SETTRUE;
11812 
11813         // The false probability is the sum of all unhandled cases.
11814         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
11815                      getCurSDLoc(), I->Prob, UnhandledProbs);
11816 
11817         if (CurMBB == SwitchMBB)
11818           visitSwitchCase(CB, SwitchMBB);
11819         else
11820           SL->SwitchCases.push_back(CB);
11821 
11822         break;
11823       }
11824     }
11825     CurMBB = Fallthrough;
11826   }
11827 }
11828 
11829 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
11830                                         const SwitchWorkListItem &W,
11831                                         Value *Cond,
11832                                         MachineBasicBlock *SwitchMBB) {
11833   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
11834          "Clusters not sorted?");
11835   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
11836 
11837   auto [LastLeft, FirstRight, LeftProb, RightProb] =
11838       SL->computeSplitWorkItemInfo(W);
11839 
11840   // Use the first element on the right as pivot since we will make less-than
11841   // comparisons against it.
11842   CaseClusterIt PivotCluster = FirstRight;
11843   assert(PivotCluster > W.FirstCluster);
11844   assert(PivotCluster <= W.LastCluster);
11845 
11846   CaseClusterIt FirstLeft = W.FirstCluster;
11847   CaseClusterIt LastRight = W.LastCluster;
11848 
11849   const ConstantInt *Pivot = PivotCluster->Low;
11850 
11851   // New blocks will be inserted immediately after the current one.
11852   MachineFunction::iterator BBI(W.MBB);
11853   ++BBI;
11854 
11855   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
11856   // we can branch to its destination directly if it's squeezed exactly in
11857   // between the known lower bound and Pivot - 1.
11858   MachineBasicBlock *LeftMBB;
11859   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
11860       FirstLeft->Low == W.GE &&
11861       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
11862     LeftMBB = FirstLeft->MBB;
11863   } else {
11864     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11865     FuncInfo.MF->insert(BBI, LeftMBB);
11866     WorkList.push_back(
11867         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
11868     // Put Cond in a virtual register to make it available from the new blocks.
11869     ExportFromCurrentBlock(Cond);
11870   }
11871 
11872   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
11873   // single cluster, RHS.Low == Pivot, and we can branch to its destination
11874   // directly if RHS.High equals the current upper bound.
11875   MachineBasicBlock *RightMBB;
11876   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
11877       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
11878     RightMBB = FirstRight->MBB;
11879   } else {
11880     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11881     FuncInfo.MF->insert(BBI, RightMBB);
11882     WorkList.push_back(
11883         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
11884     // Put Cond in a virtual register to make it available from the new blocks.
11885     ExportFromCurrentBlock(Cond);
11886   }
11887 
11888   // Create the CaseBlock record that will be used to lower the branch.
11889   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
11890                getCurSDLoc(), LeftProb, RightProb);
11891 
11892   if (W.MBB == SwitchMBB)
11893     visitSwitchCase(CB, SwitchMBB);
11894   else
11895     SL->SwitchCases.push_back(CB);
11896 }
11897 
11898 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
11899 // from the swith statement.
11900 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
11901                                             BranchProbability PeeledCaseProb) {
11902   if (PeeledCaseProb == BranchProbability::getOne())
11903     return BranchProbability::getZero();
11904   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
11905 
11906   uint32_t Numerator = CaseProb.getNumerator();
11907   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
11908   return BranchProbability(Numerator, std::max(Numerator, Denominator));
11909 }
11910 
11911 // Try to peel the top probability case if it exceeds the threshold.
11912 // Return current MachineBasicBlock for the switch statement if the peeling
11913 // does not occur.
11914 // If the peeling is performed, return the newly created MachineBasicBlock
11915 // for the peeled switch statement. Also update Clusters to remove the peeled
11916 // case. PeeledCaseProb is the BranchProbability for the peeled case.
11917 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
11918     const SwitchInst &SI, CaseClusterVector &Clusters,
11919     BranchProbability &PeeledCaseProb) {
11920   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11921   // Don't perform if there is only one cluster or optimizing for size.
11922   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
11923       TM.getOptLevel() == CodeGenOptLevel::None ||
11924       SwitchMBB->getParent()->getFunction().hasMinSize())
11925     return SwitchMBB;
11926 
11927   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
11928   unsigned PeeledCaseIndex = 0;
11929   bool SwitchPeeled = false;
11930   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
11931     CaseCluster &CC = Clusters[Index];
11932     if (CC.Prob < TopCaseProb)
11933       continue;
11934     TopCaseProb = CC.Prob;
11935     PeeledCaseIndex = Index;
11936     SwitchPeeled = true;
11937   }
11938   if (!SwitchPeeled)
11939     return SwitchMBB;
11940 
11941   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
11942                     << TopCaseProb << "\n");
11943 
11944   // Record the MBB for the peeled switch statement.
11945   MachineFunction::iterator BBI(SwitchMBB);
11946   ++BBI;
11947   MachineBasicBlock *PeeledSwitchMBB =
11948       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
11949   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
11950 
11951   ExportFromCurrentBlock(SI.getCondition());
11952   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
11953   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
11954                           nullptr,   nullptr,      TopCaseProb.getCompl()};
11955   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
11956 
11957   Clusters.erase(PeeledCaseIt);
11958   for (CaseCluster &CC : Clusters) {
11959     LLVM_DEBUG(
11960         dbgs() << "Scale the probablity for one cluster, before scaling: "
11961                << CC.Prob << "\n");
11962     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
11963     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
11964   }
11965   PeeledCaseProb = TopCaseProb;
11966   return PeeledSwitchMBB;
11967 }
11968 
11969 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
11970   // Extract cases from the switch.
11971   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11972   CaseClusterVector Clusters;
11973   Clusters.reserve(SI.getNumCases());
11974   for (auto I : SI.cases()) {
11975     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
11976     const ConstantInt *CaseVal = I.getCaseValue();
11977     BranchProbability Prob =
11978         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
11979             : BranchProbability(1, SI.getNumCases() + 1);
11980     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
11981   }
11982 
11983   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
11984 
11985   // Cluster adjacent cases with the same destination. We do this at all
11986   // optimization levels because it's cheap to do and will make codegen faster
11987   // if there are many clusters.
11988   sortAndRangeify(Clusters);
11989 
11990   // The branch probablity of the peeled case.
11991   BranchProbability PeeledCaseProb = BranchProbability::getZero();
11992   MachineBasicBlock *PeeledSwitchMBB =
11993       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
11994 
11995   // If there is only the default destination, jump there directly.
11996   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11997   if (Clusters.empty()) {
11998     assert(PeeledSwitchMBB == SwitchMBB);
11999     SwitchMBB->addSuccessor(DefaultMBB);
12000     if (DefaultMBB != NextBlock(SwitchMBB)) {
12001       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
12002                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
12003     }
12004     return;
12005   }
12006 
12007   SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(),
12008                      DAG.getBFI());
12009   SL->findBitTestClusters(Clusters, &SI);
12010 
12011   LLVM_DEBUG({
12012     dbgs() << "Case clusters: ";
12013     for (const CaseCluster &C : Clusters) {
12014       if (C.Kind == CC_JumpTable)
12015         dbgs() << "JT:";
12016       if (C.Kind == CC_BitTests)
12017         dbgs() << "BT:";
12018 
12019       C.Low->getValue().print(dbgs(), true);
12020       if (C.Low != C.High) {
12021         dbgs() << '-';
12022         C.High->getValue().print(dbgs(), true);
12023       }
12024       dbgs() << ' ';
12025     }
12026     dbgs() << '\n';
12027   });
12028 
12029   assert(!Clusters.empty());
12030   SwitchWorkList WorkList;
12031   CaseClusterIt First = Clusters.begin();
12032   CaseClusterIt Last = Clusters.end() - 1;
12033   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
12034   // Scale the branchprobability for DefaultMBB if the peel occurs and
12035   // DefaultMBB is not replaced.
12036   if (PeeledCaseProb != BranchProbability::getZero() &&
12037       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
12038     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
12039   WorkList.push_back(
12040       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
12041 
12042   while (!WorkList.empty()) {
12043     SwitchWorkListItem W = WorkList.pop_back_val();
12044     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
12045 
12046     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None &&
12047         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
12048       // For optimized builds, lower large range as a balanced binary tree.
12049       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
12050       continue;
12051     }
12052 
12053     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
12054   }
12055 }
12056 
12057 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
12058   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12059   auto DL = getCurSDLoc();
12060   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12061   setValue(&I, DAG.getStepVector(DL, ResultVT));
12062 }
12063 
12064 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
12065   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12066   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12067 
12068   SDLoc DL = getCurSDLoc();
12069   SDValue V = getValue(I.getOperand(0));
12070   assert(VT == V.getValueType() && "Malformed vector.reverse!");
12071 
12072   if (VT.isScalableVector()) {
12073     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
12074     return;
12075   }
12076 
12077   // Use VECTOR_SHUFFLE for the fixed-length vector
12078   // to maintain existing behavior.
12079   SmallVector<int, 8> Mask;
12080   unsigned NumElts = VT.getVectorMinNumElements();
12081   for (unsigned i = 0; i != NumElts; ++i)
12082     Mask.push_back(NumElts - 1 - i);
12083 
12084   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
12085 }
12086 
12087 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) {
12088   auto DL = getCurSDLoc();
12089   SDValue InVec = getValue(I.getOperand(0));
12090   EVT OutVT =
12091       InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
12092 
12093   unsigned OutNumElts = OutVT.getVectorMinNumElements();
12094 
12095   // ISD Node needs the input vectors split into two equal parts
12096   SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
12097                            DAG.getVectorIdxConstant(0, DL));
12098   SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
12099                            DAG.getVectorIdxConstant(OutNumElts, DL));
12100 
12101   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
12102   // legalisation and combines.
12103   if (OutVT.isFixedLengthVector()) {
12104     SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
12105                                         createStrideMask(0, 2, OutNumElts));
12106     SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
12107                                        createStrideMask(1, 2, OutNumElts));
12108     SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc());
12109     setValue(&I, Res);
12110     return;
12111   }
12112 
12113   SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL,
12114                             DAG.getVTList(OutVT, OutVT), Lo, Hi);
12115   setValue(&I, Res);
12116 }
12117 
12118 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) {
12119   auto DL = getCurSDLoc();
12120   EVT InVT = getValue(I.getOperand(0)).getValueType();
12121   SDValue InVec0 = getValue(I.getOperand(0));
12122   SDValue InVec1 = getValue(I.getOperand(1));
12123   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12124   EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12125 
12126   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
12127   // legalisation and combines.
12128   if (OutVT.isFixedLengthVector()) {
12129     unsigned NumElts = InVT.getVectorMinNumElements();
12130     SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1);
12131     setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT),
12132                                       createInterleaveMask(NumElts, 2)));
12133     return;
12134   }
12135 
12136   SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL,
12137                             DAG.getVTList(InVT, InVT), InVec0, InVec1);
12138   Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0),
12139                     Res.getValue(1));
12140   setValue(&I, Res);
12141 }
12142 
12143 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
12144   SmallVector<EVT, 4> ValueVTs;
12145   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
12146                   ValueVTs);
12147   unsigned NumValues = ValueVTs.size();
12148   if (NumValues == 0) return;
12149 
12150   SmallVector<SDValue, 4> Values(NumValues);
12151   SDValue Op = getValue(I.getOperand(0));
12152 
12153   for (unsigned i = 0; i != NumValues; ++i)
12154     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
12155                             SDValue(Op.getNode(), Op.getResNo() + i));
12156 
12157   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12158                            DAG.getVTList(ValueVTs), Values));
12159 }
12160 
12161 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
12162   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12163   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12164 
12165   SDLoc DL = getCurSDLoc();
12166   SDValue V1 = getValue(I.getOperand(0));
12167   SDValue V2 = getValue(I.getOperand(1));
12168   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
12169 
12170   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
12171   if (VT.isScalableVector()) {
12172     MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
12173     setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
12174                              DAG.getConstant(Imm, DL, IdxVT)));
12175     return;
12176   }
12177 
12178   unsigned NumElts = VT.getVectorNumElements();
12179 
12180   uint64_t Idx = (NumElts + Imm) % NumElts;
12181 
12182   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
12183   SmallVector<int, 8> Mask;
12184   for (unsigned i = 0; i < NumElts; ++i)
12185     Mask.push_back(Idx + i);
12186   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
12187 }
12188 
12189 // Consider the following MIR after SelectionDAG, which produces output in
12190 // phyregs in the first case or virtregs in the second case.
12191 //
12192 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx
12193 // %5:gr32 = COPY $ebx
12194 // %6:gr32 = COPY $edx
12195 // %1:gr32 = COPY %6:gr32
12196 // %0:gr32 = COPY %5:gr32
12197 //
12198 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32
12199 // %1:gr32 = COPY %6:gr32
12200 // %0:gr32 = COPY %5:gr32
12201 //
12202 // Given %0, we'd like to return $ebx in the first case and %5 in the second.
12203 // Given %1, we'd like to return $edx in the first case and %6 in the second.
12204 //
12205 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap
12206 // to a single virtreg (such as %0). The remaining outputs monotonically
12207 // increase in virtreg number from there. If a callbr has no outputs, then it
12208 // should not have a corresponding callbr landingpad; in fact, the callbr
12209 // landingpad would not even be able to refer to such a callbr.
12210 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) {
12211   MachineInstr *MI = MRI.def_begin(Reg)->getParent();
12212   // There is definitely at least one copy.
12213   assert(MI->getOpcode() == TargetOpcode::COPY &&
12214          "start of copy chain MUST be COPY");
12215   Reg = MI->getOperand(1).getReg();
12216   MI = MRI.def_begin(Reg)->getParent();
12217   // There may be an optional second copy.
12218   if (MI->getOpcode() == TargetOpcode::COPY) {
12219     assert(Reg.isVirtual() && "expected COPY of virtual register");
12220     Reg = MI->getOperand(1).getReg();
12221     assert(Reg.isPhysical() && "expected COPY of physical register");
12222     MI = MRI.def_begin(Reg)->getParent();
12223   }
12224   // The start of the chain must be an INLINEASM_BR.
12225   assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR &&
12226          "end of copy chain MUST be INLINEASM_BR");
12227   return Reg;
12228 }
12229 
12230 // We must do this walk rather than the simpler
12231 //   setValue(&I, getCopyFromRegs(CBR, CBR->getType()));
12232 // otherwise we will end up with copies of virtregs only valid along direct
12233 // edges.
12234 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) {
12235   SmallVector<EVT, 8> ResultVTs;
12236   SmallVector<SDValue, 8> ResultValues;
12237   const auto *CBR =
12238       cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator());
12239 
12240   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12241   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
12242   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
12243 
12244   unsigned InitialDef = FuncInfo.ValueMap[CBR];
12245   SDValue Chain = DAG.getRoot();
12246 
12247   // Re-parse the asm constraints string.
12248   TargetLowering::AsmOperandInfoVector TargetConstraints =
12249       TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR);
12250   for (auto &T : TargetConstraints) {
12251     SDISelAsmOperandInfo OpInfo(T);
12252     if (OpInfo.Type != InlineAsm::isOutput)
12253       continue;
12254 
12255     // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the
12256     // individual constraint.
12257     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
12258 
12259     switch (OpInfo.ConstraintType) {
12260     case TargetLowering::C_Register:
12261     case TargetLowering::C_RegisterClass: {
12262       // Fill in OpInfo.AssignedRegs.Regs.
12263       getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo);
12264 
12265       // getRegistersForValue may produce 1 to many registers based on whether
12266       // the OpInfo.ConstraintVT is legal on the target or not.
12267       for (size_t i = 0, e = OpInfo.AssignedRegs.Regs.size(); i != e; ++i) {
12268         Register OriginalDef = FollowCopyChain(MRI, InitialDef++);
12269         if (Register::isPhysicalRegister(OriginalDef))
12270           FuncInfo.MBB->addLiveIn(OriginalDef);
12271         // Update the assigned registers to use the original defs.
12272         OpInfo.AssignedRegs.Regs[i] = OriginalDef;
12273       }
12274 
12275       SDValue V = OpInfo.AssignedRegs.getCopyFromRegs(
12276           DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR);
12277       ResultValues.push_back(V);
12278       ResultVTs.push_back(OpInfo.ConstraintVT);
12279       break;
12280     }
12281     case TargetLowering::C_Other: {
12282       SDValue Flag;
12283       SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
12284                                                   OpInfo, DAG);
12285       ++InitialDef;
12286       ResultValues.push_back(V);
12287       ResultVTs.push_back(OpInfo.ConstraintVT);
12288       break;
12289     }
12290     default:
12291       break;
12292     }
12293   }
12294   SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12295                           DAG.getVTList(ResultVTs), ResultValues);
12296   setValue(&I, V);
12297 }
12298