xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 14120227a34365e829d05c1413033d235d7d272c)
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/RuntimeLibcallUtil.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/MemoryModelRelaxationAnnotations.h"
84 #include "llvm/IR/Metadata.h"
85 #include "llvm/IR/Module.h"
86 #include "llvm/IR/Operator.h"
87 #include "llvm/IR/PatternMatch.h"
88 #include "llvm/IR/Statepoint.h"
89 #include "llvm/IR/Type.h"
90 #include "llvm/IR/User.h"
91 #include "llvm/IR/Value.h"
92 #include "llvm/MC/MCContext.h"
93 #include "llvm/Support/AtomicOrdering.h"
94 #include "llvm/Support/Casting.h"
95 #include "llvm/Support/CommandLine.h"
96 #include "llvm/Support/Compiler.h"
97 #include "llvm/Support/Debug.h"
98 #include "llvm/Support/InstructionCost.h"
99 #include "llvm/Support/MathExtras.h"
100 #include "llvm/Support/raw_ostream.h"
101 #include "llvm/Target/TargetIntrinsicInfo.h"
102 #include "llvm/Target/TargetMachine.h"
103 #include "llvm/Target/TargetOptions.h"
104 #include "llvm/TargetParser/Triple.h"
105 #include "llvm/Transforms/Utils/Local.h"
106 #include <cstddef>
107 #include <deque>
108 #include <iterator>
109 #include <limits>
110 #include <optional>
111 #include <tuple>
112 
113 using namespace llvm;
114 using namespace PatternMatch;
115 using namespace SwitchCG;
116 
117 #define DEBUG_TYPE "isel"
118 
119 /// LimitFloatPrecision - Generate low-precision inline sequences for
120 /// some float libcalls (6, 8 or 12 bits).
121 static unsigned LimitFloatPrecision;
122 
123 static cl::opt<bool>
124     InsertAssertAlign("insert-assert-align", cl::init(true),
125                       cl::desc("Insert the experimental `assertalign` node."),
126                       cl::ReallyHidden);
127 
128 static cl::opt<unsigned, true>
129     LimitFPPrecision("limit-float-precision",
130                      cl::desc("Generate low-precision inline sequences "
131                               "for some float libcalls"),
132                      cl::location(LimitFloatPrecision), cl::Hidden,
133                      cl::init(0));
134 
135 static cl::opt<unsigned> SwitchPeelThreshold(
136     "switch-peel-threshold", cl::Hidden, cl::init(66),
137     cl::desc("Set the case probability threshold for peeling the case from a "
138              "switch statement. A value greater than 100 will void this "
139              "optimization"));
140 
141 // Limit the width of DAG chains. This is important in general to prevent
142 // DAG-based analysis from blowing up. For example, alias analysis and
143 // load clustering may not complete in reasonable time. It is difficult to
144 // recognize and avoid this situation within each individual analysis, and
145 // future analyses are likely to have the same behavior. Limiting DAG width is
146 // the safe approach and will be especially important with global DAGs.
147 //
148 // MaxParallelChains default is arbitrarily high to avoid affecting
149 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
150 // sequence over this should have been converted to llvm.memcpy by the
151 // frontend. It is easy to induce this behavior with .ll code such as:
152 // %buffer = alloca [4096 x i8]
153 // %data = load [4096 x i8]* %argPtr
154 // store [4096 x i8] %data, [4096 x i8]* %buffer
155 static const unsigned MaxParallelChains = 64;
156 
157 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
158                                       const SDValue *Parts, unsigned NumParts,
159                                       MVT PartVT, EVT ValueVT, const Value *V,
160                                       SDValue InChain,
161                                       std::optional<CallingConv::ID> CC);
162 
163 /// getCopyFromParts - Create a value that contains the specified legal parts
164 /// combined into the value they represent.  If the parts combine to a type
165 /// larger than ValueVT then AssertOp can be used to specify whether the extra
166 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
167 /// (ISD::AssertSext).
168 static SDValue
169 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts,
170                  unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V,
171                  SDValue InChain,
172                  std::optional<CallingConv::ID> CC = std::nullopt,
173                  std::optional<ISD::NodeType> AssertOp = std::nullopt) {
174   // Let the target assemble the parts if it wants to
175   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
176   if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
177                                                    PartVT, ValueVT, CC))
178     return Val;
179 
180   if (ValueVT.isVector())
181     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
182                                   InChain, CC);
183 
184   assert(NumParts > 0 && "No parts to assemble!");
185   SDValue Val = Parts[0];
186 
187   if (NumParts > 1) {
188     // Assemble the value from multiple parts.
189     if (ValueVT.isInteger()) {
190       unsigned PartBits = PartVT.getSizeInBits();
191       unsigned ValueBits = ValueVT.getSizeInBits();
192 
193       // Assemble the power of 2 part.
194       unsigned RoundParts = llvm::bit_floor(NumParts);
195       unsigned RoundBits = PartBits * RoundParts;
196       EVT RoundVT = RoundBits == ValueBits ?
197         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
198       SDValue Lo, Hi;
199 
200       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
201 
202       if (RoundParts > 2) {
203         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, PartVT, HalfVT, V,
204                               InChain);
205         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, RoundParts / 2,
206                               PartVT, HalfVT, V, InChain);
207       } else {
208         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
209         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
210       }
211 
212       if (DAG.getDataLayout().isBigEndian())
213         std::swap(Lo, Hi);
214 
215       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
216 
217       if (RoundParts < NumParts) {
218         // Assemble the trailing non-power-of-2 part.
219         unsigned OddParts = NumParts - RoundParts;
220         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
221         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
222                               OddVT, V, InChain, CC);
223 
224         // Combine the round and odd parts.
225         Lo = Val;
226         if (DAG.getDataLayout().isBigEndian())
227           std::swap(Lo, Hi);
228         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
229         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
230         Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
231                          DAG.getConstant(Lo.getValueSizeInBits(), DL,
232                                          TLI.getShiftAmountTy(
233                                              TotalVT, DAG.getDataLayout())));
234         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
235         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
236       }
237     } else if (PartVT.isFloatingPoint()) {
238       // FP split into multiple FP parts (for ppcf128)
239       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
240              "Unexpected split");
241       SDValue Lo, Hi;
242       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
243       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
244       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
245         std::swap(Lo, Hi);
246       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
247     } else {
248       // FP split into integer parts (soft fp)
249       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
250              !PartVT.isVector() && "Unexpected split");
251       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
252       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V,
253                              InChain, CC);
254     }
255   }
256 
257   // There is now one part, held in Val.  Correct it to match ValueVT.
258   // PartEVT is the type of the register class that holds the value.
259   // ValueVT is the type of the inline asm operation.
260   EVT PartEVT = Val.getValueType();
261 
262   if (PartEVT == ValueVT)
263     return Val;
264 
265   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
266       ValueVT.bitsLT(PartEVT)) {
267     // For an FP value in an integer part, we need to truncate to the right
268     // width first.
269     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
270     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
271   }
272 
273   // Handle types that have the same size.
274   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
275     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
276 
277   // Handle types with different sizes.
278   if (PartEVT.isInteger() && ValueVT.isInteger()) {
279     if (ValueVT.bitsLT(PartEVT)) {
280       // For a truncate, see if we have any information to
281       // indicate whether the truncated bits will always be
282       // zero or sign-extension.
283       if (AssertOp)
284         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
285                           DAG.getValueType(ValueVT));
286       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
287     }
288     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
289   }
290 
291   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
292     // FP_ROUND's are always exact here.
293     if (ValueVT.bitsLT(Val.getValueType())) {
294 
295       SDValue NoChange =
296           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
297 
298       if (DAG.getMachineFunction().getFunction().getAttributes().hasFnAttr(
299               llvm::Attribute::StrictFP)) {
300         return DAG.getNode(ISD::STRICT_FP_ROUND, DL,
301                            DAG.getVTList(ValueVT, MVT::Other), InChain, Val,
302                            NoChange);
303       }
304 
305       return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val, NoChange);
306     }
307 
308     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
309   }
310 
311   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
312   // then truncating.
313   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
314       ValueVT.bitsLT(PartEVT)) {
315     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
316     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
317   }
318 
319   report_fatal_error("Unknown mismatch in getCopyFromParts!");
320 }
321 
322 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
323                                               const Twine &ErrMsg) {
324   const Instruction *I = dyn_cast_or_null<Instruction>(V);
325   if (!V)
326     return Ctx.emitError(ErrMsg);
327 
328   const char *AsmError = ", possible invalid constraint for vector type";
329   if (const CallInst *CI = dyn_cast<CallInst>(I))
330     if (CI->isInlineAsm())
331       return Ctx.emitError(I, ErrMsg + AsmError);
332 
333   return Ctx.emitError(I, ErrMsg);
334 }
335 
336 /// getCopyFromPartsVector - Create a value that contains the specified legal
337 /// parts combined into the value they represent.  If the parts combine to a
338 /// type larger than ValueVT then AssertOp can be used to specify whether the
339 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
340 /// ValueVT (ISD::AssertSext).
341 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
342                                       const SDValue *Parts, unsigned NumParts,
343                                       MVT PartVT, EVT ValueVT, const Value *V,
344                                       SDValue InChain,
345                                       std::optional<CallingConv::ID> CallConv) {
346   assert(ValueVT.isVector() && "Not a vector value");
347   assert(NumParts > 0 && "No parts to assemble!");
348   const bool IsABIRegCopy = CallConv.has_value();
349 
350   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
351   SDValue Val = Parts[0];
352 
353   // Handle a multi-element vector.
354   if (NumParts > 1) {
355     EVT IntermediateVT;
356     MVT RegisterVT;
357     unsigned NumIntermediates;
358     unsigned NumRegs;
359 
360     if (IsABIRegCopy) {
361       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
362           *DAG.getContext(), *CallConv, ValueVT, IntermediateVT,
363           NumIntermediates, RegisterVT);
364     } else {
365       NumRegs =
366           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
367                                      NumIntermediates, RegisterVT);
368     }
369 
370     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
371     NumParts = NumRegs; // Silence a compiler warning.
372     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
373     assert(RegisterVT.getSizeInBits() ==
374            Parts[0].getSimpleValueType().getSizeInBits() &&
375            "Part type sizes don't match!");
376 
377     // Assemble the parts into intermediate operands.
378     SmallVector<SDValue, 8> Ops(NumIntermediates);
379     if (NumIntermediates == NumParts) {
380       // If the register was not expanded, truncate or copy the value,
381       // as appropriate.
382       for (unsigned i = 0; i != NumParts; ++i)
383         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, PartVT, IntermediateVT,
384                                   V, InChain, CallConv);
385     } else if (NumParts > 0) {
386       // If the intermediate type was expanded, build the intermediate
387       // operands from the parts.
388       assert(NumParts % NumIntermediates == 0 &&
389              "Must expand into a divisible number of parts!");
390       unsigned Factor = NumParts / NumIntermediates;
391       for (unsigned i = 0; i != NumIntermediates; ++i)
392         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, PartVT,
393                                   IntermediateVT, V, InChain, CallConv);
394     }
395 
396     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
397     // intermediate operands.
398     EVT BuiltVectorTy =
399         IntermediateVT.isVector()
400             ? EVT::getVectorVT(
401                   *DAG.getContext(), IntermediateVT.getScalarType(),
402                   IntermediateVT.getVectorElementCount() * NumParts)
403             : EVT::getVectorVT(*DAG.getContext(),
404                                IntermediateVT.getScalarType(),
405                                NumIntermediates);
406     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
407                                                 : ISD::BUILD_VECTOR,
408                       DL, BuiltVectorTy, Ops);
409   }
410 
411   // There is now one part, held in Val.  Correct it to match ValueVT.
412   EVT PartEVT = Val.getValueType();
413 
414   if (PartEVT == ValueVT)
415     return Val;
416 
417   if (PartEVT.isVector()) {
418     // Vector/Vector bitcast.
419     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
420       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
421 
422     // If the parts vector has more elements than the value vector, then we
423     // have a vector widening case (e.g. <2 x float> -> <4 x float>).
424     // Extract the elements we want.
425     if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
426       assert((PartEVT.getVectorElementCount().getKnownMinValue() >
427               ValueVT.getVectorElementCount().getKnownMinValue()) &&
428              (PartEVT.getVectorElementCount().isScalable() ==
429               ValueVT.getVectorElementCount().isScalable()) &&
430              "Cannot narrow, it would be a lossy transformation");
431       PartEVT =
432           EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(),
433                            ValueVT.getVectorElementCount());
434       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val,
435                         DAG.getVectorIdxConstant(0, DL));
436       if (PartEVT == ValueVT)
437         return Val;
438       if (PartEVT.isInteger() && ValueVT.isFloatingPoint())
439         return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
440 
441       // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>).
442       if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
443         return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
444     }
445 
446     // Promoted vector extract
447     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
448   }
449 
450   // Trivial bitcast if the types are the same size and the destination
451   // vector type is legal.
452   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
453       TLI.isTypeLegal(ValueVT))
454     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
455 
456   if (ValueVT.getVectorNumElements() != 1) {
457      // Certain ABIs require that vectors are passed as integers. For vectors
458      // are the same size, this is an obvious bitcast.
459      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
460        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
461      } else if (ValueVT.bitsLT(PartEVT)) {
462        const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
463        EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
464        // Drop the extra bits.
465        Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
466        return DAG.getBitcast(ValueVT, Val);
467      }
468 
469      diagnosePossiblyInvalidConstraint(
470          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
471      return DAG.getUNDEF(ValueVT);
472   }
473 
474   // Handle cases such as i8 -> <1 x i1>
475   EVT ValueSVT = ValueVT.getVectorElementType();
476   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
477     unsigned ValueSize = ValueSVT.getSizeInBits();
478     if (ValueSize == PartEVT.getSizeInBits()) {
479       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
480     } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) {
481       // It's possible a scalar floating point type gets softened to integer and
482       // then promoted to a larger integer. If PartEVT is the larger integer
483       // we need to truncate it and then bitcast to the FP type.
484       assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types");
485       EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
486       Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
487       Val = DAG.getBitcast(ValueSVT, Val);
488     } else {
489       Val = ValueVT.isFloatingPoint()
490                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
491                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
492     }
493   }
494 
495   return DAG.getBuildVector(ValueVT, DL, Val);
496 }
497 
498 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
499                                  SDValue Val, SDValue *Parts, unsigned NumParts,
500                                  MVT PartVT, const Value *V,
501                                  std::optional<CallingConv::ID> CallConv);
502 
503 /// getCopyToParts - Create a series of nodes that contain the specified value
504 /// split into legal parts.  If the parts contain more bits than Val, then, for
505 /// integers, ExtendKind can be used to specify how to generate the extra bits.
506 static void
507 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
508                unsigned NumParts, MVT PartVT, const Value *V,
509                std::optional<CallingConv::ID> CallConv = std::nullopt,
510                ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
511   // Let the target split the parts if it wants to
512   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
513   if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
514                                       CallConv))
515     return;
516   EVT ValueVT = Val.getValueType();
517 
518   // Handle the vector case separately.
519   if (ValueVT.isVector())
520     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
521                                 CallConv);
522 
523   unsigned OrigNumParts = NumParts;
524   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
525          "Copying to an illegal type!");
526 
527   if (NumParts == 0)
528     return;
529 
530   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
531   EVT PartEVT = PartVT;
532   if (PartEVT == ValueVT) {
533     assert(NumParts == 1 && "No-op copy with multiple parts!");
534     Parts[0] = Val;
535     return;
536   }
537 
538   unsigned PartBits = PartVT.getSizeInBits();
539   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
540     // If the parts cover more bits than the value has, promote the value.
541     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
542       assert(NumParts == 1 && "Do not know what to promote to!");
543       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
544     } else {
545       if (ValueVT.isFloatingPoint()) {
546         // FP values need to be bitcast, then extended if they are being put
547         // into a larger container.
548         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
549         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
550       }
551       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
552              ValueVT.isInteger() &&
553              "Unknown mismatch!");
554       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
555       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
556       if (PartVT == MVT::x86mmx)
557         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
558     }
559   } else if (PartBits == ValueVT.getSizeInBits()) {
560     // Different types of the same size.
561     assert(NumParts == 1 && PartEVT != ValueVT);
562     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
563   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
564     // If the parts cover less bits than value has, truncate the value.
565     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
566            ValueVT.isInteger() &&
567            "Unknown mismatch!");
568     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
569     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
570     if (PartVT == MVT::x86mmx)
571       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
572   }
573 
574   // The value may have changed - recompute ValueVT.
575   ValueVT = Val.getValueType();
576   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
577          "Failed to tile the value with PartVT!");
578 
579   if (NumParts == 1) {
580     if (PartEVT != ValueVT) {
581       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
582                                         "scalar-to-vector conversion failed");
583       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
584     }
585 
586     Parts[0] = Val;
587     return;
588   }
589 
590   // Expand the value into multiple parts.
591   if (NumParts & (NumParts - 1)) {
592     // The number of parts is not a power of 2.  Split off and copy the tail.
593     assert(PartVT.isInteger() && ValueVT.isInteger() &&
594            "Do not know what to expand to!");
595     unsigned RoundParts = llvm::bit_floor(NumParts);
596     unsigned RoundBits = RoundParts * PartBits;
597     unsigned OddParts = NumParts - RoundParts;
598     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
599       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL));
600 
601     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
602                    CallConv);
603 
604     if (DAG.getDataLayout().isBigEndian())
605       // The odd parts were reversed by getCopyToParts - unreverse them.
606       std::reverse(Parts + RoundParts, Parts + NumParts);
607 
608     NumParts = RoundParts;
609     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
610     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
611   }
612 
613   // The number of parts is a power of 2.  Repeatedly bisect the value using
614   // EXTRACT_ELEMENT.
615   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
616                          EVT::getIntegerVT(*DAG.getContext(),
617                                            ValueVT.getSizeInBits()),
618                          Val);
619 
620   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
621     for (unsigned i = 0; i < NumParts; i += StepSize) {
622       unsigned ThisBits = StepSize * PartBits / 2;
623       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
624       SDValue &Part0 = Parts[i];
625       SDValue &Part1 = Parts[i+StepSize/2];
626 
627       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
628                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
629       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
630                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
631 
632       if (ThisBits == PartBits && ThisVT != PartVT) {
633         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
634         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
635       }
636     }
637   }
638 
639   if (DAG.getDataLayout().isBigEndian())
640     std::reverse(Parts, Parts + OrigNumParts);
641 }
642 
643 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val,
644                                      const SDLoc &DL, EVT PartVT) {
645   if (!PartVT.isVector())
646     return SDValue();
647 
648   EVT ValueVT = Val.getValueType();
649   EVT PartEVT = PartVT.getVectorElementType();
650   EVT ValueEVT = ValueVT.getVectorElementType();
651   ElementCount PartNumElts = PartVT.getVectorElementCount();
652   ElementCount ValueNumElts = ValueVT.getVectorElementCount();
653 
654   // We only support widening vectors with equivalent element types and
655   // fixed/scalable properties. If a target needs to widen a fixed-length type
656   // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
657   if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
658       PartNumElts.isScalable() != ValueNumElts.isScalable())
659     return SDValue();
660 
661   // Have a try for bf16 because some targets share its ABI with fp16.
662   if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) {
663     assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
664            "Cannot widen to illegal type");
665     Val = DAG.getNode(ISD::BITCAST, DL,
666                       ValueVT.changeVectorElementType(MVT::f16), Val);
667   } else if (PartEVT != ValueEVT) {
668     return SDValue();
669   }
670 
671   // Widening a scalable vector to another scalable vector is done by inserting
672   // the vector into a larger undef one.
673   if (PartNumElts.isScalable())
674     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
675                        Val, DAG.getVectorIdxConstant(0, DL));
676 
677   // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
678   // undef elements.
679   SmallVector<SDValue, 16> Ops;
680   DAG.ExtractVectorElements(Val, Ops);
681   SDValue EltUndef = DAG.getUNDEF(PartEVT);
682   Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
683 
684   // FIXME: Use CONCAT for 2x -> 4x.
685   return DAG.getBuildVector(PartVT, DL, Ops);
686 }
687 
688 /// getCopyToPartsVector - Create a series of nodes that contain the specified
689 /// value split into legal parts.
690 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
691                                  SDValue Val, SDValue *Parts, unsigned NumParts,
692                                  MVT PartVT, const Value *V,
693                                  std::optional<CallingConv::ID> CallConv) {
694   EVT ValueVT = Val.getValueType();
695   assert(ValueVT.isVector() && "Not a vector");
696   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
697   const bool IsABIRegCopy = CallConv.has_value();
698 
699   if (NumParts == 1) {
700     EVT PartEVT = PartVT;
701     if (PartEVT == ValueVT) {
702       // Nothing to do.
703     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
704       // Bitconvert vector->vector case.
705       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
706     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
707       Val = Widened;
708     } else if (PartVT.isVector() &&
709                PartEVT.getVectorElementType().bitsGE(
710                    ValueVT.getVectorElementType()) &&
711                PartEVT.getVectorElementCount() ==
712                    ValueVT.getVectorElementCount()) {
713 
714       // Promoted vector extract
715       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
716     } else if (PartEVT.isVector() &&
717                PartEVT.getVectorElementType() !=
718                    ValueVT.getVectorElementType() &&
719                TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
720                    TargetLowering::TypeWidenVector) {
721       // Combination of widening and promotion.
722       EVT WidenVT =
723           EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(),
724                            PartVT.getVectorElementCount());
725       SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
726       Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
727     } else {
728       // Don't extract an integer from a float vector. This can happen if the
729       // FP type gets softened to integer and then promoted. The promotion
730       // prevents it from being picked up by the earlier bitcast case.
731       if (ValueVT.getVectorElementCount().isScalar() &&
732           (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) {
733         // If we reach this condition and PartVT is FP, this means that
734         // ValueVT is also FP and both have a different size, otherwise we
735         // would have bitcasted them. Producing an EXTRACT_VECTOR_ELT here
736         // would be invalid since that would mean the smaller FP type has to
737         // be extended to the larger one.
738         if (PartVT.isFloatingPoint()) {
739           Val = DAG.getBitcast(ValueVT.getScalarType(), Val);
740           Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
741         } else
742           Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
743                             DAG.getVectorIdxConstant(0, DL));
744       } else {
745         uint64_t ValueSize = ValueVT.getFixedSizeInBits();
746         assert(PartVT.getFixedSizeInBits() > ValueSize &&
747                "lossy conversion of vector to scalar type");
748         EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
749         Val = DAG.getBitcast(IntermediateType, Val);
750         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
751       }
752     }
753 
754     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
755     Parts[0] = Val;
756     return;
757   }
758 
759   // Handle a multi-element vector.
760   EVT IntermediateVT;
761   MVT RegisterVT;
762   unsigned NumIntermediates;
763   unsigned NumRegs;
764   if (IsABIRegCopy) {
765     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
766         *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates,
767         RegisterVT);
768   } else {
769     NumRegs =
770         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
771                                    NumIntermediates, RegisterVT);
772   }
773 
774   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
775   NumParts = NumRegs; // Silence a compiler warning.
776   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
777 
778   assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
779          "Mixing scalable and fixed vectors when copying in parts");
780 
781   std::optional<ElementCount> DestEltCnt;
782 
783   if (IntermediateVT.isVector())
784     DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
785   else
786     DestEltCnt = ElementCount::getFixed(NumIntermediates);
787 
788   EVT BuiltVectorTy = EVT::getVectorVT(
789       *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt);
790 
791   if (ValueVT == BuiltVectorTy) {
792     // Nothing to do.
793   } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
794     // Bitconvert vector->vector case.
795     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
796   } else {
797     if (BuiltVectorTy.getVectorElementType().bitsGT(
798             ValueVT.getVectorElementType())) {
799       // Integer promotion.
800       ValueVT = EVT::getVectorVT(*DAG.getContext(),
801                                  BuiltVectorTy.getVectorElementType(),
802                                  ValueVT.getVectorElementCount());
803       Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
804     }
805 
806     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
807       Val = Widened;
808     }
809   }
810 
811   assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
812 
813   // Split the vector into intermediate operands.
814   SmallVector<SDValue, 8> Ops(NumIntermediates);
815   for (unsigned i = 0; i != NumIntermediates; ++i) {
816     if (IntermediateVT.isVector()) {
817       // This does something sensible for scalable vectors - see the
818       // definition of EXTRACT_SUBVECTOR for further details.
819       unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
820       Ops[i] =
821           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
822                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
823     } else {
824       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
825                            DAG.getVectorIdxConstant(i, DL));
826     }
827   }
828 
829   // Split the intermediate operands into legal parts.
830   if (NumParts == NumIntermediates) {
831     // If the register was not expanded, promote or copy the value,
832     // as appropriate.
833     for (unsigned i = 0; i != NumParts; ++i)
834       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
835   } else if (NumParts > 0) {
836     // If the intermediate type was expanded, split each the value into
837     // legal parts.
838     assert(NumIntermediates != 0 && "division by zero");
839     assert(NumParts % NumIntermediates == 0 &&
840            "Must expand into a divisible number of parts!");
841     unsigned Factor = NumParts / NumIntermediates;
842     for (unsigned i = 0; i != NumIntermediates; ++i)
843       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
844                      CallConv);
845   }
846 }
847 
848 RegsForValue::RegsForValue(const SmallVector<Register, 4> &regs, MVT regvt,
849                            EVT valuevt, std::optional<CallingConv::ID> CC)
850     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
851       RegCount(1, regs.size()), CallConv(CC) {}
852 
853 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
854                            const DataLayout &DL, Register Reg, Type *Ty,
855                            std::optional<CallingConv::ID> CC) {
856   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
857 
858   CallConv = CC;
859 
860   for (EVT ValueVT : ValueVTs) {
861     unsigned NumRegs =
862         isABIMangled()
863             ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT)
864             : TLI.getNumRegisters(Context, ValueVT);
865     MVT RegisterVT =
866         isABIMangled()
867             ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT)
868             : TLI.getRegisterType(Context, ValueVT);
869     for (unsigned i = 0; i != NumRegs; ++i)
870       Regs.push_back(Reg + i);
871     RegVTs.push_back(RegisterVT);
872     RegCount.push_back(NumRegs);
873     Reg = Reg.id() + NumRegs;
874   }
875 }
876 
877 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
878                                       FunctionLoweringInfo &FuncInfo,
879                                       const SDLoc &dl, SDValue &Chain,
880                                       SDValue *Glue, const Value *V) const {
881   // A Value with type {} or [0 x %t] needs no registers.
882   if (ValueVTs.empty())
883     return SDValue();
884 
885   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
886 
887   // Assemble the legal parts into the final values.
888   SmallVector<SDValue, 4> Values(ValueVTs.size());
889   SmallVector<SDValue, 8> Parts;
890   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
891     // Copy the legal parts from the registers.
892     EVT ValueVT = ValueVTs[Value];
893     unsigned NumRegs = RegCount[Value];
894     MVT RegisterVT = isABIMangled()
895                          ? TLI.getRegisterTypeForCallingConv(
896                                *DAG.getContext(), *CallConv, RegVTs[Value])
897                          : RegVTs[Value];
898 
899     Parts.resize(NumRegs);
900     for (unsigned i = 0; i != NumRegs; ++i) {
901       SDValue P;
902       if (!Glue) {
903         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
904       } else {
905         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue);
906         *Glue = P.getValue(2);
907       }
908 
909       Chain = P.getValue(1);
910       Parts[i] = P;
911 
912       // If the source register was virtual and if we know something about it,
913       // add an assert node.
914       if (!Register::isVirtualRegister(Regs[Part + i]) ||
915           !RegisterVT.isInteger())
916         continue;
917 
918       const FunctionLoweringInfo::LiveOutInfo *LOI =
919         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
920       if (!LOI)
921         continue;
922 
923       unsigned RegSize = RegisterVT.getScalarSizeInBits();
924       unsigned NumSignBits = LOI->NumSignBits;
925       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
926 
927       if (NumZeroBits == RegSize) {
928         // The current value is a zero.
929         // Explicitly express that as it would be easier for
930         // optimizations to kick in.
931         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
932         continue;
933       }
934 
935       // FIXME: We capture more information than the dag can represent.  For
936       // now, just use the tightest assertzext/assertsext possible.
937       bool isSExt;
938       EVT FromVT(MVT::Other);
939       if (NumZeroBits) {
940         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
941         isSExt = false;
942       } else if (NumSignBits > 1) {
943         FromVT =
944             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
945         isSExt = true;
946       } else {
947         continue;
948       }
949       // Add an assertion node.
950       assert(FromVT != MVT::Other);
951       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
952                              RegisterVT, P, DAG.getValueType(FromVT));
953     }
954 
955     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
956                                      RegisterVT, ValueVT, V, Chain, CallConv);
957     Part += NumRegs;
958     Parts.clear();
959   }
960 
961   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
962 }
963 
964 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
965                                  const SDLoc &dl, SDValue &Chain, SDValue *Glue,
966                                  const Value *V,
967                                  ISD::NodeType PreferredExtendType) const {
968   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
969   ISD::NodeType ExtendKind = PreferredExtendType;
970 
971   // Get the list of the values's legal parts.
972   unsigned NumRegs = Regs.size();
973   SmallVector<SDValue, 8> Parts(NumRegs);
974   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
975     unsigned NumParts = RegCount[Value];
976 
977     MVT RegisterVT = isABIMangled()
978                          ? TLI.getRegisterTypeForCallingConv(
979                                *DAG.getContext(), *CallConv, RegVTs[Value])
980                          : RegVTs[Value];
981 
982     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
983       ExtendKind = ISD::ZERO_EXTEND;
984 
985     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
986                    NumParts, RegisterVT, V, CallConv, ExtendKind);
987     Part += NumParts;
988   }
989 
990   // Copy the parts into the registers.
991   SmallVector<SDValue, 8> Chains(NumRegs);
992   for (unsigned i = 0; i != NumRegs; ++i) {
993     SDValue Part;
994     if (!Glue) {
995       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
996     } else {
997       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue);
998       *Glue = Part.getValue(1);
999     }
1000 
1001     Chains[i] = Part.getValue(0);
1002   }
1003 
1004   if (NumRegs == 1 || Glue)
1005     // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is
1006     // flagged to it. That is the CopyToReg nodes and the user are considered
1007     // a single scheduling unit. If we create a TokenFactor and return it as
1008     // chain, then the TokenFactor is both a predecessor (operand) of the
1009     // user as well as a successor (the TF operands are flagged to the user).
1010     // c1, f1 = CopyToReg
1011     // c2, f2 = CopyToReg
1012     // c3     = TokenFactor c1, c2
1013     // ...
1014     //        = op c3, ..., f2
1015     Chain = Chains[NumRegs-1];
1016   else
1017     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
1018 }
1019 
1020 void RegsForValue::AddInlineAsmOperands(InlineAsm::Kind Code, bool HasMatching,
1021                                         unsigned MatchingIdx, const SDLoc &dl,
1022                                         SelectionDAG &DAG,
1023                                         std::vector<SDValue> &Ops) const {
1024   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1025 
1026   InlineAsm::Flag Flag(Code, Regs.size());
1027   if (HasMatching)
1028     Flag.setMatchingOp(MatchingIdx);
1029   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
1030     // Put the register class of the virtual registers in the flag word.  That
1031     // way, later passes can recompute register class constraints for inline
1032     // assembly as well as normal instructions.
1033     // Don't do this for tied operands that can use the regclass information
1034     // from the def.
1035     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1036     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
1037     Flag.setRegClass(RC->getID());
1038   }
1039 
1040   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
1041   Ops.push_back(Res);
1042 
1043   if (Code == InlineAsm::Kind::Clobber) {
1044     // Clobbers should always have a 1:1 mapping with registers, and may
1045     // reference registers that have illegal (e.g. vector) types. Hence, we
1046     // shouldn't try to apply any sort of splitting logic to them.
1047     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
1048            "No 1:1 mapping from clobbers to regs?");
1049     Register SP = TLI.getStackPointerRegisterToSaveRestore();
1050     (void)SP;
1051     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
1052       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
1053       assert(
1054           (Regs[I] != SP ||
1055            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
1056           "If we clobbered the stack pointer, MFI should know about it.");
1057     }
1058     return;
1059   }
1060 
1061   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1062     MVT RegisterVT = RegVTs[Value];
1063     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
1064                                            RegisterVT);
1065     for (unsigned i = 0; i != NumRegs; ++i) {
1066       assert(Reg < Regs.size() && "Mismatch in # registers expected");
1067       unsigned TheReg = Regs[Reg++];
1068       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1069     }
1070   }
1071 }
1072 
1073 SmallVector<std::pair<Register, TypeSize>, 4>
1074 RegsForValue::getRegsAndSizes() const {
1075   SmallVector<std::pair<Register, TypeSize>, 4> OutVec;
1076   unsigned I = 0;
1077   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1078     unsigned RegCount = std::get<0>(CountAndVT);
1079     MVT RegisterVT = std::get<1>(CountAndVT);
1080     TypeSize RegisterSize = RegisterVT.getSizeInBits();
1081     for (unsigned E = I + RegCount; I != E; ++I)
1082       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1083   }
1084   return OutVec;
1085 }
1086 
1087 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1088                                AssumptionCache *ac,
1089                                const TargetLibraryInfo *li) {
1090   AA = aa;
1091   AC = ac;
1092   GFI = gfi;
1093   LibInfo = li;
1094   Context = DAG.getContext();
1095   LPadToCallSiteMap.clear();
1096   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1097   AssignmentTrackingEnabled = isAssignmentTrackingEnabled(
1098       *DAG.getMachineFunction().getFunction().getParent());
1099 }
1100 
1101 void SelectionDAGBuilder::clear() {
1102   NodeMap.clear();
1103   UnusedArgNodeMap.clear();
1104   PendingLoads.clear();
1105   PendingExports.clear();
1106   PendingConstrainedFP.clear();
1107   PendingConstrainedFPStrict.clear();
1108   CurInst = nullptr;
1109   HasTailCall = false;
1110   SDNodeOrder = LowestSDNodeOrder;
1111   StatepointLowering.clear();
1112 }
1113 
1114 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1115   DanglingDebugInfoMap.clear();
1116 }
1117 
1118 // Update DAG root to include dependencies on Pending chains.
1119 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1120   SDValue Root = DAG.getRoot();
1121 
1122   if (Pending.empty())
1123     return Root;
1124 
1125   // Add current root to PendingChains, unless we already indirectly
1126   // depend on it.
1127   if (Root.getOpcode() != ISD::EntryToken) {
1128     unsigned i = 0, e = Pending.size();
1129     for (; i != e; ++i) {
1130       assert(Pending[i].getNode()->getNumOperands() > 1);
1131       if (Pending[i].getNode()->getOperand(0) == Root)
1132         break;  // Don't add the root if we already indirectly depend on it.
1133     }
1134 
1135     if (i == e)
1136       Pending.push_back(Root);
1137   }
1138 
1139   if (Pending.size() == 1)
1140     Root = Pending[0];
1141   else
1142     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1143 
1144   DAG.setRoot(Root);
1145   Pending.clear();
1146   return Root;
1147 }
1148 
1149 SDValue SelectionDAGBuilder::getMemoryRoot() {
1150   return updateRoot(PendingLoads);
1151 }
1152 
1153 SDValue SelectionDAGBuilder::getRoot() {
1154   // Chain up all pending constrained intrinsics together with all
1155   // pending loads, by simply appending them to PendingLoads and
1156   // then calling getMemoryRoot().
1157   PendingLoads.reserve(PendingLoads.size() +
1158                        PendingConstrainedFP.size() +
1159                        PendingConstrainedFPStrict.size());
1160   PendingLoads.append(PendingConstrainedFP.begin(),
1161                       PendingConstrainedFP.end());
1162   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1163                       PendingConstrainedFPStrict.end());
1164   PendingConstrainedFP.clear();
1165   PendingConstrainedFPStrict.clear();
1166   return getMemoryRoot();
1167 }
1168 
1169 SDValue SelectionDAGBuilder::getControlRoot() {
1170   // We need to emit pending fpexcept.strict constrained intrinsics,
1171   // so append them to the PendingExports list.
1172   PendingExports.append(PendingConstrainedFPStrict.begin(),
1173                         PendingConstrainedFPStrict.end());
1174   PendingConstrainedFPStrict.clear();
1175   return updateRoot(PendingExports);
1176 }
1177 
1178 void SelectionDAGBuilder::handleDebugDeclare(Value *Address,
1179                                              DILocalVariable *Variable,
1180                                              DIExpression *Expression,
1181                                              DebugLoc DL) {
1182   assert(Variable && "Missing variable");
1183 
1184   // Check if address has undef value.
1185   if (!Address || isa<UndefValue>(Address) ||
1186       (Address->use_empty() && !isa<Argument>(Address))) {
1187     LLVM_DEBUG(
1188         dbgs()
1189         << "dbg_declare: Dropping debug info (bad/undef/unused-arg address)\n");
1190     return;
1191   }
1192 
1193   bool IsParameter = Variable->isParameter() || isa<Argument>(Address);
1194 
1195   SDValue &N = NodeMap[Address];
1196   if (!N.getNode() && isa<Argument>(Address))
1197     // Check unused arguments map.
1198     N = UnusedArgNodeMap[Address];
1199   SDDbgValue *SDV;
1200   if (N.getNode()) {
1201     if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
1202       Address = BCI->getOperand(0);
1203     // Parameters are handled specially.
1204     auto *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
1205     if (IsParameter && FINode) {
1206       // Byval parameter. We have a frame index at this point.
1207       SDV = DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
1208                                       /*IsIndirect*/ true, DL, SDNodeOrder);
1209     } else if (isa<Argument>(Address)) {
1210       // Address is an argument, so try to emit its dbg value using
1211       // virtual register info from the FuncInfo.ValueMap.
1212       EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1213                                FuncArgumentDbgValueKind::Declare, N);
1214       return;
1215     } else {
1216       SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
1217                             true, DL, SDNodeOrder);
1218     }
1219     DAG.AddDbgValue(SDV, IsParameter);
1220   } else {
1221     // If Address is an argument then try to emit its dbg value using
1222     // virtual register info from the FuncInfo.ValueMap.
1223     if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1224                                   FuncArgumentDbgValueKind::Declare, N)) {
1225       LLVM_DEBUG(dbgs() << "dbg_declare: Dropping debug info"
1226                         << " (could not emit func-arg dbg_value)\n");
1227     }
1228   }
1229   return;
1230 }
1231 
1232 void SelectionDAGBuilder::visitDbgInfo(const Instruction &I) {
1233   // Add SDDbgValue nodes for any var locs here. Do so before updating
1234   // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1235   if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) {
1236     // Add SDDbgValue nodes for any var locs here. Do so before updating
1237     // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1238     for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I);
1239          It != End; ++It) {
1240       auto *Var = FnVarLocs->getDILocalVariable(It->VariableID);
1241       dropDanglingDebugInfo(Var, It->Expr);
1242       if (It->Values.isKillLocation(It->Expr)) {
1243         handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder);
1244         continue;
1245       }
1246       SmallVector<Value *> Values(It->Values.location_ops());
1247       if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder,
1248                             It->Values.hasArgList())) {
1249         SmallVector<Value *, 4> Vals(It->Values.location_ops());
1250         addDanglingDebugInfo(Vals,
1251                              FnVarLocs->getDILocalVariable(It->VariableID),
1252                              It->Expr, Vals.size() > 1, It->DL, SDNodeOrder);
1253       }
1254     }
1255   }
1256 
1257   // We must skip DbgVariableRecords if they've already been processed above as
1258   // we have just emitted the debug values resulting from assignment tracking
1259   // analysis, making any existing DbgVariableRecords redundant (and probably
1260   // less correct). We still need to process DbgLabelRecords. This does sink
1261   // DbgLabelRecords to the bottom of the group of debug records. That sholdn't
1262   // be important as it does so deterministcally and ordering between
1263   // DbgLabelRecords and DbgVariableRecords is immaterial (other than for MIR/IR
1264   // printing).
1265   bool SkipDbgVariableRecords = DAG.getFunctionVarLocs();
1266   // Is there is any debug-info attached to this instruction, in the form of
1267   // DbgRecord non-instruction debug-info records.
1268   for (DbgRecord &DR : I.getDbgRecordRange()) {
1269     if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
1270       assert(DLR->getLabel() && "Missing label");
1271       SDDbgLabel *SDV =
1272           DAG.getDbgLabel(DLR->getLabel(), DLR->getDebugLoc(), SDNodeOrder);
1273       DAG.AddDbgLabel(SDV);
1274       continue;
1275     }
1276 
1277     if (SkipDbgVariableRecords)
1278       continue;
1279     DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR);
1280     DILocalVariable *Variable = DVR.getVariable();
1281     DIExpression *Expression = DVR.getExpression();
1282     dropDanglingDebugInfo(Variable, Expression);
1283 
1284     if (DVR.getType() == DbgVariableRecord::LocationType::Declare) {
1285       if (FuncInfo.PreprocessedDVRDeclares.contains(&DVR))
1286         continue;
1287       LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DVR
1288                         << "\n");
1289       handleDebugDeclare(DVR.getVariableLocationOp(0), Variable, Expression,
1290                          DVR.getDebugLoc());
1291       continue;
1292     }
1293 
1294     // A DbgVariableRecord with no locations is a kill location.
1295     SmallVector<Value *, 4> Values(DVR.location_ops());
1296     if (Values.empty()) {
1297       handleKillDebugValue(Variable, Expression, DVR.getDebugLoc(),
1298                            SDNodeOrder);
1299       continue;
1300     }
1301 
1302     // A DbgVariableRecord with an undef or absent location is also a kill
1303     // location.
1304     if (llvm::any_of(Values,
1305                      [](Value *V) { return !V || isa<UndefValue>(V); })) {
1306       handleKillDebugValue(Variable, Expression, DVR.getDebugLoc(),
1307                            SDNodeOrder);
1308       continue;
1309     }
1310 
1311     bool IsVariadic = DVR.hasArgList();
1312     if (!handleDebugValue(Values, Variable, Expression, DVR.getDebugLoc(),
1313                           SDNodeOrder, IsVariadic)) {
1314       addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
1315                            DVR.getDebugLoc(), SDNodeOrder);
1316     }
1317   }
1318 }
1319 
1320 void SelectionDAGBuilder::visit(const Instruction &I) {
1321   visitDbgInfo(I);
1322 
1323   // Set up outgoing PHI node register values before emitting the terminator.
1324   if (I.isTerminator()) {
1325     HandlePHINodesInSuccessorBlocks(I.getParent());
1326   }
1327 
1328   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1329   if (!isa<DbgInfoIntrinsic>(I))
1330     ++SDNodeOrder;
1331 
1332   CurInst = &I;
1333 
1334   // Set inserted listener only if required.
1335   bool NodeInserted = false;
1336   std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener;
1337   MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections);
1338   MDNode *MMRA = I.getMetadata(LLVMContext::MD_mmra);
1339   if (PCSectionsMD || MMRA) {
1340     InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>(
1341         DAG, [&](SDNode *) { NodeInserted = true; });
1342   }
1343 
1344   visit(I.getOpcode(), I);
1345 
1346   if (!I.isTerminator() && !HasTailCall &&
1347       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1348     CopyToExportRegsIfNeeded(&I);
1349 
1350   // Handle metadata.
1351   if (PCSectionsMD || MMRA) {
1352     auto It = NodeMap.find(&I);
1353     if (It != NodeMap.end()) {
1354       if (PCSectionsMD)
1355         DAG.addPCSections(It->second.getNode(), PCSectionsMD);
1356       if (MMRA)
1357         DAG.addMMRAMetadata(It->second.getNode(), MMRA);
1358     } else if (NodeInserted) {
1359       // This should not happen; if it does, don't let it go unnoticed so we can
1360       // fix it. Relevant visit*() function is probably missing a setValue().
1361       errs() << "warning: loosing !pcsections and/or !mmra metadata ["
1362              << I.getModule()->getName() << "]\n";
1363       LLVM_DEBUG(I.dump());
1364       assert(false);
1365     }
1366   }
1367 
1368   CurInst = nullptr;
1369 }
1370 
1371 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1372   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1373 }
1374 
1375 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1376   // Note: this doesn't use InstVisitor, because it has to work with
1377   // ConstantExpr's in addition to instructions.
1378   switch (Opcode) {
1379   default: llvm_unreachable("Unknown instruction type encountered!");
1380     // Build the switch statement using the Instruction.def file.
1381 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1382     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1383 #include "llvm/IR/Instruction.def"
1384   }
1385 }
1386 
1387 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG,
1388                                             DILocalVariable *Variable,
1389                                             DebugLoc DL, unsigned Order,
1390                                             SmallVectorImpl<Value *> &Values,
1391                                             DIExpression *Expression) {
1392   // For variadic dbg_values we will now insert an undef.
1393   // FIXME: We can potentially recover these!
1394   SmallVector<SDDbgOperand, 2> Locs;
1395   for (const Value *V : Values) {
1396     auto *Undef = UndefValue::get(V->getType());
1397     Locs.push_back(SDDbgOperand::fromConst(Undef));
1398   }
1399   SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {},
1400                                         /*IsIndirect=*/false, DL, Order,
1401                                         /*IsVariadic=*/true);
1402   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1403   return true;
1404 }
1405 
1406 void SelectionDAGBuilder::addDanglingDebugInfo(SmallVectorImpl<Value *> &Values,
1407                                                DILocalVariable *Var,
1408                                                DIExpression *Expr,
1409                                                bool IsVariadic, DebugLoc DL,
1410                                                unsigned Order) {
1411   if (IsVariadic) {
1412     handleDanglingVariadicDebugInfo(DAG, Var, DL, Order, Values, Expr);
1413     return;
1414   }
1415   // TODO: Dangling debug info will eventually either be resolved or produce
1416   // an Undef DBG_VALUE. However in the resolution case, a gap may appear
1417   // between the original dbg.value location and its resolved DBG_VALUE,
1418   // which we should ideally fill with an extra Undef DBG_VALUE.
1419   assert(Values.size() == 1);
1420   DanglingDebugInfoMap[Values[0]].emplace_back(Var, Expr, DL, Order);
1421 }
1422 
1423 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1424                                                 const DIExpression *Expr) {
1425   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1426     DIVariable *DanglingVariable = DDI.getVariable();
1427     DIExpression *DanglingExpr = DDI.getExpression();
1428     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1429       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for "
1430                         << printDDI(nullptr, DDI) << "\n");
1431       return true;
1432     }
1433     return false;
1434   };
1435 
1436   for (auto &DDIMI : DanglingDebugInfoMap) {
1437     DanglingDebugInfoVector &DDIV = DDIMI.second;
1438 
1439     // If debug info is to be dropped, run it through final checks to see
1440     // whether it can be salvaged.
1441     for (auto &DDI : DDIV)
1442       if (isMatchingDbgValue(DDI))
1443         salvageUnresolvedDbgValue(DDIMI.first, DDI);
1444 
1445     erase_if(DDIV, isMatchingDbgValue);
1446   }
1447 }
1448 
1449 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1450 // generate the debug data structures now that we've seen its definition.
1451 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1452                                                    SDValue Val) {
1453   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1454   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1455     return;
1456 
1457   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1458   for (auto &DDI : DDIV) {
1459     DebugLoc DL = DDI.getDebugLoc();
1460     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1461     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1462     DILocalVariable *Variable = DDI.getVariable();
1463     DIExpression *Expr = DDI.getExpression();
1464     assert(Variable->isValidLocationForIntrinsic(DL) &&
1465            "Expected inlined-at fields to agree");
1466     SDDbgValue *SDV;
1467     if (Val.getNode()) {
1468       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1469       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1470       // we couldn't resolve it directly when examining the DbgValue intrinsic
1471       // in the first place we should not be more successful here). Unless we
1472       // have some test case that prove this to be correct we should avoid
1473       // calling EmitFuncArgumentDbgValue here.
1474       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL,
1475                                     FuncArgumentDbgValueKind::Value, Val)) {
1476         LLVM_DEBUG(dbgs() << "Resolve dangling debug info for "
1477                           << printDDI(V, DDI) << "\n");
1478         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1479         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1480         // inserted after the definition of Val when emitting the instructions
1481         // after ISel. An alternative could be to teach
1482         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1483         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1484                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1485                    << ValSDNodeOrder << "\n");
1486         SDV = getDbgValue(Val, Variable, Expr, DL,
1487                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1488         DAG.AddDbgValue(SDV, false);
1489       } else
1490         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for "
1491                           << printDDI(V, DDI)
1492                           << " in EmitFuncArgumentDbgValue\n");
1493     } else {
1494       LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(V, DDI)
1495                         << "\n");
1496       auto Undef = UndefValue::get(V->getType());
1497       auto SDV =
1498           DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder);
1499       DAG.AddDbgValue(SDV, false);
1500     }
1501   }
1502   DDIV.clear();
1503 }
1504 
1505 void SelectionDAGBuilder::salvageUnresolvedDbgValue(const Value *V,
1506                                                     DanglingDebugInfo &DDI) {
1507   // TODO: For the variadic implementation, instead of only checking the fail
1508   // state of `handleDebugValue`, we need know specifically which values were
1509   // invalid, so that we attempt to salvage only those values when processing
1510   // a DIArgList.
1511   const Value *OrigV = V;
1512   DILocalVariable *Var = DDI.getVariable();
1513   DIExpression *Expr = DDI.getExpression();
1514   DebugLoc DL = DDI.getDebugLoc();
1515   unsigned SDOrder = DDI.getSDNodeOrder();
1516 
1517   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1518   // that DW_OP_stack_value is desired.
1519   bool StackValue = true;
1520 
1521   // Can this Value can be encoded without any further work?
1522   if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false))
1523     return;
1524 
1525   // Attempt to salvage back through as many instructions as possible. Bail if
1526   // a non-instruction is seen, such as a constant expression or global
1527   // variable. FIXME: Further work could recover those too.
1528   while (isa<Instruction>(V)) {
1529     const Instruction &VAsInst = *cast<const Instruction>(V);
1530     // Temporary "0", awaiting real implementation.
1531     SmallVector<uint64_t, 16> Ops;
1532     SmallVector<Value *, 4> AdditionalValues;
1533     V = salvageDebugInfoImpl(const_cast<Instruction &>(VAsInst),
1534                              Expr->getNumLocationOperands(), Ops,
1535                              AdditionalValues);
1536     // If we cannot salvage any further, and haven't yet found a suitable debug
1537     // expression, bail out.
1538     if (!V)
1539       break;
1540 
1541     // TODO: If AdditionalValues isn't empty, then the salvage can only be
1542     // represented with a DBG_VALUE_LIST, so we give up. When we have support
1543     // here for variadic dbg_values, remove that condition.
1544     if (!AdditionalValues.empty())
1545       break;
1546 
1547     // New value and expr now represent this debuginfo.
1548     Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue);
1549 
1550     // Some kind of simplification occurred: check whether the operand of the
1551     // salvaged debug expression can be encoded in this DAG.
1552     if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) {
1553       LLVM_DEBUG(
1554           dbgs() << "Salvaged debug location info for:\n  " << *Var << "\n"
1555                  << *OrigV << "\nBy stripping back to:\n  " << *V << "\n");
1556       return;
1557     }
1558   }
1559 
1560   // This was the final opportunity to salvage this debug information, and it
1561   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1562   // any earlier variable location.
1563   assert(OrigV && "V shouldn't be null");
1564   auto *Undef = UndefValue::get(OrigV->getType());
1565   auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1566   DAG.AddDbgValue(SDV, false);
1567   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  "
1568                     << printDDI(OrigV, DDI) << "\n");
1569 }
1570 
1571 void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var,
1572                                                DIExpression *Expr,
1573                                                DebugLoc DbgLoc,
1574                                                unsigned Order) {
1575   Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context));
1576   DIExpression *NewExpr =
1577       const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr));
1578   handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order,
1579                    /*IsVariadic*/ false);
1580 }
1581 
1582 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1583                                            DILocalVariable *Var,
1584                                            DIExpression *Expr, DebugLoc DbgLoc,
1585                                            unsigned Order, bool IsVariadic) {
1586   if (Values.empty())
1587     return true;
1588 
1589   // Filter EntryValue locations out early.
1590   if (visitEntryValueDbgValue(Values, Var, Expr, DbgLoc))
1591     return true;
1592 
1593   SmallVector<SDDbgOperand> LocationOps;
1594   SmallVector<SDNode *> Dependencies;
1595   for (const Value *V : Values) {
1596     // Constant value.
1597     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1598         isa<ConstantPointerNull>(V)) {
1599       LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1600       continue;
1601     }
1602 
1603     // Look through IntToPtr constants.
1604     if (auto *CE = dyn_cast<ConstantExpr>(V))
1605       if (CE->getOpcode() == Instruction::IntToPtr) {
1606         LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0)));
1607         continue;
1608       }
1609 
1610     // If the Value is a frame index, we can create a FrameIndex debug value
1611     // without relying on the DAG at all.
1612     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1613       auto SI = FuncInfo.StaticAllocaMap.find(AI);
1614       if (SI != FuncInfo.StaticAllocaMap.end()) {
1615         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1616         continue;
1617       }
1618     }
1619 
1620     // Do not use getValue() in here; we don't want to generate code at
1621     // this point if it hasn't been done yet.
1622     SDValue N = NodeMap[V];
1623     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1624       N = UnusedArgNodeMap[V];
1625 
1626     if (N.getNode()) {
1627       // Only emit func arg dbg value for non-variadic dbg.values for now.
1628       if (!IsVariadic &&
1629           EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc,
1630                                    FuncArgumentDbgValueKind::Value, N))
1631         return true;
1632       if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1633         // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1634         // describe stack slot locations.
1635         //
1636         // Consider "int x = 0; int *px = &x;". There are two kinds of
1637         // interesting debug values here after optimization:
1638         //
1639         //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
1640         //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1641         //
1642         // Both describe the direct values of their associated variables.
1643         Dependencies.push_back(N.getNode());
1644         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1645         continue;
1646       }
1647       LocationOps.emplace_back(
1648           SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1649       continue;
1650     }
1651 
1652     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1653     // Special rules apply for the first dbg.values of parameter variables in a
1654     // function. Identify them by the fact they reference Argument Values, that
1655     // they're parameters, and they are parameters of the current function. We
1656     // need to let them dangle until they get an SDNode.
1657     bool IsParamOfFunc =
1658         isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt();
1659     if (IsParamOfFunc)
1660       return false;
1661 
1662     // The value is not used in this block yet (or it would have an SDNode).
1663     // We still want the value to appear for the user if possible -- if it has
1664     // an associated VReg, we can refer to that instead.
1665     auto VMI = FuncInfo.ValueMap.find(V);
1666     if (VMI != FuncInfo.ValueMap.end()) {
1667       unsigned Reg = VMI->second;
1668       // If this is a PHI node, it may be split up into several MI PHI nodes
1669       // (in FunctionLoweringInfo::set).
1670       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1671                        V->getType(), std::nullopt);
1672       if (RFV.occupiesMultipleRegs()) {
1673         // FIXME: We could potentially support variadic dbg_values here.
1674         if (IsVariadic)
1675           return false;
1676         unsigned Offset = 0;
1677         unsigned BitsToDescribe = 0;
1678         if (auto VarSize = Var->getSizeInBits())
1679           BitsToDescribe = *VarSize;
1680         if (auto Fragment = Expr->getFragmentInfo())
1681           BitsToDescribe = Fragment->SizeInBits;
1682         for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1683           // Bail out if all bits are described already.
1684           if (Offset >= BitsToDescribe)
1685             break;
1686           // TODO: handle scalable vectors.
1687           unsigned RegisterSize = RegAndSize.second;
1688           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1689                                       ? BitsToDescribe - Offset
1690                                       : RegisterSize;
1691           auto FragmentExpr = DIExpression::createFragmentExpression(
1692               Expr, Offset, FragmentSize);
1693           if (!FragmentExpr)
1694             continue;
1695           SDDbgValue *SDV = DAG.getVRegDbgValue(
1696               Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, Order);
1697           DAG.AddDbgValue(SDV, false);
1698           Offset += RegisterSize;
1699         }
1700         return true;
1701       }
1702       // We can use simple vreg locations for variadic dbg_values as well.
1703       LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1704       continue;
1705     }
1706     // We failed to create a SDDbgOperand for V.
1707     return false;
1708   }
1709 
1710   // We have created a SDDbgOperand for each Value in Values.
1711   assert(!LocationOps.empty());
1712   SDDbgValue *SDV =
1713       DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1714                           /*IsIndirect=*/false, DbgLoc, Order, IsVariadic);
1715   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1716   return true;
1717 }
1718 
1719 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1720   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1721   for (auto &Pair : DanglingDebugInfoMap)
1722     for (auto &DDI : Pair.second)
1723       salvageUnresolvedDbgValue(const_cast<Value *>(Pair.first), DDI);
1724   clearDanglingDebugInfo();
1725 }
1726 
1727 /// getCopyFromRegs - If there was virtual register allocated for the value V
1728 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1729 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1730   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1731   SDValue Result;
1732 
1733   if (It != FuncInfo.ValueMap.end()) {
1734     Register InReg = It->second;
1735 
1736     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1737                      DAG.getDataLayout(), InReg, Ty,
1738                      std::nullopt); // This is not an ABI copy.
1739     SDValue Chain = DAG.getEntryNode();
1740     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1741                                  V);
1742     resolveDanglingDebugInfo(V, Result);
1743   }
1744 
1745   return Result;
1746 }
1747 
1748 /// getValue - Return an SDValue for the given Value.
1749 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1750   // If we already have an SDValue for this value, use it. It's important
1751   // to do this first, so that we don't create a CopyFromReg if we already
1752   // have a regular SDValue.
1753   SDValue &N = NodeMap[V];
1754   if (N.getNode()) return N;
1755 
1756   // If there's a virtual register allocated and initialized for this
1757   // value, use it.
1758   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1759     return copyFromReg;
1760 
1761   // Otherwise create a new SDValue and remember it.
1762   SDValue Val = getValueImpl(V);
1763   NodeMap[V] = Val;
1764   resolveDanglingDebugInfo(V, Val);
1765   return Val;
1766 }
1767 
1768 /// getNonRegisterValue - Return an SDValue for the given Value, but
1769 /// don't look in FuncInfo.ValueMap for a virtual register.
1770 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1771   // If we already have an SDValue for this value, use it.
1772   SDValue &N = NodeMap[V];
1773   if (N.getNode()) {
1774     if (isIntOrFPConstant(N)) {
1775       // Remove the debug location from the node as the node is about to be used
1776       // in a location which may differ from the original debug location.  This
1777       // is relevant to Constant and ConstantFP nodes because they can appear
1778       // as constant expressions inside PHI nodes.
1779       N->setDebugLoc(DebugLoc());
1780     }
1781     return N;
1782   }
1783 
1784   // Otherwise create a new SDValue and remember it.
1785   SDValue Val = getValueImpl(V);
1786   NodeMap[V] = Val;
1787   resolveDanglingDebugInfo(V, Val);
1788   return Val;
1789 }
1790 
1791 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1792 /// Create an SDValue for the given value.
1793 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1794   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1795 
1796   if (const Constant *C = dyn_cast<Constant>(V)) {
1797     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1798 
1799     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1800       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1801 
1802     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1803       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1804 
1805     if (const ConstantPtrAuth *CPA = dyn_cast<ConstantPtrAuth>(C)) {
1806       return DAG.getNode(ISD::PtrAuthGlobalAddress, getCurSDLoc(), VT,
1807                          getValue(CPA->getPointer()), getValue(CPA->getKey()),
1808                          getValue(CPA->getAddrDiscriminator()),
1809                          getValue(CPA->getDiscriminator()));
1810     }
1811 
1812     if (isa<ConstantPointerNull>(C)) {
1813       unsigned AS = V->getType()->getPointerAddressSpace();
1814       return DAG.getConstant(0, getCurSDLoc(),
1815                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1816     }
1817 
1818     if (match(C, m_VScale()))
1819       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1820 
1821     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1822       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1823 
1824     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1825       return DAG.getUNDEF(VT);
1826 
1827     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1828       visit(CE->getOpcode(), *CE);
1829       SDValue N1 = NodeMap[V];
1830       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1831       return N1;
1832     }
1833 
1834     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1835       SmallVector<SDValue, 4> Constants;
1836       for (const Use &U : C->operands()) {
1837         SDNode *Val = getValue(U).getNode();
1838         // If the operand is an empty aggregate, there are no values.
1839         if (!Val) continue;
1840         // Add each leaf value from the operand to the Constants list
1841         // to form a flattened list of all the values.
1842         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1843           Constants.push_back(SDValue(Val, i));
1844       }
1845 
1846       return DAG.getMergeValues(Constants, getCurSDLoc());
1847     }
1848 
1849     if (const ConstantDataSequential *CDS =
1850           dyn_cast<ConstantDataSequential>(C)) {
1851       SmallVector<SDValue, 4> Ops;
1852       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1853         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1854         // Add each leaf value from the operand to the Constants list
1855         // to form a flattened list of all the values.
1856         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1857           Ops.push_back(SDValue(Val, i));
1858       }
1859 
1860       if (isa<ArrayType>(CDS->getType()))
1861         return DAG.getMergeValues(Ops, getCurSDLoc());
1862       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1863     }
1864 
1865     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1866       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1867              "Unknown struct or array constant!");
1868 
1869       SmallVector<EVT, 4> ValueVTs;
1870       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1871       unsigned NumElts = ValueVTs.size();
1872       if (NumElts == 0)
1873         return SDValue(); // empty struct
1874       SmallVector<SDValue, 4> Constants(NumElts);
1875       for (unsigned i = 0; i != NumElts; ++i) {
1876         EVT EltVT = ValueVTs[i];
1877         if (isa<UndefValue>(C))
1878           Constants[i] = DAG.getUNDEF(EltVT);
1879         else if (EltVT.isFloatingPoint())
1880           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1881         else
1882           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1883       }
1884 
1885       return DAG.getMergeValues(Constants, getCurSDLoc());
1886     }
1887 
1888     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1889       return DAG.getBlockAddress(BA, VT);
1890 
1891     if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1892       return getValue(Equiv->getGlobalValue());
1893 
1894     if (const auto *NC = dyn_cast<NoCFIValue>(C))
1895       return getValue(NC->getGlobalValue());
1896 
1897     if (VT == MVT::aarch64svcount) {
1898       assert(C->isNullValue() && "Can only zero this target type!");
1899       return DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT,
1900                          DAG.getConstant(0, getCurSDLoc(), MVT::nxv16i1));
1901     }
1902 
1903     VectorType *VecTy = cast<VectorType>(V->getType());
1904 
1905     // Now that we know the number and type of the elements, get that number of
1906     // elements into the Ops array based on what kind of constant it is.
1907     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1908       SmallVector<SDValue, 16> Ops;
1909       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1910       for (unsigned i = 0; i != NumElements; ++i)
1911         Ops.push_back(getValue(CV->getOperand(i)));
1912 
1913       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1914     }
1915 
1916     if (isa<ConstantAggregateZero>(C)) {
1917       EVT EltVT =
1918           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1919 
1920       SDValue Op;
1921       if (EltVT.isFloatingPoint())
1922         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1923       else
1924         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1925 
1926       return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op);
1927     }
1928 
1929     llvm_unreachable("Unknown vector constant");
1930   }
1931 
1932   // If this is a static alloca, generate it as the frameindex instead of
1933   // computation.
1934   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1935     DenseMap<const AllocaInst*, int>::iterator SI =
1936       FuncInfo.StaticAllocaMap.find(AI);
1937     if (SI != FuncInfo.StaticAllocaMap.end())
1938       return DAG.getFrameIndex(
1939           SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType()));
1940   }
1941 
1942   // If this is an instruction which fast-isel has deferred, select it now.
1943   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1944     Register InReg = FuncInfo.InitializeRegForValue(Inst);
1945 
1946     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1947                      Inst->getType(), std::nullopt);
1948     SDValue Chain = DAG.getEntryNode();
1949     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1950   }
1951 
1952   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V))
1953     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1954 
1955   if (const auto *BB = dyn_cast<BasicBlock>(V))
1956     return DAG.getBasicBlock(FuncInfo.getMBB(BB));
1957 
1958   llvm_unreachable("Can't get register for value!");
1959 }
1960 
1961 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1962   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1963   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1964   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1965   bool IsSEH = isAsynchronousEHPersonality(Pers);
1966   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1967   if (!IsSEH)
1968     CatchPadMBB->setIsEHScopeEntry();
1969   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1970   if (IsMSVCCXX || IsCoreCLR)
1971     CatchPadMBB->setIsEHFuncletEntry();
1972 }
1973 
1974 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1975   // Update machine-CFG edge.
1976   MachineBasicBlock *TargetMBB = FuncInfo.getMBB(I.getSuccessor());
1977   FuncInfo.MBB->addSuccessor(TargetMBB);
1978   TargetMBB->setIsEHCatchretTarget(true);
1979   DAG.getMachineFunction().setHasEHCatchret(true);
1980 
1981   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1982   bool IsSEH = isAsynchronousEHPersonality(Pers);
1983   if (IsSEH) {
1984     // If this is not a fall-through branch or optimizations are switched off,
1985     // emit the branch.
1986     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1987         TM.getOptLevel() == CodeGenOptLevel::None)
1988       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1989                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1990     return;
1991   }
1992 
1993   // Figure out the funclet membership for the catchret's successor.
1994   // This will be used by the FuncletLayout pass to determine how to order the
1995   // BB's.
1996   // A 'catchret' returns to the outer scope's color.
1997   Value *ParentPad = I.getCatchSwitchParentPad();
1998   const BasicBlock *SuccessorColor;
1999   if (isa<ConstantTokenNone>(ParentPad))
2000     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
2001   else
2002     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
2003   assert(SuccessorColor && "No parent funclet for catchret!");
2004   MachineBasicBlock *SuccessorColorMBB = FuncInfo.getMBB(SuccessorColor);
2005   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
2006 
2007   // Create the terminator node.
2008   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
2009                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
2010                             DAG.getBasicBlock(SuccessorColorMBB));
2011   DAG.setRoot(Ret);
2012 }
2013 
2014 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
2015   // Don't emit any special code for the cleanuppad instruction. It just marks
2016   // the start of an EH scope/funclet.
2017   FuncInfo.MBB->setIsEHScopeEntry();
2018   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
2019   if (Pers != EHPersonality::Wasm_CXX) {
2020     FuncInfo.MBB->setIsEHFuncletEntry();
2021     FuncInfo.MBB->setIsCleanupFuncletEntry();
2022   }
2023 }
2024 
2025 // In wasm EH, even though a catchpad may not catch an exception if a tag does
2026 // not match, it is OK to add only the first unwind destination catchpad to the
2027 // successors, because there will be at least one invoke instruction within the
2028 // catch scope that points to the next unwind destination, if one exists, so
2029 // CFGSort cannot mess up with BB sorting order.
2030 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
2031 // call within them, and catchpads only consisting of 'catch (...)' have a
2032 // '__cxa_end_catch' call within them, both of which generate invokes in case
2033 // the next unwind destination exists, i.e., the next unwind destination is not
2034 // the caller.)
2035 //
2036 // Having at most one EH pad successor is also simpler and helps later
2037 // transformations.
2038 //
2039 // For example,
2040 // current:
2041 //   invoke void @foo to ... unwind label %catch.dispatch
2042 // catch.dispatch:
2043 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
2044 // catch.start:
2045 //   ...
2046 //   ... in this BB or some other child BB dominated by this BB there will be an
2047 //   invoke that points to 'next' BB as an unwind destination
2048 //
2049 // next: ; We don't need to add this to 'current' BB's successor
2050 //   ...
2051 static void findWasmUnwindDestinations(
2052     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2053     BranchProbability Prob,
2054     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2055         &UnwindDests) {
2056   while (EHPadBB) {
2057     const Instruction *Pad = EHPadBB->getFirstNonPHI();
2058     if (isa<CleanupPadInst>(Pad)) {
2059       // Stop on cleanup pads.
2060       UnwindDests.emplace_back(FuncInfo.getMBB(EHPadBB), Prob);
2061       UnwindDests.back().first->setIsEHScopeEntry();
2062       break;
2063     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
2064       // Add the catchpad handlers to the possible destinations. We don't
2065       // continue to the unwind destination of the catchswitch for wasm.
2066       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2067         UnwindDests.emplace_back(FuncInfo.getMBB(CatchPadBB), Prob);
2068         UnwindDests.back().first->setIsEHScopeEntry();
2069       }
2070       break;
2071     } else {
2072       continue;
2073     }
2074   }
2075 }
2076 
2077 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
2078 /// many places it could ultimately go. In the IR, we have a single unwind
2079 /// destination, but in the machine CFG, we enumerate all the possible blocks.
2080 /// This function skips over imaginary basic blocks that hold catchswitch
2081 /// instructions, and finds all the "real" machine
2082 /// basic block destinations. As those destinations may not be successors of
2083 /// EHPadBB, here we also calculate the edge probability to those destinations.
2084 /// The passed-in Prob is the edge probability to EHPadBB.
2085 static void findUnwindDestinations(
2086     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2087     BranchProbability Prob,
2088     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2089         &UnwindDests) {
2090   EHPersonality Personality =
2091     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
2092   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
2093   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
2094   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
2095   bool IsSEH = isAsynchronousEHPersonality(Personality);
2096 
2097   if (IsWasmCXX) {
2098     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
2099     assert(UnwindDests.size() <= 1 &&
2100            "There should be at most one unwind destination for wasm");
2101     return;
2102   }
2103 
2104   while (EHPadBB) {
2105     const Instruction *Pad = EHPadBB->getFirstNonPHI();
2106     BasicBlock *NewEHPadBB = nullptr;
2107     if (isa<LandingPadInst>(Pad)) {
2108       // Stop on landingpads. They are not funclets.
2109       UnwindDests.emplace_back(FuncInfo.getMBB(EHPadBB), Prob);
2110       break;
2111     } else if (isa<CleanupPadInst>(Pad)) {
2112       // Stop on cleanup pads. Cleanups are always funclet entries for all known
2113       // personalities.
2114       UnwindDests.emplace_back(FuncInfo.getMBB(EHPadBB), Prob);
2115       UnwindDests.back().first->setIsEHScopeEntry();
2116       UnwindDests.back().first->setIsEHFuncletEntry();
2117       break;
2118     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
2119       // Add the catchpad handlers to the possible destinations.
2120       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2121         UnwindDests.emplace_back(FuncInfo.getMBB(CatchPadBB), Prob);
2122         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
2123         if (IsMSVCCXX || IsCoreCLR)
2124           UnwindDests.back().first->setIsEHFuncletEntry();
2125         if (!IsSEH)
2126           UnwindDests.back().first->setIsEHScopeEntry();
2127       }
2128       NewEHPadBB = CatchSwitch->getUnwindDest();
2129     } else {
2130       continue;
2131     }
2132 
2133     BranchProbabilityInfo *BPI = FuncInfo.BPI;
2134     if (BPI && NewEHPadBB)
2135       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
2136     EHPadBB = NewEHPadBB;
2137   }
2138 }
2139 
2140 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
2141   // Update successor info.
2142   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2143   auto UnwindDest = I.getUnwindDest();
2144   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2145   BranchProbability UnwindDestProb =
2146       (BPI && UnwindDest)
2147           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
2148           : BranchProbability::getZero();
2149   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
2150   for (auto &UnwindDest : UnwindDests) {
2151     UnwindDest.first->setIsEHPad();
2152     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
2153   }
2154   FuncInfo.MBB->normalizeSuccProbs();
2155 
2156   // Create the terminator node.
2157   SDValue Ret =
2158       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
2159   DAG.setRoot(Ret);
2160 }
2161 
2162 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
2163   report_fatal_error("visitCatchSwitch not yet implemented!");
2164 }
2165 
2166 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
2167   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2168   auto &DL = DAG.getDataLayout();
2169   SDValue Chain = getControlRoot();
2170   SmallVector<ISD::OutputArg, 8> Outs;
2171   SmallVector<SDValue, 8> OutVals;
2172 
2173   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
2174   // lower
2175   //
2176   //   %val = call <ty> @llvm.experimental.deoptimize()
2177   //   ret <ty> %val
2178   //
2179   // differently.
2180   if (I.getParent()->getTerminatingDeoptimizeCall()) {
2181     LowerDeoptimizingReturn();
2182     return;
2183   }
2184 
2185   if (!FuncInfo.CanLowerReturn) {
2186     Register DemoteReg = FuncInfo.DemoteRegister;
2187     const Function *F = I.getParent()->getParent();
2188 
2189     // Emit a store of the return value through the virtual register.
2190     // Leave Outs empty so that LowerReturn won't try to load return
2191     // registers the usual way.
2192     SmallVector<EVT, 1> PtrValueVTs;
2193     ComputeValueVTs(TLI, DL,
2194                     PointerType::get(F->getContext(),
2195                                      DAG.getDataLayout().getAllocaAddrSpace()),
2196                     PtrValueVTs);
2197 
2198     SDValue RetPtr =
2199         DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]);
2200     SDValue RetOp = getValue(I.getOperand(0));
2201 
2202     SmallVector<EVT, 4> ValueVTs, MemVTs;
2203     SmallVector<uint64_t, 4> Offsets;
2204     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
2205                     &Offsets, 0);
2206     unsigned NumValues = ValueVTs.size();
2207 
2208     SmallVector<SDValue, 4> Chains(NumValues);
2209     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
2210     for (unsigned i = 0; i != NumValues; ++i) {
2211       // An aggregate return value cannot wrap around the address space, so
2212       // offsets to its parts don't wrap either.
2213       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
2214                                            TypeSize::getFixed(Offsets[i]));
2215 
2216       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
2217       if (MemVTs[i] != ValueVTs[i])
2218         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
2219       Chains[i] = DAG.getStore(
2220           Chain, getCurSDLoc(), Val,
2221           // FIXME: better loc info would be nice.
2222           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
2223           commonAlignment(BaseAlign, Offsets[i]));
2224     }
2225 
2226     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
2227                         MVT::Other, Chains);
2228   } else if (I.getNumOperands() != 0) {
2229     SmallVector<EVT, 4> ValueVTs;
2230     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
2231     unsigned NumValues = ValueVTs.size();
2232     if (NumValues) {
2233       SDValue RetOp = getValue(I.getOperand(0));
2234 
2235       const Function *F = I.getParent()->getParent();
2236 
2237       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
2238           I.getOperand(0)->getType(), F->getCallingConv(),
2239           /*IsVarArg*/ false, DL);
2240 
2241       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
2242       if (F->getAttributes().hasRetAttr(Attribute::SExt))
2243         ExtendKind = ISD::SIGN_EXTEND;
2244       else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
2245         ExtendKind = ISD::ZERO_EXTEND;
2246 
2247       LLVMContext &Context = F->getContext();
2248       bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
2249 
2250       for (unsigned j = 0; j != NumValues; ++j) {
2251         EVT VT = ValueVTs[j];
2252 
2253         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2254           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
2255 
2256         CallingConv::ID CC = F->getCallingConv();
2257 
2258         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
2259         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2260         SmallVector<SDValue, 4> Parts(NumParts);
2261         getCopyToParts(DAG, getCurSDLoc(),
2262                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2263                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
2264 
2265         // 'inreg' on function refers to return value
2266         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2267         if (RetInReg)
2268           Flags.setInReg();
2269 
2270         if (I.getOperand(0)->getType()->isPointerTy()) {
2271           Flags.setPointer();
2272           Flags.setPointerAddrSpace(
2273               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2274         }
2275 
2276         if (NeedsRegBlock) {
2277           Flags.setInConsecutiveRegs();
2278           if (j == NumValues - 1)
2279             Flags.setInConsecutiveRegsLast();
2280         }
2281 
2282         // Propagate extension type if any
2283         if (ExtendKind == ISD::SIGN_EXTEND)
2284           Flags.setSExt();
2285         else if (ExtendKind == ISD::ZERO_EXTEND)
2286           Flags.setZExt();
2287         else if (F->getAttributes().hasRetAttr(Attribute::NoExt))
2288           Flags.setNoExt();
2289 
2290         for (unsigned i = 0; i < NumParts; ++i) {
2291           Outs.push_back(ISD::OutputArg(Flags,
2292                                         Parts[i].getValueType().getSimpleVT(),
2293                                         VT, /*isfixed=*/true, 0, 0));
2294           OutVals.push_back(Parts[i]);
2295         }
2296       }
2297     }
2298   }
2299 
2300   // Push in swifterror virtual register as the last element of Outs. This makes
2301   // sure swifterror virtual register will be returned in the swifterror
2302   // physical register.
2303   const Function *F = I.getParent()->getParent();
2304   if (TLI.supportSwiftError() &&
2305       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2306     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2307     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2308     Flags.setSwiftError();
2309     Outs.push_back(ISD::OutputArg(
2310         Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
2311         /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
2312     // Create SDNode for the swifterror virtual register.
2313     OutVals.push_back(
2314         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2315                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2316                         EVT(TLI.getPointerTy(DL))));
2317   }
2318 
2319   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2320   CallingConv::ID CallConv =
2321     DAG.getMachineFunction().getFunction().getCallingConv();
2322   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2323       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2324 
2325   // Verify that the target's LowerReturn behaved as expected.
2326   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2327          "LowerReturn didn't return a valid chain!");
2328 
2329   // Update the DAG with the new chain value resulting from return lowering.
2330   DAG.setRoot(Chain);
2331 }
2332 
2333 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2334 /// created for it, emit nodes to copy the value into the virtual
2335 /// registers.
2336 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2337   // Skip empty types
2338   if (V->getType()->isEmptyTy())
2339     return;
2340 
2341   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2342   if (VMI != FuncInfo.ValueMap.end()) {
2343     assert((!V->use_empty() || isa<CallBrInst>(V)) &&
2344            "Unused value assigned virtual registers!");
2345     CopyValueToVirtualRegister(V, VMI->second);
2346   }
2347 }
2348 
2349 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2350 /// the current basic block, add it to ValueMap now so that we'll get a
2351 /// CopyTo/FromReg.
2352 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2353   // No need to export constants.
2354   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2355 
2356   // Already exported?
2357   if (FuncInfo.isExportedInst(V)) return;
2358 
2359   Register Reg = FuncInfo.InitializeRegForValue(V);
2360   CopyValueToVirtualRegister(V, Reg);
2361 }
2362 
2363 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2364                                                      const BasicBlock *FromBB) {
2365   // The operands of the setcc have to be in this block.  We don't know
2366   // how to export them from some other block.
2367   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2368     // Can export from current BB.
2369     if (VI->getParent() == FromBB)
2370       return true;
2371 
2372     // Is already exported, noop.
2373     return FuncInfo.isExportedInst(V);
2374   }
2375 
2376   // If this is an argument, we can export it if the BB is the entry block or
2377   // if it is already exported.
2378   if (isa<Argument>(V)) {
2379     if (FromBB->isEntryBlock())
2380       return true;
2381 
2382     // Otherwise, can only export this if it is already exported.
2383     return FuncInfo.isExportedInst(V);
2384   }
2385 
2386   // Otherwise, constants can always be exported.
2387   return true;
2388 }
2389 
2390 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2391 BranchProbability
2392 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2393                                         const MachineBasicBlock *Dst) const {
2394   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2395   const BasicBlock *SrcBB = Src->getBasicBlock();
2396   const BasicBlock *DstBB = Dst->getBasicBlock();
2397   if (!BPI) {
2398     // If BPI is not available, set the default probability as 1 / N, where N is
2399     // the number of successors.
2400     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2401     return BranchProbability(1, SuccSize);
2402   }
2403   return BPI->getEdgeProbability(SrcBB, DstBB);
2404 }
2405 
2406 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2407                                                MachineBasicBlock *Dst,
2408                                                BranchProbability Prob) {
2409   if (!FuncInfo.BPI)
2410     Src->addSuccessorWithoutProb(Dst);
2411   else {
2412     if (Prob.isUnknown())
2413       Prob = getEdgeProbability(Src, Dst);
2414     Src->addSuccessor(Dst, Prob);
2415   }
2416 }
2417 
2418 static bool InBlock(const Value *V, const BasicBlock *BB) {
2419   if (const Instruction *I = dyn_cast<Instruction>(V))
2420     return I->getParent() == BB;
2421   return true;
2422 }
2423 
2424 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2425 /// This function emits a branch and is used at the leaves of an OR or an
2426 /// AND operator tree.
2427 void
2428 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2429                                                   MachineBasicBlock *TBB,
2430                                                   MachineBasicBlock *FBB,
2431                                                   MachineBasicBlock *CurBB,
2432                                                   MachineBasicBlock *SwitchBB,
2433                                                   BranchProbability TProb,
2434                                                   BranchProbability FProb,
2435                                                   bool InvertCond) {
2436   const BasicBlock *BB = CurBB->getBasicBlock();
2437 
2438   // If the leaf of the tree is a comparison, merge the condition into
2439   // the caseblock.
2440   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2441     // The operands of the cmp have to be in this block.  We don't know
2442     // how to export them from some other block.  If this is the first block
2443     // of the sequence, no exporting is needed.
2444     if (CurBB == SwitchBB ||
2445         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2446          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2447       ISD::CondCode Condition;
2448       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2449         ICmpInst::Predicate Pred =
2450             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2451         Condition = getICmpCondCode(Pred);
2452       } else {
2453         const FCmpInst *FC = cast<FCmpInst>(Cond);
2454         FCmpInst::Predicate Pred =
2455             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2456         Condition = getFCmpCondCode(Pred);
2457         if (TM.Options.NoNaNsFPMath)
2458           Condition = getFCmpCodeWithoutNaN(Condition);
2459       }
2460 
2461       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2462                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2463       SL->SwitchCases.push_back(CB);
2464       return;
2465     }
2466   }
2467 
2468   // Create a CaseBlock record representing this branch.
2469   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2470   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2471                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2472   SL->SwitchCases.push_back(CB);
2473 }
2474 
2475 // Collect dependencies on V recursively. This is used for the cost analysis in
2476 // `shouldKeepJumpConditionsTogether`.
2477 static bool collectInstructionDeps(
2478     SmallMapVector<const Instruction *, bool, 8> *Deps, const Value *V,
2479     SmallMapVector<const Instruction *, bool, 8> *Necessary = nullptr,
2480     unsigned Depth = 0) {
2481   // Return false if we have an incomplete count.
2482   if (Depth >= SelectionDAG::MaxRecursionDepth)
2483     return false;
2484 
2485   auto *I = dyn_cast<Instruction>(V);
2486   if (I == nullptr)
2487     return true;
2488 
2489   if (Necessary != nullptr) {
2490     // This instruction is necessary for the other side of the condition so
2491     // don't count it.
2492     if (Necessary->contains(I))
2493       return true;
2494   }
2495 
2496   // Already added this dep.
2497   if (!Deps->try_emplace(I, false).second)
2498     return true;
2499 
2500   for (unsigned OpIdx = 0, E = I->getNumOperands(); OpIdx < E; ++OpIdx)
2501     if (!collectInstructionDeps(Deps, I->getOperand(OpIdx), Necessary,
2502                                 Depth + 1))
2503       return false;
2504   return true;
2505 }
2506 
2507 bool SelectionDAGBuilder::shouldKeepJumpConditionsTogether(
2508     const FunctionLoweringInfo &FuncInfo, const BranchInst &I,
2509     Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs,
2510     TargetLoweringBase::CondMergingParams Params) const {
2511   if (I.getNumSuccessors() != 2)
2512     return false;
2513 
2514   if (!I.isConditional())
2515     return false;
2516 
2517   if (Params.BaseCost < 0)
2518     return false;
2519 
2520   // Baseline cost.
2521   InstructionCost CostThresh = Params.BaseCost;
2522 
2523   BranchProbabilityInfo *BPI = nullptr;
2524   if (Params.LikelyBias || Params.UnlikelyBias)
2525     BPI = FuncInfo.BPI;
2526   if (BPI != nullptr) {
2527     // See if we are either likely to get an early out or compute both lhs/rhs
2528     // of the condition.
2529     BasicBlock *IfFalse = I.getSuccessor(0);
2530     BasicBlock *IfTrue = I.getSuccessor(1);
2531 
2532     std::optional<bool> Likely;
2533     if (BPI->isEdgeHot(I.getParent(), IfTrue))
2534       Likely = true;
2535     else if (BPI->isEdgeHot(I.getParent(), IfFalse))
2536       Likely = false;
2537 
2538     if (Likely) {
2539       if (Opc == (*Likely ? Instruction::And : Instruction::Or))
2540         // Its likely we will have to compute both lhs and rhs of condition
2541         CostThresh += Params.LikelyBias;
2542       else {
2543         if (Params.UnlikelyBias < 0)
2544           return false;
2545         // Its likely we will get an early out.
2546         CostThresh -= Params.UnlikelyBias;
2547       }
2548     }
2549   }
2550 
2551   if (CostThresh <= 0)
2552     return false;
2553 
2554   // Collect "all" instructions that lhs condition is dependent on.
2555   // Use map for stable iteration (to avoid non-determanism of iteration of
2556   // SmallPtrSet). The `bool` value is just a dummy.
2557   SmallMapVector<const Instruction *, bool, 8> LhsDeps, RhsDeps;
2558   collectInstructionDeps(&LhsDeps, Lhs);
2559   // Collect "all" instructions that rhs condition is dependent on AND are
2560   // dependencies of lhs. This gives us an estimate on which instructions we
2561   // stand to save by splitting the condition.
2562   if (!collectInstructionDeps(&RhsDeps, Rhs, &LhsDeps))
2563     return false;
2564   // Add the compare instruction itself unless its a dependency on the LHS.
2565   if (const auto *RhsI = dyn_cast<Instruction>(Rhs))
2566     if (!LhsDeps.contains(RhsI))
2567       RhsDeps.try_emplace(RhsI, false);
2568 
2569   const auto &TLI = DAG.getTargetLoweringInfo();
2570   const auto &TTI =
2571       TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction());
2572 
2573   InstructionCost CostOfIncluding = 0;
2574   // See if this instruction will need to computed independently of whether RHS
2575   // is.
2576   Value *BrCond = I.getCondition();
2577   auto ShouldCountInsn = [&RhsDeps, &BrCond](const Instruction *Ins) {
2578     for (const auto *U : Ins->users()) {
2579       // If user is independent of RHS calculation we don't need to count it.
2580       if (auto *UIns = dyn_cast<Instruction>(U))
2581         if (UIns != BrCond && !RhsDeps.contains(UIns))
2582           return false;
2583     }
2584     return true;
2585   };
2586 
2587   // Prune instructions from RHS Deps that are dependencies of unrelated
2588   // instructions. The value (SelectionDAG::MaxRecursionDepth) is fairly
2589   // arbitrary and just meant to cap the how much time we spend in the pruning
2590   // loop. Its highly unlikely to come into affect.
2591   const unsigned MaxPruneIters = SelectionDAG::MaxRecursionDepth;
2592   // Stop after a certain point. No incorrectness from including too many
2593   // instructions.
2594   for (unsigned PruneIters = 0; PruneIters < MaxPruneIters; ++PruneIters) {
2595     const Instruction *ToDrop = nullptr;
2596     for (const auto &InsPair : RhsDeps) {
2597       if (!ShouldCountInsn(InsPair.first)) {
2598         ToDrop = InsPair.first;
2599         break;
2600       }
2601     }
2602     if (ToDrop == nullptr)
2603       break;
2604     RhsDeps.erase(ToDrop);
2605   }
2606 
2607   for (const auto &InsPair : RhsDeps) {
2608     // Finally accumulate latency that we can only attribute to computing the
2609     // RHS condition. Use latency because we are essentially trying to calculate
2610     // the cost of the dependency chain.
2611     // Possible TODO: We could try to estimate ILP and make this more precise.
2612     CostOfIncluding +=
2613         TTI.getInstructionCost(InsPair.first, TargetTransformInfo::TCK_Latency);
2614 
2615     if (CostOfIncluding > CostThresh)
2616       return false;
2617   }
2618   return true;
2619 }
2620 
2621 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2622                                                MachineBasicBlock *TBB,
2623                                                MachineBasicBlock *FBB,
2624                                                MachineBasicBlock *CurBB,
2625                                                MachineBasicBlock *SwitchBB,
2626                                                Instruction::BinaryOps Opc,
2627                                                BranchProbability TProb,
2628                                                BranchProbability FProb,
2629                                                bool InvertCond) {
2630   // Skip over not part of the tree and remember to invert op and operands at
2631   // next level.
2632   Value *NotCond;
2633   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2634       InBlock(NotCond, CurBB->getBasicBlock())) {
2635     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2636                          !InvertCond);
2637     return;
2638   }
2639 
2640   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2641   const Value *BOpOp0, *BOpOp1;
2642   // Compute the effective opcode for Cond, taking into account whether it needs
2643   // to be inverted, e.g.
2644   //   and (not (or A, B)), C
2645   // gets lowered as
2646   //   and (and (not A, not B), C)
2647   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2648   if (BOp) {
2649     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2650                ? Instruction::And
2651                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2652                       ? Instruction::Or
2653                       : (Instruction::BinaryOps)0);
2654     if (InvertCond) {
2655       if (BOpc == Instruction::And)
2656         BOpc = Instruction::Or;
2657       else if (BOpc == Instruction::Or)
2658         BOpc = Instruction::And;
2659     }
2660   }
2661 
2662   // If this node is not part of the or/and tree, emit it as a branch.
2663   // Note that all nodes in the tree should have same opcode.
2664   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2665   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2666       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2667       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2668     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2669                                  TProb, FProb, InvertCond);
2670     return;
2671   }
2672 
2673   //  Create TmpBB after CurBB.
2674   MachineFunction::iterator BBI(CurBB);
2675   MachineFunction &MF = DAG.getMachineFunction();
2676   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2677   CurBB->getParent()->insert(++BBI, TmpBB);
2678 
2679   if (Opc == Instruction::Or) {
2680     // Codegen X | Y as:
2681     // BB1:
2682     //   jmp_if_X TBB
2683     //   jmp TmpBB
2684     // TmpBB:
2685     //   jmp_if_Y TBB
2686     //   jmp FBB
2687     //
2688 
2689     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2690     // The requirement is that
2691     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2692     //     = TrueProb for original BB.
2693     // Assuming the original probabilities are A and B, one choice is to set
2694     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2695     // A/(1+B) and 2B/(1+B). This choice assumes that
2696     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2697     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2698     // TmpBB, but the math is more complicated.
2699 
2700     auto NewTrueProb = TProb / 2;
2701     auto NewFalseProb = TProb / 2 + FProb;
2702     // Emit the LHS condition.
2703     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2704                          NewFalseProb, InvertCond);
2705 
2706     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2707     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2708     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2709     // Emit the RHS condition into TmpBB.
2710     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2711                          Probs[1], InvertCond);
2712   } else {
2713     assert(Opc == Instruction::And && "Unknown merge op!");
2714     // Codegen X & Y as:
2715     // BB1:
2716     //   jmp_if_X TmpBB
2717     //   jmp FBB
2718     // TmpBB:
2719     //   jmp_if_Y TBB
2720     //   jmp FBB
2721     //
2722     //  This requires creation of TmpBB after CurBB.
2723 
2724     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2725     // The requirement is that
2726     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2727     //     = FalseProb for original BB.
2728     // Assuming the original probabilities are A and B, one choice is to set
2729     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2730     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2731     // TrueProb for BB1 * FalseProb for TmpBB.
2732 
2733     auto NewTrueProb = TProb + FProb / 2;
2734     auto NewFalseProb = FProb / 2;
2735     // Emit the LHS condition.
2736     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2737                          NewFalseProb, InvertCond);
2738 
2739     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2740     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2741     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2742     // Emit the RHS condition into TmpBB.
2743     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2744                          Probs[1], InvertCond);
2745   }
2746 }
2747 
2748 /// If the set of cases should be emitted as a series of branches, return true.
2749 /// If we should emit this as a bunch of and/or'd together conditions, return
2750 /// false.
2751 bool
2752 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2753   if (Cases.size() != 2) return true;
2754 
2755   // If this is two comparisons of the same values or'd or and'd together, they
2756   // will get folded into a single comparison, so don't emit two blocks.
2757   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2758        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2759       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2760        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2761     return false;
2762   }
2763 
2764   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2765   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2766   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2767       Cases[0].CC == Cases[1].CC &&
2768       isa<Constant>(Cases[0].CmpRHS) &&
2769       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2770     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2771       return false;
2772     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2773       return false;
2774   }
2775 
2776   return true;
2777 }
2778 
2779 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2780   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2781 
2782   // Update machine-CFG edges.
2783   MachineBasicBlock *Succ0MBB = FuncInfo.getMBB(I.getSuccessor(0));
2784 
2785   if (I.isUnconditional()) {
2786     // Update machine-CFG edges.
2787     BrMBB->addSuccessor(Succ0MBB);
2788 
2789     // If this is not a fall-through branch or optimizations are switched off,
2790     // emit the branch.
2791     if (Succ0MBB != NextBlock(BrMBB) ||
2792         TM.getOptLevel() == CodeGenOptLevel::None) {
2793       auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
2794                             getControlRoot(), DAG.getBasicBlock(Succ0MBB));
2795       setValue(&I, Br);
2796       DAG.setRoot(Br);
2797     }
2798 
2799     return;
2800   }
2801 
2802   // If this condition is one of the special cases we handle, do special stuff
2803   // now.
2804   const Value *CondVal = I.getCondition();
2805   MachineBasicBlock *Succ1MBB = FuncInfo.getMBB(I.getSuccessor(1));
2806 
2807   // If this is a series of conditions that are or'd or and'd together, emit
2808   // this as a sequence of branches instead of setcc's with and/or operations.
2809   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2810   // unpredictable branches, and vector extracts because those jumps are likely
2811   // expensive for any target), this should improve performance.
2812   // For example, instead of something like:
2813   //     cmp A, B
2814   //     C = seteq
2815   //     cmp D, E
2816   //     F = setle
2817   //     or C, F
2818   //     jnz foo
2819   // Emit:
2820   //     cmp A, B
2821   //     je foo
2822   //     cmp D, E
2823   //     jle foo
2824   bool IsUnpredictable = I.hasMetadata(LLVMContext::MD_unpredictable);
2825   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2826   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2827       BOp->hasOneUse() && !IsUnpredictable) {
2828     Value *Vec;
2829     const Value *BOp0, *BOp1;
2830     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2831     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2832       Opcode = Instruction::And;
2833     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2834       Opcode = Instruction::Or;
2835 
2836     if (Opcode &&
2837         !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2838           match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value()))) &&
2839         !shouldKeepJumpConditionsTogether(
2840             FuncInfo, I, Opcode, BOp0, BOp1,
2841             DAG.getTargetLoweringInfo().getJumpConditionMergingParams(
2842                 Opcode, BOp0, BOp1))) {
2843       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2844                            getEdgeProbability(BrMBB, Succ0MBB),
2845                            getEdgeProbability(BrMBB, Succ1MBB),
2846                            /*InvertCond=*/false);
2847       // If the compares in later blocks need to use values not currently
2848       // exported from this block, export them now.  This block should always
2849       // be the first entry.
2850       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2851 
2852       // Allow some cases to be rejected.
2853       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2854         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2855           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2856           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2857         }
2858 
2859         // Emit the branch for this block.
2860         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2861         SL->SwitchCases.erase(SL->SwitchCases.begin());
2862         return;
2863       }
2864 
2865       // Okay, we decided not to do this, remove any inserted MBB's and clear
2866       // SwitchCases.
2867       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2868         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2869 
2870       SL->SwitchCases.clear();
2871     }
2872   }
2873 
2874   // Create a CaseBlock record representing this branch.
2875   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2876                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc(),
2877                BranchProbability::getUnknown(), BranchProbability::getUnknown(),
2878                IsUnpredictable);
2879 
2880   // Use visitSwitchCase to actually insert the fast branch sequence for this
2881   // cond branch.
2882   visitSwitchCase(CB, BrMBB);
2883 }
2884 
2885 /// visitSwitchCase - Emits the necessary code to represent a single node in
2886 /// the binary search tree resulting from lowering a switch instruction.
2887 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2888                                           MachineBasicBlock *SwitchBB) {
2889   SDValue Cond;
2890   SDValue CondLHS = getValue(CB.CmpLHS);
2891   SDLoc dl = CB.DL;
2892 
2893   if (CB.CC == ISD::SETTRUE) {
2894     // Branch or fall through to TrueBB.
2895     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2896     SwitchBB->normalizeSuccProbs();
2897     if (CB.TrueBB != NextBlock(SwitchBB)) {
2898       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2899                               DAG.getBasicBlock(CB.TrueBB)));
2900     }
2901     return;
2902   }
2903 
2904   auto &TLI = DAG.getTargetLoweringInfo();
2905   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2906 
2907   // Build the setcc now.
2908   if (!CB.CmpMHS) {
2909     // Fold "(X == true)" to X and "(X == false)" to !X to
2910     // handle common cases produced by branch lowering.
2911     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2912         CB.CC == ISD::SETEQ)
2913       Cond = CondLHS;
2914     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2915              CB.CC == ISD::SETEQ) {
2916       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2917       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2918     } else {
2919       SDValue CondRHS = getValue(CB.CmpRHS);
2920 
2921       // If a pointer's DAG type is larger than its memory type then the DAG
2922       // values are zero-extended. This breaks signed comparisons so truncate
2923       // back to the underlying type before doing the compare.
2924       if (CondLHS.getValueType() != MemVT) {
2925         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2926         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2927       }
2928       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2929     }
2930   } else {
2931     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2932 
2933     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2934     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2935 
2936     SDValue CmpOp = getValue(CB.CmpMHS);
2937     EVT VT = CmpOp.getValueType();
2938 
2939     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2940       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2941                           ISD::SETLE);
2942     } else {
2943       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2944                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2945       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2946                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2947     }
2948   }
2949 
2950   // Update successor info
2951   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2952   // TrueBB and FalseBB are always different unless the incoming IR is
2953   // degenerate. This only happens when running llc on weird IR.
2954   if (CB.TrueBB != CB.FalseBB)
2955     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2956   SwitchBB->normalizeSuccProbs();
2957 
2958   // If the lhs block is the next block, invert the condition so that we can
2959   // fall through to the lhs instead of the rhs block.
2960   if (CB.TrueBB == NextBlock(SwitchBB)) {
2961     std::swap(CB.TrueBB, CB.FalseBB);
2962     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2963     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2964   }
2965 
2966   SDNodeFlags Flags;
2967   Flags.setUnpredictable(CB.IsUnpredictable);
2968   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, MVT::Other, getControlRoot(),
2969                                Cond, DAG.getBasicBlock(CB.TrueBB), Flags);
2970 
2971   setValue(CurInst, BrCond);
2972 
2973   // Insert the false branch. Do this even if it's a fall through branch,
2974   // this makes it easier to do DAG optimizations which require inverting
2975   // the branch condition.
2976   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2977                        DAG.getBasicBlock(CB.FalseBB));
2978 
2979   DAG.setRoot(BrCond);
2980 }
2981 
2982 /// visitJumpTable - Emit JumpTable node in the current MBB
2983 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2984   // Emit the code for the jump table
2985   assert(JT.SL && "Should set SDLoc for SelectionDAG!");
2986   assert(JT.Reg && "Should lower JT Header first!");
2987   EVT PTy = DAG.getTargetLoweringInfo().getJumpTableRegTy(DAG.getDataLayout());
2988   SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy);
2989   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2990   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other,
2991                                     Index.getValue(1), Table, Index);
2992   DAG.setRoot(BrJumpTable);
2993 }
2994 
2995 /// visitJumpTableHeader - This function emits necessary code to produce index
2996 /// in the JumpTable from switch case.
2997 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2998                                                JumpTableHeader &JTH,
2999                                                MachineBasicBlock *SwitchBB) {
3000   assert(JT.SL && "Should set SDLoc for SelectionDAG!");
3001   const SDLoc &dl = *JT.SL;
3002 
3003   // Subtract the lowest switch case value from the value being switched on.
3004   SDValue SwitchOp = getValue(JTH.SValue);
3005   EVT VT = SwitchOp.getValueType();
3006   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
3007                             DAG.getConstant(JTH.First, dl, VT));
3008 
3009   // The SDNode we just created, which holds the value being switched on minus
3010   // the smallest case value, needs to be copied to a virtual register so it
3011   // can be used as an index into the jump table in a subsequent basic block.
3012   // This value may be smaller or larger than the target's pointer type, and
3013   // therefore require extension or truncating.
3014   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3015   SwitchOp =
3016       DAG.getZExtOrTrunc(Sub, dl, TLI.getJumpTableRegTy(DAG.getDataLayout()));
3017 
3018   Register JumpTableReg =
3019       FuncInfo.CreateReg(TLI.getJumpTableRegTy(DAG.getDataLayout()));
3020   SDValue CopyTo =
3021       DAG.getCopyToReg(getControlRoot(), dl, JumpTableReg, SwitchOp);
3022   JT.Reg = JumpTableReg;
3023 
3024   if (!JTH.FallthroughUnreachable) {
3025     // Emit the range check for the jump table, and branch to the default block
3026     // for the switch statement if the value being switched on exceeds the
3027     // largest case in the switch.
3028     SDValue CMP = DAG.getSetCC(
3029         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3030                                    Sub.getValueType()),
3031         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
3032 
3033     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
3034                                  MVT::Other, CopyTo, CMP,
3035                                  DAG.getBasicBlock(JT.Default));
3036 
3037     // Avoid emitting unnecessary branches to the next block.
3038     if (JT.MBB != NextBlock(SwitchBB))
3039       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
3040                            DAG.getBasicBlock(JT.MBB));
3041 
3042     DAG.setRoot(BrCond);
3043   } else {
3044     // Avoid emitting unnecessary branches to the next block.
3045     if (JT.MBB != NextBlock(SwitchBB))
3046       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
3047                               DAG.getBasicBlock(JT.MBB)));
3048     else
3049       DAG.setRoot(CopyTo);
3050   }
3051 }
3052 
3053 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
3054 /// variable if there exists one.
3055 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
3056                                  SDValue &Chain) {
3057   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3058   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
3059   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
3060   MachineFunction &MF = DAG.getMachineFunction();
3061   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
3062   MachineSDNode *Node =
3063       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
3064   if (Global) {
3065     MachinePointerInfo MPInfo(Global);
3066     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
3067                  MachineMemOperand::MODereferenceable;
3068     MachineMemOperand *MemRef = MF.getMachineMemOperand(
3069         MPInfo, Flags, LocationSize::precise(PtrTy.getSizeInBits() / 8),
3070         DAG.getEVTAlign(PtrTy));
3071     DAG.setNodeMemRefs(Node, {MemRef});
3072   }
3073   if (PtrTy != PtrMemTy)
3074     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
3075   return SDValue(Node, 0);
3076 }
3077 
3078 /// Codegen a new tail for a stack protector check ParentMBB which has had its
3079 /// tail spliced into a stack protector check success bb.
3080 ///
3081 /// For a high level explanation of how this fits into the stack protector
3082 /// generation see the comment on the declaration of class
3083 /// StackProtectorDescriptor.
3084 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
3085                                                   MachineBasicBlock *ParentBB) {
3086 
3087   // First create the loads to the guard/stack slot for the comparison.
3088   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3089   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
3090   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
3091 
3092   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3093   int FI = MFI.getStackProtectorIndex();
3094 
3095   SDValue Guard;
3096   SDLoc dl = getCurSDLoc();
3097   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
3098   const Module &M = *ParentBB->getParent()->getFunction().getParent();
3099   Align Align =
3100       DAG.getDataLayout().getPrefTypeAlign(PointerType::get(M.getContext(), 0));
3101 
3102   // Generate code to load the content of the guard slot.
3103   SDValue GuardVal = DAG.getLoad(
3104       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
3105       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
3106       MachineMemOperand::MOVolatile);
3107 
3108   if (TLI.useStackGuardXorFP())
3109     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
3110 
3111   // Retrieve guard check function, nullptr if instrumentation is inlined.
3112   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
3113     // The target provides a guard check function to validate the guard value.
3114     // Generate a call to that function with the content of the guard slot as
3115     // argument.
3116     FunctionType *FnTy = GuardCheckFn->getFunctionType();
3117     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3118 
3119     TargetLowering::ArgListTy Args;
3120     TargetLowering::ArgListEntry Entry;
3121     Entry.Node = GuardVal;
3122     Entry.Ty = FnTy->getParamType(0);
3123     if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
3124       Entry.IsInReg = true;
3125     Args.push_back(Entry);
3126 
3127     TargetLowering::CallLoweringInfo CLI(DAG);
3128     CLI.setDebugLoc(getCurSDLoc())
3129         .setChain(DAG.getEntryNode())
3130         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
3131                    getValue(GuardCheckFn), std::move(Args));
3132 
3133     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
3134     DAG.setRoot(Result.second);
3135     return;
3136   }
3137 
3138   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
3139   // Otherwise, emit a volatile load to retrieve the stack guard value.
3140   SDValue Chain = DAG.getEntryNode();
3141   if (TLI.useLoadStackGuardNode()) {
3142     Guard = getLoadStackGuard(DAG, dl, Chain);
3143   } else {
3144     const Value *IRGuard = TLI.getSDagStackGuard(M);
3145     SDValue GuardPtr = getValue(IRGuard);
3146 
3147     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
3148                         MachinePointerInfo(IRGuard, 0), Align,
3149                         MachineMemOperand::MOVolatile);
3150   }
3151 
3152   // Perform the comparison via a getsetcc.
3153   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
3154                                                         *DAG.getContext(),
3155                                                         Guard.getValueType()),
3156                              Guard, GuardVal, ISD::SETNE);
3157 
3158   // If the guard/stackslot do not equal, branch to failure MBB.
3159   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
3160                                MVT::Other, GuardVal.getOperand(0),
3161                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
3162   // Otherwise branch to success MBB.
3163   SDValue Br = DAG.getNode(ISD::BR, dl,
3164                            MVT::Other, BrCond,
3165                            DAG.getBasicBlock(SPD.getSuccessMBB()));
3166 
3167   DAG.setRoot(Br);
3168 }
3169 
3170 /// Codegen the failure basic block for a stack protector check.
3171 ///
3172 /// A failure stack protector machine basic block consists simply of a call to
3173 /// __stack_chk_fail().
3174 ///
3175 /// For a high level explanation of how this fits into the stack protector
3176 /// generation see the comment on the declaration of class
3177 /// StackProtectorDescriptor.
3178 void
3179 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
3180   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3181   TargetLowering::MakeLibCallOptions CallOptions;
3182   CallOptions.setDiscardResult(true);
3183   SDValue Chain =
3184       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
3185                       std::nullopt, CallOptions, getCurSDLoc())
3186           .second;
3187   // On PS4/PS5, the "return address" must still be within the calling
3188   // function, even if it's at the very end, so emit an explicit TRAP here.
3189   // Passing 'true' for doesNotReturn above won't generate the trap for us.
3190   if (TM.getTargetTriple().isPS())
3191     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
3192   // WebAssembly needs an unreachable instruction after a non-returning call,
3193   // because the function return type can be different from __stack_chk_fail's
3194   // return type (void).
3195   if (TM.getTargetTriple().isWasm())
3196     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
3197 
3198   DAG.setRoot(Chain);
3199 }
3200 
3201 /// visitBitTestHeader - This function emits necessary code to produce value
3202 /// suitable for "bit tests"
3203 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
3204                                              MachineBasicBlock *SwitchBB) {
3205   SDLoc dl = getCurSDLoc();
3206 
3207   // Subtract the minimum value.
3208   SDValue SwitchOp = getValue(B.SValue);
3209   EVT VT = SwitchOp.getValueType();
3210   SDValue RangeSub =
3211       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
3212 
3213   // Determine the type of the test operands.
3214   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3215   bool UsePtrType = false;
3216   if (!TLI.isTypeLegal(VT)) {
3217     UsePtrType = true;
3218   } else {
3219     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
3220       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
3221         // Switch table case range are encoded into series of masks.
3222         // Just use pointer type, it's guaranteed to fit.
3223         UsePtrType = true;
3224         break;
3225       }
3226   }
3227   SDValue Sub = RangeSub;
3228   if (UsePtrType) {
3229     VT = TLI.getPointerTy(DAG.getDataLayout());
3230     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
3231   }
3232 
3233   B.RegVT = VT.getSimpleVT();
3234   B.Reg = FuncInfo.CreateReg(B.RegVT);
3235   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
3236 
3237   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
3238 
3239   if (!B.FallthroughUnreachable)
3240     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
3241   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
3242   SwitchBB->normalizeSuccProbs();
3243 
3244   SDValue Root = CopyTo;
3245   if (!B.FallthroughUnreachable) {
3246     // Conditional branch to the default block.
3247     SDValue RangeCmp = DAG.getSetCC(dl,
3248         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3249                                RangeSub.getValueType()),
3250         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
3251         ISD::SETUGT);
3252 
3253     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
3254                        DAG.getBasicBlock(B.Default));
3255   }
3256 
3257   // Avoid emitting unnecessary branches to the next block.
3258   if (MBB != NextBlock(SwitchBB))
3259     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
3260 
3261   DAG.setRoot(Root);
3262 }
3263 
3264 /// visitBitTestCase - this function produces one "bit test"
3265 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
3266                                            MachineBasicBlock *NextMBB,
3267                                            BranchProbability BranchProbToNext,
3268                                            Register Reg, BitTestCase &B,
3269                                            MachineBasicBlock *SwitchBB) {
3270   SDLoc dl = getCurSDLoc();
3271   MVT VT = BB.RegVT;
3272   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
3273   SDValue Cmp;
3274   unsigned PopCount = llvm::popcount(B.Mask);
3275   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3276   if (PopCount == 1) {
3277     // Testing for a single bit; just compare the shift count with what it
3278     // would need to be to shift a 1 bit in that position.
3279     Cmp = DAG.getSetCC(
3280         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3281         ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT),
3282         ISD::SETEQ);
3283   } else if (PopCount == BB.Range) {
3284     // There is only one zero bit in the range, test for it directly.
3285     Cmp = DAG.getSetCC(
3286         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3287         ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE);
3288   } else {
3289     // Make desired shift
3290     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
3291                                     DAG.getConstant(1, dl, VT), ShiftOp);
3292 
3293     // Emit bit tests and jumps
3294     SDValue AndOp = DAG.getNode(ISD::AND, dl,
3295                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
3296     Cmp = DAG.getSetCC(
3297         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3298         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
3299   }
3300 
3301   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
3302   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
3303   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
3304   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
3305   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
3306   // one as they are relative probabilities (and thus work more like weights),
3307   // and hence we need to normalize them to let the sum of them become one.
3308   SwitchBB->normalizeSuccProbs();
3309 
3310   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
3311                               MVT::Other, getControlRoot(),
3312                               Cmp, DAG.getBasicBlock(B.TargetBB));
3313 
3314   // Avoid emitting unnecessary branches to the next block.
3315   if (NextMBB != NextBlock(SwitchBB))
3316     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
3317                         DAG.getBasicBlock(NextMBB));
3318 
3319   DAG.setRoot(BrAnd);
3320 }
3321 
3322 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
3323   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
3324 
3325   // Retrieve successors. Look through artificial IR level blocks like
3326   // catchswitch for successors.
3327   MachineBasicBlock *Return = FuncInfo.getMBB(I.getSuccessor(0));
3328   const BasicBlock *EHPadBB = I.getSuccessor(1);
3329   MachineBasicBlock *EHPadMBB = FuncInfo.getMBB(EHPadBB);
3330 
3331   // Deopt and ptrauth bundles are lowered in helper functions, and we don't
3332   // have to do anything here to lower funclet bundles.
3333   assert(!I.hasOperandBundlesOtherThan(
3334              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
3335               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
3336               LLVMContext::OB_cfguardtarget, LLVMContext::OB_ptrauth,
3337               LLVMContext::OB_clang_arc_attachedcall}) &&
3338          "Cannot lower invokes with arbitrary operand bundles yet!");
3339 
3340   const Value *Callee(I.getCalledOperand());
3341   const Function *Fn = dyn_cast<Function>(Callee);
3342   if (isa<InlineAsm>(Callee))
3343     visitInlineAsm(I, EHPadBB);
3344   else if (Fn && Fn->isIntrinsic()) {
3345     switch (Fn->getIntrinsicID()) {
3346     default:
3347       llvm_unreachable("Cannot invoke this intrinsic");
3348     case Intrinsic::donothing:
3349       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
3350     case Intrinsic::seh_try_begin:
3351     case Intrinsic::seh_scope_begin:
3352     case Intrinsic::seh_try_end:
3353     case Intrinsic::seh_scope_end:
3354       if (EHPadMBB)
3355           // a block referenced by EH table
3356           // so dtor-funclet not removed by opts
3357           EHPadMBB->setMachineBlockAddressTaken();
3358       break;
3359     case Intrinsic::experimental_patchpoint_void:
3360     case Intrinsic::experimental_patchpoint:
3361       visitPatchpoint(I, EHPadBB);
3362       break;
3363     case Intrinsic::experimental_gc_statepoint:
3364       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
3365       break;
3366     case Intrinsic::wasm_rethrow: {
3367       // This is usually done in visitTargetIntrinsic, but this intrinsic is
3368       // special because it can be invoked, so we manually lower it to a DAG
3369       // node here.
3370       SmallVector<SDValue, 8> Ops;
3371       Ops.push_back(getControlRoot()); // inchain for the terminator node
3372       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3373       Ops.push_back(
3374           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
3375                                 TLI.getPointerTy(DAG.getDataLayout())));
3376       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3377       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3378       break;
3379     }
3380     }
3381   } else if (I.hasDeoptState()) {
3382     // Currently we do not lower any intrinsic calls with deopt operand bundles.
3383     // Eventually we will support lowering the @llvm.experimental.deoptimize
3384     // intrinsic, and right now there are no plans to support other intrinsics
3385     // with deopt state.
3386     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
3387   } else if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
3388     LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), EHPadBB);
3389   } else {
3390     LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
3391   }
3392 
3393   // If the value of the invoke is used outside of its defining block, make it
3394   // available as a virtual register.
3395   // We already took care of the exported value for the statepoint instruction
3396   // during call to the LowerStatepoint.
3397   if (!isa<GCStatepointInst>(I)) {
3398     CopyToExportRegsIfNeeded(&I);
3399   }
3400 
3401   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
3402   BranchProbabilityInfo *BPI = FuncInfo.BPI;
3403   BranchProbability EHPadBBProb =
3404       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3405           : BranchProbability::getZero();
3406   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
3407 
3408   // Update successor info.
3409   addSuccessorWithProb(InvokeMBB, Return);
3410   for (auto &UnwindDest : UnwindDests) {
3411     UnwindDest.first->setIsEHPad();
3412     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3413   }
3414   InvokeMBB->normalizeSuccProbs();
3415 
3416   // Drop into normal successor.
3417   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
3418                           DAG.getBasicBlock(Return)));
3419 }
3420 
3421 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3422   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3423 
3424   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3425   // have to do anything here to lower funclet bundles.
3426   assert(!I.hasOperandBundlesOtherThan(
3427              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
3428          "Cannot lower callbrs with arbitrary operand bundles yet!");
3429 
3430   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
3431   visitInlineAsm(I);
3432   CopyToExportRegsIfNeeded(&I);
3433 
3434   // Retrieve successors.
3435   SmallPtrSet<BasicBlock *, 8> Dests;
3436   Dests.insert(I.getDefaultDest());
3437   MachineBasicBlock *Return = FuncInfo.getMBB(I.getDefaultDest());
3438 
3439   // Update successor info.
3440   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3441   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
3442     BasicBlock *Dest = I.getIndirectDest(i);
3443     MachineBasicBlock *Target = FuncInfo.getMBB(Dest);
3444     Target->setIsInlineAsmBrIndirectTarget();
3445     Target->setMachineBlockAddressTaken();
3446     Target->setLabelMustBeEmitted();
3447     // Don't add duplicate machine successors.
3448     if (Dests.insert(Dest).second)
3449       addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3450   }
3451   CallBrMBB->normalizeSuccProbs();
3452 
3453   // Drop into default successor.
3454   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3455                           MVT::Other, getControlRoot(),
3456                           DAG.getBasicBlock(Return)));
3457 }
3458 
3459 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3460   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3461 }
3462 
3463 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3464   assert(FuncInfo.MBB->isEHPad() &&
3465          "Call to landingpad not in landing pad!");
3466 
3467   // If there aren't registers to copy the values into (e.g., during SjLj
3468   // exceptions), then don't bother to create these DAG nodes.
3469   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3470   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3471   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3472       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3473     return;
3474 
3475   // If landingpad's return type is token type, we don't create DAG nodes
3476   // for its exception pointer and selector value. The extraction of exception
3477   // pointer or selector value from token type landingpads is not currently
3478   // supported.
3479   if (LP.getType()->isTokenTy())
3480     return;
3481 
3482   SmallVector<EVT, 2> ValueVTs;
3483   SDLoc dl = getCurSDLoc();
3484   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3485   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3486 
3487   // Get the two live-in registers as SDValues. The physregs have already been
3488   // copied into virtual registers.
3489   SDValue Ops[2];
3490   if (FuncInfo.ExceptionPointerVirtReg) {
3491     Ops[0] = DAG.getZExtOrTrunc(
3492         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3493                            FuncInfo.ExceptionPointerVirtReg,
3494                            TLI.getPointerTy(DAG.getDataLayout())),
3495         dl, ValueVTs[0]);
3496   } else {
3497     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3498   }
3499   Ops[1] = DAG.getZExtOrTrunc(
3500       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3501                          FuncInfo.ExceptionSelectorVirtReg,
3502                          TLI.getPointerTy(DAG.getDataLayout())),
3503       dl, ValueVTs[1]);
3504 
3505   // Merge into one.
3506   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3507                             DAG.getVTList(ValueVTs), Ops);
3508   setValue(&LP, Res);
3509 }
3510 
3511 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3512                                            MachineBasicBlock *Last) {
3513   // Update JTCases.
3514   for (JumpTableBlock &JTB : SL->JTCases)
3515     if (JTB.first.HeaderBB == First)
3516       JTB.first.HeaderBB = Last;
3517 
3518   // Update BitTestCases.
3519   for (BitTestBlock &BTB : SL->BitTestCases)
3520     if (BTB.Parent == First)
3521       BTB.Parent = Last;
3522 }
3523 
3524 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3525   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3526 
3527   // Update machine-CFG edges with unique successors.
3528   SmallSet<BasicBlock*, 32> Done;
3529   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3530     BasicBlock *BB = I.getSuccessor(i);
3531     bool Inserted = Done.insert(BB).second;
3532     if (!Inserted)
3533         continue;
3534 
3535     MachineBasicBlock *Succ = FuncInfo.getMBB(BB);
3536     addSuccessorWithProb(IndirectBrMBB, Succ);
3537   }
3538   IndirectBrMBB->normalizeSuccProbs();
3539 
3540   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3541                           MVT::Other, getControlRoot(),
3542                           getValue(I.getAddress())));
3543 }
3544 
3545 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3546   if (!DAG.getTarget().Options.TrapUnreachable)
3547     return;
3548 
3549   // We may be able to ignore unreachable behind a noreturn call.
3550   if (const CallInst *Call = dyn_cast_or_null<CallInst>(I.getPrevNode());
3551       Call && Call->doesNotReturn()) {
3552     if (DAG.getTarget().Options.NoTrapAfterNoreturn)
3553       return;
3554     // Do not emit an additional trap instruction.
3555     if (Call->isNonContinuableTrap())
3556       return;
3557   }
3558 
3559   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3560 }
3561 
3562 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3563   SDNodeFlags Flags;
3564   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3565     Flags.copyFMF(*FPOp);
3566 
3567   SDValue Op = getValue(I.getOperand(0));
3568   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3569                                     Op, Flags);
3570   setValue(&I, UnNodeValue);
3571 }
3572 
3573 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3574   SDNodeFlags Flags;
3575   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3576     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3577     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3578   }
3579   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3580     Flags.setExact(ExactOp->isExact());
3581   if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&I))
3582     Flags.setDisjoint(DisjointOp->isDisjoint());
3583   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3584     Flags.copyFMF(*FPOp);
3585 
3586   SDValue Op1 = getValue(I.getOperand(0));
3587   SDValue Op2 = getValue(I.getOperand(1));
3588   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3589                                      Op1, Op2, Flags);
3590   setValue(&I, BinNodeValue);
3591 }
3592 
3593 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3594   SDValue Op1 = getValue(I.getOperand(0));
3595   SDValue Op2 = getValue(I.getOperand(1));
3596 
3597   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3598       Op1.getValueType(), DAG.getDataLayout());
3599 
3600   // Coerce the shift amount to the right type if we can. This exposes the
3601   // truncate or zext to optimization early.
3602   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3603     assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) &&
3604            "Unexpected shift type");
3605     Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3606   }
3607 
3608   bool nuw = false;
3609   bool nsw = false;
3610   bool exact = false;
3611 
3612   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3613 
3614     if (const OverflowingBinaryOperator *OFBinOp =
3615             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3616       nuw = OFBinOp->hasNoUnsignedWrap();
3617       nsw = OFBinOp->hasNoSignedWrap();
3618     }
3619     if (const PossiblyExactOperator *ExactOp =
3620             dyn_cast<const PossiblyExactOperator>(&I))
3621       exact = ExactOp->isExact();
3622   }
3623   SDNodeFlags Flags;
3624   Flags.setExact(exact);
3625   Flags.setNoSignedWrap(nsw);
3626   Flags.setNoUnsignedWrap(nuw);
3627   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3628                             Flags);
3629   setValue(&I, Res);
3630 }
3631 
3632 void SelectionDAGBuilder::visitSDiv(const User &I) {
3633   SDValue Op1 = getValue(I.getOperand(0));
3634   SDValue Op2 = getValue(I.getOperand(1));
3635 
3636   SDNodeFlags Flags;
3637   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3638                  cast<PossiblyExactOperator>(&I)->isExact());
3639   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3640                            Op2, Flags));
3641 }
3642 
3643 void SelectionDAGBuilder::visitICmp(const ICmpInst &I) {
3644   ICmpInst::Predicate predicate = I.getPredicate();
3645   SDValue Op1 = getValue(I.getOperand(0));
3646   SDValue Op2 = getValue(I.getOperand(1));
3647   ISD::CondCode Opcode = getICmpCondCode(predicate);
3648 
3649   auto &TLI = DAG.getTargetLoweringInfo();
3650   EVT MemVT =
3651       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3652 
3653   // If a pointer's DAG type is larger than its memory type then the DAG values
3654   // are zero-extended. This breaks signed comparisons so truncate back to the
3655   // underlying type before doing the compare.
3656   if (Op1.getValueType() != MemVT) {
3657     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3658     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3659   }
3660 
3661   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3662                                                         I.getType());
3663   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3664 }
3665 
3666 void SelectionDAGBuilder::visitFCmp(const FCmpInst &I) {
3667   FCmpInst::Predicate predicate = I.getPredicate();
3668   SDValue Op1 = getValue(I.getOperand(0));
3669   SDValue Op2 = getValue(I.getOperand(1));
3670 
3671   ISD::CondCode Condition = getFCmpCondCode(predicate);
3672   auto *FPMO = cast<FPMathOperator>(&I);
3673   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3674     Condition = getFCmpCodeWithoutNaN(Condition);
3675 
3676   SDNodeFlags Flags;
3677   Flags.copyFMF(*FPMO);
3678   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3679 
3680   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3681                                                         I.getType());
3682   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3683 }
3684 
3685 // Check if the condition of the select has one use or two users that are both
3686 // selects with the same condition.
3687 static bool hasOnlySelectUsers(const Value *Cond) {
3688   return llvm::all_of(Cond->users(), [](const Value *V) {
3689     return isa<SelectInst>(V);
3690   });
3691 }
3692 
3693 void SelectionDAGBuilder::visitSelect(const User &I) {
3694   SmallVector<EVT, 4> ValueVTs;
3695   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3696                   ValueVTs);
3697   unsigned NumValues = ValueVTs.size();
3698   if (NumValues == 0) return;
3699 
3700   SmallVector<SDValue, 4> Values(NumValues);
3701   SDValue Cond     = getValue(I.getOperand(0));
3702   SDValue LHSVal   = getValue(I.getOperand(1));
3703   SDValue RHSVal   = getValue(I.getOperand(2));
3704   SmallVector<SDValue, 1> BaseOps(1, Cond);
3705   ISD::NodeType OpCode =
3706       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3707 
3708   bool IsUnaryAbs = false;
3709   bool Negate = false;
3710 
3711   SDNodeFlags Flags;
3712   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3713     Flags.copyFMF(*FPOp);
3714 
3715   Flags.setUnpredictable(
3716       cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable));
3717 
3718   // Min/max matching is only viable if all output VTs are the same.
3719   if (all_equal(ValueVTs)) {
3720     EVT VT = ValueVTs[0];
3721     LLVMContext &Ctx = *DAG.getContext();
3722     auto &TLI = DAG.getTargetLoweringInfo();
3723 
3724     // We care about the legality of the operation after it has been type
3725     // legalized.
3726     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3727       VT = TLI.getTypeToTransformTo(Ctx, VT);
3728 
3729     // If the vselect is legal, assume we want to leave this as a vector setcc +
3730     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3731     // min/max is legal on the scalar type.
3732     bool UseScalarMinMax = VT.isVector() &&
3733       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3734 
3735     // ValueTracking's select pattern matching does not account for -0.0,
3736     // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that
3737     // -0.0 is less than +0.0.
3738     const Value *LHS, *RHS;
3739     auto SPR = matchSelectPattern(&I, LHS, RHS);
3740     ISD::NodeType Opc = ISD::DELETED_NODE;
3741     switch (SPR.Flavor) {
3742     case SPF_UMAX:    Opc = ISD::UMAX; break;
3743     case SPF_UMIN:    Opc = ISD::UMIN; break;
3744     case SPF_SMAX:    Opc = ISD::SMAX; break;
3745     case SPF_SMIN:    Opc = ISD::SMIN; break;
3746     case SPF_FMINNUM:
3747       switch (SPR.NaNBehavior) {
3748       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3749       case SPNB_RETURNS_NAN: break;
3750       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3751       case SPNB_RETURNS_ANY:
3752         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) ||
3753             (UseScalarMinMax &&
3754              TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType())))
3755           Opc = ISD::FMINNUM;
3756         break;
3757       }
3758       break;
3759     case SPF_FMAXNUM:
3760       switch (SPR.NaNBehavior) {
3761       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3762       case SPNB_RETURNS_NAN: break;
3763       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3764       case SPNB_RETURNS_ANY:
3765         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) ||
3766             (UseScalarMinMax &&
3767              TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType())))
3768           Opc = ISD::FMAXNUM;
3769         break;
3770       }
3771       break;
3772     case SPF_NABS:
3773       Negate = true;
3774       [[fallthrough]];
3775     case SPF_ABS:
3776       IsUnaryAbs = true;
3777       Opc = ISD::ABS;
3778       break;
3779     default: break;
3780     }
3781 
3782     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3783         (TLI.isOperationLegalOrCustomOrPromote(Opc, VT) ||
3784          (UseScalarMinMax &&
3785           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3786         // If the underlying comparison instruction is used by any other
3787         // instruction, the consumed instructions won't be destroyed, so it is
3788         // not profitable to convert to a min/max.
3789         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3790       OpCode = Opc;
3791       LHSVal = getValue(LHS);
3792       RHSVal = getValue(RHS);
3793       BaseOps.clear();
3794     }
3795 
3796     if (IsUnaryAbs) {
3797       OpCode = Opc;
3798       LHSVal = getValue(LHS);
3799       BaseOps.clear();
3800     }
3801   }
3802 
3803   if (IsUnaryAbs) {
3804     for (unsigned i = 0; i != NumValues; ++i) {
3805       SDLoc dl = getCurSDLoc();
3806       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3807       Values[i] =
3808           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3809       if (Negate)
3810         Values[i] = DAG.getNegative(Values[i], dl, VT);
3811     }
3812   } else {
3813     for (unsigned i = 0; i != NumValues; ++i) {
3814       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3815       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3816       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3817       Values[i] = DAG.getNode(
3818           OpCode, getCurSDLoc(),
3819           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3820     }
3821   }
3822 
3823   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3824                            DAG.getVTList(ValueVTs), Values));
3825 }
3826 
3827 void SelectionDAGBuilder::visitTrunc(const User &I) {
3828   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3829   SDValue N = getValue(I.getOperand(0));
3830   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3831                                                         I.getType());
3832   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3833 }
3834 
3835 void SelectionDAGBuilder::visitZExt(const User &I) {
3836   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3837   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3838   SDValue N = getValue(I.getOperand(0));
3839   auto &TLI = DAG.getTargetLoweringInfo();
3840   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3841 
3842   SDNodeFlags Flags;
3843   if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
3844     Flags.setNonNeg(PNI->hasNonNeg());
3845 
3846   // Eagerly use nonneg information to canonicalize towards sign_extend if
3847   // that is the target's preference.
3848   // TODO: Let the target do this later.
3849   if (Flags.hasNonNeg() &&
3850       TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) {
3851     setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3852     return;
3853   }
3854 
3855   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags));
3856 }
3857 
3858 void SelectionDAGBuilder::visitSExt(const User &I) {
3859   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3860   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3861   SDValue N = getValue(I.getOperand(0));
3862   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3863                                                         I.getType());
3864   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3865 }
3866 
3867 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3868   // FPTrunc is never a no-op cast, no need to check
3869   SDValue N = getValue(I.getOperand(0));
3870   SDLoc dl = getCurSDLoc();
3871   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3872   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3873   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3874                            DAG.getTargetConstant(
3875                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3876 }
3877 
3878 void SelectionDAGBuilder::visitFPExt(const User &I) {
3879   // FPExt is never a no-op cast, no need to check
3880   SDValue N = getValue(I.getOperand(0));
3881   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3882                                                         I.getType());
3883   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3884 }
3885 
3886 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3887   // FPToUI is never a no-op cast, no need to check
3888   SDValue N = getValue(I.getOperand(0));
3889   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3890                                                         I.getType());
3891   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3892 }
3893 
3894 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3895   // FPToSI is never a no-op cast, no need to check
3896   SDValue N = getValue(I.getOperand(0));
3897   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3898                                                         I.getType());
3899   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3900 }
3901 
3902 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3903   // UIToFP is never a no-op cast, no need to check
3904   SDValue N = getValue(I.getOperand(0));
3905   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3906                                                         I.getType());
3907   SDNodeFlags Flags;
3908   if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
3909     Flags.setNonNeg(PNI->hasNonNeg());
3910 
3911   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N, Flags));
3912 }
3913 
3914 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3915   // SIToFP is never a no-op cast, no need to check
3916   SDValue N = getValue(I.getOperand(0));
3917   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3918                                                         I.getType());
3919   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3920 }
3921 
3922 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3923   // What to do depends on the size of the integer and the size of the pointer.
3924   // We can either truncate, zero extend, or no-op, accordingly.
3925   SDValue N = getValue(I.getOperand(0));
3926   auto &TLI = DAG.getTargetLoweringInfo();
3927   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3928                                                         I.getType());
3929   EVT PtrMemVT =
3930       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3931   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3932   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3933   setValue(&I, N);
3934 }
3935 
3936 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3937   // What to do depends on the size of the integer and the size of the pointer.
3938   // We can either truncate, zero extend, or no-op, accordingly.
3939   SDValue N = getValue(I.getOperand(0));
3940   auto &TLI = DAG.getTargetLoweringInfo();
3941   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3942   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3943   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3944   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3945   setValue(&I, N);
3946 }
3947 
3948 void SelectionDAGBuilder::visitBitCast(const User &I) {
3949   SDValue N = getValue(I.getOperand(0));
3950   SDLoc dl = getCurSDLoc();
3951   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3952                                                         I.getType());
3953 
3954   // BitCast assures us that source and destination are the same size so this is
3955   // either a BITCAST or a no-op.
3956   if (DestVT != N.getValueType())
3957     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3958                              DestVT, N)); // convert types.
3959   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3960   // might fold any kind of constant expression to an integer constant and that
3961   // is not what we are looking for. Only recognize a bitcast of a genuine
3962   // constant integer as an opaque constant.
3963   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3964     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3965                                  /*isOpaque*/true));
3966   else
3967     setValue(&I, N);            // noop cast.
3968 }
3969 
3970 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3971   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3972   const Value *SV = I.getOperand(0);
3973   SDValue N = getValue(SV);
3974   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3975 
3976   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3977   unsigned DestAS = I.getType()->getPointerAddressSpace();
3978 
3979   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3980     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3981 
3982   setValue(&I, N);
3983 }
3984 
3985 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3986   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3987   SDValue InVec = getValue(I.getOperand(0));
3988   SDValue InVal = getValue(I.getOperand(1));
3989   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3990                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3991   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3992                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3993                            InVec, InVal, InIdx));
3994 }
3995 
3996 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3997   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3998   SDValue InVec = getValue(I.getOperand(0));
3999   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
4000                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
4001   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
4002                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
4003                            InVec, InIdx));
4004 }
4005 
4006 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
4007   SDValue Src1 = getValue(I.getOperand(0));
4008   SDValue Src2 = getValue(I.getOperand(1));
4009   ArrayRef<int> Mask;
4010   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
4011     Mask = SVI->getShuffleMask();
4012   else
4013     Mask = cast<ConstantExpr>(I).getShuffleMask();
4014   SDLoc DL = getCurSDLoc();
4015   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4016   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4017   EVT SrcVT = Src1.getValueType();
4018 
4019   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
4020       VT.isScalableVector()) {
4021     // Canonical splat form of first element of first input vector.
4022     SDValue FirstElt =
4023         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
4024                     DAG.getVectorIdxConstant(0, DL));
4025     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
4026     return;
4027   }
4028 
4029   // For now, we only handle splats for scalable vectors.
4030   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
4031   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
4032   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
4033 
4034   unsigned SrcNumElts = SrcVT.getVectorNumElements();
4035   unsigned MaskNumElts = Mask.size();
4036 
4037   if (SrcNumElts == MaskNumElts) {
4038     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
4039     return;
4040   }
4041 
4042   // Normalize the shuffle vector since mask and vector length don't match.
4043   if (SrcNumElts < MaskNumElts) {
4044     // Mask is longer than the source vectors. We can use concatenate vector to
4045     // make the mask and vectors lengths match.
4046 
4047     if (MaskNumElts % SrcNumElts == 0) {
4048       // Mask length is a multiple of the source vector length.
4049       // Check if the shuffle is some kind of concatenation of the input
4050       // vectors.
4051       unsigned NumConcat = MaskNumElts / SrcNumElts;
4052       bool IsConcat = true;
4053       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
4054       for (unsigned i = 0; i != MaskNumElts; ++i) {
4055         int Idx = Mask[i];
4056         if (Idx < 0)
4057           continue;
4058         // Ensure the indices in each SrcVT sized piece are sequential and that
4059         // the same source is used for the whole piece.
4060         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
4061             (ConcatSrcs[i / SrcNumElts] >= 0 &&
4062              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
4063           IsConcat = false;
4064           break;
4065         }
4066         // Remember which source this index came from.
4067         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
4068       }
4069 
4070       // The shuffle is concatenating multiple vectors together. Just emit
4071       // a CONCAT_VECTORS operation.
4072       if (IsConcat) {
4073         SmallVector<SDValue, 8> ConcatOps;
4074         for (auto Src : ConcatSrcs) {
4075           if (Src < 0)
4076             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
4077           else if (Src == 0)
4078             ConcatOps.push_back(Src1);
4079           else
4080             ConcatOps.push_back(Src2);
4081         }
4082         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
4083         return;
4084       }
4085     }
4086 
4087     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
4088     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
4089     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
4090                                     PaddedMaskNumElts);
4091 
4092     // Pad both vectors with undefs to make them the same length as the mask.
4093     SDValue UndefVal = DAG.getUNDEF(SrcVT);
4094 
4095     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
4096     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
4097     MOps1[0] = Src1;
4098     MOps2[0] = Src2;
4099 
4100     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
4101     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
4102 
4103     // Readjust mask for new input vector length.
4104     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
4105     for (unsigned i = 0; i != MaskNumElts; ++i) {
4106       int Idx = Mask[i];
4107       if (Idx >= (int)SrcNumElts)
4108         Idx -= SrcNumElts - PaddedMaskNumElts;
4109       MappedOps[i] = Idx;
4110     }
4111 
4112     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
4113 
4114     // If the concatenated vector was padded, extract a subvector with the
4115     // correct number of elements.
4116     if (MaskNumElts != PaddedMaskNumElts)
4117       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
4118                            DAG.getVectorIdxConstant(0, DL));
4119 
4120     setValue(&I, Result);
4121     return;
4122   }
4123 
4124   if (SrcNumElts > MaskNumElts) {
4125     // Analyze the access pattern of the vector to see if we can extract
4126     // two subvectors and do the shuffle.
4127     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
4128     bool CanExtract = true;
4129     for (int Idx : Mask) {
4130       unsigned Input = 0;
4131       if (Idx < 0)
4132         continue;
4133 
4134       if (Idx >= (int)SrcNumElts) {
4135         Input = 1;
4136         Idx -= SrcNumElts;
4137       }
4138 
4139       // If all the indices come from the same MaskNumElts sized portion of
4140       // the sources we can use extract. Also make sure the extract wouldn't
4141       // extract past the end of the source.
4142       int NewStartIdx = alignDown(Idx, MaskNumElts);
4143       if (NewStartIdx + MaskNumElts > SrcNumElts ||
4144           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
4145         CanExtract = false;
4146       // Make sure we always update StartIdx as we use it to track if all
4147       // elements are undef.
4148       StartIdx[Input] = NewStartIdx;
4149     }
4150 
4151     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
4152       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
4153       return;
4154     }
4155     if (CanExtract) {
4156       // Extract appropriate subvector and generate a vector shuffle
4157       for (unsigned Input = 0; Input < 2; ++Input) {
4158         SDValue &Src = Input == 0 ? Src1 : Src2;
4159         if (StartIdx[Input] < 0)
4160           Src = DAG.getUNDEF(VT);
4161         else {
4162           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
4163                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
4164         }
4165       }
4166 
4167       // Calculate new mask.
4168       SmallVector<int, 8> MappedOps(Mask);
4169       for (int &Idx : MappedOps) {
4170         if (Idx >= (int)SrcNumElts)
4171           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
4172         else if (Idx >= 0)
4173           Idx -= StartIdx[0];
4174       }
4175 
4176       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
4177       return;
4178     }
4179   }
4180 
4181   // We can't use either concat vectors or extract subvectors so fall back to
4182   // replacing the shuffle with extract and build vector.
4183   // to insert and build vector.
4184   EVT EltVT = VT.getVectorElementType();
4185   SmallVector<SDValue,8> Ops;
4186   for (int Idx : Mask) {
4187     SDValue Res;
4188 
4189     if (Idx < 0) {
4190       Res = DAG.getUNDEF(EltVT);
4191     } else {
4192       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
4193       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
4194 
4195       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
4196                         DAG.getVectorIdxConstant(Idx, DL));
4197     }
4198 
4199     Ops.push_back(Res);
4200   }
4201 
4202   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
4203 }
4204 
4205 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
4206   ArrayRef<unsigned> Indices = I.getIndices();
4207   const Value *Op0 = I.getOperand(0);
4208   const Value *Op1 = I.getOperand(1);
4209   Type *AggTy = I.getType();
4210   Type *ValTy = Op1->getType();
4211   bool IntoUndef = isa<UndefValue>(Op0);
4212   bool FromUndef = isa<UndefValue>(Op1);
4213 
4214   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4215 
4216   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4217   SmallVector<EVT, 4> AggValueVTs;
4218   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
4219   SmallVector<EVT, 4> ValValueVTs;
4220   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4221 
4222   unsigned NumAggValues = AggValueVTs.size();
4223   unsigned NumValValues = ValValueVTs.size();
4224   SmallVector<SDValue, 4> Values(NumAggValues);
4225 
4226   // Ignore an insertvalue that produces an empty object
4227   if (!NumAggValues) {
4228     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4229     return;
4230   }
4231 
4232   SDValue Agg = getValue(Op0);
4233   unsigned i = 0;
4234   // Copy the beginning value(s) from the original aggregate.
4235   for (; i != LinearIndex; ++i)
4236     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4237                 SDValue(Agg.getNode(), Agg.getResNo() + i);
4238   // Copy values from the inserted value(s).
4239   if (NumValValues) {
4240     SDValue Val = getValue(Op1);
4241     for (; i != LinearIndex + NumValValues; ++i)
4242       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4243                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
4244   }
4245   // Copy remaining value(s) from the original aggregate.
4246   for (; i != NumAggValues; ++i)
4247     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4248                 SDValue(Agg.getNode(), Agg.getResNo() + i);
4249 
4250   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
4251                            DAG.getVTList(AggValueVTs), Values));
4252 }
4253 
4254 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
4255   ArrayRef<unsigned> Indices = I.getIndices();
4256   const Value *Op0 = I.getOperand(0);
4257   Type *AggTy = Op0->getType();
4258   Type *ValTy = I.getType();
4259   bool OutOfUndef = isa<UndefValue>(Op0);
4260 
4261   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4262 
4263   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4264   SmallVector<EVT, 4> ValValueVTs;
4265   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4266 
4267   unsigned NumValValues = ValValueVTs.size();
4268 
4269   // Ignore a extractvalue that produces an empty object
4270   if (!NumValValues) {
4271     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4272     return;
4273   }
4274 
4275   SmallVector<SDValue, 4> Values(NumValValues);
4276 
4277   SDValue Agg = getValue(Op0);
4278   // Copy out the selected value(s).
4279   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
4280     Values[i - LinearIndex] =
4281       OutOfUndef ?
4282         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
4283         SDValue(Agg.getNode(), Agg.getResNo() + i);
4284 
4285   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
4286                            DAG.getVTList(ValValueVTs), Values));
4287 }
4288 
4289 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
4290   Value *Op0 = I.getOperand(0);
4291   // Note that the pointer operand may be a vector of pointers. Take the scalar
4292   // element which holds a pointer.
4293   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
4294   SDValue N = getValue(Op0);
4295   SDLoc dl = getCurSDLoc();
4296   auto &TLI = DAG.getTargetLoweringInfo();
4297   GEPNoWrapFlags NW = cast<GEPOperator>(I).getNoWrapFlags();
4298 
4299   // Normalize Vector GEP - all scalar operands should be converted to the
4300   // splat vector.
4301   bool IsVectorGEP = I.getType()->isVectorTy();
4302   ElementCount VectorElementCount =
4303       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
4304                   : ElementCount::getFixed(0);
4305 
4306   if (IsVectorGEP && !N.getValueType().isVector()) {
4307     LLVMContext &Context = *DAG.getContext();
4308     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
4309     N = DAG.getSplat(VT, dl, N);
4310   }
4311 
4312   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
4313        GTI != E; ++GTI) {
4314     const Value *Idx = GTI.getOperand();
4315     if (StructType *StTy = GTI.getStructTypeOrNull()) {
4316       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
4317       if (Field) {
4318         // N = N + Offset
4319         uint64_t Offset =
4320             DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
4321 
4322         // In an inbounds GEP with an offset that is nonnegative even when
4323         // interpreted as signed, assume there is no unsigned overflow.
4324         SDNodeFlags Flags;
4325         if (NW.hasNoUnsignedWrap() ||
4326             (int64_t(Offset) >= 0 && NW.hasNoUnsignedSignedWrap()))
4327           Flags.setNoUnsignedWrap(true);
4328 
4329         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
4330                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
4331       }
4332     } else {
4333       // IdxSize is the width of the arithmetic according to IR semantics.
4334       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
4335       // (and fix up the result later).
4336       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
4337       MVT IdxTy = MVT::getIntegerVT(IdxSize);
4338       TypeSize ElementSize =
4339           GTI.getSequentialElementStride(DAG.getDataLayout());
4340       // We intentionally mask away the high bits here; ElementSize may not
4341       // fit in IdxTy.
4342       APInt ElementMul(IdxSize, ElementSize.getKnownMinValue());
4343       bool ElementScalable = ElementSize.isScalable();
4344 
4345       // If this is a scalar constant or a splat vector of constants,
4346       // handle it quickly.
4347       const auto *C = dyn_cast<Constant>(Idx);
4348       if (C && isa<VectorType>(C->getType()))
4349         C = C->getSplatValue();
4350 
4351       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
4352       if (CI && CI->isZero())
4353         continue;
4354       if (CI && !ElementScalable) {
4355         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
4356         LLVMContext &Context = *DAG.getContext();
4357         SDValue OffsVal;
4358         if (IsVectorGEP)
4359           OffsVal = DAG.getConstant(
4360               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
4361         else
4362           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
4363 
4364         // In an inbounds GEP with an offset that is nonnegative even when
4365         // interpreted as signed, assume there is no unsigned overflow.
4366         SDNodeFlags Flags;
4367         if (NW.hasNoUnsignedWrap() ||
4368             (Offs.isNonNegative() && NW.hasNoUnsignedSignedWrap()))
4369           Flags.setNoUnsignedWrap(true);
4370 
4371         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
4372 
4373         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
4374         continue;
4375       }
4376 
4377       // N = N + Idx * ElementMul;
4378       SDValue IdxN = getValue(Idx);
4379 
4380       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
4381         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
4382                                   VectorElementCount);
4383         IdxN = DAG.getSplat(VT, dl, IdxN);
4384       }
4385 
4386       // If the index is smaller or larger than intptr_t, truncate or extend
4387       // it.
4388       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
4389 
4390       if (ElementScalable) {
4391         EVT VScaleTy = N.getValueType().getScalarType();
4392         SDValue VScale = DAG.getNode(
4393             ISD::VSCALE, dl, VScaleTy,
4394             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
4395         if (IsVectorGEP)
4396           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
4397         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
4398       } else {
4399         // If this is a multiply by a power of two, turn it into a shl
4400         // immediately.  This is a very common case.
4401         if (ElementMul != 1) {
4402           if (ElementMul.isPowerOf2()) {
4403             unsigned Amt = ElementMul.logBase2();
4404             IdxN = DAG.getNode(ISD::SHL, dl,
4405                                N.getValueType(), IdxN,
4406                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
4407           } else {
4408             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
4409                                             IdxN.getValueType());
4410             IdxN = DAG.getNode(ISD::MUL, dl,
4411                                N.getValueType(), IdxN, Scale);
4412           }
4413         }
4414       }
4415 
4416       N = DAG.getNode(ISD::ADD, dl,
4417                       N.getValueType(), N, IdxN);
4418     }
4419   }
4420 
4421   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4422   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4423   if (IsVectorGEP) {
4424     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4425     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4426   }
4427 
4428   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4429     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4430 
4431   setValue(&I, N);
4432 }
4433 
4434 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4435   // If this is a fixed sized alloca in the entry block of the function,
4436   // allocate it statically on the stack.
4437   if (FuncInfo.StaticAllocaMap.count(&I))
4438     return;   // getValue will auto-populate this.
4439 
4440   SDLoc dl = getCurSDLoc();
4441   Type *Ty = I.getAllocatedType();
4442   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4443   auto &DL = DAG.getDataLayout();
4444   TypeSize TySize = DL.getTypeAllocSize(Ty);
4445   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4446 
4447   SDValue AllocSize = getValue(I.getArraySize());
4448 
4449   EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace());
4450   if (AllocSize.getValueType() != IntPtr)
4451     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4452 
4453   if (TySize.isScalable())
4454     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4455                             DAG.getVScale(dl, IntPtr,
4456                                           APInt(IntPtr.getScalarSizeInBits(),
4457                                                 TySize.getKnownMinValue())));
4458   else {
4459     SDValue TySizeValue =
4460         DAG.getConstant(TySize.getFixedValue(), dl, MVT::getIntegerVT(64));
4461     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4462                             DAG.getZExtOrTrunc(TySizeValue, dl, IntPtr));
4463   }
4464 
4465   // Handle alignment.  If the requested alignment is less than or equal to
4466   // the stack alignment, ignore it.  If the size is greater than or equal to
4467   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4468   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4469   if (*Alignment <= StackAlign)
4470     Alignment = std::nullopt;
4471 
4472   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4473   // Round the size of the allocation up to the stack alignment size
4474   // by add SA-1 to the size. This doesn't overflow because we're computing
4475   // an address inside an alloca.
4476   SDNodeFlags Flags;
4477   Flags.setNoUnsignedWrap(true);
4478   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4479                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4480 
4481   // Mask out the low bits for alignment purposes.
4482   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4483                           DAG.getSignedConstant(~StackAlignMask, dl, IntPtr));
4484 
4485   SDValue Ops[] = {
4486       getRoot(), AllocSize,
4487       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4488   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4489   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4490   setValue(&I, DSA);
4491   DAG.setRoot(DSA.getValue(1));
4492 
4493   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4494 }
4495 
4496 static const MDNode *getRangeMetadata(const Instruction &I) {
4497   // If !noundef is not present, then !range violation results in a poison
4498   // value rather than immediate undefined behavior. In theory, transferring
4499   // these annotations to SDAG is fine, but in practice there are key SDAG
4500   // transforms that are known not to be poison-safe, such as folding logical
4501   // and/or to bitwise and/or. For now, only transfer !range if !noundef is
4502   // also present.
4503   if (!I.hasMetadata(LLVMContext::MD_noundef))
4504     return nullptr;
4505   return I.getMetadata(LLVMContext::MD_range);
4506 }
4507 
4508 static std::optional<ConstantRange> getRange(const Instruction &I) {
4509   if (const auto *CB = dyn_cast<CallBase>(&I)) {
4510     // see comment in getRangeMetadata about this check
4511     if (CB->hasRetAttr(Attribute::NoUndef))
4512       return CB->getRange();
4513   }
4514   if (const MDNode *Range = getRangeMetadata(I))
4515     return getConstantRangeFromMetadata(*Range);
4516   return std::nullopt;
4517 }
4518 
4519 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4520   if (I.isAtomic())
4521     return visitAtomicLoad(I);
4522 
4523   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4524   const Value *SV = I.getOperand(0);
4525   if (TLI.supportSwiftError()) {
4526     // Swifterror values can come from either a function parameter with
4527     // swifterror attribute or an alloca with swifterror attribute.
4528     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4529       if (Arg->hasSwiftErrorAttr())
4530         return visitLoadFromSwiftError(I);
4531     }
4532 
4533     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4534       if (Alloca->isSwiftError())
4535         return visitLoadFromSwiftError(I);
4536     }
4537   }
4538 
4539   SDValue Ptr = getValue(SV);
4540 
4541   Type *Ty = I.getType();
4542   SmallVector<EVT, 4> ValueVTs, MemVTs;
4543   SmallVector<TypeSize, 4> Offsets;
4544   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4545   unsigned NumValues = ValueVTs.size();
4546   if (NumValues == 0)
4547     return;
4548 
4549   Align Alignment = I.getAlign();
4550   AAMDNodes AAInfo = I.getAAMetadata();
4551   const MDNode *Ranges = getRangeMetadata(I);
4552   bool isVolatile = I.isVolatile();
4553   MachineMemOperand::Flags MMOFlags =
4554       TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4555 
4556   SDValue Root;
4557   bool ConstantMemory = false;
4558   if (isVolatile)
4559     // Serialize volatile loads with other side effects.
4560     Root = getRoot();
4561   else if (NumValues > MaxParallelChains)
4562     Root = getMemoryRoot();
4563   else if (AA &&
4564            AA->pointsToConstantMemory(MemoryLocation(
4565                SV,
4566                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4567                AAInfo))) {
4568     // Do not serialize (non-volatile) loads of constant memory with anything.
4569     Root = DAG.getEntryNode();
4570     ConstantMemory = true;
4571     MMOFlags |= MachineMemOperand::MOInvariant;
4572   } else {
4573     // Do not serialize non-volatile loads against each other.
4574     Root = DAG.getRoot();
4575   }
4576 
4577   SDLoc dl = getCurSDLoc();
4578 
4579   if (isVolatile)
4580     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4581 
4582   SmallVector<SDValue, 4> Values(NumValues);
4583   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4584 
4585   unsigned ChainI = 0;
4586   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4587     // Serializing loads here may result in excessive register pressure, and
4588     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4589     // could recover a bit by hoisting nodes upward in the chain by recognizing
4590     // they are side-effect free or do not alias. The optimizer should really
4591     // avoid this case by converting large object/array copies to llvm.memcpy
4592     // (MaxParallelChains should always remain as failsafe).
4593     if (ChainI == MaxParallelChains) {
4594       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4595       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4596                                   ArrayRef(Chains.data(), ChainI));
4597       Root = Chain;
4598       ChainI = 0;
4599     }
4600 
4601     // TODO: MachinePointerInfo only supports a fixed length offset.
4602     MachinePointerInfo PtrInfo =
4603         !Offsets[i].isScalable() || Offsets[i].isZero()
4604             ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue())
4605             : MachinePointerInfo();
4606 
4607     SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4608     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment,
4609                             MMOFlags, AAInfo, Ranges);
4610     Chains[ChainI] = L.getValue(1);
4611 
4612     if (MemVTs[i] != ValueVTs[i])
4613       L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]);
4614 
4615     Values[i] = L;
4616   }
4617 
4618   if (!ConstantMemory) {
4619     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4620                                 ArrayRef(Chains.data(), ChainI));
4621     if (isVolatile)
4622       DAG.setRoot(Chain);
4623     else
4624       PendingLoads.push_back(Chain);
4625   }
4626 
4627   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4628                            DAG.getVTList(ValueVTs), Values));
4629 }
4630 
4631 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4632   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4633          "call visitStoreToSwiftError when backend supports swifterror");
4634 
4635   SmallVector<EVT, 4> ValueVTs;
4636   SmallVector<uint64_t, 4> Offsets;
4637   const Value *SrcV = I.getOperand(0);
4638   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4639                   SrcV->getType(), ValueVTs, &Offsets, 0);
4640   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4641          "expect a single EVT for swifterror");
4642 
4643   SDValue Src = getValue(SrcV);
4644   // Create a virtual register, then update the virtual register.
4645   Register VReg =
4646       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4647   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4648   // Chain can be getRoot or getControlRoot.
4649   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4650                                       SDValue(Src.getNode(), Src.getResNo()));
4651   DAG.setRoot(CopyNode);
4652 }
4653 
4654 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4655   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4656          "call visitLoadFromSwiftError when backend supports swifterror");
4657 
4658   assert(!I.isVolatile() &&
4659          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4660          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4661          "Support volatile, non temporal, invariant for load_from_swift_error");
4662 
4663   const Value *SV = I.getOperand(0);
4664   Type *Ty = I.getType();
4665   assert(
4666       (!AA ||
4667        !AA->pointsToConstantMemory(MemoryLocation(
4668            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4669            I.getAAMetadata()))) &&
4670       "load_from_swift_error should not be constant memory");
4671 
4672   SmallVector<EVT, 4> ValueVTs;
4673   SmallVector<uint64_t, 4> Offsets;
4674   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4675                   ValueVTs, &Offsets, 0);
4676   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4677          "expect a single EVT for swifterror");
4678 
4679   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4680   SDValue L = DAG.getCopyFromReg(
4681       getRoot(), getCurSDLoc(),
4682       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4683 
4684   setValue(&I, L);
4685 }
4686 
4687 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4688   if (I.isAtomic())
4689     return visitAtomicStore(I);
4690 
4691   const Value *SrcV = I.getOperand(0);
4692   const Value *PtrV = I.getOperand(1);
4693 
4694   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4695   if (TLI.supportSwiftError()) {
4696     // Swifterror values can come from either a function parameter with
4697     // swifterror attribute or an alloca with swifterror attribute.
4698     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4699       if (Arg->hasSwiftErrorAttr())
4700         return visitStoreToSwiftError(I);
4701     }
4702 
4703     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4704       if (Alloca->isSwiftError())
4705         return visitStoreToSwiftError(I);
4706     }
4707   }
4708 
4709   SmallVector<EVT, 4> ValueVTs, MemVTs;
4710   SmallVector<TypeSize, 4> Offsets;
4711   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4712                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4713   unsigned NumValues = ValueVTs.size();
4714   if (NumValues == 0)
4715     return;
4716 
4717   // Get the lowered operands. Note that we do this after
4718   // checking if NumResults is zero, because with zero results
4719   // the operands won't have values in the map.
4720   SDValue Src = getValue(SrcV);
4721   SDValue Ptr = getValue(PtrV);
4722 
4723   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4724   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4725   SDLoc dl = getCurSDLoc();
4726   Align Alignment = I.getAlign();
4727   AAMDNodes AAInfo = I.getAAMetadata();
4728 
4729   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4730 
4731   unsigned ChainI = 0;
4732   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4733     // See visitLoad comments.
4734     if (ChainI == MaxParallelChains) {
4735       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4736                                   ArrayRef(Chains.data(), ChainI));
4737       Root = Chain;
4738       ChainI = 0;
4739     }
4740 
4741     // TODO: MachinePointerInfo only supports a fixed length offset.
4742     MachinePointerInfo PtrInfo =
4743         !Offsets[i].isScalable() || Offsets[i].isZero()
4744             ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue())
4745             : MachinePointerInfo();
4746 
4747     SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4748     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4749     if (MemVTs[i] != ValueVTs[i])
4750       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4751     SDValue St =
4752         DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags, AAInfo);
4753     Chains[ChainI] = St;
4754   }
4755 
4756   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4757                                   ArrayRef(Chains.data(), ChainI));
4758   setValue(&I, StoreNode);
4759   DAG.setRoot(StoreNode);
4760 }
4761 
4762 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4763                                            bool IsCompressing) {
4764   SDLoc sdl = getCurSDLoc();
4765 
4766   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4767                                Align &Alignment) {
4768     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4769     Src0 = I.getArgOperand(0);
4770     Ptr = I.getArgOperand(1);
4771     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getAlignValue();
4772     Mask = I.getArgOperand(3);
4773   };
4774   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4775                                     Align &Alignment) {
4776     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4777     Src0 = I.getArgOperand(0);
4778     Ptr = I.getArgOperand(1);
4779     Mask = I.getArgOperand(2);
4780     Alignment = I.getParamAlign(1).valueOrOne();
4781   };
4782 
4783   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4784   Align Alignment;
4785   if (IsCompressing)
4786     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4787   else
4788     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4789 
4790   SDValue Ptr = getValue(PtrOperand);
4791   SDValue Src0 = getValue(Src0Operand);
4792   SDValue Mask = getValue(MaskOperand);
4793   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4794 
4795   EVT VT = Src0.getValueType();
4796 
4797   auto MMOFlags = MachineMemOperand::MOStore;
4798   if (I.hasMetadata(LLVMContext::MD_nontemporal))
4799     MMOFlags |= MachineMemOperand::MONonTemporal;
4800 
4801   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4802       MachinePointerInfo(PtrOperand), MMOFlags,
4803       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata());
4804 
4805   const auto &TLI = DAG.getTargetLoweringInfo();
4806   const auto &TTI =
4807       TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction());
4808   SDValue StoreNode =
4809       !IsCompressing &&
4810               TTI.hasConditionalLoadStoreForType(I.getArgOperand(0)->getType())
4811           ? TLI.visitMaskedStore(DAG, sdl, getMemoryRoot(), MMO, Ptr, Src0,
4812                                  Mask)
4813           : DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask,
4814                                VT, MMO, ISD::UNINDEXED, /*Truncating=*/false,
4815                                IsCompressing);
4816   DAG.setRoot(StoreNode);
4817   setValue(&I, StoreNode);
4818 }
4819 
4820 // Get a uniform base for the Gather/Scatter intrinsic.
4821 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4822 // We try to represent it as a base pointer + vector of indices.
4823 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4824 // The first operand of the GEP may be a single pointer or a vector of pointers
4825 // Example:
4826 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4827 //  or
4828 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4829 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4830 //
4831 // When the first GEP operand is a single pointer - it is the uniform base we
4832 // are looking for. If first operand of the GEP is a splat vector - we
4833 // extract the splat value and use it as a uniform base.
4834 // In all other cases the function returns 'false'.
4835 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4836                            ISD::MemIndexType &IndexType, SDValue &Scale,
4837                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB,
4838                            uint64_t ElemSize) {
4839   SelectionDAG& DAG = SDB->DAG;
4840   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4841   const DataLayout &DL = DAG.getDataLayout();
4842 
4843   assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4844 
4845   // Handle splat constant pointer.
4846   if (auto *C = dyn_cast<Constant>(Ptr)) {
4847     C = C->getSplatValue();
4848     if (!C)
4849       return false;
4850 
4851     Base = SDB->getValue(C);
4852 
4853     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4854     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4855     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4856     IndexType = ISD::SIGNED_SCALED;
4857     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4858     return true;
4859   }
4860 
4861   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4862   if (!GEP || GEP->getParent() != CurBB)
4863     return false;
4864 
4865   if (GEP->getNumOperands() != 2)
4866     return false;
4867 
4868   const Value *BasePtr = GEP->getPointerOperand();
4869   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4870 
4871   // Make sure the base is scalar and the index is a vector.
4872   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4873     return false;
4874 
4875   TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
4876   if (ScaleVal.isScalable())
4877     return false;
4878 
4879   // Target may not support the required addressing mode.
4880   if (ScaleVal != 1 &&
4881       !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize))
4882     return false;
4883 
4884   Base = SDB->getValue(BasePtr);
4885   Index = SDB->getValue(IndexVal);
4886   IndexType = ISD::SIGNED_SCALED;
4887 
4888   Scale =
4889       DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4890   return true;
4891 }
4892 
4893 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4894   SDLoc sdl = getCurSDLoc();
4895 
4896   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4897   const Value *Ptr = I.getArgOperand(1);
4898   SDValue Src0 = getValue(I.getArgOperand(0));
4899   SDValue Mask = getValue(I.getArgOperand(3));
4900   EVT VT = Src0.getValueType();
4901   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4902                         ->getMaybeAlignValue()
4903                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4904   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4905 
4906   SDValue Base;
4907   SDValue Index;
4908   ISD::MemIndexType IndexType;
4909   SDValue Scale;
4910   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4911                                     I.getParent(), VT.getScalarStoreSize());
4912 
4913   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4914   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4915       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4916       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata());
4917   if (!UniformBase) {
4918     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4919     Index = getValue(Ptr);
4920     IndexType = ISD::SIGNED_SCALED;
4921     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4922   }
4923 
4924   EVT IdxVT = Index.getValueType();
4925   EVT EltTy = IdxVT.getVectorElementType();
4926   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4927     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4928     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4929   }
4930 
4931   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4932   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4933                                          Ops, MMO, IndexType, false);
4934   DAG.setRoot(Scatter);
4935   setValue(&I, Scatter);
4936 }
4937 
4938 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4939   SDLoc sdl = getCurSDLoc();
4940 
4941   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4942                               Align &Alignment) {
4943     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4944     Ptr = I.getArgOperand(0);
4945     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getAlignValue();
4946     Mask = I.getArgOperand(2);
4947     Src0 = I.getArgOperand(3);
4948   };
4949   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4950                                  Align &Alignment) {
4951     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4952     Ptr = I.getArgOperand(0);
4953     Alignment = I.getParamAlign(0).valueOrOne();
4954     Mask = I.getArgOperand(1);
4955     Src0 = I.getArgOperand(2);
4956   };
4957 
4958   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4959   Align Alignment;
4960   if (IsExpanding)
4961     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4962   else
4963     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4964 
4965   SDValue Ptr = getValue(PtrOperand);
4966   SDValue Src0 = getValue(Src0Operand);
4967   SDValue Mask = getValue(MaskOperand);
4968   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4969 
4970   EVT VT = Src0.getValueType();
4971   AAMDNodes AAInfo = I.getAAMetadata();
4972   const MDNode *Ranges = getRangeMetadata(I);
4973 
4974   // Do not serialize masked loads of constant memory with anything.
4975   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
4976   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4977 
4978   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4979 
4980   auto MMOFlags = MachineMemOperand::MOLoad;
4981   if (I.hasMetadata(LLVMContext::MD_nontemporal))
4982     MMOFlags |= MachineMemOperand::MONonTemporal;
4983 
4984   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4985       MachinePointerInfo(PtrOperand), MMOFlags,
4986       LocationSize::beforeOrAfterPointer(), Alignment, AAInfo, Ranges);
4987 
4988   const auto &TLI = DAG.getTargetLoweringInfo();
4989   const auto &TTI =
4990       TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction());
4991   // The Load/Res may point to different values and both of them are output
4992   // variables.
4993   SDValue Load;
4994   SDValue Res;
4995   if (!IsExpanding &&
4996       TTI.hasConditionalLoadStoreForType(Src0Operand->getType()))
4997     Res = TLI.visitMaskedLoad(DAG, sdl, InChain, MMO, Load, Ptr, Src0, Mask);
4998   else
4999     Res = Load =
5000         DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
5001                           ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
5002   if (AddToChain)
5003     PendingLoads.push_back(Load.getValue(1));
5004   setValue(&I, Res);
5005 }
5006 
5007 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
5008   SDLoc sdl = getCurSDLoc();
5009 
5010   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
5011   const Value *Ptr = I.getArgOperand(0);
5012   SDValue Src0 = getValue(I.getArgOperand(3));
5013   SDValue Mask = getValue(I.getArgOperand(2));
5014 
5015   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5016   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5017   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
5018                         ->getMaybeAlignValue()
5019                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
5020 
5021   const MDNode *Ranges = getRangeMetadata(I);
5022 
5023   SDValue Root = DAG.getRoot();
5024   SDValue Base;
5025   SDValue Index;
5026   ISD::MemIndexType IndexType;
5027   SDValue Scale;
5028   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
5029                                     I.getParent(), VT.getScalarStoreSize());
5030   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
5031   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5032       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
5033       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata(),
5034       Ranges);
5035 
5036   if (!UniformBase) {
5037     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5038     Index = getValue(Ptr);
5039     IndexType = ISD::SIGNED_SCALED;
5040     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5041   }
5042 
5043   EVT IdxVT = Index.getValueType();
5044   EVT EltTy = IdxVT.getVectorElementType();
5045   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
5046     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
5047     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
5048   }
5049 
5050   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
5051   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
5052                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
5053 
5054   PendingLoads.push_back(Gather.getValue(1));
5055   setValue(&I, Gather);
5056 }
5057 
5058 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
5059   SDLoc dl = getCurSDLoc();
5060   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
5061   AtomicOrdering FailureOrdering = I.getFailureOrdering();
5062   SyncScope::ID SSID = I.getSyncScopeID();
5063 
5064   SDValue InChain = getRoot();
5065 
5066   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
5067   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
5068 
5069   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5070   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5071 
5072   MachineFunction &MF = DAG.getMachineFunction();
5073   MachineMemOperand *MMO = MF.getMachineMemOperand(
5074       MachinePointerInfo(I.getPointerOperand()), Flags,
5075       LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT),
5076       AAMDNodes(), nullptr, SSID, SuccessOrdering, FailureOrdering);
5077 
5078   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
5079                                    dl, MemVT, VTs, InChain,
5080                                    getValue(I.getPointerOperand()),
5081                                    getValue(I.getCompareOperand()),
5082                                    getValue(I.getNewValOperand()), MMO);
5083 
5084   SDValue OutChain = L.getValue(2);
5085 
5086   setValue(&I, L);
5087   DAG.setRoot(OutChain);
5088 }
5089 
5090 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
5091   SDLoc dl = getCurSDLoc();
5092   ISD::NodeType NT;
5093   switch (I.getOperation()) {
5094   default: llvm_unreachable("Unknown atomicrmw operation");
5095   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
5096   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
5097   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
5098   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
5099   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
5100   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
5101   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
5102   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
5103   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
5104   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
5105   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
5106   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
5107   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
5108   case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break;
5109   case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break;
5110   case AtomicRMWInst::UIncWrap:
5111     NT = ISD::ATOMIC_LOAD_UINC_WRAP;
5112     break;
5113   case AtomicRMWInst::UDecWrap:
5114     NT = ISD::ATOMIC_LOAD_UDEC_WRAP;
5115     break;
5116   case AtomicRMWInst::USubCond:
5117     NT = ISD::ATOMIC_LOAD_USUB_COND;
5118     break;
5119   case AtomicRMWInst::USubSat:
5120     NT = ISD::ATOMIC_LOAD_USUB_SAT;
5121     break;
5122   }
5123   AtomicOrdering Ordering = I.getOrdering();
5124   SyncScope::ID SSID = I.getSyncScopeID();
5125 
5126   SDValue InChain = getRoot();
5127 
5128   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
5129   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5130   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5131 
5132   MachineFunction &MF = DAG.getMachineFunction();
5133   MachineMemOperand *MMO = MF.getMachineMemOperand(
5134       MachinePointerInfo(I.getPointerOperand()), Flags,
5135       LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT),
5136       AAMDNodes(), nullptr, SSID, Ordering);
5137 
5138   SDValue L =
5139     DAG.getAtomic(NT, dl, MemVT, InChain,
5140                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
5141                   MMO);
5142 
5143   SDValue OutChain = L.getValue(1);
5144 
5145   setValue(&I, L);
5146   DAG.setRoot(OutChain);
5147 }
5148 
5149 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
5150   SDLoc dl = getCurSDLoc();
5151   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5152   SDValue Ops[3];
5153   Ops[0] = getRoot();
5154   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
5155                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
5156   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
5157                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
5158   SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
5159   setValue(&I, N);
5160   DAG.setRoot(N);
5161 }
5162 
5163 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
5164   SDLoc dl = getCurSDLoc();
5165   AtomicOrdering Order = I.getOrdering();
5166   SyncScope::ID SSID = I.getSyncScopeID();
5167 
5168   SDValue InChain = getRoot();
5169 
5170   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5171   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5172   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
5173 
5174   if (!TLI.supportsUnalignedAtomics() &&
5175       I.getAlign().value() < MemVT.getSizeInBits() / 8)
5176     report_fatal_error("Cannot generate unaligned atomic load");
5177 
5178   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
5179 
5180   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5181       MachinePointerInfo(I.getPointerOperand()), Flags,
5182       LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(),
5183       nullptr, SSID, Order);
5184 
5185   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
5186 
5187   SDValue Ptr = getValue(I.getPointerOperand());
5188   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
5189                             Ptr, MMO);
5190 
5191   SDValue OutChain = L.getValue(1);
5192   if (MemVT != VT)
5193     L = DAG.getPtrExtOrTrunc(L, dl, VT);
5194 
5195   setValue(&I, L);
5196   DAG.setRoot(OutChain);
5197 }
5198 
5199 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
5200   SDLoc dl = getCurSDLoc();
5201 
5202   AtomicOrdering Ordering = I.getOrdering();
5203   SyncScope::ID SSID = I.getSyncScopeID();
5204 
5205   SDValue InChain = getRoot();
5206 
5207   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5208   EVT MemVT =
5209       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
5210 
5211   if (!TLI.supportsUnalignedAtomics() &&
5212       I.getAlign().value() < MemVT.getSizeInBits() / 8)
5213     report_fatal_error("Cannot generate unaligned atomic store");
5214 
5215   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
5216 
5217   MachineFunction &MF = DAG.getMachineFunction();
5218   MachineMemOperand *MMO = MF.getMachineMemOperand(
5219       MachinePointerInfo(I.getPointerOperand()), Flags,
5220       LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(),
5221       nullptr, SSID, Ordering);
5222 
5223   SDValue Val = getValue(I.getValueOperand());
5224   if (Val.getValueType() != MemVT)
5225     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
5226   SDValue Ptr = getValue(I.getPointerOperand());
5227 
5228   SDValue OutChain =
5229       DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO);
5230 
5231   setValue(&I, OutChain);
5232   DAG.setRoot(OutChain);
5233 }
5234 
5235 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
5236 /// node.
5237 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
5238                                                unsigned Intrinsic) {
5239   // Ignore the callsite's attributes. A specific call site may be marked with
5240   // readnone, but the lowering code will expect the chain based on the
5241   // definition.
5242   const Function *F = I.getCalledFunction();
5243   bool HasChain = !F->doesNotAccessMemory();
5244   bool OnlyLoad =
5245       HasChain && F->onlyReadsMemory() && F->willReturn() && F->doesNotThrow();
5246 
5247   // Build the operand list.
5248   SmallVector<SDValue, 8> Ops;
5249   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
5250     if (OnlyLoad) {
5251       // We don't need to serialize loads against other loads.
5252       Ops.push_back(DAG.getRoot());
5253     } else {
5254       Ops.push_back(getRoot());
5255     }
5256   }
5257 
5258   // Info is set by getTgtMemIntrinsic
5259   TargetLowering::IntrinsicInfo Info;
5260   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5261   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
5262                                                DAG.getMachineFunction(),
5263                                                Intrinsic);
5264 
5265   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
5266   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
5267       Info.opc == ISD::INTRINSIC_W_CHAIN)
5268     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
5269                                         TLI.getPointerTy(DAG.getDataLayout())));
5270 
5271   // Add all operands of the call to the operand list.
5272   for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
5273     const Value *Arg = I.getArgOperand(i);
5274     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
5275       Ops.push_back(getValue(Arg));
5276       continue;
5277     }
5278 
5279     // Use TargetConstant instead of a regular constant for immarg.
5280     EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
5281     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
5282       assert(CI->getBitWidth() <= 64 &&
5283              "large intrinsic immediates not handled");
5284       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
5285     } else {
5286       Ops.push_back(
5287           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
5288     }
5289   }
5290 
5291   SmallVector<EVT, 4> ValueVTs;
5292   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
5293 
5294   if (HasChain)
5295     ValueVTs.push_back(MVT::Other);
5296 
5297   SDVTList VTs = DAG.getVTList(ValueVTs);
5298 
5299   // Propagate fast-math-flags from IR to node(s).
5300   SDNodeFlags Flags;
5301   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
5302     Flags.copyFMF(*FPMO);
5303   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
5304 
5305   // Create the node.
5306   SDValue Result;
5307 
5308   if (auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl)) {
5309     auto *Token = Bundle->Inputs[0].get();
5310     SDValue ConvControlToken = getValue(Token);
5311     assert(Ops.back().getValueType() != MVT::Glue &&
5312            "Did not expected another glue node here.");
5313     ConvControlToken =
5314         DAG.getNode(ISD::CONVERGENCECTRL_GLUE, {}, MVT::Glue, ConvControlToken);
5315     Ops.push_back(ConvControlToken);
5316   }
5317 
5318   // In some cases, custom collection of operands from CallInst I may be needed.
5319   TLI.CollectTargetIntrinsicOperands(I, Ops, DAG);
5320   if (IsTgtIntrinsic) {
5321     // This is target intrinsic that touches memory
5322     //
5323     // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic
5324     //       didn't yield anything useful.
5325     MachinePointerInfo MPI;
5326     if (Info.ptrVal)
5327       MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
5328     else if (Info.fallbackAddressSpace)
5329       MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
5330     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops,
5331                                      Info.memVT, MPI, Info.align, Info.flags,
5332                                      Info.size, I.getAAMetadata());
5333   } else if (!HasChain) {
5334     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
5335   } else if (!I.getType()->isVoidTy()) {
5336     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
5337   } else {
5338     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
5339   }
5340 
5341   if (HasChain) {
5342     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
5343     if (OnlyLoad)
5344       PendingLoads.push_back(Chain);
5345     else
5346       DAG.setRoot(Chain);
5347   }
5348 
5349   if (!I.getType()->isVoidTy()) {
5350     if (!isa<VectorType>(I.getType()))
5351       Result = lowerRangeToAssertZExt(DAG, I, Result);
5352 
5353     MaybeAlign Alignment = I.getRetAlign();
5354 
5355     // Insert `assertalign` node if there's an alignment.
5356     if (InsertAssertAlign && Alignment) {
5357       Result =
5358           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
5359     }
5360   }
5361 
5362   setValue(&I, Result);
5363 }
5364 
5365 /// GetSignificand - Get the significand and build it into a floating-point
5366 /// number with exponent of 1:
5367 ///
5368 ///   Op = (Op & 0x007fffff) | 0x3f800000;
5369 ///
5370 /// where Op is the hexadecimal representation of floating point value.
5371 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
5372   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5373                            DAG.getConstant(0x007fffff, dl, MVT::i32));
5374   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
5375                            DAG.getConstant(0x3f800000, dl, MVT::i32));
5376   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
5377 }
5378 
5379 /// GetExponent - Get the exponent:
5380 ///
5381 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
5382 ///
5383 /// where Op is the hexadecimal representation of floating point value.
5384 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
5385                            const TargetLowering &TLI, const SDLoc &dl) {
5386   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5387                            DAG.getConstant(0x7f800000, dl, MVT::i32));
5388   SDValue t1 = DAG.getNode(
5389       ISD::SRL, dl, MVT::i32, t0,
5390       DAG.getConstant(23, dl,
5391                       TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout())));
5392   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
5393                            DAG.getConstant(127, dl, MVT::i32));
5394   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
5395 }
5396 
5397 /// getF32Constant - Get 32-bit floating point constant.
5398 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
5399                               const SDLoc &dl) {
5400   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
5401                            MVT::f32);
5402 }
5403 
5404 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
5405                                        SelectionDAG &DAG) {
5406   // TODO: What fast-math-flags should be set on the floating-point nodes?
5407 
5408   //   IntegerPartOfX = ((int32_t)(t0);
5409   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
5410 
5411   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
5412   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
5413   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
5414 
5415   //   IntegerPartOfX <<= 23;
5416   IntegerPartOfX =
5417       DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
5418                   DAG.getConstant(23, dl,
5419                                   DAG.getTargetLoweringInfo().getShiftAmountTy(
5420                                       MVT::i32, DAG.getDataLayout())));
5421 
5422   SDValue TwoToFractionalPartOfX;
5423   if (LimitFloatPrecision <= 6) {
5424     // For floating-point precision of 6:
5425     //
5426     //   TwoToFractionalPartOfX =
5427     //     0.997535578f +
5428     //       (0.735607626f + 0.252464424f * x) * x;
5429     //
5430     // error 0.0144103317, which is 6 bits
5431     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5432                              getF32Constant(DAG, 0x3e814304, dl));
5433     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5434                              getF32Constant(DAG, 0x3f3c50c8, dl));
5435     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5436     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5437                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
5438   } else if (LimitFloatPrecision <= 12) {
5439     // For floating-point precision of 12:
5440     //
5441     //   TwoToFractionalPartOfX =
5442     //     0.999892986f +
5443     //       (0.696457318f +
5444     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
5445     //
5446     // error 0.000107046256, which is 13 to 14 bits
5447     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5448                              getF32Constant(DAG, 0x3da235e3, dl));
5449     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5450                              getF32Constant(DAG, 0x3e65b8f3, dl));
5451     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5452     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5453                              getF32Constant(DAG, 0x3f324b07, dl));
5454     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5455     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5456                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
5457   } else { // LimitFloatPrecision <= 18
5458     // For floating-point precision of 18:
5459     //
5460     //   TwoToFractionalPartOfX =
5461     //     0.999999982f +
5462     //       (0.693148872f +
5463     //         (0.240227044f +
5464     //           (0.554906021e-1f +
5465     //             (0.961591928e-2f +
5466     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5467     // error 2.47208000*10^(-7), which is better than 18 bits
5468     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5469                              getF32Constant(DAG, 0x3924b03e, dl));
5470     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5471                              getF32Constant(DAG, 0x3ab24b87, dl));
5472     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5473     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5474                              getF32Constant(DAG, 0x3c1d8c17, dl));
5475     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5476     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5477                              getF32Constant(DAG, 0x3d634a1d, dl));
5478     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5479     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5480                              getF32Constant(DAG, 0x3e75fe14, dl));
5481     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5482     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5483                               getF32Constant(DAG, 0x3f317234, dl));
5484     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5485     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5486                                          getF32Constant(DAG, 0x3f800000, dl));
5487   }
5488 
5489   // Add the exponent into the result in integer domain.
5490   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5491   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5492                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5493 }
5494 
5495 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5496 /// limited-precision mode.
5497 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5498                          const TargetLowering &TLI, SDNodeFlags Flags) {
5499   if (Op.getValueType() == MVT::f32 &&
5500       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5501 
5502     // Put the exponent in the right bit position for later addition to the
5503     // final result:
5504     //
5505     // t0 = Op * log2(e)
5506 
5507     // TODO: What fast-math-flags should be set here?
5508     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5509                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5510     return getLimitedPrecisionExp2(t0, dl, DAG);
5511   }
5512 
5513   // No special expansion.
5514   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5515 }
5516 
5517 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5518 /// limited-precision mode.
5519 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5520                          const TargetLowering &TLI, SDNodeFlags Flags) {
5521   // TODO: What fast-math-flags should be set on the floating-point nodes?
5522 
5523   if (Op.getValueType() == MVT::f32 &&
5524       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5525     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5526 
5527     // Scale the exponent by log(2).
5528     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5529     SDValue LogOfExponent =
5530         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5531                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5532 
5533     // Get the significand and build it into a floating-point number with
5534     // exponent of 1.
5535     SDValue X = GetSignificand(DAG, Op1, dl);
5536 
5537     SDValue LogOfMantissa;
5538     if (LimitFloatPrecision <= 6) {
5539       // For floating-point precision of 6:
5540       //
5541       //   LogofMantissa =
5542       //     -1.1609546f +
5543       //       (1.4034025f - 0.23903021f * x) * x;
5544       //
5545       // error 0.0034276066, which is better than 8 bits
5546       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5547                                getF32Constant(DAG, 0xbe74c456, dl));
5548       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5549                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5550       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5551       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5552                                   getF32Constant(DAG, 0x3f949a29, dl));
5553     } else if (LimitFloatPrecision <= 12) {
5554       // For floating-point precision of 12:
5555       //
5556       //   LogOfMantissa =
5557       //     -1.7417939f +
5558       //       (2.8212026f +
5559       //         (-1.4699568f +
5560       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5561       //
5562       // error 0.000061011436, which is 14 bits
5563       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5564                                getF32Constant(DAG, 0xbd67b6d6, dl));
5565       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5566                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5567       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5568       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5569                                getF32Constant(DAG, 0x3fbc278b, dl));
5570       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5571       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5572                                getF32Constant(DAG, 0x40348e95, dl));
5573       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5574       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5575                                   getF32Constant(DAG, 0x3fdef31a, dl));
5576     } else { // LimitFloatPrecision <= 18
5577       // For floating-point precision of 18:
5578       //
5579       //   LogOfMantissa =
5580       //     -2.1072184f +
5581       //       (4.2372794f +
5582       //         (-3.7029485f +
5583       //           (2.2781945f +
5584       //             (-0.87823314f +
5585       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5586       //
5587       // error 0.0000023660568, which is better than 18 bits
5588       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5589                                getF32Constant(DAG, 0xbc91e5ac, dl));
5590       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5591                                getF32Constant(DAG, 0x3e4350aa, dl));
5592       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5593       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5594                                getF32Constant(DAG, 0x3f60d3e3, dl));
5595       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5596       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5597                                getF32Constant(DAG, 0x4011cdf0, dl));
5598       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5599       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5600                                getF32Constant(DAG, 0x406cfd1c, dl));
5601       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5602       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5603                                getF32Constant(DAG, 0x408797cb, dl));
5604       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5605       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5606                                   getF32Constant(DAG, 0x4006dcab, dl));
5607     }
5608 
5609     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5610   }
5611 
5612   // No special expansion.
5613   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5614 }
5615 
5616 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5617 /// limited-precision mode.
5618 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5619                           const TargetLowering &TLI, SDNodeFlags Flags) {
5620   // TODO: What fast-math-flags should be set on the floating-point nodes?
5621 
5622   if (Op.getValueType() == MVT::f32 &&
5623       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5624     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5625 
5626     // Get the exponent.
5627     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5628 
5629     // Get the significand and build it into a floating-point number with
5630     // exponent of 1.
5631     SDValue X = GetSignificand(DAG, Op1, dl);
5632 
5633     // Different possible minimax approximations of significand in
5634     // floating-point for various degrees of accuracy over [1,2].
5635     SDValue Log2ofMantissa;
5636     if (LimitFloatPrecision <= 6) {
5637       // For floating-point precision of 6:
5638       //
5639       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5640       //
5641       // error 0.0049451742, which is more than 7 bits
5642       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5643                                getF32Constant(DAG, 0xbeb08fe0, dl));
5644       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5645                                getF32Constant(DAG, 0x40019463, dl));
5646       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5647       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5648                                    getF32Constant(DAG, 0x3fd6633d, dl));
5649     } else if (LimitFloatPrecision <= 12) {
5650       // For floating-point precision of 12:
5651       //
5652       //   Log2ofMantissa =
5653       //     -2.51285454f +
5654       //       (4.07009056f +
5655       //         (-2.12067489f +
5656       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5657       //
5658       // error 0.0000876136000, which is better than 13 bits
5659       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5660                                getF32Constant(DAG, 0xbda7262e, dl));
5661       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5662                                getF32Constant(DAG, 0x3f25280b, dl));
5663       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5664       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5665                                getF32Constant(DAG, 0x4007b923, dl));
5666       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5667       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5668                                getF32Constant(DAG, 0x40823e2f, dl));
5669       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5670       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5671                                    getF32Constant(DAG, 0x4020d29c, dl));
5672     } else { // LimitFloatPrecision <= 18
5673       // For floating-point precision of 18:
5674       //
5675       //   Log2ofMantissa =
5676       //     -3.0400495f +
5677       //       (6.1129976f +
5678       //         (-5.3420409f +
5679       //           (3.2865683f +
5680       //             (-1.2669343f +
5681       //               (0.27515199f -
5682       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5683       //
5684       // error 0.0000018516, which is better than 18 bits
5685       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5686                                getF32Constant(DAG, 0xbcd2769e, dl));
5687       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5688                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5689       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5690       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5691                                getF32Constant(DAG, 0x3fa22ae7, dl));
5692       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5693       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5694                                getF32Constant(DAG, 0x40525723, dl));
5695       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5696       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5697                                getF32Constant(DAG, 0x40aaf200, dl));
5698       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5699       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5700                                getF32Constant(DAG, 0x40c39dad, dl));
5701       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5702       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5703                                    getF32Constant(DAG, 0x4042902c, dl));
5704     }
5705 
5706     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5707   }
5708 
5709   // No special expansion.
5710   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5711 }
5712 
5713 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5714 /// limited-precision mode.
5715 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5716                            const TargetLowering &TLI, SDNodeFlags Flags) {
5717   // TODO: What fast-math-flags should be set on the floating-point nodes?
5718 
5719   if (Op.getValueType() == MVT::f32 &&
5720       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5721     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5722 
5723     // Scale the exponent by log10(2) [0.30102999f].
5724     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5725     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5726                                         getF32Constant(DAG, 0x3e9a209a, dl));
5727 
5728     // Get the significand and build it into a floating-point number with
5729     // exponent of 1.
5730     SDValue X = GetSignificand(DAG, Op1, dl);
5731 
5732     SDValue Log10ofMantissa;
5733     if (LimitFloatPrecision <= 6) {
5734       // For floating-point precision of 6:
5735       //
5736       //   Log10ofMantissa =
5737       //     -0.50419619f +
5738       //       (0.60948995f - 0.10380950f * x) * x;
5739       //
5740       // error 0.0014886165, which is 6 bits
5741       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5742                                getF32Constant(DAG, 0xbdd49a13, dl));
5743       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5744                                getF32Constant(DAG, 0x3f1c0789, dl));
5745       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5746       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5747                                     getF32Constant(DAG, 0x3f011300, dl));
5748     } else if (LimitFloatPrecision <= 12) {
5749       // For floating-point precision of 12:
5750       //
5751       //   Log10ofMantissa =
5752       //     -0.64831180f +
5753       //       (0.91751397f +
5754       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5755       //
5756       // error 0.00019228036, which is better than 12 bits
5757       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5758                                getF32Constant(DAG, 0x3d431f31, dl));
5759       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5760                                getF32Constant(DAG, 0x3ea21fb2, dl));
5761       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5762       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5763                                getF32Constant(DAG, 0x3f6ae232, dl));
5764       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5765       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5766                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5767     } else { // LimitFloatPrecision <= 18
5768       // For floating-point precision of 18:
5769       //
5770       //   Log10ofMantissa =
5771       //     -0.84299375f +
5772       //       (1.5327582f +
5773       //         (-1.0688956f +
5774       //           (0.49102474f +
5775       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5776       //
5777       // error 0.0000037995730, which is better than 18 bits
5778       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5779                                getF32Constant(DAG, 0x3c5d51ce, dl));
5780       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5781                                getF32Constant(DAG, 0x3e00685a, dl));
5782       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5783       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5784                                getF32Constant(DAG, 0x3efb6798, dl));
5785       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5786       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5787                                getF32Constant(DAG, 0x3f88d192, dl));
5788       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5789       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5790                                getF32Constant(DAG, 0x3fc4316c, dl));
5791       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5792       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5793                                     getF32Constant(DAG, 0x3f57ce70, dl));
5794     }
5795 
5796     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5797   }
5798 
5799   // No special expansion.
5800   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5801 }
5802 
5803 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5804 /// limited-precision mode.
5805 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5806                           const TargetLowering &TLI, SDNodeFlags Flags) {
5807   if (Op.getValueType() == MVT::f32 &&
5808       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5809     return getLimitedPrecisionExp2(Op, dl, DAG);
5810 
5811   // No special expansion.
5812   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5813 }
5814 
5815 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5816 /// limited-precision mode with x == 10.0f.
5817 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5818                          SelectionDAG &DAG, const TargetLowering &TLI,
5819                          SDNodeFlags Flags) {
5820   bool IsExp10 = false;
5821   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5822       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5823     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5824       APFloat Ten(10.0f);
5825       IsExp10 = LHSC->isExactlyValue(Ten);
5826     }
5827   }
5828 
5829   // TODO: What fast-math-flags should be set on the FMUL node?
5830   if (IsExp10) {
5831     // Put the exponent in the right bit position for later addition to the
5832     // final result:
5833     //
5834     //   #define LOG2OF10 3.3219281f
5835     //   t0 = Op * LOG2OF10;
5836     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5837                              getF32Constant(DAG, 0x40549a78, dl));
5838     return getLimitedPrecisionExp2(t0, dl, DAG);
5839   }
5840 
5841   // No special expansion.
5842   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5843 }
5844 
5845 /// ExpandPowI - Expand a llvm.powi intrinsic.
5846 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5847                           SelectionDAG &DAG) {
5848   // If RHS is a constant, we can expand this out to a multiplication tree if
5849   // it's beneficial on the target, otherwise we end up lowering to a call to
5850   // __powidf2 (for example).
5851   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5852     unsigned Val = RHSC->getSExtValue();
5853 
5854     // powi(x, 0) -> 1.0
5855     if (Val == 0)
5856       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5857 
5858     if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI(
5859             Val, DAG.shouldOptForSize())) {
5860       // Get the exponent as a positive value.
5861       if ((int)Val < 0)
5862         Val = -Val;
5863       // We use the simple binary decomposition method to generate the multiply
5864       // sequence.  There are more optimal ways to do this (for example,
5865       // powi(x,15) generates one more multiply than it should), but this has
5866       // the benefit of being both really simple and much better than a libcall.
5867       SDValue Res; // Logically starts equal to 1.0
5868       SDValue CurSquare = LHS;
5869       // TODO: Intrinsics should have fast-math-flags that propagate to these
5870       // nodes.
5871       while (Val) {
5872         if (Val & 1) {
5873           if (Res.getNode())
5874             Res =
5875                 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
5876           else
5877             Res = CurSquare; // 1.0*CurSquare.
5878         }
5879 
5880         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5881                                 CurSquare, CurSquare);
5882         Val >>= 1;
5883       }
5884 
5885       // If the original was negative, invert the result, producing 1/(x*x*x).
5886       if (RHSC->getSExtValue() < 0)
5887         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5888                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5889       return Res;
5890     }
5891   }
5892 
5893   // Otherwise, expand to a libcall.
5894   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5895 }
5896 
5897 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5898                             SDValue LHS, SDValue RHS, SDValue Scale,
5899                             SelectionDAG &DAG, const TargetLowering &TLI) {
5900   EVT VT = LHS.getValueType();
5901   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5902   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5903   LLVMContext &Ctx = *DAG.getContext();
5904 
5905   // If the type is legal but the operation isn't, this node might survive all
5906   // the way to operation legalization. If we end up there and we do not have
5907   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5908   // node.
5909 
5910   // Coax the legalizer into expanding the node during type legalization instead
5911   // by bumping the size by one bit. This will force it to Promote, enabling the
5912   // early expansion and avoiding the need to expand later.
5913 
5914   // We don't have to do this if Scale is 0; that can always be expanded, unless
5915   // it's a saturating signed operation. Those can experience true integer
5916   // division overflow, a case which we must avoid.
5917 
5918   // FIXME: We wouldn't have to do this (or any of the early
5919   // expansion/promotion) if it was possible to expand a libcall of an
5920   // illegal type during operation legalization. But it's not, so things
5921   // get a bit hacky.
5922   unsigned ScaleInt = Scale->getAsZExtVal();
5923   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5924       (TLI.isTypeLegal(VT) ||
5925        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5926     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5927         Opcode, VT, ScaleInt);
5928     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5929       EVT PromVT;
5930       if (VT.isScalarInteger())
5931         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5932       else if (VT.isVector()) {
5933         PromVT = VT.getVectorElementType();
5934         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5935         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5936       } else
5937         llvm_unreachable("Wrong VT for DIVFIX?");
5938       LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT);
5939       RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT);
5940       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5941       // For saturating operations, we need to shift up the LHS to get the
5942       // proper saturation width, and then shift down again afterwards.
5943       if (Saturating)
5944         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5945                           DAG.getConstant(1, DL, ShiftTy));
5946       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5947       if (Saturating)
5948         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5949                           DAG.getConstant(1, DL, ShiftTy));
5950       return DAG.getZExtOrTrunc(Res, DL, VT);
5951     }
5952   }
5953 
5954   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5955 }
5956 
5957 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5958 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5959 static void
5960 getUnderlyingArgRegs(SmallVectorImpl<std::pair<Register, TypeSize>> &Regs,
5961                      const SDValue &N) {
5962   switch (N.getOpcode()) {
5963   case ISD::CopyFromReg: {
5964     SDValue Op = N.getOperand(1);
5965     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5966                       Op.getValueType().getSizeInBits());
5967     return;
5968   }
5969   case ISD::BITCAST:
5970   case ISD::AssertZext:
5971   case ISD::AssertSext:
5972   case ISD::TRUNCATE:
5973     getUnderlyingArgRegs(Regs, N.getOperand(0));
5974     return;
5975   case ISD::BUILD_PAIR:
5976   case ISD::BUILD_VECTOR:
5977   case ISD::CONCAT_VECTORS:
5978     for (SDValue Op : N->op_values())
5979       getUnderlyingArgRegs(Regs, Op);
5980     return;
5981   default:
5982     return;
5983   }
5984 }
5985 
5986 /// If the DbgValueInst is a dbg_value of a function argument, create the
5987 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5988 /// instruction selection, they will be inserted to the entry BB.
5989 /// We don't currently support this for variadic dbg_values, as they shouldn't
5990 /// appear for function arguments or in the prologue.
5991 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5992     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5993     DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
5994   const Argument *Arg = dyn_cast<Argument>(V);
5995   if (!Arg)
5996     return false;
5997 
5998   MachineFunction &MF = DAG.getMachineFunction();
5999   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6000 
6001   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
6002   // we've been asked to pursue.
6003   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
6004                               bool Indirect) {
6005     if (Reg.isVirtual() && MF.useDebugInstrRef()) {
6006       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
6007       // pointing at the VReg, which will be patched up later.
6008       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
6009       SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg(
6010           /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
6011           /* isKill */ false, /* isDead */ false,
6012           /* isUndef */ false, /* isEarlyClobber */ false,
6013           /* SubReg */ 0, /* isDebug */ true)});
6014 
6015       auto *NewDIExpr = FragExpr;
6016       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
6017       // the DIExpression.
6018       if (Indirect)
6019         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
6020       SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0});
6021       NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops);
6022       return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr);
6023     } else {
6024       // Create a completely standard DBG_VALUE.
6025       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
6026       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
6027     }
6028   };
6029 
6030   if (Kind == FuncArgumentDbgValueKind::Value) {
6031     // ArgDbgValues are hoisted to the beginning of the entry block. So we
6032     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
6033     // the entry block.
6034     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
6035     if (!IsInEntryBlock)
6036       return false;
6037 
6038     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
6039     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
6040     // variable that also is a param.
6041     //
6042     // Although, if we are at the top of the entry block already, we can still
6043     // emit using ArgDbgValue. This might catch some situations when the
6044     // dbg.value refers to an argument that isn't used in the entry block, so
6045     // any CopyToReg node would be optimized out and the only way to express
6046     // this DBG_VALUE is by using the physical reg (or FI) as done in this
6047     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
6048     // we should only emit as ArgDbgValue if the Variable is an argument to the
6049     // current function, and the dbg.value intrinsic is found in the entry
6050     // block.
6051     bool VariableIsFunctionInputArg = Variable->isParameter() &&
6052         !DL->getInlinedAt();
6053     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
6054     if (!IsInPrologue && !VariableIsFunctionInputArg)
6055       return false;
6056 
6057     // Here we assume that a function argument on IR level only can be used to
6058     // describe one input parameter on source level. If we for example have
6059     // source code like this
6060     //
6061     //    struct A { long x, y; };
6062     //    void foo(struct A a, long b) {
6063     //      ...
6064     //      b = a.x;
6065     //      ...
6066     //    }
6067     //
6068     // and IR like this
6069     //
6070     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
6071     //  entry:
6072     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
6073     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
6074     //    call void @llvm.dbg.value(metadata i32 %b, "b",
6075     //    ...
6076     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
6077     //    ...
6078     //
6079     // then the last dbg.value is describing a parameter "b" using a value that
6080     // is an argument. But since we already has used %a1 to describe a parameter
6081     // we should not handle that last dbg.value here (that would result in an
6082     // incorrect hoisting of the DBG_VALUE to the function entry).
6083     // Notice that we allow one dbg.value per IR level argument, to accommodate
6084     // for the situation with fragments above.
6085     // If there is no node for the value being handled, we return true to skip
6086     // the normal generation of debug info, as it would kill existing debug
6087     // info for the parameter in case of duplicates.
6088     if (VariableIsFunctionInputArg) {
6089       unsigned ArgNo = Arg->getArgNo();
6090       if (ArgNo >= FuncInfo.DescribedArgs.size())
6091         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
6092       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
6093         return !NodeMap[V].getNode();
6094       FuncInfo.DescribedArgs.set(ArgNo);
6095     }
6096   }
6097 
6098   bool IsIndirect = false;
6099   std::optional<MachineOperand> Op;
6100   // Some arguments' frame index is recorded during argument lowering.
6101   int FI = FuncInfo.getArgumentFrameIndex(Arg);
6102   if (FI != std::numeric_limits<int>::max())
6103     Op = MachineOperand::CreateFI(FI);
6104 
6105   SmallVector<std::pair<Register, TypeSize>, 8> ArgRegsAndSizes;
6106   if (!Op && N.getNode()) {
6107     getUnderlyingArgRegs(ArgRegsAndSizes, N);
6108     Register Reg;
6109     if (ArgRegsAndSizes.size() == 1)
6110       Reg = ArgRegsAndSizes.front().first;
6111 
6112     if (Reg && Reg.isVirtual()) {
6113       MachineRegisterInfo &RegInfo = MF.getRegInfo();
6114       Register PR = RegInfo.getLiveInPhysReg(Reg);
6115       if (PR)
6116         Reg = PR;
6117     }
6118     if (Reg) {
6119       Op = MachineOperand::CreateReg(Reg, false);
6120       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6121     }
6122   }
6123 
6124   if (!Op && N.getNode()) {
6125     // Check if frame index is available.
6126     SDValue LCandidate = peekThroughBitcasts(N);
6127     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
6128       if (FrameIndexSDNode *FINode =
6129           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
6130         Op = MachineOperand::CreateFI(FINode->getIndex());
6131   }
6132 
6133   if (!Op) {
6134     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
6135     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<Register, TypeSize>>
6136                                          SplitRegs) {
6137       unsigned Offset = 0;
6138       for (const auto &RegAndSize : SplitRegs) {
6139         // If the expression is already a fragment, the current register
6140         // offset+size might extend beyond the fragment. In this case, only
6141         // the register bits that are inside the fragment are relevant.
6142         int RegFragmentSizeInBits = RegAndSize.second;
6143         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
6144           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
6145           // The register is entirely outside the expression fragment,
6146           // so is irrelevant for debug info.
6147           if (Offset >= ExprFragmentSizeInBits)
6148             break;
6149           // The register is partially outside the expression fragment, only
6150           // the low bits within the fragment are relevant for debug info.
6151           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
6152             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
6153           }
6154         }
6155 
6156         auto FragmentExpr = DIExpression::createFragmentExpression(
6157             Expr, Offset, RegFragmentSizeInBits);
6158         Offset += RegAndSize.second;
6159         // If a valid fragment expression cannot be created, the variable's
6160         // correct value cannot be determined and so it is set as Undef.
6161         if (!FragmentExpr) {
6162           SDDbgValue *SDV = DAG.getConstantDbgValue(
6163               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
6164           DAG.AddDbgValue(SDV, false);
6165           continue;
6166         }
6167         MachineInstr *NewMI =
6168             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr,
6169                              Kind != FuncArgumentDbgValueKind::Value);
6170         FuncInfo.ArgDbgValues.push_back(NewMI);
6171       }
6172     };
6173 
6174     // Check if ValueMap has reg number.
6175     DenseMap<const Value *, Register>::const_iterator
6176       VMI = FuncInfo.ValueMap.find(V);
6177     if (VMI != FuncInfo.ValueMap.end()) {
6178       const auto &TLI = DAG.getTargetLoweringInfo();
6179       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
6180                        V->getType(), std::nullopt);
6181       if (RFV.occupiesMultipleRegs()) {
6182         splitMultiRegDbgValue(RFV.getRegsAndSizes());
6183         return true;
6184       }
6185 
6186       Op = MachineOperand::CreateReg(VMI->second, false);
6187       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6188     } else if (ArgRegsAndSizes.size() > 1) {
6189       // This was split due to the calling convention, and no virtual register
6190       // mapping exists for the value.
6191       splitMultiRegDbgValue(ArgRegsAndSizes);
6192       return true;
6193     }
6194   }
6195 
6196   if (!Op)
6197     return false;
6198 
6199   assert(Variable->isValidLocationForIntrinsic(DL) &&
6200          "Expected inlined-at fields to agree");
6201   MachineInstr *NewMI = nullptr;
6202 
6203   if (Op->isReg())
6204     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
6205   else
6206     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
6207                     Variable, Expr);
6208 
6209   // Otherwise, use ArgDbgValues.
6210   FuncInfo.ArgDbgValues.push_back(NewMI);
6211   return true;
6212 }
6213 
6214 /// Return the appropriate SDDbgValue based on N.
6215 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
6216                                              DILocalVariable *Variable,
6217                                              DIExpression *Expr,
6218                                              const DebugLoc &dl,
6219                                              unsigned DbgSDNodeOrder) {
6220   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
6221     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
6222     // stack slot locations.
6223     //
6224     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
6225     // debug values here after optimization:
6226     //
6227     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
6228     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
6229     //
6230     // Both describe the direct values of their associated variables.
6231     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
6232                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6233   }
6234   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
6235                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6236 }
6237 
6238 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
6239   switch (Intrinsic) {
6240   case Intrinsic::smul_fix:
6241     return ISD::SMULFIX;
6242   case Intrinsic::umul_fix:
6243     return ISD::UMULFIX;
6244   case Intrinsic::smul_fix_sat:
6245     return ISD::SMULFIXSAT;
6246   case Intrinsic::umul_fix_sat:
6247     return ISD::UMULFIXSAT;
6248   case Intrinsic::sdiv_fix:
6249     return ISD::SDIVFIX;
6250   case Intrinsic::udiv_fix:
6251     return ISD::UDIVFIX;
6252   case Intrinsic::sdiv_fix_sat:
6253     return ISD::SDIVFIXSAT;
6254   case Intrinsic::udiv_fix_sat:
6255     return ISD::UDIVFIXSAT;
6256   default:
6257     llvm_unreachable("Unhandled fixed point intrinsic");
6258   }
6259 }
6260 
6261 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
6262                                            const char *FunctionName) {
6263   assert(FunctionName && "FunctionName must not be nullptr");
6264   SDValue Callee = DAG.getExternalSymbol(
6265       FunctionName,
6266       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6267   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
6268 }
6269 
6270 /// Given a @llvm.call.preallocated.setup, return the corresponding
6271 /// preallocated call.
6272 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
6273   assert(cast<CallBase>(PreallocatedSetup)
6274                  ->getCalledFunction()
6275                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
6276          "expected call_preallocated_setup Value");
6277   for (const auto *U : PreallocatedSetup->users()) {
6278     auto *UseCall = cast<CallBase>(U);
6279     const Function *Fn = UseCall->getCalledFunction();
6280     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
6281       return UseCall;
6282     }
6283   }
6284   llvm_unreachable("expected corresponding call to preallocated setup/arg");
6285 }
6286 
6287 /// If DI is a debug value with an EntryValue expression, lower it using the
6288 /// corresponding physical register of the associated Argument value
6289 /// (guaranteed to exist by the verifier).
6290 bool SelectionDAGBuilder::visitEntryValueDbgValue(
6291     ArrayRef<const Value *> Values, DILocalVariable *Variable,
6292     DIExpression *Expr, DebugLoc DbgLoc) {
6293   if (!Expr->isEntryValue() || !hasSingleElement(Values))
6294     return false;
6295 
6296   // These properties are guaranteed by the verifier.
6297   const Argument *Arg = cast<Argument>(Values[0]);
6298   assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync));
6299 
6300   auto ArgIt = FuncInfo.ValueMap.find(Arg);
6301   if (ArgIt == FuncInfo.ValueMap.end()) {
6302     LLVM_DEBUG(
6303         dbgs() << "Dropping dbg.value: expression is entry_value but "
6304                   "couldn't find an associated register for the Argument\n");
6305     return true;
6306   }
6307   Register ArgVReg = ArgIt->getSecond();
6308 
6309   for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
6310     if (ArgVReg == VirtReg || ArgVReg == PhysReg) {
6311       SDDbgValue *SDV = DAG.getVRegDbgValue(
6312           Variable, Expr, PhysReg, false /*IsIndidrect*/, DbgLoc, SDNodeOrder);
6313       DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/);
6314       return true;
6315     }
6316   LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but "
6317                        "couldn't find a physical register\n");
6318   return true;
6319 }
6320 
6321 /// Lower the call to the specified intrinsic function.
6322 void SelectionDAGBuilder::visitConvergenceControl(const CallInst &I,
6323                                                   unsigned Intrinsic) {
6324   SDLoc sdl = getCurSDLoc();
6325   switch (Intrinsic) {
6326   case Intrinsic::experimental_convergence_anchor:
6327     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ANCHOR, sdl, MVT::Untyped));
6328     break;
6329   case Intrinsic::experimental_convergence_entry:
6330     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ENTRY, sdl, MVT::Untyped));
6331     break;
6332   case Intrinsic::experimental_convergence_loop: {
6333     auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl);
6334     auto *Token = Bundle->Inputs[0].get();
6335     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_LOOP, sdl, MVT::Untyped,
6336                              getValue(Token)));
6337     break;
6338   }
6339   }
6340 }
6341 
6342 void SelectionDAGBuilder::visitVectorHistogram(const CallInst &I,
6343                                                unsigned IntrinsicID) {
6344   // For now, we're only lowering an 'add' histogram.
6345   // We can add others later, e.g. saturating adds, min/max.
6346   assert(IntrinsicID == Intrinsic::experimental_vector_histogram_add &&
6347          "Tried to lower unsupported histogram type");
6348   SDLoc sdl = getCurSDLoc();
6349   Value *Ptr = I.getOperand(0);
6350   SDValue Inc = getValue(I.getOperand(1));
6351   SDValue Mask = getValue(I.getOperand(2));
6352 
6353   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6354   DataLayout TargetDL = DAG.getDataLayout();
6355   EVT VT = Inc.getValueType();
6356   Align Alignment = DAG.getEVTAlign(VT);
6357 
6358   const MDNode *Ranges = getRangeMetadata(I);
6359 
6360   SDValue Root = DAG.getRoot();
6361   SDValue Base;
6362   SDValue Index;
6363   ISD::MemIndexType IndexType;
6364   SDValue Scale;
6365   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
6366                                     I.getParent(), VT.getScalarStoreSize());
6367 
6368   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
6369 
6370   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6371       MachinePointerInfo(AS),
6372       MachineMemOperand::MOLoad | MachineMemOperand::MOStore,
6373       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
6374 
6375   if (!UniformBase) {
6376     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6377     Index = getValue(Ptr);
6378     IndexType = ISD::SIGNED_SCALED;
6379     Scale =
6380         DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6381   }
6382 
6383   EVT IdxVT = Index.getValueType();
6384   EVT EltTy = IdxVT.getVectorElementType();
6385   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
6386     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
6387     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
6388   }
6389 
6390   SDValue ID = DAG.getTargetConstant(IntrinsicID, sdl, MVT::i32);
6391 
6392   SDValue Ops[] = {Root, Inc, Mask, Base, Index, Scale, ID};
6393   SDValue Histogram = DAG.getMaskedHistogram(DAG.getVTList(MVT::Other), VT, sdl,
6394                                              Ops, MMO, IndexType);
6395 
6396   setValue(&I, Histogram);
6397   DAG.setRoot(Histogram);
6398 }
6399 
6400 /// Lower the call to the specified intrinsic function.
6401 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
6402                                              unsigned Intrinsic) {
6403   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6404   SDLoc sdl = getCurSDLoc();
6405   DebugLoc dl = getCurDebugLoc();
6406   SDValue Res;
6407 
6408   SDNodeFlags Flags;
6409   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
6410     Flags.copyFMF(*FPOp);
6411 
6412   switch (Intrinsic) {
6413   default:
6414     // By default, turn this into a target intrinsic node.
6415     visitTargetIntrinsic(I, Intrinsic);
6416     return;
6417   case Intrinsic::vscale: {
6418     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6419     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
6420     return;
6421   }
6422   case Intrinsic::vastart:  visitVAStart(I); return;
6423   case Intrinsic::vaend:    visitVAEnd(I); return;
6424   case Intrinsic::vacopy:   visitVACopy(I); return;
6425   case Intrinsic::returnaddress:
6426     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
6427                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6428                              getValue(I.getArgOperand(0))));
6429     return;
6430   case Intrinsic::addressofreturnaddress:
6431     setValue(&I,
6432              DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
6433                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6434     return;
6435   case Intrinsic::sponentry:
6436     setValue(&I,
6437              DAG.getNode(ISD::SPONENTRY, sdl,
6438                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6439     return;
6440   case Intrinsic::frameaddress:
6441     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
6442                              TLI.getFrameIndexTy(DAG.getDataLayout()),
6443                              getValue(I.getArgOperand(0))));
6444     return;
6445   case Intrinsic::read_volatile_register:
6446   case Intrinsic::read_register: {
6447     Value *Reg = I.getArgOperand(0);
6448     SDValue Chain = getRoot();
6449     SDValue RegName =
6450         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6451     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6452     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
6453       DAG.getVTList(VT, MVT::Other), Chain, RegName);
6454     setValue(&I, Res);
6455     DAG.setRoot(Res.getValue(1));
6456     return;
6457   }
6458   case Intrinsic::write_register: {
6459     Value *Reg = I.getArgOperand(0);
6460     Value *RegValue = I.getArgOperand(1);
6461     SDValue Chain = getRoot();
6462     SDValue RegName =
6463         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6464     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
6465                             RegName, getValue(RegValue)));
6466     return;
6467   }
6468   case Intrinsic::memcpy: {
6469     const auto &MCI = cast<MemCpyInst>(I);
6470     SDValue Op1 = getValue(I.getArgOperand(0));
6471     SDValue Op2 = getValue(I.getArgOperand(1));
6472     SDValue Op3 = getValue(I.getArgOperand(2));
6473     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
6474     Align DstAlign = MCI.getDestAlign().valueOrOne();
6475     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6476     Align Alignment = std::min(DstAlign, SrcAlign);
6477     bool isVol = MCI.isVolatile();
6478     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6479     // node.
6480     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6481     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6482                                /* AlwaysInline */ false, &I, std::nullopt,
6483                                MachinePointerInfo(I.getArgOperand(0)),
6484                                MachinePointerInfo(I.getArgOperand(1)),
6485                                I.getAAMetadata(), AA);
6486     updateDAGForMaybeTailCall(MC);
6487     return;
6488   }
6489   case Intrinsic::memcpy_inline: {
6490     const auto &MCI = cast<MemCpyInlineInst>(I);
6491     SDValue Dst = getValue(I.getArgOperand(0));
6492     SDValue Src = getValue(I.getArgOperand(1));
6493     SDValue Size = getValue(I.getArgOperand(2));
6494     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
6495     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
6496     Align DstAlign = MCI.getDestAlign().valueOrOne();
6497     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6498     Align Alignment = std::min(DstAlign, SrcAlign);
6499     bool isVol = MCI.isVolatile();
6500     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6501     // node.
6502     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
6503                                /* AlwaysInline */ true, &I, std::nullopt,
6504                                MachinePointerInfo(I.getArgOperand(0)),
6505                                MachinePointerInfo(I.getArgOperand(1)),
6506                                I.getAAMetadata(), AA);
6507     updateDAGForMaybeTailCall(MC);
6508     return;
6509   }
6510   case Intrinsic::memset: {
6511     const auto &MSI = cast<MemSetInst>(I);
6512     SDValue Op1 = getValue(I.getArgOperand(0));
6513     SDValue Op2 = getValue(I.getArgOperand(1));
6514     SDValue Op3 = getValue(I.getArgOperand(2));
6515     // @llvm.memset defines 0 and 1 to both mean no alignment.
6516     Align Alignment = MSI.getDestAlign().valueOrOne();
6517     bool isVol = MSI.isVolatile();
6518     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6519     SDValue MS = DAG.getMemset(
6520         Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false,
6521         &I, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
6522     updateDAGForMaybeTailCall(MS);
6523     return;
6524   }
6525   case Intrinsic::memset_inline: {
6526     const auto &MSII = cast<MemSetInlineInst>(I);
6527     SDValue Dst = getValue(I.getArgOperand(0));
6528     SDValue Value = getValue(I.getArgOperand(1));
6529     SDValue Size = getValue(I.getArgOperand(2));
6530     assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size");
6531     // @llvm.memset defines 0 and 1 to both mean no alignment.
6532     Align DstAlign = MSII.getDestAlign().valueOrOne();
6533     bool isVol = MSII.isVolatile();
6534     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6535     SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol,
6536                                /* AlwaysInline */ true, &I,
6537                                MachinePointerInfo(I.getArgOperand(0)),
6538                                I.getAAMetadata());
6539     updateDAGForMaybeTailCall(MC);
6540     return;
6541   }
6542   case Intrinsic::memmove: {
6543     const auto &MMI = cast<MemMoveInst>(I);
6544     SDValue Op1 = getValue(I.getArgOperand(0));
6545     SDValue Op2 = getValue(I.getArgOperand(1));
6546     SDValue Op3 = getValue(I.getArgOperand(2));
6547     // @llvm.memmove defines 0 and 1 to both mean no alignment.
6548     Align DstAlign = MMI.getDestAlign().valueOrOne();
6549     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
6550     Align Alignment = std::min(DstAlign, SrcAlign);
6551     bool isVol = MMI.isVolatile();
6552     // FIXME: Support passing different dest/src alignments to the memmove DAG
6553     // node.
6554     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6555     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, &I,
6556                                 /* OverrideTailCall */ std::nullopt,
6557                                 MachinePointerInfo(I.getArgOperand(0)),
6558                                 MachinePointerInfo(I.getArgOperand(1)),
6559                                 I.getAAMetadata(), AA);
6560     updateDAGForMaybeTailCall(MM);
6561     return;
6562   }
6563   case Intrinsic::memcpy_element_unordered_atomic: {
6564     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
6565     SDValue Dst = getValue(MI.getRawDest());
6566     SDValue Src = getValue(MI.getRawSource());
6567     SDValue Length = getValue(MI.getLength());
6568 
6569     Type *LengthTy = MI.getLength()->getType();
6570     unsigned ElemSz = MI.getElementSizeInBytes();
6571     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6572     SDValue MC =
6573         DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6574                             isTC, MachinePointerInfo(MI.getRawDest()),
6575                             MachinePointerInfo(MI.getRawSource()));
6576     updateDAGForMaybeTailCall(MC);
6577     return;
6578   }
6579   case Intrinsic::memmove_element_unordered_atomic: {
6580     auto &MI = cast<AtomicMemMoveInst>(I);
6581     SDValue Dst = getValue(MI.getRawDest());
6582     SDValue Src = getValue(MI.getRawSource());
6583     SDValue Length = getValue(MI.getLength());
6584 
6585     Type *LengthTy = MI.getLength()->getType();
6586     unsigned ElemSz = MI.getElementSizeInBytes();
6587     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6588     SDValue MC =
6589         DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6590                              isTC, MachinePointerInfo(MI.getRawDest()),
6591                              MachinePointerInfo(MI.getRawSource()));
6592     updateDAGForMaybeTailCall(MC);
6593     return;
6594   }
6595   case Intrinsic::memset_element_unordered_atomic: {
6596     auto &MI = cast<AtomicMemSetInst>(I);
6597     SDValue Dst = getValue(MI.getRawDest());
6598     SDValue Val = getValue(MI.getValue());
6599     SDValue Length = getValue(MI.getLength());
6600 
6601     Type *LengthTy = MI.getLength()->getType();
6602     unsigned ElemSz = MI.getElementSizeInBytes();
6603     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6604     SDValue MC =
6605         DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
6606                             isTC, MachinePointerInfo(MI.getRawDest()));
6607     updateDAGForMaybeTailCall(MC);
6608     return;
6609   }
6610   case Intrinsic::call_preallocated_setup: {
6611     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
6612     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6613     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
6614                               getRoot(), SrcValue);
6615     setValue(&I, Res);
6616     DAG.setRoot(Res);
6617     return;
6618   }
6619   case Intrinsic::call_preallocated_arg: {
6620     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6621     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6622     SDValue Ops[3];
6623     Ops[0] = getRoot();
6624     Ops[1] = SrcValue;
6625     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6626                                    MVT::i32); // arg index
6627     SDValue Res = DAG.getNode(
6628         ISD::PREALLOCATED_ARG, sdl,
6629         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6630     setValue(&I, Res);
6631     DAG.setRoot(Res.getValue(1));
6632     return;
6633   }
6634   case Intrinsic::dbg_declare: {
6635     const auto &DI = cast<DbgDeclareInst>(I);
6636     // Debug intrinsics are handled separately in assignment tracking mode.
6637     // Some intrinsics are handled right after Argument lowering.
6638     if (AssignmentTrackingEnabled ||
6639         FuncInfo.PreprocessedDbgDeclares.count(&DI))
6640       return;
6641     LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DI << "\n");
6642     DILocalVariable *Variable = DI.getVariable();
6643     DIExpression *Expression = DI.getExpression();
6644     dropDanglingDebugInfo(Variable, Expression);
6645     // Assume dbg.declare can not currently use DIArgList, i.e.
6646     // it is non-variadic.
6647     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6648     handleDebugDeclare(DI.getVariableLocationOp(0), Variable, Expression,
6649                        DI.getDebugLoc());
6650     return;
6651   }
6652   case Intrinsic::dbg_label: {
6653     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6654     DILabel *Label = DI.getLabel();
6655     assert(Label && "Missing label");
6656 
6657     SDDbgLabel *SDV;
6658     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6659     DAG.AddDbgLabel(SDV);
6660     return;
6661   }
6662   case Intrinsic::dbg_assign: {
6663     // Debug intrinsics are handled separately in assignment tracking mode.
6664     if (AssignmentTrackingEnabled)
6665       return;
6666     // If assignment tracking hasn't been enabled then fall through and treat
6667     // the dbg.assign as a dbg.value.
6668     [[fallthrough]];
6669   }
6670   case Intrinsic::dbg_value: {
6671     // Debug intrinsics are handled separately in assignment tracking mode.
6672     if (AssignmentTrackingEnabled)
6673       return;
6674     const DbgValueInst &DI = cast<DbgValueInst>(I);
6675     assert(DI.getVariable() && "Missing variable");
6676 
6677     DILocalVariable *Variable = DI.getVariable();
6678     DIExpression *Expression = DI.getExpression();
6679     dropDanglingDebugInfo(Variable, Expression);
6680 
6681     if (DI.isKillLocation()) {
6682       handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder);
6683       return;
6684     }
6685 
6686     SmallVector<Value *, 4> Values(DI.getValues());
6687     if (Values.empty())
6688       return;
6689 
6690     bool IsVariadic = DI.hasArgList();
6691     if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(),
6692                           SDNodeOrder, IsVariadic))
6693       addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
6694                            DI.getDebugLoc(), SDNodeOrder);
6695     return;
6696   }
6697 
6698   case Intrinsic::eh_typeid_for: {
6699     // Find the type id for the given typeinfo.
6700     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6701     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6702     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6703     setValue(&I, Res);
6704     return;
6705   }
6706 
6707   case Intrinsic::eh_return_i32:
6708   case Intrinsic::eh_return_i64:
6709     DAG.getMachineFunction().setCallsEHReturn(true);
6710     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6711                             MVT::Other,
6712                             getControlRoot(),
6713                             getValue(I.getArgOperand(0)),
6714                             getValue(I.getArgOperand(1))));
6715     return;
6716   case Intrinsic::eh_unwind_init:
6717     DAG.getMachineFunction().setCallsUnwindInit(true);
6718     return;
6719   case Intrinsic::eh_dwarf_cfa:
6720     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6721                              TLI.getPointerTy(DAG.getDataLayout()),
6722                              getValue(I.getArgOperand(0))));
6723     return;
6724   case Intrinsic::eh_sjlj_callsite: {
6725     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
6726     assert(FuncInfo.getCurrentCallSite() == 0 && "Overlapping call sites!");
6727 
6728     FuncInfo.setCurrentCallSite(CI->getZExtValue());
6729     return;
6730   }
6731   case Intrinsic::eh_sjlj_functioncontext: {
6732     // Get and store the index of the function context.
6733     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6734     AllocaInst *FnCtx =
6735       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6736     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6737     MFI.setFunctionContextIndex(FI);
6738     return;
6739   }
6740   case Intrinsic::eh_sjlj_setjmp: {
6741     SDValue Ops[2];
6742     Ops[0] = getRoot();
6743     Ops[1] = getValue(I.getArgOperand(0));
6744     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6745                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6746     setValue(&I, Op.getValue(0));
6747     DAG.setRoot(Op.getValue(1));
6748     return;
6749   }
6750   case Intrinsic::eh_sjlj_longjmp:
6751     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6752                             getRoot(), getValue(I.getArgOperand(0))));
6753     return;
6754   case Intrinsic::eh_sjlj_setup_dispatch:
6755     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6756                             getRoot()));
6757     return;
6758   case Intrinsic::masked_gather:
6759     visitMaskedGather(I);
6760     return;
6761   case Intrinsic::masked_load:
6762     visitMaskedLoad(I);
6763     return;
6764   case Intrinsic::masked_scatter:
6765     visitMaskedScatter(I);
6766     return;
6767   case Intrinsic::masked_store:
6768     visitMaskedStore(I);
6769     return;
6770   case Intrinsic::masked_expandload:
6771     visitMaskedLoad(I, true /* IsExpanding */);
6772     return;
6773   case Intrinsic::masked_compressstore:
6774     visitMaskedStore(I, true /* IsCompressing */);
6775     return;
6776   case Intrinsic::powi:
6777     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6778                             getValue(I.getArgOperand(1)), DAG));
6779     return;
6780   case Intrinsic::log:
6781     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6782     return;
6783   case Intrinsic::log2:
6784     setValue(&I,
6785              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6786     return;
6787   case Intrinsic::log10:
6788     setValue(&I,
6789              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6790     return;
6791   case Intrinsic::exp:
6792     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6793     return;
6794   case Intrinsic::exp2:
6795     setValue(&I,
6796              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6797     return;
6798   case Intrinsic::pow:
6799     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6800                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6801     return;
6802   case Intrinsic::sqrt:
6803   case Intrinsic::fabs:
6804   case Intrinsic::sin:
6805   case Intrinsic::cos:
6806   case Intrinsic::tan:
6807   case Intrinsic::asin:
6808   case Intrinsic::acos:
6809   case Intrinsic::atan:
6810   case Intrinsic::sinh:
6811   case Intrinsic::cosh:
6812   case Intrinsic::tanh:
6813   case Intrinsic::exp10:
6814   case Intrinsic::floor:
6815   case Intrinsic::ceil:
6816   case Intrinsic::trunc:
6817   case Intrinsic::rint:
6818   case Intrinsic::nearbyint:
6819   case Intrinsic::round:
6820   case Intrinsic::roundeven:
6821   case Intrinsic::canonicalize: {
6822     unsigned Opcode;
6823     // clang-format off
6824     switch (Intrinsic) {
6825     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6826     case Intrinsic::sqrt:         Opcode = ISD::FSQRT;         break;
6827     case Intrinsic::fabs:         Opcode = ISD::FABS;          break;
6828     case Intrinsic::sin:          Opcode = ISD::FSIN;          break;
6829     case Intrinsic::cos:          Opcode = ISD::FCOS;          break;
6830     case Intrinsic::tan:          Opcode = ISD::FTAN;          break;
6831     case Intrinsic::asin:         Opcode = ISD::FASIN;         break;
6832     case Intrinsic::acos:         Opcode = ISD::FACOS;         break;
6833     case Intrinsic::atan:         Opcode = ISD::FATAN;         break;
6834     case Intrinsic::sinh:         Opcode = ISD::FSINH;         break;
6835     case Intrinsic::cosh:         Opcode = ISD::FCOSH;         break;
6836     case Intrinsic::tanh:         Opcode = ISD::FTANH;         break;
6837     case Intrinsic::exp10:        Opcode = ISD::FEXP10;        break;
6838     case Intrinsic::floor:        Opcode = ISD::FFLOOR;        break;
6839     case Intrinsic::ceil:         Opcode = ISD::FCEIL;         break;
6840     case Intrinsic::trunc:        Opcode = ISD::FTRUNC;        break;
6841     case Intrinsic::rint:         Opcode = ISD::FRINT;         break;
6842     case Intrinsic::nearbyint:    Opcode = ISD::FNEARBYINT;    break;
6843     case Intrinsic::round:        Opcode = ISD::FROUND;        break;
6844     case Intrinsic::roundeven:    Opcode = ISD::FROUNDEVEN;    break;
6845     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6846     }
6847     // clang-format on
6848 
6849     setValue(&I, DAG.getNode(Opcode, sdl,
6850                              getValue(I.getArgOperand(0)).getValueType(),
6851                              getValue(I.getArgOperand(0)), Flags));
6852     return;
6853   }
6854   case Intrinsic::lround:
6855   case Intrinsic::llround:
6856   case Intrinsic::lrint:
6857   case Intrinsic::llrint: {
6858     unsigned Opcode;
6859     // clang-format off
6860     switch (Intrinsic) {
6861     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6862     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6863     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6864     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6865     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6866     }
6867     // clang-format on
6868 
6869     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6870     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6871                              getValue(I.getArgOperand(0))));
6872     return;
6873   }
6874   case Intrinsic::minnum:
6875     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6876                              getValue(I.getArgOperand(0)).getValueType(),
6877                              getValue(I.getArgOperand(0)),
6878                              getValue(I.getArgOperand(1)), Flags));
6879     return;
6880   case Intrinsic::maxnum:
6881     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6882                              getValue(I.getArgOperand(0)).getValueType(),
6883                              getValue(I.getArgOperand(0)),
6884                              getValue(I.getArgOperand(1)), Flags));
6885     return;
6886   case Intrinsic::minimum:
6887     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6888                              getValue(I.getArgOperand(0)).getValueType(),
6889                              getValue(I.getArgOperand(0)),
6890                              getValue(I.getArgOperand(1)), Flags));
6891     return;
6892   case Intrinsic::maximum:
6893     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6894                              getValue(I.getArgOperand(0)).getValueType(),
6895                              getValue(I.getArgOperand(0)),
6896                              getValue(I.getArgOperand(1)), Flags));
6897     return;
6898   case Intrinsic::minimumnum:
6899     setValue(&I, DAG.getNode(ISD::FMINIMUMNUM, sdl,
6900                              getValue(I.getArgOperand(0)).getValueType(),
6901                              getValue(I.getArgOperand(0)),
6902                              getValue(I.getArgOperand(1)), Flags));
6903     return;
6904   case Intrinsic::maximumnum:
6905     setValue(&I, DAG.getNode(ISD::FMAXIMUMNUM, sdl,
6906                              getValue(I.getArgOperand(0)).getValueType(),
6907                              getValue(I.getArgOperand(0)),
6908                              getValue(I.getArgOperand(1)), Flags));
6909     return;
6910   case Intrinsic::copysign:
6911     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6912                              getValue(I.getArgOperand(0)).getValueType(),
6913                              getValue(I.getArgOperand(0)),
6914                              getValue(I.getArgOperand(1)), Flags));
6915     return;
6916   case Intrinsic::ldexp:
6917     setValue(&I, DAG.getNode(ISD::FLDEXP, sdl,
6918                              getValue(I.getArgOperand(0)).getValueType(),
6919                              getValue(I.getArgOperand(0)),
6920                              getValue(I.getArgOperand(1)), Flags));
6921     return;
6922   case Intrinsic::frexp: {
6923     SmallVector<EVT, 2> ValueVTs;
6924     ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
6925     SDVTList VTs = DAG.getVTList(ValueVTs);
6926     setValue(&I,
6927              DAG.getNode(ISD::FFREXP, sdl, VTs, getValue(I.getArgOperand(0))));
6928     return;
6929   }
6930   case Intrinsic::arithmetic_fence: {
6931     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6932                              getValue(I.getArgOperand(0)).getValueType(),
6933                              getValue(I.getArgOperand(0)), Flags));
6934     return;
6935   }
6936   case Intrinsic::fma:
6937     setValue(&I, DAG.getNode(
6938                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6939                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6940                      getValue(I.getArgOperand(2)), Flags));
6941     return;
6942 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6943   case Intrinsic::INTRINSIC:
6944 #include "llvm/IR/ConstrainedOps.def"
6945     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6946     return;
6947 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6948 #include "llvm/IR/VPIntrinsics.def"
6949     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6950     return;
6951   case Intrinsic::fptrunc_round: {
6952     // Get the last argument, the metadata and convert it to an integer in the
6953     // call
6954     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
6955     std::optional<RoundingMode> RoundMode =
6956         convertStrToRoundingMode(cast<MDString>(MD)->getString());
6957 
6958     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6959 
6960     // Propagate fast-math-flags from IR to node(s).
6961     SDNodeFlags Flags;
6962     Flags.copyFMF(*cast<FPMathOperator>(&I));
6963     SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
6964 
6965     SDValue Result;
6966     Result = DAG.getNode(
6967         ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
6968         DAG.getTargetConstant((int)*RoundMode, sdl, MVT::i32));
6969     setValue(&I, Result);
6970 
6971     return;
6972   }
6973   case Intrinsic::fmuladd: {
6974     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6975     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6976         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6977       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6978                                getValue(I.getArgOperand(0)).getValueType(),
6979                                getValue(I.getArgOperand(0)),
6980                                getValue(I.getArgOperand(1)),
6981                                getValue(I.getArgOperand(2)), Flags));
6982     } else {
6983       // TODO: Intrinsic calls should have fast-math-flags.
6984       SDValue Mul = DAG.getNode(
6985           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6986           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6987       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6988                                 getValue(I.getArgOperand(0)).getValueType(),
6989                                 Mul, getValue(I.getArgOperand(2)), Flags);
6990       setValue(&I, Add);
6991     }
6992     return;
6993   }
6994   case Intrinsic::convert_to_fp16:
6995     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6996                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6997                                          getValue(I.getArgOperand(0)),
6998                                          DAG.getTargetConstant(0, sdl,
6999                                                                MVT::i32))));
7000     return;
7001   case Intrinsic::convert_from_fp16:
7002     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
7003                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
7004                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
7005                                          getValue(I.getArgOperand(0)))));
7006     return;
7007   case Intrinsic::fptosi_sat: {
7008     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7009     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
7010                              getValue(I.getArgOperand(0)),
7011                              DAG.getValueType(VT.getScalarType())));
7012     return;
7013   }
7014   case Intrinsic::fptoui_sat: {
7015     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7016     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
7017                              getValue(I.getArgOperand(0)),
7018                              DAG.getValueType(VT.getScalarType())));
7019     return;
7020   }
7021   case Intrinsic::set_rounding:
7022     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
7023                       {getRoot(), getValue(I.getArgOperand(0))});
7024     setValue(&I, Res);
7025     DAG.setRoot(Res.getValue(0));
7026     return;
7027   case Intrinsic::is_fpclass: {
7028     const DataLayout DLayout = DAG.getDataLayout();
7029     EVT DestVT = TLI.getValueType(DLayout, I.getType());
7030     EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
7031     FPClassTest Test = static_cast<FPClassTest>(
7032         cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
7033     MachineFunction &MF = DAG.getMachineFunction();
7034     const Function &F = MF.getFunction();
7035     SDValue Op = getValue(I.getArgOperand(0));
7036     SDNodeFlags Flags;
7037     Flags.setNoFPExcept(
7038         !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
7039     // If ISD::IS_FPCLASS should be expanded, do it right now, because the
7040     // expansion can use illegal types. Making expansion early allows
7041     // legalizing these types prior to selection.
7042     if (!TLI.isOperationLegal(ISD::IS_FPCLASS, ArgVT) &&
7043         !TLI.isOperationCustom(ISD::IS_FPCLASS, ArgVT)) {
7044       SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
7045       setValue(&I, Result);
7046       return;
7047     }
7048 
7049     SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
7050     SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
7051     setValue(&I, V);
7052     return;
7053   }
7054   case Intrinsic::get_fpenv: {
7055     const DataLayout DLayout = DAG.getDataLayout();
7056     EVT EnvVT = TLI.getValueType(DLayout, I.getType());
7057     Align TempAlign = DAG.getEVTAlign(EnvVT);
7058     SDValue Chain = getRoot();
7059     // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node
7060     // and temporary storage in stack.
7061     if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) {
7062       Res = DAG.getNode(
7063           ISD::GET_FPENV, sdl,
7064           DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7065                         MVT::Other),
7066           Chain);
7067     } else {
7068       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7069       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7070       auto MPI =
7071           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7072       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7073           MPI, MachineMemOperand::MOStore, LocationSize::beforeOrAfterPointer(),
7074           TempAlign);
7075       Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7076       Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI);
7077     }
7078     setValue(&I, Res);
7079     DAG.setRoot(Res.getValue(1));
7080     return;
7081   }
7082   case Intrinsic::set_fpenv: {
7083     const DataLayout DLayout = DAG.getDataLayout();
7084     SDValue Env = getValue(I.getArgOperand(0));
7085     EVT EnvVT = Env.getValueType();
7086     Align TempAlign = DAG.getEVTAlign(EnvVT);
7087     SDValue Chain = getRoot();
7088     // If SET_FPENV is custom or legal, use it. Otherwise use loading
7089     // environment from memory.
7090     if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) {
7091       Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env);
7092     } else {
7093       // Allocate space in stack, copy environment bits into it and use this
7094       // memory in SET_FPENV_MEM.
7095       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7096       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7097       auto MPI =
7098           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7099       Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign,
7100                            MachineMemOperand::MOStore);
7101       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7102           MPI, MachineMemOperand::MOLoad, LocationSize::beforeOrAfterPointer(),
7103           TempAlign);
7104       Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7105     }
7106     DAG.setRoot(Chain);
7107     return;
7108   }
7109   case Intrinsic::reset_fpenv:
7110     DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot()));
7111     return;
7112   case Intrinsic::get_fpmode:
7113     Res = DAG.getNode(
7114         ISD::GET_FPMODE, sdl,
7115         DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7116                       MVT::Other),
7117         DAG.getRoot());
7118     setValue(&I, Res);
7119     DAG.setRoot(Res.getValue(1));
7120     return;
7121   case Intrinsic::set_fpmode:
7122     Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()},
7123                       getValue(I.getArgOperand(0)));
7124     DAG.setRoot(Res);
7125     return;
7126   case Intrinsic::reset_fpmode: {
7127     Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot());
7128     DAG.setRoot(Res);
7129     return;
7130   }
7131   case Intrinsic::pcmarker: {
7132     SDValue Tmp = getValue(I.getArgOperand(0));
7133     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
7134     return;
7135   }
7136   case Intrinsic::readcyclecounter: {
7137     SDValue Op = getRoot();
7138     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
7139                       DAG.getVTList(MVT::i64, MVT::Other), Op);
7140     setValue(&I, Res);
7141     DAG.setRoot(Res.getValue(1));
7142     return;
7143   }
7144   case Intrinsic::readsteadycounter: {
7145     SDValue Op = getRoot();
7146     Res = DAG.getNode(ISD::READSTEADYCOUNTER, sdl,
7147                       DAG.getVTList(MVT::i64, MVT::Other), Op);
7148     setValue(&I, Res);
7149     DAG.setRoot(Res.getValue(1));
7150     return;
7151   }
7152   case Intrinsic::bitreverse:
7153     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
7154                              getValue(I.getArgOperand(0)).getValueType(),
7155                              getValue(I.getArgOperand(0))));
7156     return;
7157   case Intrinsic::bswap:
7158     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
7159                              getValue(I.getArgOperand(0)).getValueType(),
7160                              getValue(I.getArgOperand(0))));
7161     return;
7162   case Intrinsic::cttz: {
7163     SDValue Arg = getValue(I.getArgOperand(0));
7164     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7165     EVT Ty = Arg.getValueType();
7166     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
7167                              sdl, Ty, Arg));
7168     return;
7169   }
7170   case Intrinsic::ctlz: {
7171     SDValue Arg = getValue(I.getArgOperand(0));
7172     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7173     EVT Ty = Arg.getValueType();
7174     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
7175                              sdl, Ty, Arg));
7176     return;
7177   }
7178   case Intrinsic::ctpop: {
7179     SDValue Arg = getValue(I.getArgOperand(0));
7180     EVT Ty = Arg.getValueType();
7181     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
7182     return;
7183   }
7184   case Intrinsic::fshl:
7185   case Intrinsic::fshr: {
7186     bool IsFSHL = Intrinsic == Intrinsic::fshl;
7187     SDValue X = getValue(I.getArgOperand(0));
7188     SDValue Y = getValue(I.getArgOperand(1));
7189     SDValue Z = getValue(I.getArgOperand(2));
7190     EVT VT = X.getValueType();
7191 
7192     if (X == Y) {
7193       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
7194       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
7195     } else {
7196       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
7197       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
7198     }
7199     return;
7200   }
7201   case Intrinsic::sadd_sat: {
7202     SDValue Op1 = getValue(I.getArgOperand(0));
7203     SDValue Op2 = getValue(I.getArgOperand(1));
7204     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7205     return;
7206   }
7207   case Intrinsic::uadd_sat: {
7208     SDValue Op1 = getValue(I.getArgOperand(0));
7209     SDValue Op2 = getValue(I.getArgOperand(1));
7210     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7211     return;
7212   }
7213   case Intrinsic::ssub_sat: {
7214     SDValue Op1 = getValue(I.getArgOperand(0));
7215     SDValue Op2 = getValue(I.getArgOperand(1));
7216     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7217     return;
7218   }
7219   case Intrinsic::usub_sat: {
7220     SDValue Op1 = getValue(I.getArgOperand(0));
7221     SDValue Op2 = getValue(I.getArgOperand(1));
7222     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7223     return;
7224   }
7225   case Intrinsic::sshl_sat: {
7226     SDValue Op1 = getValue(I.getArgOperand(0));
7227     SDValue Op2 = getValue(I.getArgOperand(1));
7228     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
7229     return;
7230   }
7231   case Intrinsic::ushl_sat: {
7232     SDValue Op1 = getValue(I.getArgOperand(0));
7233     SDValue Op2 = getValue(I.getArgOperand(1));
7234     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
7235     return;
7236   }
7237   case Intrinsic::smul_fix:
7238   case Intrinsic::umul_fix:
7239   case Intrinsic::smul_fix_sat:
7240   case Intrinsic::umul_fix_sat: {
7241     SDValue Op1 = getValue(I.getArgOperand(0));
7242     SDValue Op2 = getValue(I.getArgOperand(1));
7243     SDValue Op3 = getValue(I.getArgOperand(2));
7244     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7245                              Op1.getValueType(), Op1, Op2, Op3));
7246     return;
7247   }
7248   case Intrinsic::sdiv_fix:
7249   case Intrinsic::udiv_fix:
7250   case Intrinsic::sdiv_fix_sat:
7251   case Intrinsic::udiv_fix_sat: {
7252     SDValue Op1 = getValue(I.getArgOperand(0));
7253     SDValue Op2 = getValue(I.getArgOperand(1));
7254     SDValue Op3 = getValue(I.getArgOperand(2));
7255     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7256                               Op1, Op2, Op3, DAG, TLI));
7257     return;
7258   }
7259   case Intrinsic::smax: {
7260     SDValue Op1 = getValue(I.getArgOperand(0));
7261     SDValue Op2 = getValue(I.getArgOperand(1));
7262     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
7263     return;
7264   }
7265   case Intrinsic::smin: {
7266     SDValue Op1 = getValue(I.getArgOperand(0));
7267     SDValue Op2 = getValue(I.getArgOperand(1));
7268     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
7269     return;
7270   }
7271   case Intrinsic::umax: {
7272     SDValue Op1 = getValue(I.getArgOperand(0));
7273     SDValue Op2 = getValue(I.getArgOperand(1));
7274     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
7275     return;
7276   }
7277   case Intrinsic::umin: {
7278     SDValue Op1 = getValue(I.getArgOperand(0));
7279     SDValue Op2 = getValue(I.getArgOperand(1));
7280     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
7281     return;
7282   }
7283   case Intrinsic::abs: {
7284     // TODO: Preserve "int min is poison" arg in SDAG?
7285     SDValue Op1 = getValue(I.getArgOperand(0));
7286     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
7287     return;
7288   }
7289   case Intrinsic::scmp: {
7290     SDValue Op1 = getValue(I.getArgOperand(0));
7291     SDValue Op2 = getValue(I.getArgOperand(1));
7292     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7293     setValue(&I, DAG.getNode(ISD::SCMP, sdl, DestVT, Op1, Op2));
7294     break;
7295   }
7296   case Intrinsic::ucmp: {
7297     SDValue Op1 = getValue(I.getArgOperand(0));
7298     SDValue Op2 = getValue(I.getArgOperand(1));
7299     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7300     setValue(&I, DAG.getNode(ISD::UCMP, sdl, DestVT, Op1, Op2));
7301     break;
7302   }
7303   case Intrinsic::stacksave: {
7304     SDValue Op = getRoot();
7305     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7306     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
7307     setValue(&I, Res);
7308     DAG.setRoot(Res.getValue(1));
7309     return;
7310   }
7311   case Intrinsic::stackrestore:
7312     Res = getValue(I.getArgOperand(0));
7313     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
7314     return;
7315   case Intrinsic::get_dynamic_area_offset: {
7316     SDValue Op = getRoot();
7317     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7318     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7319     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
7320     // target.
7321     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
7322       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
7323                          " intrinsic!");
7324     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
7325                       Op);
7326     DAG.setRoot(Op);
7327     setValue(&I, Res);
7328     return;
7329   }
7330   case Intrinsic::stackguard: {
7331     MachineFunction &MF = DAG.getMachineFunction();
7332     const Module &M = *MF.getFunction().getParent();
7333     EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7334     SDValue Chain = getRoot();
7335     if (TLI.useLoadStackGuardNode()) {
7336       Res = getLoadStackGuard(DAG, sdl, Chain);
7337       Res = DAG.getPtrExtOrTrunc(Res, sdl, PtrTy);
7338     } else {
7339       const Value *Global = TLI.getSDagStackGuard(M);
7340       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
7341       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
7342                         MachinePointerInfo(Global, 0), Align,
7343                         MachineMemOperand::MOVolatile);
7344     }
7345     if (TLI.useStackGuardXorFP())
7346       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
7347     DAG.setRoot(Chain);
7348     setValue(&I, Res);
7349     return;
7350   }
7351   case Intrinsic::stackprotector: {
7352     // Emit code into the DAG to store the stack guard onto the stack.
7353     MachineFunction &MF = DAG.getMachineFunction();
7354     MachineFrameInfo &MFI = MF.getFrameInfo();
7355     SDValue Src, Chain = getRoot();
7356 
7357     if (TLI.useLoadStackGuardNode())
7358       Src = getLoadStackGuard(DAG, sdl, Chain);
7359     else
7360       Src = getValue(I.getArgOperand(0));   // The guard's value.
7361 
7362     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
7363 
7364     int FI = FuncInfo.StaticAllocaMap[Slot];
7365     MFI.setStackProtectorIndex(FI);
7366     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7367 
7368     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
7369 
7370     // Store the stack protector onto the stack.
7371     Res = DAG.getStore(
7372         Chain, sdl, Src, FIN,
7373         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
7374         MaybeAlign(), MachineMemOperand::MOVolatile);
7375     setValue(&I, Res);
7376     DAG.setRoot(Res);
7377     return;
7378   }
7379   case Intrinsic::objectsize:
7380     llvm_unreachable("llvm.objectsize.* should have been lowered already");
7381 
7382   case Intrinsic::is_constant:
7383     llvm_unreachable("llvm.is.constant.* should have been lowered already");
7384 
7385   case Intrinsic::annotation:
7386   case Intrinsic::ptr_annotation:
7387   case Intrinsic::launder_invariant_group:
7388   case Intrinsic::strip_invariant_group:
7389     // Drop the intrinsic, but forward the value
7390     setValue(&I, getValue(I.getOperand(0)));
7391     return;
7392 
7393   case Intrinsic::assume:
7394   case Intrinsic::experimental_noalias_scope_decl:
7395   case Intrinsic::var_annotation:
7396   case Intrinsic::sideeffect:
7397     // Discard annotate attributes, noalias scope declarations, assumptions, and
7398     // artificial side-effects.
7399     return;
7400 
7401   case Intrinsic::codeview_annotation: {
7402     // Emit a label associated with this metadata.
7403     MachineFunction &MF = DAG.getMachineFunction();
7404     MCSymbol *Label = MF.getContext().createTempSymbol("annotation", true);
7405     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
7406     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
7407     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
7408     DAG.setRoot(Res);
7409     return;
7410   }
7411 
7412   case Intrinsic::init_trampoline: {
7413     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
7414 
7415     SDValue Ops[6];
7416     Ops[0] = getRoot();
7417     Ops[1] = getValue(I.getArgOperand(0));
7418     Ops[2] = getValue(I.getArgOperand(1));
7419     Ops[3] = getValue(I.getArgOperand(2));
7420     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
7421     Ops[5] = DAG.getSrcValue(F);
7422 
7423     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
7424 
7425     DAG.setRoot(Res);
7426     return;
7427   }
7428   case Intrinsic::adjust_trampoline:
7429     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
7430                              TLI.getPointerTy(DAG.getDataLayout()),
7431                              getValue(I.getArgOperand(0))));
7432     return;
7433   case Intrinsic::gcroot: {
7434     assert(DAG.getMachineFunction().getFunction().hasGC() &&
7435            "only valid in functions with gc specified, enforced by Verifier");
7436     assert(GFI && "implied by previous");
7437     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
7438     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
7439 
7440     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
7441     GFI->addStackRoot(FI->getIndex(), TypeMap);
7442     return;
7443   }
7444   case Intrinsic::gcread:
7445   case Intrinsic::gcwrite:
7446     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
7447   case Intrinsic::get_rounding:
7448     Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot());
7449     setValue(&I, Res);
7450     DAG.setRoot(Res.getValue(1));
7451     return;
7452 
7453   case Intrinsic::expect:
7454     // Just replace __builtin_expect(exp, c) with EXP.
7455     setValue(&I, getValue(I.getArgOperand(0)));
7456     return;
7457 
7458   case Intrinsic::ubsantrap:
7459   case Intrinsic::debugtrap:
7460   case Intrinsic::trap: {
7461     StringRef TrapFuncName =
7462         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
7463     if (TrapFuncName.empty()) {
7464       switch (Intrinsic) {
7465       case Intrinsic::trap:
7466         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
7467         break;
7468       case Intrinsic::debugtrap:
7469         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
7470         break;
7471       case Intrinsic::ubsantrap:
7472         DAG.setRoot(DAG.getNode(
7473             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
7474             DAG.getTargetConstant(
7475                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
7476                 MVT::i32)));
7477         break;
7478       default: llvm_unreachable("unknown trap intrinsic");
7479       }
7480       DAG.addNoMergeSiteInfo(DAG.getRoot().getNode(),
7481                              I.hasFnAttr(Attribute::NoMerge));
7482       return;
7483     }
7484     TargetLowering::ArgListTy Args;
7485     if (Intrinsic == Intrinsic::ubsantrap) {
7486       Args.push_back(TargetLoweringBase::ArgListEntry());
7487       Args[0].Val = I.getArgOperand(0);
7488       Args[0].Node = getValue(Args[0].Val);
7489       Args[0].Ty = Args[0].Val->getType();
7490     }
7491 
7492     TargetLowering::CallLoweringInfo CLI(DAG);
7493     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
7494         CallingConv::C, I.getType(),
7495         DAG.getExternalSymbol(TrapFuncName.data(),
7496                               TLI.getPointerTy(DAG.getDataLayout())),
7497         std::move(Args));
7498     CLI.NoMerge = I.hasFnAttr(Attribute::NoMerge);
7499     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7500     DAG.setRoot(Result.second);
7501     return;
7502   }
7503 
7504   case Intrinsic::allow_runtime_check:
7505   case Intrinsic::allow_ubsan_check:
7506     setValue(&I, getValue(ConstantInt::getTrue(I.getType())));
7507     return;
7508 
7509   case Intrinsic::uadd_with_overflow:
7510   case Intrinsic::sadd_with_overflow:
7511   case Intrinsic::usub_with_overflow:
7512   case Intrinsic::ssub_with_overflow:
7513   case Intrinsic::umul_with_overflow:
7514   case Intrinsic::smul_with_overflow: {
7515     ISD::NodeType Op;
7516     switch (Intrinsic) {
7517     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7518     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
7519     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
7520     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
7521     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
7522     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
7523     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
7524     }
7525     SDValue Op1 = getValue(I.getArgOperand(0));
7526     SDValue Op2 = getValue(I.getArgOperand(1));
7527 
7528     EVT ResultVT = Op1.getValueType();
7529     EVT OverflowVT = MVT::i1;
7530     if (ResultVT.isVector())
7531       OverflowVT = EVT::getVectorVT(
7532           *Context, OverflowVT, ResultVT.getVectorElementCount());
7533 
7534     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
7535     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
7536     return;
7537   }
7538   case Intrinsic::prefetch: {
7539     SDValue Ops[5];
7540     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7541     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
7542     Ops[0] = DAG.getRoot();
7543     Ops[1] = getValue(I.getArgOperand(0));
7544     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
7545                                    MVT::i32);
7546     Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl,
7547                                    MVT::i32);
7548     Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl,
7549                                    MVT::i32);
7550     SDValue Result = DAG.getMemIntrinsicNode(
7551         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
7552         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
7553         /* align */ std::nullopt, Flags);
7554 
7555     // Chain the prefetch in parallel with any pending loads, to stay out of
7556     // the way of later optimizations.
7557     PendingLoads.push_back(Result);
7558     Result = getRoot();
7559     DAG.setRoot(Result);
7560     return;
7561   }
7562   case Intrinsic::lifetime_start:
7563   case Intrinsic::lifetime_end: {
7564     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
7565     // Stack coloring is not enabled in O0, discard region information.
7566     if (TM.getOptLevel() == CodeGenOptLevel::None)
7567       return;
7568 
7569     const int64_t ObjectSize =
7570         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
7571     Value *const ObjectPtr = I.getArgOperand(1);
7572     SmallVector<const Value *, 4> Allocas;
7573     getUnderlyingObjects(ObjectPtr, Allocas);
7574 
7575     for (const Value *Alloca : Allocas) {
7576       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
7577 
7578       // Could not find an Alloca.
7579       if (!LifetimeObject)
7580         continue;
7581 
7582       // First check that the Alloca is static, otherwise it won't have a
7583       // valid frame index.
7584       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
7585       if (SI == FuncInfo.StaticAllocaMap.end())
7586         return;
7587 
7588       const int FrameIndex = SI->second;
7589       int64_t Offset;
7590       if (GetPointerBaseWithConstantOffset(
7591               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
7592         Offset = -1; // Cannot determine offset from alloca to lifetime object.
7593       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
7594                                 Offset);
7595       DAG.setRoot(Res);
7596     }
7597     return;
7598   }
7599   case Intrinsic::pseudoprobe: {
7600     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
7601     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7602     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
7603     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
7604     DAG.setRoot(Res);
7605     return;
7606   }
7607   case Intrinsic::invariant_start:
7608     // Discard region information.
7609     setValue(&I,
7610              DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
7611     return;
7612   case Intrinsic::invariant_end:
7613     // Discard region information.
7614     return;
7615   case Intrinsic::clear_cache: {
7616     SDValue InputChain = DAG.getRoot();
7617     SDValue StartVal = getValue(I.getArgOperand(0));
7618     SDValue EndVal = getValue(I.getArgOperand(1));
7619     Res = DAG.getNode(ISD::CLEAR_CACHE, sdl, DAG.getVTList(MVT::Other),
7620                       {InputChain, StartVal, EndVal});
7621     setValue(&I, Res);
7622     DAG.setRoot(Res);
7623     return;
7624   }
7625   case Intrinsic::donothing:
7626   case Intrinsic::seh_try_begin:
7627   case Intrinsic::seh_scope_begin:
7628   case Intrinsic::seh_try_end:
7629   case Intrinsic::seh_scope_end:
7630     // ignore
7631     return;
7632   case Intrinsic::experimental_stackmap:
7633     visitStackmap(I);
7634     return;
7635   case Intrinsic::experimental_patchpoint_void:
7636   case Intrinsic::experimental_patchpoint:
7637     visitPatchpoint(I);
7638     return;
7639   case Intrinsic::experimental_gc_statepoint:
7640     LowerStatepoint(cast<GCStatepointInst>(I));
7641     return;
7642   case Intrinsic::experimental_gc_result:
7643     visitGCResult(cast<GCResultInst>(I));
7644     return;
7645   case Intrinsic::experimental_gc_relocate:
7646     visitGCRelocate(cast<GCRelocateInst>(I));
7647     return;
7648   case Intrinsic::instrprof_cover:
7649     llvm_unreachable("instrprof failed to lower a cover");
7650   case Intrinsic::instrprof_increment:
7651     llvm_unreachable("instrprof failed to lower an increment");
7652   case Intrinsic::instrprof_timestamp:
7653     llvm_unreachable("instrprof failed to lower a timestamp");
7654   case Intrinsic::instrprof_value_profile:
7655     llvm_unreachable("instrprof failed to lower a value profiling call");
7656   case Intrinsic::instrprof_mcdc_parameters:
7657     llvm_unreachable("instrprof failed to lower mcdc parameters");
7658   case Intrinsic::instrprof_mcdc_tvbitmap_update:
7659     llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update");
7660   case Intrinsic::localescape: {
7661     MachineFunction &MF = DAG.getMachineFunction();
7662     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
7663 
7664     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
7665     // is the same on all targets.
7666     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
7667       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
7668       if (isa<ConstantPointerNull>(Arg))
7669         continue; // Skip null pointers. They represent a hole in index space.
7670       AllocaInst *Slot = cast<AllocaInst>(Arg);
7671       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
7672              "can only escape static allocas");
7673       int FI = FuncInfo.StaticAllocaMap[Slot];
7674       MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
7675           GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
7676       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
7677               TII->get(TargetOpcode::LOCAL_ESCAPE))
7678           .addSym(FrameAllocSym)
7679           .addFrameIndex(FI);
7680     }
7681 
7682     return;
7683   }
7684 
7685   case Intrinsic::localrecover: {
7686     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
7687     MachineFunction &MF = DAG.getMachineFunction();
7688 
7689     // Get the symbol that defines the frame offset.
7690     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
7691     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
7692     unsigned IdxVal =
7693         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
7694     MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
7695         GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
7696 
7697     Value *FP = I.getArgOperand(1);
7698     SDValue FPVal = getValue(FP);
7699     EVT PtrVT = FPVal.getValueType();
7700 
7701     // Create a MCSymbol for the label to avoid any target lowering
7702     // that would make this PC relative.
7703     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
7704     SDValue OffsetVal =
7705         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
7706 
7707     // Add the offset to the FP.
7708     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
7709     setValue(&I, Add);
7710 
7711     return;
7712   }
7713 
7714   case Intrinsic::fake_use: {
7715     Value *V = I.getArgOperand(0);
7716     SDValue Ops[2];
7717     // For Values not declared or previously used in this basic block, the
7718     // NodeMap will not have an entry, and `getValue` will assert if V has no
7719     // valid register value.
7720     auto FakeUseValue = [&]() -> SDValue {
7721       SDValue &N = NodeMap[V];
7722       if (N.getNode())
7723         return N;
7724 
7725       // If there's a virtual register allocated and initialized for this
7726       // value, use it.
7727       if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
7728         return copyFromReg;
7729       // FIXME: Do we want to preserve constants? It seems pointless.
7730       if (isa<Constant>(V))
7731         return getValue(V);
7732       return SDValue();
7733     }();
7734     if (!FakeUseValue || FakeUseValue.isUndef())
7735       return;
7736     Ops[0] = getRoot();
7737     Ops[1] = FakeUseValue;
7738     // Also, do not translate a fake use with an undef operand, or any other
7739     // empty SDValues.
7740     if (!Ops[1] || Ops[1].isUndef())
7741       return;
7742     DAG.setRoot(DAG.getNode(ISD::FAKE_USE, sdl, MVT::Other, Ops));
7743     return;
7744   }
7745 
7746   case Intrinsic::eh_exceptionpointer:
7747   case Intrinsic::eh_exceptioncode: {
7748     // Get the exception pointer vreg, copy from it, and resize it to fit.
7749     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
7750     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
7751     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
7752     Register VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
7753     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
7754     if (Intrinsic == Intrinsic::eh_exceptioncode)
7755       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
7756     setValue(&I, N);
7757     return;
7758   }
7759   case Intrinsic::xray_customevent: {
7760     // Here we want to make sure that the intrinsic behaves as if it has a
7761     // specific calling convention.
7762     const auto &Triple = DAG.getTarget().getTargetTriple();
7763     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7764       return;
7765 
7766     SmallVector<SDValue, 8> Ops;
7767 
7768     // We want to say that we always want the arguments in registers.
7769     SDValue LogEntryVal = getValue(I.getArgOperand(0));
7770     SDValue StrSizeVal = getValue(I.getArgOperand(1));
7771     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7772     SDValue Chain = getRoot();
7773     Ops.push_back(LogEntryVal);
7774     Ops.push_back(StrSizeVal);
7775     Ops.push_back(Chain);
7776 
7777     // We need to enforce the calling convention for the callsite, so that
7778     // argument ordering is enforced correctly, and that register allocation can
7779     // see that some registers may be assumed clobbered and have to preserve
7780     // them across calls to the intrinsic.
7781     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
7782                                            sdl, NodeTys, Ops);
7783     SDValue patchableNode = SDValue(MN, 0);
7784     DAG.setRoot(patchableNode);
7785     setValue(&I, patchableNode);
7786     return;
7787   }
7788   case Intrinsic::xray_typedevent: {
7789     // Here we want to make sure that the intrinsic behaves as if it has a
7790     // specific calling convention.
7791     const auto &Triple = DAG.getTarget().getTargetTriple();
7792     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7793       return;
7794 
7795     SmallVector<SDValue, 8> Ops;
7796 
7797     // We want to say that we always want the arguments in registers.
7798     // It's unclear to me how manipulating the selection DAG here forces callers
7799     // to provide arguments in registers instead of on the stack.
7800     SDValue LogTypeId = getValue(I.getArgOperand(0));
7801     SDValue LogEntryVal = getValue(I.getArgOperand(1));
7802     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7803     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7804     SDValue Chain = getRoot();
7805     Ops.push_back(LogTypeId);
7806     Ops.push_back(LogEntryVal);
7807     Ops.push_back(StrSizeVal);
7808     Ops.push_back(Chain);
7809 
7810     // We need to enforce the calling convention for the callsite, so that
7811     // argument ordering is enforced correctly, and that register allocation can
7812     // see that some registers may be assumed clobbered and have to preserve
7813     // them across calls to the intrinsic.
7814     MachineSDNode *MN = DAG.getMachineNode(
7815         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7816     SDValue patchableNode = SDValue(MN, 0);
7817     DAG.setRoot(patchableNode);
7818     setValue(&I, patchableNode);
7819     return;
7820   }
7821   case Intrinsic::experimental_deoptimize:
7822     LowerDeoptimizeCall(&I);
7823     return;
7824   case Intrinsic::stepvector:
7825     visitStepVector(I);
7826     return;
7827   case Intrinsic::vector_reduce_fadd:
7828   case Intrinsic::vector_reduce_fmul:
7829   case Intrinsic::vector_reduce_add:
7830   case Intrinsic::vector_reduce_mul:
7831   case Intrinsic::vector_reduce_and:
7832   case Intrinsic::vector_reduce_or:
7833   case Intrinsic::vector_reduce_xor:
7834   case Intrinsic::vector_reduce_smax:
7835   case Intrinsic::vector_reduce_smin:
7836   case Intrinsic::vector_reduce_umax:
7837   case Intrinsic::vector_reduce_umin:
7838   case Intrinsic::vector_reduce_fmax:
7839   case Intrinsic::vector_reduce_fmin:
7840   case Intrinsic::vector_reduce_fmaximum:
7841   case Intrinsic::vector_reduce_fminimum:
7842     visitVectorReduce(I, Intrinsic);
7843     return;
7844 
7845   case Intrinsic::icall_branch_funnel: {
7846     SmallVector<SDValue, 16> Ops;
7847     Ops.push_back(getValue(I.getArgOperand(0)));
7848 
7849     int64_t Offset;
7850     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7851         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7852     if (!Base)
7853       report_fatal_error(
7854           "llvm.icall.branch.funnel operand must be a GlobalValue");
7855     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7856 
7857     struct BranchFunnelTarget {
7858       int64_t Offset;
7859       SDValue Target;
7860     };
7861     SmallVector<BranchFunnelTarget, 8> Targets;
7862 
7863     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7864       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7865           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7866       if (ElemBase != Base)
7867         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7868                            "to the same GlobalValue");
7869 
7870       SDValue Val = getValue(I.getArgOperand(Op + 1));
7871       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7872       if (!GA)
7873         report_fatal_error(
7874             "llvm.icall.branch.funnel operand must be a GlobalValue");
7875       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7876                                      GA->getGlobal(), sdl, Val.getValueType(),
7877                                      GA->getOffset())});
7878     }
7879     llvm::sort(Targets,
7880                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7881                  return T1.Offset < T2.Offset;
7882                });
7883 
7884     for (auto &T : Targets) {
7885       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7886       Ops.push_back(T.Target);
7887     }
7888 
7889     Ops.push_back(DAG.getRoot()); // Chain
7890     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7891                                  MVT::Other, Ops),
7892               0);
7893     DAG.setRoot(N);
7894     setValue(&I, N);
7895     HasTailCall = true;
7896     return;
7897   }
7898 
7899   case Intrinsic::wasm_landingpad_index:
7900     // Information this intrinsic contained has been transferred to
7901     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7902     // delete it now.
7903     return;
7904 
7905   case Intrinsic::aarch64_settag:
7906   case Intrinsic::aarch64_settag_zero: {
7907     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7908     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7909     SDValue Val = TSI.EmitTargetCodeForSetTag(
7910         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7911         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7912         ZeroMemory);
7913     DAG.setRoot(Val);
7914     setValue(&I, Val);
7915     return;
7916   }
7917   case Intrinsic::amdgcn_cs_chain: {
7918     assert(I.arg_size() == 5 && "Additional args not supported yet");
7919     assert(cast<ConstantInt>(I.getOperand(4))->isZero() &&
7920            "Non-zero flags not supported yet");
7921 
7922     // At this point we don't care if it's amdgpu_cs_chain or
7923     // amdgpu_cs_chain_preserve.
7924     CallingConv::ID CC = CallingConv::AMDGPU_CS_Chain;
7925 
7926     Type *RetTy = I.getType();
7927     assert(RetTy->isVoidTy() && "Should not return");
7928 
7929     SDValue Callee = getValue(I.getOperand(0));
7930 
7931     // We only have 2 actual args: one for the SGPRs and one for the VGPRs.
7932     // We'll also tack the value of the EXEC mask at the end.
7933     TargetLowering::ArgListTy Args;
7934     Args.reserve(3);
7935 
7936     for (unsigned Idx : {2, 3, 1}) {
7937       TargetLowering::ArgListEntry Arg;
7938       Arg.Node = getValue(I.getOperand(Idx));
7939       Arg.Ty = I.getOperand(Idx)->getType();
7940       Arg.setAttributes(&I, Idx);
7941       Args.push_back(Arg);
7942     }
7943 
7944     assert(Args[0].IsInReg && "SGPR args should be marked inreg");
7945     assert(!Args[1].IsInReg && "VGPR args should not be marked inreg");
7946     Args[2].IsInReg = true; // EXEC should be inreg
7947 
7948     TargetLowering::CallLoweringInfo CLI(DAG);
7949     CLI.setDebugLoc(getCurSDLoc())
7950         .setChain(getRoot())
7951         .setCallee(CC, RetTy, Callee, std::move(Args))
7952         .setNoReturn(true)
7953         .setTailCall(true)
7954         .setConvergent(I.isConvergent());
7955     CLI.CB = &I;
7956     std::pair<SDValue, SDValue> Result =
7957         lowerInvokable(CLI, /*EHPadBB*/ nullptr);
7958     (void)Result;
7959     assert(!Result.first.getNode() && !Result.second.getNode() &&
7960            "Should've lowered as tail call");
7961 
7962     HasTailCall = true;
7963     return;
7964   }
7965   case Intrinsic::ptrmask: {
7966     SDValue Ptr = getValue(I.getOperand(0));
7967     SDValue Mask = getValue(I.getOperand(1));
7968 
7969     // On arm64_32, pointers are 32 bits when stored in memory, but
7970     // zero-extended to 64 bits when in registers.  Thus the mask is 32 bits to
7971     // match the index type, but the pointer is 64 bits, so the the mask must be
7972     // zero-extended up to 64 bits to match the pointer.
7973     EVT PtrVT =
7974         TLI.getValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
7975     EVT MemVT =
7976         TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
7977     assert(PtrVT == Ptr.getValueType());
7978     assert(MemVT == Mask.getValueType());
7979     if (MemVT != PtrVT)
7980       Mask = DAG.getPtrExtOrTrunc(Mask, sdl, PtrVT);
7981 
7982     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask));
7983     return;
7984   }
7985   case Intrinsic::threadlocal_address: {
7986     setValue(&I, getValue(I.getOperand(0)));
7987     return;
7988   }
7989   case Intrinsic::get_active_lane_mask: {
7990     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7991     SDValue Index = getValue(I.getOperand(0));
7992     EVT ElementVT = Index.getValueType();
7993 
7994     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
7995       visitTargetIntrinsic(I, Intrinsic);
7996       return;
7997     }
7998 
7999     SDValue TripCount = getValue(I.getOperand(1));
8000     EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT,
8001                                  CCVT.getVectorElementCount());
8002 
8003     SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
8004     SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
8005     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
8006     SDValue VectorInduction = DAG.getNode(
8007         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
8008     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
8009                                  VectorTripCount, ISD::CondCode::SETULT);
8010     setValue(&I, SetCC);
8011     return;
8012   }
8013   case Intrinsic::experimental_get_vector_length: {
8014     assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 &&
8015            "Expected positive VF");
8016     unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue();
8017     bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne();
8018 
8019     SDValue Count = getValue(I.getOperand(0));
8020     EVT CountVT = Count.getValueType();
8021 
8022     if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) {
8023       visitTargetIntrinsic(I, Intrinsic);
8024       return;
8025     }
8026 
8027     // Expand to a umin between the trip count and the maximum elements the type
8028     // can hold.
8029     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8030 
8031     // Extend the trip count to at least the result VT.
8032     if (CountVT.bitsLT(VT)) {
8033       Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count);
8034       CountVT = VT;
8035     }
8036 
8037     SDValue MaxEVL = DAG.getElementCount(sdl, CountVT,
8038                                          ElementCount::get(VF, IsScalable));
8039 
8040     SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL);
8041     // Clip to the result type if needed.
8042     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin);
8043 
8044     setValue(&I, Trunc);
8045     return;
8046   }
8047   case Intrinsic::experimental_vector_partial_reduce_add: {
8048 
8049     if (!TLI.shouldExpandPartialReductionIntrinsic(cast<IntrinsicInst>(&I))) {
8050       visitTargetIntrinsic(I, Intrinsic);
8051       return;
8052     }
8053 
8054     setValue(&I, DAG.getPartialReduceAdd(sdl, EVT::getEVT(I.getType()),
8055                                          getValue(I.getOperand(0)),
8056                                          getValue(I.getOperand(1))));
8057     return;
8058   }
8059   case Intrinsic::experimental_cttz_elts: {
8060     auto DL = getCurSDLoc();
8061     SDValue Op = getValue(I.getOperand(0));
8062     EVT OpVT = Op.getValueType();
8063 
8064     if (!TLI.shouldExpandCttzElements(OpVT)) {
8065       visitTargetIntrinsic(I, Intrinsic);
8066       return;
8067     }
8068 
8069     if (OpVT.getScalarType() != MVT::i1) {
8070       // Compare the input vector elements to zero & use to count trailing zeros
8071       SDValue AllZero = DAG.getConstant(0, DL, OpVT);
8072       OpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
8073                               OpVT.getVectorElementCount());
8074       Op = DAG.getSetCC(DL, OpVT, Op, AllZero, ISD::SETNE);
8075     }
8076 
8077     // If the zero-is-poison flag is set, we can assume the upper limit
8078     // of the result is VF-1.
8079     bool ZeroIsPoison =
8080         !cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero();
8081     ConstantRange VScaleRange(1, true); // Dummy value.
8082     if (isa<ScalableVectorType>(I.getOperand(0)->getType()))
8083       VScaleRange = getVScaleRange(I.getCaller(), 64);
8084     unsigned EltWidth = TLI.getBitWidthForCttzElements(
8085         I.getType(), OpVT.getVectorElementCount(), ZeroIsPoison, &VScaleRange);
8086 
8087     MVT NewEltTy = MVT::getIntegerVT(EltWidth);
8088 
8089     // Create the new vector type & get the vector length
8090     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), NewEltTy,
8091                                  OpVT.getVectorElementCount());
8092 
8093     SDValue VL =
8094         DAG.getElementCount(DL, NewEltTy, OpVT.getVectorElementCount());
8095 
8096     SDValue StepVec = DAG.getStepVector(DL, NewVT);
8097     SDValue SplatVL = DAG.getSplat(NewVT, DL, VL);
8098     SDValue StepVL = DAG.getNode(ISD::SUB, DL, NewVT, SplatVL, StepVec);
8099     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, Op);
8100     SDValue And = DAG.getNode(ISD::AND, DL, NewVT, StepVL, Ext);
8101     SDValue Max = DAG.getNode(ISD::VECREDUCE_UMAX, DL, NewEltTy, And);
8102     SDValue Sub = DAG.getNode(ISD::SUB, DL, NewEltTy, VL, Max);
8103 
8104     EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
8105     SDValue Ret = DAG.getZExtOrTrunc(Sub, DL, RetTy);
8106 
8107     setValue(&I, Ret);
8108     return;
8109   }
8110   case Intrinsic::vector_insert: {
8111     SDValue Vec = getValue(I.getOperand(0));
8112     SDValue SubVec = getValue(I.getOperand(1));
8113     SDValue Index = getValue(I.getOperand(2));
8114 
8115     // The intrinsic's index type is i64, but the SDNode requires an index type
8116     // suitable for the target. Convert the index as required.
8117     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8118     if (Index.getValueType() != VectorIdxTy)
8119       Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8120 
8121     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8122     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
8123                              Index));
8124     return;
8125   }
8126   case Intrinsic::vector_extract: {
8127     SDValue Vec = getValue(I.getOperand(0));
8128     SDValue Index = getValue(I.getOperand(1));
8129     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8130 
8131     // The intrinsic's index type is i64, but the SDNode requires an index type
8132     // suitable for the target. Convert the index as required.
8133     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8134     if (Index.getValueType() != VectorIdxTy)
8135       Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8136 
8137     setValue(&I,
8138              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
8139     return;
8140   }
8141   case Intrinsic::vector_reverse:
8142     visitVectorReverse(I);
8143     return;
8144   case Intrinsic::vector_splice:
8145     visitVectorSplice(I);
8146     return;
8147   case Intrinsic::callbr_landingpad:
8148     visitCallBrLandingPad(I);
8149     return;
8150   case Intrinsic::vector_interleave2:
8151     visitVectorInterleave(I);
8152     return;
8153   case Intrinsic::vector_deinterleave2:
8154     visitVectorDeinterleave(I);
8155     return;
8156   case Intrinsic::experimental_vector_compress:
8157     setValue(&I, DAG.getNode(ISD::VECTOR_COMPRESS, sdl,
8158                              getValue(I.getArgOperand(0)).getValueType(),
8159                              getValue(I.getArgOperand(0)),
8160                              getValue(I.getArgOperand(1)),
8161                              getValue(I.getArgOperand(2)), Flags));
8162     return;
8163   case Intrinsic::experimental_convergence_anchor:
8164   case Intrinsic::experimental_convergence_entry:
8165   case Intrinsic::experimental_convergence_loop:
8166     visitConvergenceControl(I, Intrinsic);
8167     return;
8168   case Intrinsic::experimental_vector_histogram_add: {
8169     visitVectorHistogram(I, Intrinsic);
8170     return;
8171   }
8172   }
8173 }
8174 
8175 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
8176     const ConstrainedFPIntrinsic &FPI) {
8177   SDLoc sdl = getCurSDLoc();
8178 
8179   // We do not need to serialize constrained FP intrinsics against
8180   // each other or against (nonvolatile) loads, so they can be
8181   // chained like loads.
8182   SDValue Chain = DAG.getRoot();
8183   SmallVector<SDValue, 4> Opers;
8184   Opers.push_back(Chain);
8185   for (unsigned I = 0, E = FPI.getNonMetadataArgCount(); I != E; ++I)
8186     Opers.push_back(getValue(FPI.getArgOperand(I)));
8187 
8188   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
8189     assert(Result.getNode()->getNumValues() == 2);
8190 
8191     // Push node to the appropriate list so that future instructions can be
8192     // chained up correctly.
8193     SDValue OutChain = Result.getValue(1);
8194     switch (EB) {
8195     case fp::ExceptionBehavior::ebIgnore:
8196       // The only reason why ebIgnore nodes still need to be chained is that
8197       // they might depend on the current rounding mode, and therefore must
8198       // not be moved across instruction that may change that mode.
8199       [[fallthrough]];
8200     case fp::ExceptionBehavior::ebMayTrap:
8201       // These must not be moved across calls or instructions that may change
8202       // floating-point exception masks.
8203       PendingConstrainedFP.push_back(OutChain);
8204       break;
8205     case fp::ExceptionBehavior::ebStrict:
8206       // These must not be moved across calls or instructions that may change
8207       // floating-point exception masks or read floating-point exception flags.
8208       // In addition, they cannot be optimized out even if unused.
8209       PendingConstrainedFPStrict.push_back(OutChain);
8210       break;
8211     }
8212   };
8213 
8214   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8215   EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
8216   SDVTList VTs = DAG.getVTList(VT, MVT::Other);
8217   fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
8218 
8219   SDNodeFlags Flags;
8220   if (EB == fp::ExceptionBehavior::ebIgnore)
8221     Flags.setNoFPExcept(true);
8222 
8223   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
8224     Flags.copyFMF(*FPOp);
8225 
8226   unsigned Opcode;
8227   switch (FPI.getIntrinsicID()) {
8228   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
8229 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8230   case Intrinsic::INTRINSIC:                                                   \
8231     Opcode = ISD::STRICT_##DAGN;                                               \
8232     break;
8233 #include "llvm/IR/ConstrainedOps.def"
8234   case Intrinsic::experimental_constrained_fmuladd: {
8235     Opcode = ISD::STRICT_FMA;
8236     // Break fmuladd into fmul and fadd.
8237     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
8238         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
8239       Opers.pop_back();
8240       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
8241       pushOutChain(Mul, EB);
8242       Opcode = ISD::STRICT_FADD;
8243       Opers.clear();
8244       Opers.push_back(Mul.getValue(1));
8245       Opers.push_back(Mul.getValue(0));
8246       Opers.push_back(getValue(FPI.getArgOperand(2)));
8247     }
8248     break;
8249   }
8250   }
8251 
8252   // A few strict DAG nodes carry additional operands that are not
8253   // set up by the default code above.
8254   switch (Opcode) {
8255   default: break;
8256   case ISD::STRICT_FP_ROUND:
8257     Opers.push_back(
8258         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
8259     break;
8260   case ISD::STRICT_FSETCC:
8261   case ISD::STRICT_FSETCCS: {
8262     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
8263     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
8264     if (TM.Options.NoNaNsFPMath)
8265       Condition = getFCmpCodeWithoutNaN(Condition);
8266     Opers.push_back(DAG.getCondCode(Condition));
8267     break;
8268   }
8269   }
8270 
8271   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
8272   pushOutChain(Result, EB);
8273 
8274   SDValue FPResult = Result.getValue(0);
8275   setValue(&FPI, FPResult);
8276 }
8277 
8278 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
8279   std::optional<unsigned> ResOPC;
8280   switch (VPIntrin.getIntrinsicID()) {
8281   case Intrinsic::vp_ctlz: {
8282     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8283     ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ;
8284     break;
8285   }
8286   case Intrinsic::vp_cttz: {
8287     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8288     ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ;
8289     break;
8290   }
8291   case Intrinsic::vp_cttz_elts: {
8292     bool IsZeroPoison = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8293     ResOPC = IsZeroPoison ? ISD::VP_CTTZ_ELTS_ZERO_UNDEF : ISD::VP_CTTZ_ELTS;
8294     break;
8295   }
8296 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD)                                    \
8297   case Intrinsic::VPID:                                                        \
8298     ResOPC = ISD::VPSD;                                                        \
8299     break;
8300 #include "llvm/IR/VPIntrinsics.def"
8301   }
8302 
8303   if (!ResOPC)
8304     llvm_unreachable(
8305         "Inconsistency: no SDNode available for this VPIntrinsic!");
8306 
8307   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
8308       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
8309     if (VPIntrin.getFastMathFlags().allowReassoc())
8310       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
8311                                                 : ISD::VP_REDUCE_FMUL;
8312   }
8313 
8314   return *ResOPC;
8315 }
8316 
8317 void SelectionDAGBuilder::visitVPLoad(
8318     const VPIntrinsic &VPIntrin, EVT VT,
8319     const SmallVectorImpl<SDValue> &OpValues) {
8320   SDLoc DL = getCurSDLoc();
8321   Value *PtrOperand = VPIntrin.getArgOperand(0);
8322   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8323   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8324   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8325   SDValue LD;
8326   // Do not serialize variable-length loads of constant memory with
8327   // anything.
8328   if (!Alignment)
8329     Alignment = DAG.getEVTAlign(VT);
8330   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
8331   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
8332   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8333   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8334       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
8335       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8336   LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
8337                      MMO, false /*IsExpanding */);
8338   if (AddToChain)
8339     PendingLoads.push_back(LD.getValue(1));
8340   setValue(&VPIntrin, LD);
8341 }
8342 
8343 void SelectionDAGBuilder::visitVPGather(
8344     const VPIntrinsic &VPIntrin, EVT VT,
8345     const SmallVectorImpl<SDValue> &OpValues) {
8346   SDLoc DL = getCurSDLoc();
8347   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8348   Value *PtrOperand = VPIntrin.getArgOperand(0);
8349   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8350   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8351   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8352   SDValue LD;
8353   if (!Alignment)
8354     Alignment = DAG.getEVTAlign(VT.getScalarType());
8355   unsigned AS =
8356     PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8357   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8358       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
8359       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8360   SDValue Base, Index, Scale;
8361   ISD::MemIndexType IndexType;
8362   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
8363                                     this, VPIntrin.getParent(),
8364                                     VT.getScalarStoreSize());
8365   if (!UniformBase) {
8366     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
8367     Index = getValue(PtrOperand);
8368     IndexType = ISD::SIGNED_SCALED;
8369     Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
8370   }
8371   EVT IdxVT = Index.getValueType();
8372   EVT EltTy = IdxVT.getVectorElementType();
8373   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
8374     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
8375     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
8376   }
8377   LD = DAG.getGatherVP(
8378       DAG.getVTList(VT, MVT::Other), VT, DL,
8379       {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
8380       IndexType);
8381   PendingLoads.push_back(LD.getValue(1));
8382   setValue(&VPIntrin, LD);
8383 }
8384 
8385 void SelectionDAGBuilder::visitVPStore(
8386     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8387   SDLoc DL = getCurSDLoc();
8388   Value *PtrOperand = VPIntrin.getArgOperand(1);
8389   EVT VT = OpValues[0].getValueType();
8390   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8391   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8392   SDValue ST;
8393   if (!Alignment)
8394     Alignment = DAG.getEVTAlign(VT);
8395   SDValue Ptr = OpValues[1];
8396   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
8397   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8398       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
8399       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8400   ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
8401                       OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
8402                       /* IsTruncating */ false, /*IsCompressing*/ false);
8403   DAG.setRoot(ST);
8404   setValue(&VPIntrin, ST);
8405 }
8406 
8407 void SelectionDAGBuilder::visitVPScatter(
8408     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8409   SDLoc DL = getCurSDLoc();
8410   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8411   Value *PtrOperand = VPIntrin.getArgOperand(1);
8412   EVT VT = OpValues[0].getValueType();
8413   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8414   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8415   SDValue ST;
8416   if (!Alignment)
8417     Alignment = DAG.getEVTAlign(VT.getScalarType());
8418   unsigned AS =
8419       PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8420   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8421       MachinePointerInfo(AS), MachineMemOperand::MOStore,
8422       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8423   SDValue Base, Index, Scale;
8424   ISD::MemIndexType IndexType;
8425   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
8426                                     this, VPIntrin.getParent(),
8427                                     VT.getScalarStoreSize());
8428   if (!UniformBase) {
8429     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
8430     Index = getValue(PtrOperand);
8431     IndexType = ISD::SIGNED_SCALED;
8432     Scale =
8433       DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
8434   }
8435   EVT IdxVT = Index.getValueType();
8436   EVT EltTy = IdxVT.getVectorElementType();
8437   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
8438     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
8439     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
8440   }
8441   ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
8442                         {getMemoryRoot(), OpValues[0], Base, Index, Scale,
8443                          OpValues[2], OpValues[3]},
8444                         MMO, IndexType);
8445   DAG.setRoot(ST);
8446   setValue(&VPIntrin, ST);
8447 }
8448 
8449 void SelectionDAGBuilder::visitVPStridedLoad(
8450     const VPIntrinsic &VPIntrin, EVT VT,
8451     const SmallVectorImpl<SDValue> &OpValues) {
8452   SDLoc DL = getCurSDLoc();
8453   Value *PtrOperand = VPIntrin.getArgOperand(0);
8454   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8455   if (!Alignment)
8456     Alignment = DAG.getEVTAlign(VT.getScalarType());
8457   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8458   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8459   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
8460   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
8461   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8462   unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8463   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8464       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
8465       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8466 
8467   SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
8468                                     OpValues[2], OpValues[3], MMO,
8469                                     false /*IsExpanding*/);
8470 
8471   if (AddToChain)
8472     PendingLoads.push_back(LD.getValue(1));
8473   setValue(&VPIntrin, LD);
8474 }
8475 
8476 void SelectionDAGBuilder::visitVPStridedStore(
8477     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8478   SDLoc DL = getCurSDLoc();
8479   Value *PtrOperand = VPIntrin.getArgOperand(1);
8480   EVT VT = OpValues[0].getValueType();
8481   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8482   if (!Alignment)
8483     Alignment = DAG.getEVTAlign(VT.getScalarType());
8484   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8485   unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8486   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8487       MachinePointerInfo(AS), MachineMemOperand::MOStore,
8488       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8489 
8490   SDValue ST = DAG.getStridedStoreVP(
8491       getMemoryRoot(), DL, OpValues[0], OpValues[1],
8492       DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3],
8493       OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
8494       /*IsCompressing*/ false);
8495 
8496   DAG.setRoot(ST);
8497   setValue(&VPIntrin, ST);
8498 }
8499 
8500 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) {
8501   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8502   SDLoc DL = getCurSDLoc();
8503 
8504   ISD::CondCode Condition;
8505   CmpInst::Predicate CondCode = VPIntrin.getPredicate();
8506   bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy();
8507   if (IsFP) {
8508     // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan)
8509     // flags, but calls that don't return floating-point types can't be
8510     // FPMathOperators, like vp.fcmp. This affects constrained fcmp too.
8511     Condition = getFCmpCondCode(CondCode);
8512     if (TM.Options.NoNaNsFPMath)
8513       Condition = getFCmpCodeWithoutNaN(Condition);
8514   } else {
8515     Condition = getICmpCondCode(CondCode);
8516   }
8517 
8518   SDValue Op1 = getValue(VPIntrin.getOperand(0));
8519   SDValue Op2 = getValue(VPIntrin.getOperand(1));
8520   // #2 is the condition code
8521   SDValue MaskOp = getValue(VPIntrin.getOperand(3));
8522   SDValue EVL = getValue(VPIntrin.getOperand(4));
8523   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8524   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8525          "Unexpected target EVL type");
8526   EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL);
8527 
8528   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8529                                                         VPIntrin.getType());
8530   setValue(&VPIntrin,
8531            DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL));
8532 }
8533 
8534 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
8535     const VPIntrinsic &VPIntrin) {
8536   SDLoc DL = getCurSDLoc();
8537   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
8538 
8539   auto IID = VPIntrin.getIntrinsicID();
8540 
8541   if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin))
8542     return visitVPCmp(*CmpI);
8543 
8544   SmallVector<EVT, 4> ValueVTs;
8545   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8546   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
8547   SDVTList VTs = DAG.getVTList(ValueVTs);
8548 
8549   auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
8550 
8551   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8552   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8553          "Unexpected target EVL type");
8554 
8555   // Request operands.
8556   SmallVector<SDValue, 7> OpValues;
8557   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
8558     auto Op = getValue(VPIntrin.getArgOperand(I));
8559     if (I == EVLParamPos)
8560       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
8561     OpValues.push_back(Op);
8562   }
8563 
8564   switch (Opcode) {
8565   default: {
8566     SDNodeFlags SDFlags;
8567     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8568       SDFlags.copyFMF(*FPMO);
8569     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
8570     setValue(&VPIntrin, Result);
8571     break;
8572   }
8573   case ISD::VP_LOAD:
8574     visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
8575     break;
8576   case ISD::VP_GATHER:
8577     visitVPGather(VPIntrin, ValueVTs[0], OpValues);
8578     break;
8579   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
8580     visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
8581     break;
8582   case ISD::VP_STORE:
8583     visitVPStore(VPIntrin, OpValues);
8584     break;
8585   case ISD::VP_SCATTER:
8586     visitVPScatter(VPIntrin, OpValues);
8587     break;
8588   case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
8589     visitVPStridedStore(VPIntrin, OpValues);
8590     break;
8591   case ISD::VP_FMULADD: {
8592     assert(OpValues.size() == 5 && "Unexpected number of operands");
8593     SDNodeFlags SDFlags;
8594     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8595       SDFlags.copyFMF(*FPMO);
8596     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
8597         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) {
8598       setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags));
8599     } else {
8600       SDValue Mul = DAG.getNode(
8601           ISD::VP_FMUL, DL, VTs,
8602           {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags);
8603       SDValue Add =
8604           DAG.getNode(ISD::VP_FADD, DL, VTs,
8605                       {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags);
8606       setValue(&VPIntrin, Add);
8607     }
8608     break;
8609   }
8610   case ISD::VP_IS_FPCLASS: {
8611     const DataLayout DLayout = DAG.getDataLayout();
8612     EVT DestVT = TLI.getValueType(DLayout, VPIntrin.getType());
8613     auto Constant = OpValues[1]->getAsZExtVal();
8614     SDValue Check = DAG.getTargetConstant(Constant, DL, MVT::i32);
8615     SDValue V = DAG.getNode(ISD::VP_IS_FPCLASS, DL, DestVT,
8616                             {OpValues[0], Check, OpValues[2], OpValues[3]});
8617     setValue(&VPIntrin, V);
8618     return;
8619   }
8620   case ISD::VP_INTTOPTR: {
8621     SDValue N = OpValues[0];
8622     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType());
8623     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType());
8624     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8625                                OpValues[2]);
8626     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8627                              OpValues[2]);
8628     setValue(&VPIntrin, N);
8629     break;
8630   }
8631   case ISD::VP_PTRTOINT: {
8632     SDValue N = OpValues[0];
8633     EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8634                                                           VPIntrin.getType());
8635     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(),
8636                                        VPIntrin.getOperand(0)->getType());
8637     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8638                                OpValues[2]);
8639     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8640                              OpValues[2]);
8641     setValue(&VPIntrin, N);
8642     break;
8643   }
8644   case ISD::VP_ABS:
8645   case ISD::VP_CTLZ:
8646   case ISD::VP_CTLZ_ZERO_UNDEF:
8647   case ISD::VP_CTTZ:
8648   case ISD::VP_CTTZ_ZERO_UNDEF:
8649   case ISD::VP_CTTZ_ELTS_ZERO_UNDEF:
8650   case ISD::VP_CTTZ_ELTS: {
8651     SDValue Result =
8652         DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]});
8653     setValue(&VPIntrin, Result);
8654     break;
8655   }
8656   }
8657 }
8658 
8659 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
8660                                           const BasicBlock *EHPadBB,
8661                                           MCSymbol *&BeginLabel) {
8662   MachineFunction &MF = DAG.getMachineFunction();
8663 
8664   // Insert a label before the invoke call to mark the try range.  This can be
8665   // used to detect deletion of the invoke via the MachineModuleInfo.
8666   BeginLabel = MF.getContext().createTempSymbol();
8667 
8668   // For SjLj, keep track of which landing pads go with which invokes
8669   // so as to maintain the ordering of pads in the LSDA.
8670   unsigned CallSiteIndex = FuncInfo.getCurrentCallSite();
8671   if (CallSiteIndex) {
8672     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
8673     LPadToCallSiteMap[FuncInfo.getMBB(EHPadBB)].push_back(CallSiteIndex);
8674 
8675     // Now that the call site is handled, stop tracking it.
8676     FuncInfo.setCurrentCallSite(0);
8677   }
8678 
8679   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
8680 }
8681 
8682 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
8683                                         const BasicBlock *EHPadBB,
8684                                         MCSymbol *BeginLabel) {
8685   assert(BeginLabel && "BeginLabel should've been set");
8686 
8687   MachineFunction &MF = DAG.getMachineFunction();
8688 
8689   // Insert a label at the end of the invoke call to mark the try range.  This
8690   // can be used to detect deletion of the invoke via the MachineModuleInfo.
8691   MCSymbol *EndLabel = MF.getContext().createTempSymbol();
8692   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
8693 
8694   // Inform MachineModuleInfo of range.
8695   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
8696   // There is a platform (e.g. wasm) that uses funclet style IR but does not
8697   // actually use outlined funclets and their LSDA info style.
8698   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
8699     assert(II && "II should've been set");
8700     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
8701     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
8702   } else if (!isScopedEHPersonality(Pers)) {
8703     assert(EHPadBB);
8704     MF.addInvoke(FuncInfo.getMBB(EHPadBB), BeginLabel, EndLabel);
8705   }
8706 
8707   return Chain;
8708 }
8709 
8710 std::pair<SDValue, SDValue>
8711 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
8712                                     const BasicBlock *EHPadBB) {
8713   MCSymbol *BeginLabel = nullptr;
8714 
8715   if (EHPadBB) {
8716     // Both PendingLoads and PendingExports must be flushed here;
8717     // this call might not return.
8718     (void)getRoot();
8719     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
8720     CLI.setChain(getRoot());
8721   }
8722 
8723   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8724   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
8725 
8726   assert((CLI.IsTailCall || Result.second.getNode()) &&
8727          "Non-null chain expected with non-tail call!");
8728   assert((Result.second.getNode() || !Result.first.getNode()) &&
8729          "Null value expected with tail call!");
8730 
8731   if (!Result.second.getNode()) {
8732     // As a special case, a null chain means that a tail call has been emitted
8733     // and the DAG root is already updated.
8734     HasTailCall = true;
8735 
8736     // Since there's no actual continuation from this block, nothing can be
8737     // relying on us setting vregs for them.
8738     PendingExports.clear();
8739   } else {
8740     DAG.setRoot(Result.second);
8741   }
8742 
8743   if (EHPadBB) {
8744     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
8745                            BeginLabel));
8746     Result.second = getRoot();
8747   }
8748 
8749   return Result;
8750 }
8751 
8752 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
8753                                       bool isTailCall, bool isMustTailCall,
8754                                       const BasicBlock *EHPadBB,
8755                                       const TargetLowering::PtrAuthInfo *PAI) {
8756   auto &DL = DAG.getDataLayout();
8757   FunctionType *FTy = CB.getFunctionType();
8758   Type *RetTy = CB.getType();
8759 
8760   TargetLowering::ArgListTy Args;
8761   Args.reserve(CB.arg_size());
8762 
8763   const Value *SwiftErrorVal = nullptr;
8764   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8765 
8766   if (isTailCall) {
8767     // Avoid emitting tail calls in functions with the disable-tail-calls
8768     // attribute.
8769     auto *Caller = CB.getParent()->getParent();
8770     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
8771         "true" && !isMustTailCall)
8772       isTailCall = false;
8773 
8774     // We can't tail call inside a function with a swifterror argument. Lowering
8775     // does not support this yet. It would have to move into the swifterror
8776     // register before the call.
8777     if (TLI.supportSwiftError() &&
8778         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
8779       isTailCall = false;
8780   }
8781 
8782   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
8783     TargetLowering::ArgListEntry Entry;
8784     const Value *V = *I;
8785 
8786     // Skip empty types
8787     if (V->getType()->isEmptyTy())
8788       continue;
8789 
8790     SDValue ArgNode = getValue(V);
8791     Entry.Node = ArgNode; Entry.Ty = V->getType();
8792 
8793     Entry.setAttributes(&CB, I - CB.arg_begin());
8794 
8795     // Use swifterror virtual register as input to the call.
8796     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
8797       SwiftErrorVal = V;
8798       // We find the virtual register for the actual swifterror argument.
8799       // Instead of using the Value, we use the virtual register instead.
8800       Entry.Node =
8801           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
8802                           EVT(TLI.getPointerTy(DL)));
8803     }
8804 
8805     Args.push_back(Entry);
8806 
8807     // If we have an explicit sret argument that is an Instruction, (i.e., it
8808     // might point to function-local memory), we can't meaningfully tail-call.
8809     if (Entry.IsSRet && isa<Instruction>(V))
8810       isTailCall = false;
8811   }
8812 
8813   // If call site has a cfguardtarget operand bundle, create and add an
8814   // additional ArgListEntry.
8815   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
8816     TargetLowering::ArgListEntry Entry;
8817     Value *V = Bundle->Inputs[0];
8818     SDValue ArgNode = getValue(V);
8819     Entry.Node = ArgNode;
8820     Entry.Ty = V->getType();
8821     Entry.IsCFGuardTarget = true;
8822     Args.push_back(Entry);
8823   }
8824 
8825   // Check if target-independent constraints permit a tail call here.
8826   // Target-dependent constraints are checked within TLI->LowerCallTo.
8827   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
8828     isTailCall = false;
8829 
8830   // Disable tail calls if there is an swifterror argument. Targets have not
8831   // been updated to support tail calls.
8832   if (TLI.supportSwiftError() && SwiftErrorVal)
8833     isTailCall = false;
8834 
8835   ConstantInt *CFIType = nullptr;
8836   if (CB.isIndirectCall()) {
8837     if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
8838       if (!TLI.supportKCFIBundles())
8839         report_fatal_error(
8840             "Target doesn't support calls with kcfi operand bundles.");
8841       CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
8842       assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
8843     }
8844   }
8845 
8846   SDValue ConvControlToken;
8847   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_convergencectrl)) {
8848     auto *Token = Bundle->Inputs[0].get();
8849     ConvControlToken = getValue(Token);
8850   }
8851 
8852   TargetLowering::CallLoweringInfo CLI(DAG);
8853   CLI.setDebugLoc(getCurSDLoc())
8854       .setChain(getRoot())
8855       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
8856       .setTailCall(isTailCall)
8857       .setConvergent(CB.isConvergent())
8858       .setIsPreallocated(
8859           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
8860       .setCFIType(CFIType)
8861       .setConvergenceControlToken(ConvControlToken);
8862 
8863   // Set the pointer authentication info if we have it.
8864   if (PAI) {
8865     if (!TLI.supportPtrAuthBundles())
8866       report_fatal_error(
8867           "This target doesn't support calls with ptrauth operand bundles.");
8868     CLI.setPtrAuth(*PAI);
8869   }
8870 
8871   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8872 
8873   if (Result.first.getNode()) {
8874     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
8875     setValue(&CB, Result.first);
8876   }
8877 
8878   // The last element of CLI.InVals has the SDValue for swifterror return.
8879   // Here we copy it to a virtual register and update SwiftErrorMap for
8880   // book-keeping.
8881   if (SwiftErrorVal && TLI.supportSwiftError()) {
8882     // Get the last element of InVals.
8883     SDValue Src = CLI.InVals.back();
8884     Register VReg =
8885         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
8886     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
8887     DAG.setRoot(CopyNode);
8888   }
8889 }
8890 
8891 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
8892                              SelectionDAGBuilder &Builder) {
8893   // Check to see if this load can be trivially constant folded, e.g. if the
8894   // input is from a string literal.
8895   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
8896     // Cast pointer to the type we really want to load.
8897     Type *LoadTy =
8898         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
8899     if (LoadVT.isVector())
8900       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
8901 
8902     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
8903                                          PointerType::getUnqual(LoadTy));
8904 
8905     if (const Constant *LoadCst =
8906             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
8907                                          LoadTy, Builder.DAG.getDataLayout()))
8908       return Builder.getValue(LoadCst);
8909   }
8910 
8911   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
8912   // still constant memory, the input chain can be the entry node.
8913   SDValue Root;
8914   bool ConstantMemory = false;
8915 
8916   // Do not serialize (non-volatile) loads of constant memory with anything.
8917   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
8918     Root = Builder.DAG.getEntryNode();
8919     ConstantMemory = true;
8920   } else {
8921     // Do not serialize non-volatile loads against each other.
8922     Root = Builder.DAG.getRoot();
8923   }
8924 
8925   SDValue Ptr = Builder.getValue(PtrVal);
8926   SDValue LoadVal =
8927       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
8928                           MachinePointerInfo(PtrVal), Align(1));
8929 
8930   if (!ConstantMemory)
8931     Builder.PendingLoads.push_back(LoadVal.getValue(1));
8932   return LoadVal;
8933 }
8934 
8935 /// Record the value for an instruction that produces an integer result,
8936 /// converting the type where necessary.
8937 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
8938                                                   SDValue Value,
8939                                                   bool IsSigned) {
8940   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8941                                                     I.getType(), true);
8942   Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT);
8943   setValue(&I, Value);
8944 }
8945 
8946 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
8947 /// true and lower it. Otherwise return false, and it will be lowered like a
8948 /// normal call.
8949 /// The caller already checked that \p I calls the appropriate LibFunc with a
8950 /// correct prototype.
8951 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
8952   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
8953   const Value *Size = I.getArgOperand(2);
8954   const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
8955   if (CSize && CSize->getZExtValue() == 0) {
8956     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8957                                                           I.getType(), true);
8958     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
8959     return true;
8960   }
8961 
8962   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8963   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
8964       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
8965       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
8966   if (Res.first.getNode()) {
8967     processIntegerCallValue(I, Res.first, true);
8968     PendingLoads.push_back(Res.second);
8969     return true;
8970   }
8971 
8972   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
8973   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
8974   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
8975     return false;
8976 
8977   // If the target has a fast compare for the given size, it will return a
8978   // preferred load type for that size. Require that the load VT is legal and
8979   // that the target supports unaligned loads of that type. Otherwise, return
8980   // INVALID.
8981   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
8982     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8983     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
8984     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
8985       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
8986       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
8987       // TODO: Check alignment of src and dest ptrs.
8988       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
8989       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
8990       if (!TLI.isTypeLegal(LVT) ||
8991           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
8992           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
8993         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
8994     }
8995 
8996     return LVT;
8997   };
8998 
8999   // This turns into unaligned loads. We only do this if the target natively
9000   // supports the MVT we'll be loading or if it is small enough (<= 4) that
9001   // we'll only produce a small number of byte loads.
9002   MVT LoadVT;
9003   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
9004   switch (NumBitsToCompare) {
9005   default:
9006     return false;
9007   case 16:
9008     LoadVT = MVT::i16;
9009     break;
9010   case 32:
9011     LoadVT = MVT::i32;
9012     break;
9013   case 64:
9014   case 128:
9015   case 256:
9016     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
9017     break;
9018   }
9019 
9020   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
9021     return false;
9022 
9023   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
9024   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
9025 
9026   // Bitcast to a wide integer type if the loads are vectors.
9027   if (LoadVT.isVector()) {
9028     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
9029     LoadL = DAG.getBitcast(CmpVT, LoadL);
9030     LoadR = DAG.getBitcast(CmpVT, LoadR);
9031   }
9032 
9033   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
9034   processIntegerCallValue(I, Cmp, false);
9035   return true;
9036 }
9037 
9038 /// See if we can lower a memchr call into an optimized form. If so, return
9039 /// true and lower it. Otherwise return false, and it will be lowered like a
9040 /// normal call.
9041 /// The caller already checked that \p I calls the appropriate LibFunc with a
9042 /// correct prototype.
9043 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
9044   const Value *Src = I.getArgOperand(0);
9045   const Value *Char = I.getArgOperand(1);
9046   const Value *Length = I.getArgOperand(2);
9047 
9048   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9049   std::pair<SDValue, SDValue> Res =
9050     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
9051                                 getValue(Src), getValue(Char), getValue(Length),
9052                                 MachinePointerInfo(Src));
9053   if (Res.first.getNode()) {
9054     setValue(&I, Res.first);
9055     PendingLoads.push_back(Res.second);
9056     return true;
9057   }
9058 
9059   return false;
9060 }
9061 
9062 /// See if we can lower a mempcpy call into an optimized form. If so, return
9063 /// true and lower it. Otherwise return false, and it will be lowered like a
9064 /// normal call.
9065 /// The caller already checked that \p I calls the appropriate LibFunc with a
9066 /// correct prototype.
9067 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
9068   SDValue Dst = getValue(I.getArgOperand(0));
9069   SDValue Src = getValue(I.getArgOperand(1));
9070   SDValue Size = getValue(I.getArgOperand(2));
9071 
9072   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
9073   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
9074   // DAG::getMemcpy needs Alignment to be defined.
9075   Align Alignment = std::min(DstAlign, SrcAlign);
9076 
9077   SDLoc sdl = getCurSDLoc();
9078 
9079   // In the mempcpy context we need to pass in a false value for isTailCall
9080   // because the return pointer needs to be adjusted by the size of
9081   // the copied memory.
9082   SDValue Root = getMemoryRoot();
9083   SDValue MC = DAG.getMemcpy(
9084       Root, sdl, Dst, Src, Size, Alignment, false, false, /*CI=*/nullptr,
9085       std::nullopt, MachinePointerInfo(I.getArgOperand(0)),
9086       MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata());
9087   assert(MC.getNode() != nullptr &&
9088          "** memcpy should not be lowered as TailCall in mempcpy context **");
9089   DAG.setRoot(MC);
9090 
9091   // Check if Size needs to be truncated or extended.
9092   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
9093 
9094   // Adjust return pointer to point just past the last dst byte.
9095   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
9096                                     Dst, Size);
9097   setValue(&I, DstPlusSize);
9098   return true;
9099 }
9100 
9101 /// See if we can lower a strcpy call into an optimized form.  If so, return
9102 /// true and lower it, otherwise return false and it will be lowered like a
9103 /// normal call.
9104 /// The caller already checked that \p I calls the appropriate LibFunc with a
9105 /// correct prototype.
9106 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
9107   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9108 
9109   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9110   std::pair<SDValue, SDValue> Res =
9111     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
9112                                 getValue(Arg0), getValue(Arg1),
9113                                 MachinePointerInfo(Arg0),
9114                                 MachinePointerInfo(Arg1), isStpcpy);
9115   if (Res.first.getNode()) {
9116     setValue(&I, Res.first);
9117     DAG.setRoot(Res.second);
9118     return true;
9119   }
9120 
9121   return false;
9122 }
9123 
9124 /// See if we can lower a strcmp call into an optimized form.  If so, return
9125 /// true and lower it, otherwise return false and it will be lowered like a
9126 /// normal call.
9127 /// The caller already checked that \p I calls the appropriate LibFunc with a
9128 /// correct prototype.
9129 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
9130   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9131 
9132   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9133   std::pair<SDValue, SDValue> Res =
9134     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
9135                                 getValue(Arg0), getValue(Arg1),
9136                                 MachinePointerInfo(Arg0),
9137                                 MachinePointerInfo(Arg1));
9138   if (Res.first.getNode()) {
9139     processIntegerCallValue(I, Res.first, true);
9140     PendingLoads.push_back(Res.second);
9141     return true;
9142   }
9143 
9144   return false;
9145 }
9146 
9147 /// See if we can lower a strlen call into an optimized form.  If so, return
9148 /// true and lower it, otherwise return false and it will be lowered like a
9149 /// normal call.
9150 /// The caller already checked that \p I calls the appropriate LibFunc with a
9151 /// correct prototype.
9152 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
9153   const Value *Arg0 = I.getArgOperand(0);
9154 
9155   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9156   std::pair<SDValue, SDValue> Res =
9157     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
9158                                 getValue(Arg0), MachinePointerInfo(Arg0));
9159   if (Res.first.getNode()) {
9160     processIntegerCallValue(I, Res.first, false);
9161     PendingLoads.push_back(Res.second);
9162     return true;
9163   }
9164 
9165   return false;
9166 }
9167 
9168 /// See if we can lower a strnlen call into an optimized form.  If so, return
9169 /// true and lower it, otherwise return false and it will be lowered like a
9170 /// normal call.
9171 /// The caller already checked that \p I calls the appropriate LibFunc with a
9172 /// correct prototype.
9173 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
9174   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9175 
9176   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9177   std::pair<SDValue, SDValue> Res =
9178     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
9179                                  getValue(Arg0), getValue(Arg1),
9180                                  MachinePointerInfo(Arg0));
9181   if (Res.first.getNode()) {
9182     processIntegerCallValue(I, Res.first, false);
9183     PendingLoads.push_back(Res.second);
9184     return true;
9185   }
9186 
9187   return false;
9188 }
9189 
9190 /// See if we can lower a unary floating-point operation into an SDNode with
9191 /// the specified Opcode.  If so, return true and lower it, otherwise return
9192 /// false and it will be lowered like a normal call.
9193 /// The caller already checked that \p I calls the appropriate LibFunc with a
9194 /// correct prototype.
9195 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
9196                                               unsigned Opcode) {
9197   // We already checked this call's prototype; verify it doesn't modify errno.
9198   if (!I.onlyReadsMemory())
9199     return false;
9200 
9201   SDNodeFlags Flags;
9202   Flags.copyFMF(cast<FPMathOperator>(I));
9203 
9204   SDValue Tmp = getValue(I.getArgOperand(0));
9205   setValue(&I,
9206            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
9207   return true;
9208 }
9209 
9210 /// See if we can lower a binary floating-point operation into an SDNode with
9211 /// the specified Opcode. If so, return true and lower it. Otherwise return
9212 /// false, and it will be lowered like a normal call.
9213 /// The caller already checked that \p I calls the appropriate LibFunc with a
9214 /// correct prototype.
9215 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
9216                                                unsigned Opcode) {
9217   // We already checked this call's prototype; verify it doesn't modify errno.
9218   if (!I.onlyReadsMemory())
9219     return false;
9220 
9221   SDNodeFlags Flags;
9222   Flags.copyFMF(cast<FPMathOperator>(I));
9223 
9224   SDValue Tmp0 = getValue(I.getArgOperand(0));
9225   SDValue Tmp1 = getValue(I.getArgOperand(1));
9226   EVT VT = Tmp0.getValueType();
9227   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
9228   return true;
9229 }
9230 
9231 void SelectionDAGBuilder::visitCall(const CallInst &I) {
9232   // Handle inline assembly differently.
9233   if (I.isInlineAsm()) {
9234     visitInlineAsm(I);
9235     return;
9236   }
9237 
9238   diagnoseDontCall(I);
9239 
9240   if (Function *F = I.getCalledFunction()) {
9241     if (F->isDeclaration()) {
9242       // Is this an LLVM intrinsic or a target-specific intrinsic?
9243       unsigned IID = F->getIntrinsicID();
9244       if (!IID)
9245         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
9246           IID = II->getIntrinsicID(F);
9247 
9248       if (IID) {
9249         visitIntrinsicCall(I, IID);
9250         return;
9251       }
9252     }
9253 
9254     // Check for well-known libc/libm calls.  If the function is internal, it
9255     // can't be a library call.  Don't do the check if marked as nobuiltin for
9256     // some reason or the call site requires strict floating point semantics.
9257     LibFunc Func;
9258     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
9259         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
9260         LibInfo->hasOptimizedCodeGen(Func)) {
9261       switch (Func) {
9262       default: break;
9263       case LibFunc_bcmp:
9264         if (visitMemCmpBCmpCall(I))
9265           return;
9266         break;
9267       case LibFunc_copysign:
9268       case LibFunc_copysignf:
9269       case LibFunc_copysignl:
9270         // We already checked this call's prototype; verify it doesn't modify
9271         // errno.
9272         if (I.onlyReadsMemory()) {
9273           SDValue LHS = getValue(I.getArgOperand(0));
9274           SDValue RHS = getValue(I.getArgOperand(1));
9275           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
9276                                    LHS.getValueType(), LHS, RHS));
9277           return;
9278         }
9279         break;
9280       case LibFunc_fabs:
9281       case LibFunc_fabsf:
9282       case LibFunc_fabsl:
9283         if (visitUnaryFloatCall(I, ISD::FABS))
9284           return;
9285         break;
9286       case LibFunc_fmin:
9287       case LibFunc_fminf:
9288       case LibFunc_fminl:
9289         if (visitBinaryFloatCall(I, ISD::FMINNUM))
9290           return;
9291         break;
9292       case LibFunc_fmax:
9293       case LibFunc_fmaxf:
9294       case LibFunc_fmaxl:
9295         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
9296           return;
9297         break;
9298       case LibFunc_fminimum_num:
9299       case LibFunc_fminimum_numf:
9300       case LibFunc_fminimum_numl:
9301         if (visitBinaryFloatCall(I, ISD::FMINIMUMNUM))
9302           return;
9303         break;
9304       case LibFunc_fmaximum_num:
9305       case LibFunc_fmaximum_numf:
9306       case LibFunc_fmaximum_numl:
9307         if (visitBinaryFloatCall(I, ISD::FMAXIMUMNUM))
9308           return;
9309         break;
9310       case LibFunc_sin:
9311       case LibFunc_sinf:
9312       case LibFunc_sinl:
9313         if (visitUnaryFloatCall(I, ISD::FSIN))
9314           return;
9315         break;
9316       case LibFunc_cos:
9317       case LibFunc_cosf:
9318       case LibFunc_cosl:
9319         if (visitUnaryFloatCall(I, ISD::FCOS))
9320           return;
9321         break;
9322       case LibFunc_tan:
9323       case LibFunc_tanf:
9324       case LibFunc_tanl:
9325         if (visitUnaryFloatCall(I, ISD::FTAN))
9326           return;
9327         break;
9328       case LibFunc_asin:
9329       case LibFunc_asinf:
9330       case LibFunc_asinl:
9331         if (visitUnaryFloatCall(I, ISD::FASIN))
9332           return;
9333         break;
9334       case LibFunc_acos:
9335       case LibFunc_acosf:
9336       case LibFunc_acosl:
9337         if (visitUnaryFloatCall(I, ISD::FACOS))
9338           return;
9339         break;
9340       case LibFunc_atan:
9341       case LibFunc_atanf:
9342       case LibFunc_atanl:
9343         if (visitUnaryFloatCall(I, ISD::FATAN))
9344           return;
9345         break;
9346       case LibFunc_sinh:
9347       case LibFunc_sinhf:
9348       case LibFunc_sinhl:
9349         if (visitUnaryFloatCall(I, ISD::FSINH))
9350           return;
9351         break;
9352       case LibFunc_cosh:
9353       case LibFunc_coshf:
9354       case LibFunc_coshl:
9355         if (visitUnaryFloatCall(I, ISD::FCOSH))
9356           return;
9357         break;
9358       case LibFunc_tanh:
9359       case LibFunc_tanhf:
9360       case LibFunc_tanhl:
9361         if (visitUnaryFloatCall(I, ISD::FTANH))
9362           return;
9363         break;
9364       case LibFunc_sqrt:
9365       case LibFunc_sqrtf:
9366       case LibFunc_sqrtl:
9367       case LibFunc_sqrt_finite:
9368       case LibFunc_sqrtf_finite:
9369       case LibFunc_sqrtl_finite:
9370         if (visitUnaryFloatCall(I, ISD::FSQRT))
9371           return;
9372         break;
9373       case LibFunc_floor:
9374       case LibFunc_floorf:
9375       case LibFunc_floorl:
9376         if (visitUnaryFloatCall(I, ISD::FFLOOR))
9377           return;
9378         break;
9379       case LibFunc_nearbyint:
9380       case LibFunc_nearbyintf:
9381       case LibFunc_nearbyintl:
9382         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
9383           return;
9384         break;
9385       case LibFunc_ceil:
9386       case LibFunc_ceilf:
9387       case LibFunc_ceill:
9388         if (visitUnaryFloatCall(I, ISD::FCEIL))
9389           return;
9390         break;
9391       case LibFunc_rint:
9392       case LibFunc_rintf:
9393       case LibFunc_rintl:
9394         if (visitUnaryFloatCall(I, ISD::FRINT))
9395           return;
9396         break;
9397       case LibFunc_round:
9398       case LibFunc_roundf:
9399       case LibFunc_roundl:
9400         if (visitUnaryFloatCall(I, ISD::FROUND))
9401           return;
9402         break;
9403       case LibFunc_trunc:
9404       case LibFunc_truncf:
9405       case LibFunc_truncl:
9406         if (visitUnaryFloatCall(I, ISD::FTRUNC))
9407           return;
9408         break;
9409       case LibFunc_log2:
9410       case LibFunc_log2f:
9411       case LibFunc_log2l:
9412         if (visitUnaryFloatCall(I, ISD::FLOG2))
9413           return;
9414         break;
9415       case LibFunc_exp2:
9416       case LibFunc_exp2f:
9417       case LibFunc_exp2l:
9418         if (visitUnaryFloatCall(I, ISD::FEXP2))
9419           return;
9420         break;
9421       case LibFunc_exp10:
9422       case LibFunc_exp10f:
9423       case LibFunc_exp10l:
9424         if (visitUnaryFloatCall(I, ISD::FEXP10))
9425           return;
9426         break;
9427       case LibFunc_ldexp:
9428       case LibFunc_ldexpf:
9429       case LibFunc_ldexpl:
9430         if (visitBinaryFloatCall(I, ISD::FLDEXP))
9431           return;
9432         break;
9433       case LibFunc_memcmp:
9434         if (visitMemCmpBCmpCall(I))
9435           return;
9436         break;
9437       case LibFunc_mempcpy:
9438         if (visitMemPCpyCall(I))
9439           return;
9440         break;
9441       case LibFunc_memchr:
9442         if (visitMemChrCall(I))
9443           return;
9444         break;
9445       case LibFunc_strcpy:
9446         if (visitStrCpyCall(I, false))
9447           return;
9448         break;
9449       case LibFunc_stpcpy:
9450         if (visitStrCpyCall(I, true))
9451           return;
9452         break;
9453       case LibFunc_strcmp:
9454         if (visitStrCmpCall(I))
9455           return;
9456         break;
9457       case LibFunc_strlen:
9458         if (visitStrLenCall(I))
9459           return;
9460         break;
9461       case LibFunc_strnlen:
9462         if (visitStrNLenCall(I))
9463           return;
9464         break;
9465       }
9466     }
9467   }
9468 
9469   if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
9470     LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), /*EHPadBB=*/nullptr);
9471     return;
9472   }
9473 
9474   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
9475   // have to do anything here to lower funclet bundles.
9476   // CFGuardTarget bundles are lowered in LowerCallTo.
9477   assert(!I.hasOperandBundlesOtherThan(
9478              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
9479               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
9480               LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi,
9481               LLVMContext::OB_convergencectrl}) &&
9482          "Cannot lower calls with arbitrary operand bundles!");
9483 
9484   SDValue Callee = getValue(I.getCalledOperand());
9485 
9486   if (I.hasDeoptState())
9487     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
9488   else
9489     // Check if we can potentially perform a tail call. More detailed checking
9490     // is be done within LowerCallTo, after more information about the call is
9491     // known.
9492     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
9493 }
9494 
9495 void SelectionDAGBuilder::LowerCallSiteWithPtrAuthBundle(
9496     const CallBase &CB, const BasicBlock *EHPadBB) {
9497   auto PAB = CB.getOperandBundle("ptrauth");
9498   const Value *CalleeV = CB.getCalledOperand();
9499 
9500   // Gather the call ptrauth data from the operand bundle:
9501   //   [ i32 <key>, i64 <discriminator> ]
9502   const auto *Key = cast<ConstantInt>(PAB->Inputs[0]);
9503   const Value *Discriminator = PAB->Inputs[1];
9504 
9505   assert(Key->getType()->isIntegerTy(32) && "Invalid ptrauth key");
9506   assert(Discriminator->getType()->isIntegerTy(64) &&
9507          "Invalid ptrauth discriminator");
9508 
9509   // Look through ptrauth constants to find the raw callee.
9510   // Do a direct unauthenticated call if we found it and everything matches.
9511   if (const auto *CalleeCPA = dyn_cast<ConstantPtrAuth>(CalleeV))
9512     if (CalleeCPA->isKnownCompatibleWith(Key, Discriminator,
9513                                          DAG.getDataLayout()))
9514       return LowerCallTo(CB, getValue(CalleeCPA->getPointer()), CB.isTailCall(),
9515                          CB.isMustTailCall(), EHPadBB);
9516 
9517   // Functions should never be ptrauth-called directly.
9518   assert(!isa<Function>(CalleeV) && "invalid direct ptrauth call");
9519 
9520   // Otherwise, do an authenticated indirect call.
9521   TargetLowering::PtrAuthInfo PAI = {Key->getZExtValue(),
9522                                      getValue(Discriminator)};
9523 
9524   LowerCallTo(CB, getValue(CalleeV), CB.isTailCall(), CB.isMustTailCall(),
9525               EHPadBB, &PAI);
9526 }
9527 
9528 namespace {
9529 
9530 /// AsmOperandInfo - This contains information for each constraint that we are
9531 /// lowering.
9532 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
9533 public:
9534   /// CallOperand - If this is the result output operand or a clobber
9535   /// this is null, otherwise it is the incoming operand to the CallInst.
9536   /// This gets modified as the asm is processed.
9537   SDValue CallOperand;
9538 
9539   /// AssignedRegs - If this is a register or register class operand, this
9540   /// contains the set of register corresponding to the operand.
9541   RegsForValue AssignedRegs;
9542 
9543   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
9544     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
9545   }
9546 
9547   /// Whether or not this operand accesses memory
9548   bool hasMemory(const TargetLowering &TLI) const {
9549     // Indirect operand accesses access memory.
9550     if (isIndirect)
9551       return true;
9552 
9553     for (const auto &Code : Codes)
9554       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
9555         return true;
9556 
9557     return false;
9558   }
9559 };
9560 
9561 
9562 } // end anonymous namespace
9563 
9564 /// Make sure that the output operand \p OpInfo and its corresponding input
9565 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
9566 /// out).
9567 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
9568                                SDISelAsmOperandInfo &MatchingOpInfo,
9569                                SelectionDAG &DAG) {
9570   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
9571     return;
9572 
9573   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
9574   const auto &TLI = DAG.getTargetLoweringInfo();
9575 
9576   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
9577       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
9578                                        OpInfo.ConstraintVT);
9579   std::pair<unsigned, const TargetRegisterClass *> InputRC =
9580       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
9581                                        MatchingOpInfo.ConstraintVT);
9582   const bool OutOpIsIntOrFP =
9583       OpInfo.ConstraintVT.isInteger() || OpInfo.ConstraintVT.isFloatingPoint();
9584   const bool InOpIsIntOrFP = MatchingOpInfo.ConstraintVT.isInteger() ||
9585                              MatchingOpInfo.ConstraintVT.isFloatingPoint();
9586   if ((OutOpIsIntOrFP != InOpIsIntOrFP) || (MatchRC.second != InputRC.second)) {
9587     // FIXME: error out in a more elegant fashion
9588     report_fatal_error("Unsupported asm: input constraint"
9589                        " with a matching output constraint of"
9590                        " incompatible type!");
9591   }
9592   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
9593 }
9594 
9595 /// Get a direct memory input to behave well as an indirect operand.
9596 /// This may introduce stores, hence the need for a \p Chain.
9597 /// \return The (possibly updated) chain.
9598 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
9599                                         SDISelAsmOperandInfo &OpInfo,
9600                                         SelectionDAG &DAG) {
9601   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9602 
9603   // If we don't have an indirect input, put it in the constpool if we can,
9604   // otherwise spill it to a stack slot.
9605   // TODO: This isn't quite right. We need to handle these according to
9606   // the addressing mode that the constraint wants. Also, this may take
9607   // an additional register for the computation and we don't want that
9608   // either.
9609 
9610   // If the operand is a float, integer, or vector constant, spill to a
9611   // constant pool entry to get its address.
9612   const Value *OpVal = OpInfo.CallOperandVal;
9613   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
9614       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
9615     OpInfo.CallOperand = DAG.getConstantPool(
9616         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
9617     return Chain;
9618   }
9619 
9620   // Otherwise, create a stack slot and emit a store to it before the asm.
9621   Type *Ty = OpVal->getType();
9622   auto &DL = DAG.getDataLayout();
9623   TypeSize TySize = DL.getTypeAllocSize(Ty);
9624   MachineFunction &MF = DAG.getMachineFunction();
9625   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
9626   int StackID = 0;
9627   if (TySize.isScalable())
9628     StackID = TFI->getStackIDForScalableVectors();
9629   int SSFI = MF.getFrameInfo().CreateStackObject(TySize.getKnownMinValue(),
9630                                                  DL.getPrefTypeAlign(Ty), false,
9631                                                  nullptr, StackID);
9632   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
9633   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
9634                             MachinePointerInfo::getFixedStack(MF, SSFI),
9635                             TLI.getMemValueType(DL, Ty));
9636   OpInfo.CallOperand = StackSlot;
9637 
9638   return Chain;
9639 }
9640 
9641 /// GetRegistersForValue - Assign registers (virtual or physical) for the
9642 /// specified operand.  We prefer to assign virtual registers, to allow the
9643 /// register allocator to handle the assignment process.  However, if the asm
9644 /// uses features that we can't model on machineinstrs, we have SDISel do the
9645 /// allocation.  This produces generally horrible, but correct, code.
9646 ///
9647 ///   OpInfo describes the operand
9648 ///   RefOpInfo describes the matching operand if any, the operand otherwise
9649 static std::optional<unsigned>
9650 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
9651                      SDISelAsmOperandInfo &OpInfo,
9652                      SDISelAsmOperandInfo &RefOpInfo) {
9653   LLVMContext &Context = *DAG.getContext();
9654   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9655 
9656   MachineFunction &MF = DAG.getMachineFunction();
9657   SmallVector<Register, 4> Regs;
9658   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9659 
9660   // No work to do for memory/address operands.
9661   if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9662       OpInfo.ConstraintType == TargetLowering::C_Address)
9663     return std::nullopt;
9664 
9665   // If this is a constraint for a single physreg, or a constraint for a
9666   // register class, find it.
9667   unsigned AssignedReg;
9668   const TargetRegisterClass *RC;
9669   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
9670       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
9671   // RC is unset only on failure. Return immediately.
9672   if (!RC)
9673     return std::nullopt;
9674 
9675   // Get the actual register value type.  This is important, because the user
9676   // may have asked for (e.g.) the AX register in i32 type.  We need to
9677   // remember that AX is actually i16 to get the right extension.
9678   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
9679 
9680   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
9681     // If this is an FP operand in an integer register (or visa versa), or more
9682     // generally if the operand value disagrees with the register class we plan
9683     // to stick it in, fix the operand type.
9684     //
9685     // If this is an input value, the bitcast to the new type is done now.
9686     // Bitcast for output value is done at the end of visitInlineAsm().
9687     if ((OpInfo.Type == InlineAsm::isOutput ||
9688          OpInfo.Type == InlineAsm::isInput) &&
9689         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
9690       // Try to convert to the first EVT that the reg class contains.  If the
9691       // types are identical size, use a bitcast to convert (e.g. two differing
9692       // vector types).  Note: output bitcast is done at the end of
9693       // visitInlineAsm().
9694       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
9695         // Exclude indirect inputs while they are unsupported because the code
9696         // to perform the load is missing and thus OpInfo.CallOperand still
9697         // refers to the input address rather than the pointed-to value.
9698         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
9699           OpInfo.CallOperand =
9700               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
9701         OpInfo.ConstraintVT = RegVT;
9702         // If the operand is an FP value and we want it in integer registers,
9703         // use the corresponding integer type. This turns an f64 value into
9704         // i64, which can be passed with two i32 values on a 32-bit machine.
9705       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
9706         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
9707         if (OpInfo.Type == InlineAsm::isInput)
9708           OpInfo.CallOperand =
9709               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
9710         OpInfo.ConstraintVT = VT;
9711       }
9712     }
9713   }
9714 
9715   // No need to allocate a matching input constraint since the constraint it's
9716   // matching to has already been allocated.
9717   if (OpInfo.isMatchingInputConstraint())
9718     return std::nullopt;
9719 
9720   EVT ValueVT = OpInfo.ConstraintVT;
9721   if (OpInfo.ConstraintVT == MVT::Other)
9722     ValueVT = RegVT;
9723 
9724   // Initialize NumRegs.
9725   unsigned NumRegs = 1;
9726   if (OpInfo.ConstraintVT != MVT::Other)
9727     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
9728 
9729   // If this is a constraint for a specific physical register, like {r17},
9730   // assign it now.
9731 
9732   // If this associated to a specific register, initialize iterator to correct
9733   // place. If virtual, make sure we have enough registers
9734 
9735   // Initialize iterator if necessary
9736   TargetRegisterClass::iterator I = RC->begin();
9737   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9738 
9739   // Do not check for single registers.
9740   if (AssignedReg) {
9741     I = std::find(I, RC->end(), AssignedReg);
9742     if (I == RC->end()) {
9743       // RC does not contain the selected register, which indicates a
9744       // mismatch between the register and the required type/bitwidth.
9745       return {AssignedReg};
9746     }
9747   }
9748 
9749   for (; NumRegs; --NumRegs, ++I) {
9750     assert(I != RC->end() && "Ran out of registers to allocate!");
9751     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
9752     Regs.push_back(R);
9753   }
9754 
9755   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
9756   return std::nullopt;
9757 }
9758 
9759 static unsigned
9760 findMatchingInlineAsmOperand(unsigned OperandNo,
9761                              const std::vector<SDValue> &AsmNodeOperands) {
9762   // Scan until we find the definition we already emitted of this operand.
9763   unsigned CurOp = InlineAsm::Op_FirstOperand;
9764   for (; OperandNo; --OperandNo) {
9765     // Advance to the next operand.
9766     unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal();
9767     const InlineAsm::Flag F(OpFlag);
9768     assert(
9769         (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) &&
9770         "Skipped past definitions?");
9771     CurOp += F.getNumOperandRegisters() + 1;
9772   }
9773   return CurOp;
9774 }
9775 
9776 namespace {
9777 
9778 class ExtraFlags {
9779   unsigned Flags = 0;
9780 
9781 public:
9782   explicit ExtraFlags(const CallBase &Call) {
9783     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9784     if (IA->hasSideEffects())
9785       Flags |= InlineAsm::Extra_HasSideEffects;
9786     if (IA->isAlignStack())
9787       Flags |= InlineAsm::Extra_IsAlignStack;
9788     if (Call.isConvergent())
9789       Flags |= InlineAsm::Extra_IsConvergent;
9790     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
9791   }
9792 
9793   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
9794     // Ideally, we would only check against memory constraints.  However, the
9795     // meaning of an Other constraint can be target-specific and we can't easily
9796     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
9797     // for Other constraints as well.
9798     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9799         OpInfo.ConstraintType == TargetLowering::C_Other) {
9800       if (OpInfo.Type == InlineAsm::isInput)
9801         Flags |= InlineAsm::Extra_MayLoad;
9802       else if (OpInfo.Type == InlineAsm::isOutput)
9803         Flags |= InlineAsm::Extra_MayStore;
9804       else if (OpInfo.Type == InlineAsm::isClobber)
9805         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
9806     }
9807   }
9808 
9809   unsigned get() const { return Flags; }
9810 };
9811 
9812 } // end anonymous namespace
9813 
9814 static bool isFunction(SDValue Op) {
9815   if (Op && Op.getOpcode() == ISD::GlobalAddress) {
9816     if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
9817       auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
9818 
9819       // In normal "call dllimport func" instruction (non-inlineasm) it force
9820       // indirect access by specifing call opcode. And usually specially print
9821       // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
9822       // not do in this way now. (In fact, this is similar with "Data Access"
9823       // action). So here we ignore dllimport function.
9824       if (Fn && !Fn->hasDLLImportStorageClass())
9825         return true;
9826     }
9827   }
9828   return false;
9829 }
9830 
9831 /// visitInlineAsm - Handle a call to an InlineAsm object.
9832 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
9833                                          const BasicBlock *EHPadBB) {
9834   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9835 
9836   /// ConstraintOperands - Information about all of the constraints.
9837   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
9838 
9839   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9840   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
9841       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
9842 
9843   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
9844   // AsmDialect, MayLoad, MayStore).
9845   bool HasSideEffect = IA->hasSideEffects();
9846   ExtraFlags ExtraInfo(Call);
9847 
9848   for (auto &T : TargetConstraints) {
9849     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
9850     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
9851 
9852     if (OpInfo.CallOperandVal)
9853       OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
9854 
9855     if (!HasSideEffect)
9856       HasSideEffect = OpInfo.hasMemory(TLI);
9857 
9858     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
9859     // FIXME: Could we compute this on OpInfo rather than T?
9860 
9861     // Compute the constraint code and ConstraintType to use.
9862     TLI.ComputeConstraintToUse(T, SDValue());
9863 
9864     if (T.ConstraintType == TargetLowering::C_Immediate &&
9865         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
9866       // We've delayed emitting a diagnostic like the "n" constraint because
9867       // inlining could cause an integer showing up.
9868       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
9869                                           "' expects an integer constant "
9870                                           "expression");
9871 
9872     ExtraInfo.update(T);
9873   }
9874 
9875   // We won't need to flush pending loads if this asm doesn't touch
9876   // memory and is nonvolatile.
9877   SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
9878 
9879   bool EmitEHLabels = isa<InvokeInst>(Call);
9880   if (EmitEHLabels) {
9881     assert(EHPadBB && "InvokeInst must have an EHPadBB");
9882   }
9883   bool IsCallBr = isa<CallBrInst>(Call);
9884 
9885   if (IsCallBr || EmitEHLabels) {
9886     // If this is a callbr or invoke we need to flush pending exports since
9887     // inlineasm_br and invoke are terminators.
9888     // We need to do this before nodes are glued to the inlineasm_br node.
9889     Chain = getControlRoot();
9890   }
9891 
9892   MCSymbol *BeginLabel = nullptr;
9893   if (EmitEHLabels) {
9894     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
9895   }
9896 
9897   int OpNo = -1;
9898   SmallVector<StringRef> AsmStrs;
9899   IA->collectAsmStrs(AsmStrs);
9900 
9901   // Second pass over the constraints: compute which constraint option to use.
9902   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9903     if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
9904       OpNo++;
9905 
9906     // If this is an output operand with a matching input operand, look up the
9907     // matching input. If their types mismatch, e.g. one is an integer, the
9908     // other is floating point, or their sizes are different, flag it as an
9909     // error.
9910     if (OpInfo.hasMatchingInput()) {
9911       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
9912       patchMatchingInput(OpInfo, Input, DAG);
9913     }
9914 
9915     // Compute the constraint code and ConstraintType to use.
9916     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
9917 
9918     if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
9919          OpInfo.Type == InlineAsm::isClobber) ||
9920         OpInfo.ConstraintType == TargetLowering::C_Address)
9921       continue;
9922 
9923     // In Linux PIC model, there are 4 cases about value/label addressing:
9924     //
9925     // 1: Function call or Label jmp inside the module.
9926     // 2: Data access (such as global variable, static variable) inside module.
9927     // 3: Function call or Label jmp outside the module.
9928     // 4: Data access (such as global variable) outside the module.
9929     //
9930     // Due to current llvm inline asm architecture designed to not "recognize"
9931     // the asm code, there are quite troubles for us to treat mem addressing
9932     // differently for same value/adress used in different instuctions.
9933     // For example, in pic model, call a func may in plt way or direclty
9934     // pc-related, but lea/mov a function adress may use got.
9935     //
9936     // Here we try to "recognize" function call for the case 1 and case 3 in
9937     // inline asm. And try to adjust the constraint for them.
9938     //
9939     // TODO: Due to current inline asm didn't encourage to jmp to the outsider
9940     // label, so here we don't handle jmp function label now, but we need to
9941     // enhance it (especilly in PIC model) if we meet meaningful requirements.
9942     if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
9943         TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
9944         TM.getCodeModel() != CodeModel::Large) {
9945       OpInfo.isIndirect = false;
9946       OpInfo.ConstraintType = TargetLowering::C_Address;
9947     }
9948 
9949     // If this is a memory input, and if the operand is not indirect, do what we
9950     // need to provide an address for the memory input.
9951     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
9952         !OpInfo.isIndirect) {
9953       assert((OpInfo.isMultipleAlternative ||
9954               (OpInfo.Type == InlineAsm::isInput)) &&
9955              "Can only indirectify direct input operands!");
9956 
9957       // Memory operands really want the address of the value.
9958       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
9959 
9960       // There is no longer a Value* corresponding to this operand.
9961       OpInfo.CallOperandVal = nullptr;
9962 
9963       // It is now an indirect operand.
9964       OpInfo.isIndirect = true;
9965     }
9966 
9967   }
9968 
9969   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
9970   std::vector<SDValue> AsmNodeOperands;
9971   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
9972   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
9973       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
9974 
9975   // If we have a !srcloc metadata node associated with it, we want to attach
9976   // this to the ultimately generated inline asm machineinstr.  To do this, we
9977   // pass in the third operand as this (potentially null) inline asm MDNode.
9978   const MDNode *SrcLoc = Call.getMetadata("srcloc");
9979   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
9980 
9981   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
9982   // bits as operand 3.
9983   AsmNodeOperands.push_back(DAG.getTargetConstant(
9984       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9985 
9986   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
9987   // this, assign virtual and physical registers for inputs and otput.
9988   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9989     // Assign Registers.
9990     SDISelAsmOperandInfo &RefOpInfo =
9991         OpInfo.isMatchingInputConstraint()
9992             ? ConstraintOperands[OpInfo.getMatchedOperand()]
9993             : OpInfo;
9994     const auto RegError =
9995         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
9996     if (RegError) {
9997       const MachineFunction &MF = DAG.getMachineFunction();
9998       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9999       const char *RegName = TRI.getName(*RegError);
10000       emitInlineAsmError(Call, "register '" + Twine(RegName) +
10001                                    "' allocated for constraint '" +
10002                                    Twine(OpInfo.ConstraintCode) +
10003                                    "' does not match required type");
10004       return;
10005     }
10006 
10007     auto DetectWriteToReservedRegister = [&]() {
10008       const MachineFunction &MF = DAG.getMachineFunction();
10009       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
10010       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
10011         if (Register::isPhysicalRegister(Reg) &&
10012             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
10013           const char *RegName = TRI.getName(Reg);
10014           emitInlineAsmError(Call, "write to reserved register '" +
10015                                        Twine(RegName) + "'");
10016           return true;
10017         }
10018       }
10019       return false;
10020     };
10021     assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
10022             (OpInfo.Type == InlineAsm::isInput &&
10023              !OpInfo.isMatchingInputConstraint())) &&
10024            "Only address as input operand is allowed.");
10025 
10026     switch (OpInfo.Type) {
10027     case InlineAsm::isOutput:
10028       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10029         const InlineAsm::ConstraintCode ConstraintID =
10030             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10031         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10032                "Failed to convert memory constraint code to constraint id.");
10033 
10034         // Add information to the INLINEASM node to know about this output.
10035         InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1);
10036         OpFlags.setMemConstraint(ConstraintID);
10037         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
10038                                                         MVT::i32));
10039         AsmNodeOperands.push_back(OpInfo.CallOperand);
10040       } else {
10041         // Otherwise, this outputs to a register (directly for C_Register /
10042         // C_RegisterClass, and a target-defined fashion for
10043         // C_Immediate/C_Other). Find a register that we can use.
10044         if (OpInfo.AssignedRegs.Regs.empty()) {
10045           emitInlineAsmError(
10046               Call, "couldn't allocate output register for constraint '" +
10047                         Twine(OpInfo.ConstraintCode) + "'");
10048           return;
10049         }
10050 
10051         if (DetectWriteToReservedRegister())
10052           return;
10053 
10054         // Add information to the INLINEASM node to know that this register is
10055         // set.
10056         OpInfo.AssignedRegs.AddInlineAsmOperands(
10057             OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber
10058                                   : InlineAsm::Kind::RegDef,
10059             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
10060       }
10061       break;
10062 
10063     case InlineAsm::isInput:
10064     case InlineAsm::isLabel: {
10065       SDValue InOperandVal = OpInfo.CallOperand;
10066 
10067       if (OpInfo.isMatchingInputConstraint()) {
10068         // If this is required to match an output register we have already set,
10069         // just use its register.
10070         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
10071                                                   AsmNodeOperands);
10072         InlineAsm::Flag Flag(AsmNodeOperands[CurOp]->getAsZExtVal());
10073         if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) {
10074           if (OpInfo.isIndirect) {
10075             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
10076             emitInlineAsmError(Call, "inline asm not supported yet: "
10077                                      "don't know how to handle tied "
10078                                      "indirect register inputs");
10079             return;
10080           }
10081 
10082           SmallVector<Register, 4> Regs;
10083           MachineFunction &MF = DAG.getMachineFunction();
10084           MachineRegisterInfo &MRI = MF.getRegInfo();
10085           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
10086           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
10087           Register TiedReg = R->getReg();
10088           MVT RegVT = R->getSimpleValueType(0);
10089           const TargetRegisterClass *RC =
10090               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
10091               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
10092                                       : TRI.getMinimalPhysRegClass(TiedReg);
10093           for (unsigned i = 0, e = Flag.getNumOperandRegisters(); i != e; ++i)
10094             Regs.push_back(MRI.createVirtualRegister(RC));
10095 
10096           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
10097 
10098           SDLoc dl = getCurSDLoc();
10099           // Use the produced MatchedRegs object to
10100           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call);
10101           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, true,
10102                                            OpInfo.getMatchedOperand(), dl, DAG,
10103                                            AsmNodeOperands);
10104           break;
10105         }
10106 
10107         assert(Flag.isMemKind() && "Unknown matching constraint!");
10108         assert(Flag.getNumOperandRegisters() == 1 &&
10109                "Unexpected number of operands");
10110         // Add information to the INLINEASM node to know about this input.
10111         // See InlineAsm.h isUseOperandTiedToDef.
10112         Flag.clearMemConstraint();
10113         Flag.setMatchingOp(OpInfo.getMatchedOperand());
10114         AsmNodeOperands.push_back(DAG.getTargetConstant(
10115             Flag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
10116         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
10117         break;
10118       }
10119 
10120       // Treat indirect 'X' constraint as memory.
10121       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
10122           OpInfo.isIndirect)
10123         OpInfo.ConstraintType = TargetLowering::C_Memory;
10124 
10125       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
10126           OpInfo.ConstraintType == TargetLowering::C_Other) {
10127         std::vector<SDValue> Ops;
10128         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
10129                                           Ops, DAG);
10130         if (Ops.empty()) {
10131           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
10132             if (isa<ConstantSDNode>(InOperandVal)) {
10133               emitInlineAsmError(Call, "value out of range for constraint '" +
10134                                            Twine(OpInfo.ConstraintCode) + "'");
10135               return;
10136             }
10137 
10138           emitInlineAsmError(Call,
10139                              "invalid operand for inline asm constraint '" +
10140                                  Twine(OpInfo.ConstraintCode) + "'");
10141           return;
10142         }
10143 
10144         // Add information to the INLINEASM node to know about this input.
10145         InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size());
10146         AsmNodeOperands.push_back(DAG.getTargetConstant(
10147             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
10148         llvm::append_range(AsmNodeOperands, Ops);
10149         break;
10150       }
10151 
10152       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10153         assert((OpInfo.isIndirect ||
10154                 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
10155                "Operand must be indirect to be a mem!");
10156         assert(InOperandVal.getValueType() ==
10157                    TLI.getPointerTy(DAG.getDataLayout()) &&
10158                "Memory operands expect pointer values");
10159 
10160         const InlineAsm::ConstraintCode ConstraintID =
10161             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10162         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10163                "Failed to convert memory constraint code to constraint id.");
10164 
10165         // Add information to the INLINEASM node to know about this input.
10166         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
10167         ResOpType.setMemConstraint(ConstraintID);
10168         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
10169                                                         getCurSDLoc(),
10170                                                         MVT::i32));
10171         AsmNodeOperands.push_back(InOperandVal);
10172         break;
10173       }
10174 
10175       if (OpInfo.ConstraintType == TargetLowering::C_Address) {
10176         const InlineAsm::ConstraintCode ConstraintID =
10177             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10178         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10179                "Failed to convert memory constraint code to constraint id.");
10180 
10181         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
10182 
10183         SDValue AsmOp = InOperandVal;
10184         if (isFunction(InOperandVal)) {
10185           auto *GA = cast<GlobalAddressSDNode>(InOperandVal);
10186           ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1);
10187           AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(),
10188                                              InOperandVal.getValueType(),
10189                                              GA->getOffset());
10190         }
10191 
10192         // Add information to the INLINEASM node to know about this input.
10193         ResOpType.setMemConstraint(ConstraintID);
10194 
10195         AsmNodeOperands.push_back(
10196             DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32));
10197 
10198         AsmNodeOperands.push_back(AsmOp);
10199         break;
10200       }
10201 
10202       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
10203           OpInfo.ConstraintType != TargetLowering::C_Register) {
10204         emitInlineAsmError(Call, "unknown asm constraint '" +
10205                                      Twine(OpInfo.ConstraintCode) + "'");
10206         return;
10207       }
10208 
10209       // TODO: Support this.
10210       if (OpInfo.isIndirect) {
10211         emitInlineAsmError(
10212             Call, "Don't know how to handle indirect register inputs yet "
10213                   "for constraint '" +
10214                       Twine(OpInfo.ConstraintCode) + "'");
10215         return;
10216       }
10217 
10218       // Copy the input into the appropriate registers.
10219       if (OpInfo.AssignedRegs.Regs.empty()) {
10220         emitInlineAsmError(Call,
10221                            "couldn't allocate input reg for constraint '" +
10222                                Twine(OpInfo.ConstraintCode) + "'");
10223         return;
10224       }
10225 
10226       if (DetectWriteToReservedRegister())
10227         return;
10228 
10229       SDLoc dl = getCurSDLoc();
10230 
10231       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue,
10232                                         &Call);
10233 
10234       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, false,
10235                                                0, dl, DAG, AsmNodeOperands);
10236       break;
10237     }
10238     case InlineAsm::isClobber:
10239       // Add the clobbered value to the operand list, so that the register
10240       // allocator is aware that the physreg got clobbered.
10241       if (!OpInfo.AssignedRegs.Regs.empty())
10242         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::Clobber,
10243                                                  false, 0, getCurSDLoc(), DAG,
10244                                                  AsmNodeOperands);
10245       break;
10246     }
10247   }
10248 
10249   // Finish up input operands.  Set the input chain and add the flag last.
10250   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
10251   if (Glue.getNode()) AsmNodeOperands.push_back(Glue);
10252 
10253   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
10254   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
10255                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
10256   Glue = Chain.getValue(1);
10257 
10258   // Do additional work to generate outputs.
10259 
10260   SmallVector<EVT, 1> ResultVTs;
10261   SmallVector<SDValue, 1> ResultValues;
10262   SmallVector<SDValue, 8> OutChains;
10263 
10264   llvm::Type *CallResultType = Call.getType();
10265   ArrayRef<Type *> ResultTypes;
10266   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
10267     ResultTypes = StructResult->elements();
10268   else if (!CallResultType->isVoidTy())
10269     ResultTypes = ArrayRef(CallResultType);
10270 
10271   auto CurResultType = ResultTypes.begin();
10272   auto handleRegAssign = [&](SDValue V) {
10273     assert(CurResultType != ResultTypes.end() && "Unexpected value");
10274     assert((*CurResultType)->isSized() && "Unexpected unsized type");
10275     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
10276     ++CurResultType;
10277     // If the type of the inline asm call site return value is different but has
10278     // same size as the type of the asm output bitcast it.  One example of this
10279     // is for vectors with different width / number of elements.  This can
10280     // happen for register classes that can contain multiple different value
10281     // types.  The preg or vreg allocated may not have the same VT as was
10282     // expected.
10283     //
10284     // This can also happen for a return value that disagrees with the register
10285     // class it is put in, eg. a double in a general-purpose register on a
10286     // 32-bit machine.
10287     if (ResultVT != V.getValueType() &&
10288         ResultVT.getSizeInBits() == V.getValueSizeInBits())
10289       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
10290     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
10291              V.getValueType().isInteger()) {
10292       // If a result value was tied to an input value, the computed result
10293       // may have a wider width than the expected result.  Extract the
10294       // relevant portion.
10295       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
10296     }
10297     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
10298     ResultVTs.push_back(ResultVT);
10299     ResultValues.push_back(V);
10300   };
10301 
10302   // Deal with output operands.
10303   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
10304     if (OpInfo.Type == InlineAsm::isOutput) {
10305       SDValue Val;
10306       // Skip trivial output operands.
10307       if (OpInfo.AssignedRegs.Regs.empty())
10308         continue;
10309 
10310       switch (OpInfo.ConstraintType) {
10311       case TargetLowering::C_Register:
10312       case TargetLowering::C_RegisterClass:
10313         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
10314                                                   Chain, &Glue, &Call);
10315         break;
10316       case TargetLowering::C_Immediate:
10317       case TargetLowering::C_Other:
10318         Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(),
10319                                               OpInfo, DAG);
10320         break;
10321       case TargetLowering::C_Memory:
10322         break; // Already handled.
10323       case TargetLowering::C_Address:
10324         break; // Silence warning.
10325       case TargetLowering::C_Unknown:
10326         assert(false && "Unexpected unknown constraint");
10327       }
10328 
10329       // Indirect output manifest as stores. Record output chains.
10330       if (OpInfo.isIndirect) {
10331         const Value *Ptr = OpInfo.CallOperandVal;
10332         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
10333         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
10334                                      MachinePointerInfo(Ptr));
10335         OutChains.push_back(Store);
10336       } else {
10337         // generate CopyFromRegs to associated registers.
10338         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
10339         if (Val.getOpcode() == ISD::MERGE_VALUES) {
10340           for (const SDValue &V : Val->op_values())
10341             handleRegAssign(V);
10342         } else
10343           handleRegAssign(Val);
10344       }
10345     }
10346   }
10347 
10348   // Set results.
10349   if (!ResultValues.empty()) {
10350     assert(CurResultType == ResultTypes.end() &&
10351            "Mismatch in number of ResultTypes");
10352     assert(ResultValues.size() == ResultTypes.size() &&
10353            "Mismatch in number of output operands in asm result");
10354 
10355     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
10356                             DAG.getVTList(ResultVTs), ResultValues);
10357     setValue(&Call, V);
10358   }
10359 
10360   // Collect store chains.
10361   if (!OutChains.empty())
10362     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
10363 
10364   if (EmitEHLabels) {
10365     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
10366   }
10367 
10368   // Only Update Root if inline assembly has a memory effect.
10369   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
10370       EmitEHLabels)
10371     DAG.setRoot(Chain);
10372 }
10373 
10374 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
10375                                              const Twine &Message) {
10376   LLVMContext &Ctx = *DAG.getContext();
10377   Ctx.emitError(&Call, Message);
10378 
10379   // Make sure we leave the DAG in a valid state
10380   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10381   SmallVector<EVT, 1> ValueVTs;
10382   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
10383 
10384   if (ValueVTs.empty())
10385     return;
10386 
10387   SmallVector<SDValue, 1> Ops;
10388   for (const EVT &VT : ValueVTs)
10389     Ops.push_back(DAG.getUNDEF(VT));
10390 
10391   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
10392 }
10393 
10394 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
10395   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
10396                           MVT::Other, getRoot(),
10397                           getValue(I.getArgOperand(0)),
10398                           DAG.getSrcValue(I.getArgOperand(0))));
10399 }
10400 
10401 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
10402   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10403   const DataLayout &DL = DAG.getDataLayout();
10404   SDValue V = DAG.getVAArg(
10405       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
10406       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
10407       DL.getABITypeAlign(I.getType()).value());
10408   DAG.setRoot(V.getValue(1));
10409 
10410   if (I.getType()->isPointerTy())
10411     V = DAG.getPtrExtOrTrunc(
10412         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
10413   setValue(&I, V);
10414 }
10415 
10416 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
10417   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
10418                           MVT::Other, getRoot(),
10419                           getValue(I.getArgOperand(0)),
10420                           DAG.getSrcValue(I.getArgOperand(0))));
10421 }
10422 
10423 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
10424   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
10425                           MVT::Other, getRoot(),
10426                           getValue(I.getArgOperand(0)),
10427                           getValue(I.getArgOperand(1)),
10428                           DAG.getSrcValue(I.getArgOperand(0)),
10429                           DAG.getSrcValue(I.getArgOperand(1))));
10430 }
10431 
10432 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
10433                                                     const Instruction &I,
10434                                                     SDValue Op) {
10435   std::optional<ConstantRange> CR = getRange(I);
10436 
10437   if (!CR || CR->isFullSet() || CR->isEmptySet() || CR->isUpperWrapped())
10438     return Op;
10439 
10440   APInt Lo = CR->getUnsignedMin();
10441   if (!Lo.isMinValue())
10442     return Op;
10443 
10444   APInt Hi = CR->getUnsignedMax();
10445   unsigned Bits = std::max(Hi.getActiveBits(),
10446                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
10447 
10448   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
10449 
10450   SDLoc SL = getCurSDLoc();
10451 
10452   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
10453                              DAG.getValueType(SmallVT));
10454   unsigned NumVals = Op.getNode()->getNumValues();
10455   if (NumVals == 1)
10456     return ZExt;
10457 
10458   SmallVector<SDValue, 4> Ops;
10459 
10460   Ops.push_back(ZExt);
10461   for (unsigned I = 1; I != NumVals; ++I)
10462     Ops.push_back(Op.getValue(I));
10463 
10464   return DAG.getMergeValues(Ops, SL);
10465 }
10466 
10467 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
10468 /// the call being lowered.
10469 ///
10470 /// This is a helper for lowering intrinsics that follow a target calling
10471 /// convention or require stack pointer adjustment. Only a subset of the
10472 /// intrinsic's operands need to participate in the calling convention.
10473 void SelectionDAGBuilder::populateCallLoweringInfo(
10474     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
10475     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
10476     AttributeSet RetAttrs, bool IsPatchPoint) {
10477   TargetLowering::ArgListTy Args;
10478   Args.reserve(NumArgs);
10479 
10480   // Populate the argument list.
10481   // Attributes for args start at offset 1, after the return attribute.
10482   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
10483        ArgI != ArgE; ++ArgI) {
10484     const Value *V = Call->getOperand(ArgI);
10485 
10486     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
10487 
10488     TargetLowering::ArgListEntry Entry;
10489     Entry.Node = getValue(V);
10490     Entry.Ty = V->getType();
10491     Entry.setAttributes(Call, ArgI);
10492     Args.push_back(Entry);
10493   }
10494 
10495   CLI.setDebugLoc(getCurSDLoc())
10496       .setChain(getRoot())
10497       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args),
10498                  RetAttrs)
10499       .setDiscardResult(Call->use_empty())
10500       .setIsPatchPoint(IsPatchPoint)
10501       .setIsPreallocated(
10502           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
10503 }
10504 
10505 /// Add a stack map intrinsic call's live variable operands to a stackmap
10506 /// or patchpoint target node's operand list.
10507 ///
10508 /// Constants are converted to TargetConstants purely as an optimization to
10509 /// avoid constant materialization and register allocation.
10510 ///
10511 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
10512 /// generate addess computation nodes, and so FinalizeISel can convert the
10513 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
10514 /// address materialization and register allocation, but may also be required
10515 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
10516 /// alloca in the entry block, then the runtime may assume that the alloca's
10517 /// StackMap location can be read immediately after compilation and that the
10518 /// location is valid at any point during execution (this is similar to the
10519 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
10520 /// only available in a register, then the runtime would need to trap when
10521 /// execution reaches the StackMap in order to read the alloca's location.
10522 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
10523                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
10524                                 SelectionDAGBuilder &Builder) {
10525   SelectionDAG &DAG = Builder.DAG;
10526   for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
10527     SDValue Op = Builder.getValue(Call.getArgOperand(I));
10528 
10529     // Things on the stack are pointer-typed, meaning that they are already
10530     // legal and can be emitted directly to target nodes.
10531     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
10532       Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
10533     } else {
10534       // Otherwise emit a target independent node to be legalised.
10535       Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
10536     }
10537   }
10538 }
10539 
10540 /// Lower llvm.experimental.stackmap.
10541 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
10542   // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
10543   //                                  [live variables...])
10544 
10545   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
10546 
10547   SDValue Chain, InGlue, Callee;
10548   SmallVector<SDValue, 32> Ops;
10549 
10550   SDLoc DL = getCurSDLoc();
10551   Callee = getValue(CI.getCalledOperand());
10552 
10553   // The stackmap intrinsic only records the live variables (the arguments
10554   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
10555   // intrinsic, this won't be lowered to a function call. This means we don't
10556   // have to worry about calling conventions and target specific lowering code.
10557   // Instead we perform the call lowering right here.
10558   //
10559   // chain, flag = CALLSEQ_START(chain, 0, 0)
10560   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
10561   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
10562   //
10563   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
10564   InGlue = Chain.getValue(1);
10565 
10566   // Add the STACKMAP operands, starting with DAG house-keeping.
10567   Ops.push_back(Chain);
10568   Ops.push_back(InGlue);
10569 
10570   // Add the <id>, <numShadowBytes> operands.
10571   //
10572   // These do not require legalisation, and can be emitted directly to target
10573   // constant nodes.
10574   SDValue ID = getValue(CI.getArgOperand(0));
10575   assert(ID.getValueType() == MVT::i64);
10576   SDValue IDConst =
10577       DAG.getTargetConstant(ID->getAsZExtVal(), DL, ID.getValueType());
10578   Ops.push_back(IDConst);
10579 
10580   SDValue Shad = getValue(CI.getArgOperand(1));
10581   assert(Shad.getValueType() == MVT::i32);
10582   SDValue ShadConst =
10583       DAG.getTargetConstant(Shad->getAsZExtVal(), DL, Shad.getValueType());
10584   Ops.push_back(ShadConst);
10585 
10586   // Add the live variables.
10587   addStackMapLiveVars(CI, 2, DL, Ops, *this);
10588 
10589   // Create the STACKMAP node.
10590   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10591   Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
10592   InGlue = Chain.getValue(1);
10593 
10594   Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL);
10595 
10596   // Stackmaps don't generate values, so nothing goes into the NodeMap.
10597 
10598   // Set the root to the target-lowered call chain.
10599   DAG.setRoot(Chain);
10600 
10601   // Inform the Frame Information that we have a stackmap in this function.
10602   FuncInfo.MF->getFrameInfo().setHasStackMap();
10603 }
10604 
10605 /// Lower llvm.experimental.patchpoint directly to its target opcode.
10606 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
10607                                           const BasicBlock *EHPadBB) {
10608   // <ty> @llvm.experimental.patchpoint.<ty>(i64 <id>,
10609   //                                         i32 <numBytes>,
10610   //                                         i8* <target>,
10611   //                                         i32 <numArgs>,
10612   //                                         [Args...],
10613   //                                         [live variables...])
10614 
10615   CallingConv::ID CC = CB.getCallingConv();
10616   bool IsAnyRegCC = CC == CallingConv::AnyReg;
10617   bool HasDef = !CB.getType()->isVoidTy();
10618   SDLoc dl = getCurSDLoc();
10619   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
10620 
10621   // Handle immediate and symbolic callees.
10622   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
10623     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
10624                                    /*isTarget=*/true);
10625   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
10626     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
10627                                          SDLoc(SymbolicCallee),
10628                                          SymbolicCallee->getValueType(0));
10629 
10630   // Get the real number of arguments participating in the call <numArgs>
10631   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
10632   unsigned NumArgs = NArgVal->getAsZExtVal();
10633 
10634   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
10635   // Intrinsics include all meta-operands up to but not including CC.
10636   unsigned NumMetaOpers = PatchPointOpers::CCPos;
10637   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
10638          "Not enough arguments provided to the patchpoint intrinsic");
10639 
10640   // For AnyRegCC the arguments are lowered later on manually.
10641   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
10642   Type *ReturnTy =
10643       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
10644 
10645   TargetLowering::CallLoweringInfo CLI(DAG);
10646   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
10647                            ReturnTy, CB.getAttributes().getRetAttrs(), true);
10648   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
10649 
10650   SDNode *CallEnd = Result.second.getNode();
10651   if (CallEnd->getOpcode() == ISD::EH_LABEL)
10652     CallEnd = CallEnd->getOperand(0).getNode();
10653   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
10654     CallEnd = CallEnd->getOperand(0).getNode();
10655 
10656   /// Get a call instruction from the call sequence chain.
10657   /// Tail calls are not allowed.
10658   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
10659          "Expected a callseq node.");
10660   SDNode *Call = CallEnd->getOperand(0).getNode();
10661   bool HasGlue = Call->getGluedNode();
10662 
10663   // Replace the target specific call node with the patchable intrinsic.
10664   SmallVector<SDValue, 8> Ops;
10665 
10666   // Push the chain.
10667   Ops.push_back(*(Call->op_begin()));
10668 
10669   // Optionally, push the glue (if any).
10670   if (HasGlue)
10671     Ops.push_back(*(Call->op_end() - 1));
10672 
10673   // Push the register mask info.
10674   if (HasGlue)
10675     Ops.push_back(*(Call->op_end() - 2));
10676   else
10677     Ops.push_back(*(Call->op_end() - 1));
10678 
10679   // Add the <id> and <numBytes> constants.
10680   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
10681   Ops.push_back(DAG.getTargetConstant(IDVal->getAsZExtVal(), dl, MVT::i64));
10682   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
10683   Ops.push_back(DAG.getTargetConstant(NBytesVal->getAsZExtVal(), dl, MVT::i32));
10684 
10685   // Add the callee.
10686   Ops.push_back(Callee);
10687 
10688   // Adjust <numArgs> to account for any arguments that have been passed on the
10689   // stack instead.
10690   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
10691   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
10692   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
10693   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
10694 
10695   // Add the calling convention
10696   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
10697 
10698   // Add the arguments we omitted previously. The register allocator should
10699   // place these in any free register.
10700   if (IsAnyRegCC)
10701     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
10702       Ops.push_back(getValue(CB.getArgOperand(i)));
10703 
10704   // Push the arguments from the call instruction.
10705   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
10706   Ops.append(Call->op_begin() + 2, e);
10707 
10708   // Push live variables for the stack map.
10709   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
10710 
10711   SDVTList NodeTys;
10712   if (IsAnyRegCC && HasDef) {
10713     // Create the return types based on the intrinsic definition
10714     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10715     SmallVector<EVT, 3> ValueVTs;
10716     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
10717     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
10718 
10719     // There is always a chain and a glue type at the end
10720     ValueVTs.push_back(MVT::Other);
10721     ValueVTs.push_back(MVT::Glue);
10722     NodeTys = DAG.getVTList(ValueVTs);
10723   } else
10724     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10725 
10726   // Replace the target specific call node with a PATCHPOINT node.
10727   SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
10728 
10729   // Update the NodeMap.
10730   if (HasDef) {
10731     if (IsAnyRegCC)
10732       setValue(&CB, SDValue(PPV.getNode(), 0));
10733     else
10734       setValue(&CB, Result.first);
10735   }
10736 
10737   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
10738   // call sequence. Furthermore the location of the chain and glue can change
10739   // when the AnyReg calling convention is used and the intrinsic returns a
10740   // value.
10741   if (IsAnyRegCC && HasDef) {
10742     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
10743     SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
10744     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10745   } else
10746     DAG.ReplaceAllUsesWith(Call, PPV.getNode());
10747   DAG.DeleteNode(Call);
10748 
10749   // Inform the Frame Information that we have a patchpoint in this function.
10750   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
10751 }
10752 
10753 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
10754                                             unsigned Intrinsic) {
10755   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10756   SDValue Op1 = getValue(I.getArgOperand(0));
10757   SDValue Op2;
10758   if (I.arg_size() > 1)
10759     Op2 = getValue(I.getArgOperand(1));
10760   SDLoc dl = getCurSDLoc();
10761   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
10762   SDValue Res;
10763   SDNodeFlags SDFlags;
10764   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
10765     SDFlags.copyFMF(*FPMO);
10766 
10767   switch (Intrinsic) {
10768   case Intrinsic::vector_reduce_fadd:
10769     if (SDFlags.hasAllowReassociation())
10770       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
10771                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
10772                         SDFlags);
10773     else
10774       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
10775     break;
10776   case Intrinsic::vector_reduce_fmul:
10777     if (SDFlags.hasAllowReassociation())
10778       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
10779                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
10780                         SDFlags);
10781     else
10782       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
10783     break;
10784   case Intrinsic::vector_reduce_add:
10785     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
10786     break;
10787   case Intrinsic::vector_reduce_mul:
10788     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
10789     break;
10790   case Intrinsic::vector_reduce_and:
10791     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
10792     break;
10793   case Intrinsic::vector_reduce_or:
10794     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
10795     break;
10796   case Intrinsic::vector_reduce_xor:
10797     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
10798     break;
10799   case Intrinsic::vector_reduce_smax:
10800     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
10801     break;
10802   case Intrinsic::vector_reduce_smin:
10803     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
10804     break;
10805   case Intrinsic::vector_reduce_umax:
10806     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
10807     break;
10808   case Intrinsic::vector_reduce_umin:
10809     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
10810     break;
10811   case Intrinsic::vector_reduce_fmax:
10812     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
10813     break;
10814   case Intrinsic::vector_reduce_fmin:
10815     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
10816     break;
10817   case Intrinsic::vector_reduce_fmaximum:
10818     Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags);
10819     break;
10820   case Intrinsic::vector_reduce_fminimum:
10821     Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags);
10822     break;
10823   default:
10824     llvm_unreachable("Unhandled vector reduce intrinsic");
10825   }
10826   setValue(&I, Res);
10827 }
10828 
10829 /// Returns an AttributeList representing the attributes applied to the return
10830 /// value of the given call.
10831 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
10832   SmallVector<Attribute::AttrKind, 2> Attrs;
10833   if (CLI.RetSExt)
10834     Attrs.push_back(Attribute::SExt);
10835   if (CLI.RetZExt)
10836     Attrs.push_back(Attribute::ZExt);
10837   if (CLI.IsInReg)
10838     Attrs.push_back(Attribute::InReg);
10839 
10840   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
10841                             Attrs);
10842 }
10843 
10844 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
10845 /// implementation, which just calls LowerCall.
10846 /// FIXME: When all targets are
10847 /// migrated to using LowerCall, this hook should be integrated into SDISel.
10848 std::pair<SDValue, SDValue>
10849 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
10850   // Handle the incoming return values from the call.
10851   CLI.Ins.clear();
10852   Type *OrigRetTy = CLI.RetTy;
10853   SmallVector<EVT, 4> RetTys;
10854   SmallVector<TypeSize, 4> Offsets;
10855   auto &DL = CLI.DAG.getDataLayout();
10856   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
10857 
10858   if (CLI.IsPostTypeLegalization) {
10859     // If we are lowering a libcall after legalization, split the return type.
10860     SmallVector<EVT, 4> OldRetTys;
10861     SmallVector<TypeSize, 4> OldOffsets;
10862     RetTys.swap(OldRetTys);
10863     Offsets.swap(OldOffsets);
10864 
10865     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
10866       EVT RetVT = OldRetTys[i];
10867       uint64_t Offset = OldOffsets[i];
10868       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
10869       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
10870       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
10871       RetTys.append(NumRegs, RegisterVT);
10872       for (unsigned j = 0; j != NumRegs; ++j)
10873         Offsets.push_back(TypeSize::getFixed(Offset + j * RegisterVTByteSZ));
10874     }
10875   }
10876 
10877   SmallVector<ISD::OutputArg, 4> Outs;
10878   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
10879 
10880   bool CanLowerReturn =
10881       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
10882                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
10883 
10884   SDValue DemoteStackSlot;
10885   int DemoteStackIdx = -100;
10886   if (!CanLowerReturn) {
10887     // FIXME: equivalent assert?
10888     // assert(!CS.hasInAllocaArgument() &&
10889     //        "sret demotion is incompatible with inalloca");
10890     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
10891     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
10892     MachineFunction &MF = CLI.DAG.getMachineFunction();
10893     DemoteStackIdx =
10894         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
10895     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
10896                                               DL.getAllocaAddrSpace());
10897 
10898     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
10899     ArgListEntry Entry;
10900     Entry.Node = DemoteStackSlot;
10901     Entry.Ty = StackSlotPtrType;
10902     Entry.IsSExt = false;
10903     Entry.IsZExt = false;
10904     Entry.IsInReg = false;
10905     Entry.IsSRet = true;
10906     Entry.IsNest = false;
10907     Entry.IsByVal = false;
10908     Entry.IsByRef = false;
10909     Entry.IsReturned = false;
10910     Entry.IsSwiftSelf = false;
10911     Entry.IsSwiftAsync = false;
10912     Entry.IsSwiftError = false;
10913     Entry.IsCFGuardTarget = false;
10914     Entry.Alignment = Alignment;
10915     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
10916     CLI.NumFixedArgs += 1;
10917     CLI.getArgs()[0].IndirectType = CLI.RetTy;
10918     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
10919 
10920     // sret demotion isn't compatible with tail-calls, since the sret argument
10921     // points into the callers stack frame.
10922     CLI.IsTailCall = false;
10923   } else {
10924     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10925         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
10926     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
10927       ISD::ArgFlagsTy Flags;
10928       if (NeedsRegBlock) {
10929         Flags.setInConsecutiveRegs();
10930         if (I == RetTys.size() - 1)
10931           Flags.setInConsecutiveRegsLast();
10932       }
10933       EVT VT = RetTys[I];
10934       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10935                                                      CLI.CallConv, VT);
10936       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10937                                                        CLI.CallConv, VT);
10938       for (unsigned i = 0; i != NumRegs; ++i) {
10939         ISD::InputArg MyFlags;
10940         MyFlags.Flags = Flags;
10941         MyFlags.VT = RegisterVT;
10942         MyFlags.ArgVT = VT;
10943         MyFlags.Used = CLI.IsReturnValueUsed;
10944         if (CLI.RetTy->isPointerTy()) {
10945           MyFlags.Flags.setPointer();
10946           MyFlags.Flags.setPointerAddrSpace(
10947               cast<PointerType>(CLI.RetTy)->getAddressSpace());
10948         }
10949         if (CLI.RetSExt)
10950           MyFlags.Flags.setSExt();
10951         if (CLI.RetZExt)
10952           MyFlags.Flags.setZExt();
10953         if (CLI.IsInReg)
10954           MyFlags.Flags.setInReg();
10955         CLI.Ins.push_back(MyFlags);
10956       }
10957     }
10958   }
10959 
10960   // We push in swifterror return as the last element of CLI.Ins.
10961   ArgListTy &Args = CLI.getArgs();
10962   if (supportSwiftError()) {
10963     for (const ArgListEntry &Arg : Args) {
10964       if (Arg.IsSwiftError) {
10965         ISD::InputArg MyFlags;
10966         MyFlags.VT = getPointerTy(DL);
10967         MyFlags.ArgVT = EVT(getPointerTy(DL));
10968         MyFlags.Flags.setSwiftError();
10969         CLI.Ins.push_back(MyFlags);
10970       }
10971     }
10972   }
10973 
10974   // Handle all of the outgoing arguments.
10975   CLI.Outs.clear();
10976   CLI.OutVals.clear();
10977   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
10978     SmallVector<EVT, 4> ValueVTs;
10979     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
10980     // FIXME: Split arguments if CLI.IsPostTypeLegalization
10981     Type *FinalType = Args[i].Ty;
10982     if (Args[i].IsByVal)
10983       FinalType = Args[i].IndirectType;
10984     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10985         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
10986     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
10987          ++Value) {
10988       EVT VT = ValueVTs[Value];
10989       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
10990       SDValue Op = SDValue(Args[i].Node.getNode(),
10991                            Args[i].Node.getResNo() + Value);
10992       ISD::ArgFlagsTy Flags;
10993 
10994       // Certain targets (such as MIPS), may have a different ABI alignment
10995       // for a type depending on the context. Give the target a chance to
10996       // specify the alignment it wants.
10997       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
10998       Flags.setOrigAlign(OriginalAlignment);
10999 
11000       if (Args[i].Ty->isPointerTy()) {
11001         Flags.setPointer();
11002         Flags.setPointerAddrSpace(
11003             cast<PointerType>(Args[i].Ty)->getAddressSpace());
11004       }
11005       if (Args[i].IsZExt)
11006         Flags.setZExt();
11007       if (Args[i].IsSExt)
11008         Flags.setSExt();
11009       if (Args[i].IsNoExt)
11010         Flags.setNoExt();
11011       if (Args[i].IsInReg) {
11012         // If we are using vectorcall calling convention, a structure that is
11013         // passed InReg - is surely an HVA
11014         if (CLI.CallConv == CallingConv::X86_VectorCall &&
11015             isa<StructType>(FinalType)) {
11016           // The first value of a structure is marked
11017           if (0 == Value)
11018             Flags.setHvaStart();
11019           Flags.setHva();
11020         }
11021         // Set InReg Flag
11022         Flags.setInReg();
11023       }
11024       if (Args[i].IsSRet)
11025         Flags.setSRet();
11026       if (Args[i].IsSwiftSelf)
11027         Flags.setSwiftSelf();
11028       if (Args[i].IsSwiftAsync)
11029         Flags.setSwiftAsync();
11030       if (Args[i].IsSwiftError)
11031         Flags.setSwiftError();
11032       if (Args[i].IsCFGuardTarget)
11033         Flags.setCFGuardTarget();
11034       if (Args[i].IsByVal)
11035         Flags.setByVal();
11036       if (Args[i].IsByRef)
11037         Flags.setByRef();
11038       if (Args[i].IsPreallocated) {
11039         Flags.setPreallocated();
11040         // Set the byval flag for CCAssignFn callbacks that don't know about
11041         // preallocated.  This way we can know how many bytes we should've
11042         // allocated and how many bytes a callee cleanup function will pop.  If
11043         // we port preallocated to more targets, we'll have to add custom
11044         // preallocated handling in the various CC lowering callbacks.
11045         Flags.setByVal();
11046       }
11047       if (Args[i].IsInAlloca) {
11048         Flags.setInAlloca();
11049         // Set the byval flag for CCAssignFn callbacks that don't know about
11050         // inalloca.  This way we can know how many bytes we should've allocated
11051         // and how many bytes a callee cleanup function will pop.  If we port
11052         // inalloca to more targets, we'll have to add custom inalloca handling
11053         // in the various CC lowering callbacks.
11054         Flags.setByVal();
11055       }
11056       Align MemAlign;
11057       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
11058         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
11059         Flags.setByValSize(FrameSize);
11060 
11061         // info is not there but there are cases it cannot get right.
11062         if (auto MA = Args[i].Alignment)
11063           MemAlign = *MA;
11064         else
11065           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
11066       } else if (auto MA = Args[i].Alignment) {
11067         MemAlign = *MA;
11068       } else {
11069         MemAlign = OriginalAlignment;
11070       }
11071       Flags.setMemAlign(MemAlign);
11072       if (Args[i].IsNest)
11073         Flags.setNest();
11074       if (NeedsRegBlock)
11075         Flags.setInConsecutiveRegs();
11076 
11077       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
11078                                                  CLI.CallConv, VT);
11079       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
11080                                                         CLI.CallConv, VT);
11081       SmallVector<SDValue, 4> Parts(NumParts);
11082       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
11083 
11084       if (Args[i].IsSExt)
11085         ExtendKind = ISD::SIGN_EXTEND;
11086       else if (Args[i].IsZExt)
11087         ExtendKind = ISD::ZERO_EXTEND;
11088 
11089       // Conservatively only handle 'returned' on non-vectors that can be lowered,
11090       // for now.
11091       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
11092           CanLowerReturn) {
11093         assert((CLI.RetTy == Args[i].Ty ||
11094                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
11095                  CLI.RetTy->getPointerAddressSpace() ==
11096                      Args[i].Ty->getPointerAddressSpace())) &&
11097                RetTys.size() == NumValues && "unexpected use of 'returned'");
11098         // Before passing 'returned' to the target lowering code, ensure that
11099         // either the register MVT and the actual EVT are the same size or that
11100         // the return value and argument are extended in the same way; in these
11101         // cases it's safe to pass the argument register value unchanged as the
11102         // return register value (although it's at the target's option whether
11103         // to do so)
11104         // TODO: allow code generation to take advantage of partially preserved
11105         // registers rather than clobbering the entire register when the
11106         // parameter extension method is not compatible with the return
11107         // extension method
11108         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
11109             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
11110              CLI.RetZExt == Args[i].IsZExt))
11111           Flags.setReturned();
11112       }
11113 
11114       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
11115                      CLI.CallConv, ExtendKind);
11116 
11117       for (unsigned j = 0; j != NumParts; ++j) {
11118         // if it isn't first piece, alignment must be 1
11119         // For scalable vectors the scalable part is currently handled
11120         // by individual targets, so we just use the known minimum size here.
11121         ISD::OutputArg MyFlags(
11122             Flags, Parts[j].getValueType().getSimpleVT(), VT,
11123             i < CLI.NumFixedArgs, i,
11124             j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
11125         if (NumParts > 1 && j == 0)
11126           MyFlags.Flags.setSplit();
11127         else if (j != 0) {
11128           MyFlags.Flags.setOrigAlign(Align(1));
11129           if (j == NumParts - 1)
11130             MyFlags.Flags.setSplitEnd();
11131         }
11132 
11133         CLI.Outs.push_back(MyFlags);
11134         CLI.OutVals.push_back(Parts[j]);
11135       }
11136 
11137       if (NeedsRegBlock && Value == NumValues - 1)
11138         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
11139     }
11140   }
11141 
11142   SmallVector<SDValue, 4> InVals;
11143   CLI.Chain = LowerCall(CLI, InVals);
11144 
11145   // Update CLI.InVals to use outside of this function.
11146   CLI.InVals = InVals;
11147 
11148   // Verify that the target's LowerCall behaved as expected.
11149   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
11150          "LowerCall didn't return a valid chain!");
11151   assert((!CLI.IsTailCall || InVals.empty()) &&
11152          "LowerCall emitted a return value for a tail call!");
11153   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
11154          "LowerCall didn't emit the correct number of values!");
11155 
11156   // For a tail call, the return value is merely live-out and there aren't
11157   // any nodes in the DAG representing it. Return a special value to
11158   // indicate that a tail call has been emitted and no more Instructions
11159   // should be processed in the current block.
11160   if (CLI.IsTailCall) {
11161     CLI.DAG.setRoot(CLI.Chain);
11162     return std::make_pair(SDValue(), SDValue());
11163   }
11164 
11165 #ifndef NDEBUG
11166   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
11167     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
11168     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
11169            "LowerCall emitted a value with the wrong type!");
11170   }
11171 #endif
11172 
11173   SmallVector<SDValue, 4> ReturnValues;
11174   if (!CanLowerReturn) {
11175     // The instruction result is the result of loading from the
11176     // hidden sret parameter.
11177     SmallVector<EVT, 1> PVTs;
11178     Type *PtrRetTy =
11179         PointerType::get(OrigRetTy->getContext(), DL.getAllocaAddrSpace());
11180 
11181     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
11182     assert(PVTs.size() == 1 && "Pointers should fit in one register");
11183     EVT PtrVT = PVTs[0];
11184 
11185     unsigned NumValues = RetTys.size();
11186     ReturnValues.resize(NumValues);
11187     SmallVector<SDValue, 4> Chains(NumValues);
11188 
11189     // An aggregate return value cannot wrap around the address space, so
11190     // offsets to its parts don't wrap either.
11191     SDNodeFlags Flags;
11192     Flags.setNoUnsignedWrap(true);
11193 
11194     MachineFunction &MF = CLI.DAG.getMachineFunction();
11195     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
11196     for (unsigned i = 0; i < NumValues; ++i) {
11197       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
11198                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
11199                                                         PtrVT), Flags);
11200       SDValue L = CLI.DAG.getLoad(
11201           RetTys[i], CLI.DL, CLI.Chain, Add,
11202           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
11203                                             DemoteStackIdx, Offsets[i]),
11204           HiddenSRetAlign);
11205       ReturnValues[i] = L;
11206       Chains[i] = L.getValue(1);
11207     }
11208 
11209     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
11210   } else {
11211     // Collect the legal value parts into potentially illegal values
11212     // that correspond to the original function's return values.
11213     std::optional<ISD::NodeType> AssertOp;
11214     if (CLI.RetSExt)
11215       AssertOp = ISD::AssertSext;
11216     else if (CLI.RetZExt)
11217       AssertOp = ISD::AssertZext;
11218     unsigned CurReg = 0;
11219     for (EVT VT : RetTys) {
11220       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
11221                                                      CLI.CallConv, VT);
11222       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
11223                                                        CLI.CallConv, VT);
11224 
11225       ReturnValues.push_back(getCopyFromParts(
11226           CLI.DAG, CLI.DL, &InVals[CurReg], NumRegs, RegisterVT, VT, nullptr,
11227           CLI.Chain, CLI.CallConv, AssertOp));
11228       CurReg += NumRegs;
11229     }
11230 
11231     // For a function returning void, there is no return value. We can't create
11232     // such a node, so we just return a null return value in that case. In
11233     // that case, nothing will actually look at the value.
11234     if (ReturnValues.empty())
11235       return std::make_pair(SDValue(), CLI.Chain);
11236   }
11237 
11238   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
11239                                 CLI.DAG.getVTList(RetTys), ReturnValues);
11240   return std::make_pair(Res, CLI.Chain);
11241 }
11242 
11243 /// Places new result values for the node in Results (their number
11244 /// and types must exactly match those of the original return values of
11245 /// the node), or leaves Results empty, which indicates that the node is not
11246 /// to be custom lowered after all.
11247 void TargetLowering::LowerOperationWrapper(SDNode *N,
11248                                            SmallVectorImpl<SDValue> &Results,
11249                                            SelectionDAG &DAG) const {
11250   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
11251 
11252   if (!Res.getNode())
11253     return;
11254 
11255   // If the original node has one result, take the return value from
11256   // LowerOperation as is. It might not be result number 0.
11257   if (N->getNumValues() == 1) {
11258     Results.push_back(Res);
11259     return;
11260   }
11261 
11262   // If the original node has multiple results, then the return node should
11263   // have the same number of results.
11264   assert((N->getNumValues() == Res->getNumValues()) &&
11265       "Lowering returned the wrong number of results!");
11266 
11267   // Places new result values base on N result number.
11268   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
11269     Results.push_back(Res.getValue(I));
11270 }
11271 
11272 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11273   llvm_unreachable("LowerOperation not implemented for this target!");
11274 }
11275 
11276 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
11277                                                      unsigned Reg,
11278                                                      ISD::NodeType ExtendType) {
11279   SDValue Op = getNonRegisterValue(V);
11280   assert((Op.getOpcode() != ISD::CopyFromReg ||
11281           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
11282          "Copy from a reg to the same reg!");
11283   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
11284 
11285   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11286   // If this is an InlineAsm we have to match the registers required, not the
11287   // notional registers required by the type.
11288 
11289   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
11290                    std::nullopt); // This is not an ABI copy.
11291   SDValue Chain = DAG.getEntryNode();
11292 
11293   if (ExtendType == ISD::ANY_EXTEND) {
11294     auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
11295     if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
11296       ExtendType = PreferredExtendIt->second;
11297   }
11298   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
11299   PendingExports.push_back(Chain);
11300 }
11301 
11302 #include "llvm/CodeGen/SelectionDAGISel.h"
11303 
11304 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
11305 /// entry block, return true.  This includes arguments used by switches, since
11306 /// the switch may expand into multiple basic blocks.
11307 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
11308   // With FastISel active, we may be splitting blocks, so force creation
11309   // of virtual registers for all non-dead arguments.
11310   if (FastISel)
11311     return A->use_empty();
11312 
11313   const BasicBlock &Entry = A->getParent()->front();
11314   for (const User *U : A->users())
11315     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
11316       return false;  // Use not in entry block.
11317 
11318   return true;
11319 }
11320 
11321 using ArgCopyElisionMapTy =
11322     DenseMap<const Argument *,
11323              std::pair<const AllocaInst *, const StoreInst *>>;
11324 
11325 /// Scan the entry block of the function in FuncInfo for arguments that look
11326 /// like copies into a local alloca. Record any copied arguments in
11327 /// ArgCopyElisionCandidates.
11328 static void
11329 findArgumentCopyElisionCandidates(const DataLayout &DL,
11330                                   FunctionLoweringInfo *FuncInfo,
11331                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
11332   // Record the state of every static alloca used in the entry block. Argument
11333   // allocas are all used in the entry block, so we need approximately as many
11334   // entries as we have arguments.
11335   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
11336   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
11337   unsigned NumArgs = FuncInfo->Fn->arg_size();
11338   StaticAllocas.reserve(NumArgs * 2);
11339 
11340   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
11341     if (!V)
11342       return nullptr;
11343     V = V->stripPointerCasts();
11344     const auto *AI = dyn_cast<AllocaInst>(V);
11345     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
11346       return nullptr;
11347     auto Iter = StaticAllocas.insert({AI, Unknown});
11348     return &Iter.first->second;
11349   };
11350 
11351   // Look for stores of arguments to static allocas. Look through bitcasts and
11352   // GEPs to handle type coercions, as long as the alloca is fully initialized
11353   // by the store. Any non-store use of an alloca escapes it and any subsequent
11354   // unanalyzed store might write it.
11355   // FIXME: Handle structs initialized with multiple stores.
11356   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
11357     // Look for stores, and handle non-store uses conservatively.
11358     const auto *SI = dyn_cast<StoreInst>(&I);
11359     if (!SI) {
11360       // We will look through cast uses, so ignore them completely.
11361       if (I.isCast())
11362         continue;
11363       // Ignore debug info and pseudo op intrinsics, they don't escape or store
11364       // to allocas.
11365       if (I.isDebugOrPseudoInst())
11366         continue;
11367       // This is an unknown instruction. Assume it escapes or writes to all
11368       // static alloca operands.
11369       for (const Use &U : I.operands()) {
11370         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
11371           *Info = StaticAllocaInfo::Clobbered;
11372       }
11373       continue;
11374     }
11375 
11376     // If the stored value is a static alloca, mark it as escaped.
11377     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
11378       *Info = StaticAllocaInfo::Clobbered;
11379 
11380     // Check if the destination is a static alloca.
11381     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
11382     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
11383     if (!Info)
11384       continue;
11385     const AllocaInst *AI = cast<AllocaInst>(Dst);
11386 
11387     // Skip allocas that have been initialized or clobbered.
11388     if (*Info != StaticAllocaInfo::Unknown)
11389       continue;
11390 
11391     // Check if the stored value is an argument, and that this store fully
11392     // initializes the alloca.
11393     // If the argument type has padding bits we can't directly forward a pointer
11394     // as the upper bits may contain garbage.
11395     // Don't elide copies from the same argument twice.
11396     const Value *Val = SI->getValueOperand()->stripPointerCasts();
11397     const auto *Arg = dyn_cast<Argument>(Val);
11398     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
11399         Arg->getType()->isEmptyTy() ||
11400         DL.getTypeStoreSize(Arg->getType()) !=
11401             DL.getTypeAllocSize(AI->getAllocatedType()) ||
11402         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
11403         ArgCopyElisionCandidates.count(Arg)) {
11404       *Info = StaticAllocaInfo::Clobbered;
11405       continue;
11406     }
11407 
11408     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
11409                       << '\n');
11410 
11411     // Mark this alloca and store for argument copy elision.
11412     *Info = StaticAllocaInfo::Elidable;
11413     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
11414 
11415     // Stop scanning if we've seen all arguments. This will happen early in -O0
11416     // builds, which is useful, because -O0 builds have large entry blocks and
11417     // many allocas.
11418     if (ArgCopyElisionCandidates.size() == NumArgs)
11419       break;
11420   }
11421 }
11422 
11423 /// Try to elide argument copies from memory into a local alloca. Succeeds if
11424 /// ArgVal is a load from a suitable fixed stack object.
11425 static void tryToElideArgumentCopy(
11426     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
11427     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
11428     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
11429     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
11430     ArrayRef<SDValue> ArgVals, bool &ArgHasUses) {
11431   // Check if this is a load from a fixed stack object.
11432   auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]);
11433   if (!LNode)
11434     return;
11435   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
11436   if (!FINode)
11437     return;
11438 
11439   // Check that the fixed stack object is the right size and alignment.
11440   // Look at the alignment that the user wrote on the alloca instead of looking
11441   // at the stack object.
11442   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
11443   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
11444   const AllocaInst *AI = ArgCopyIter->second.first;
11445   int FixedIndex = FINode->getIndex();
11446   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
11447   int OldIndex = AllocaIndex;
11448   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
11449   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
11450     LLVM_DEBUG(
11451         dbgs() << "  argument copy elision failed due to bad fixed stack "
11452                   "object size\n");
11453     return;
11454   }
11455   Align RequiredAlignment = AI->getAlign();
11456   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
11457     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
11458                          "greater than stack argument alignment ("
11459                       << DebugStr(RequiredAlignment) << " vs "
11460                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
11461     return;
11462   }
11463 
11464   // Perform the elision. Delete the old stack object and replace its only use
11465   // in the variable info map. Mark the stack object as mutable and aliased.
11466   LLVM_DEBUG({
11467     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
11468            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
11469            << '\n';
11470   });
11471   MFI.RemoveStackObject(OldIndex);
11472   MFI.setIsImmutableObjectIndex(FixedIndex, false);
11473   MFI.setIsAliasedObjectIndex(FixedIndex, true);
11474   AllocaIndex = FixedIndex;
11475   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
11476   for (SDValue ArgVal : ArgVals)
11477     Chains.push_back(ArgVal.getValue(1));
11478 
11479   // Avoid emitting code for the store implementing the copy.
11480   const StoreInst *SI = ArgCopyIter->second.second;
11481   ElidedArgCopyInstrs.insert(SI);
11482 
11483   // Check for uses of the argument again so that we can avoid exporting ArgVal
11484   // if it is't used by anything other than the store.
11485   for (const Value *U : Arg.users()) {
11486     if (U != SI) {
11487       ArgHasUses = true;
11488       break;
11489     }
11490   }
11491 }
11492 
11493 void SelectionDAGISel::LowerArguments(const Function &F) {
11494   SelectionDAG &DAG = SDB->DAG;
11495   SDLoc dl = SDB->getCurSDLoc();
11496   const DataLayout &DL = DAG.getDataLayout();
11497   SmallVector<ISD::InputArg, 16> Ins;
11498 
11499   // In Naked functions we aren't going to save any registers.
11500   if (F.hasFnAttribute(Attribute::Naked))
11501     return;
11502 
11503   if (!FuncInfo->CanLowerReturn) {
11504     // Put in an sret pointer parameter before all the other parameters.
11505     SmallVector<EVT, 1> ValueVTs;
11506     ComputeValueVTs(*TLI, DAG.getDataLayout(),
11507                     PointerType::get(F.getContext(),
11508                                      DAG.getDataLayout().getAllocaAddrSpace()),
11509                     ValueVTs);
11510 
11511     // NOTE: Assuming that a pointer will never break down to more than one VT
11512     // or one register.
11513     ISD::ArgFlagsTy Flags;
11514     Flags.setSRet();
11515     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
11516     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
11517                          ISD::InputArg::NoArgIndex, 0);
11518     Ins.push_back(RetArg);
11519   }
11520 
11521   // Look for stores of arguments to static allocas. Mark such arguments with a
11522   // flag to ask the target to give us the memory location of that argument if
11523   // available.
11524   ArgCopyElisionMapTy ArgCopyElisionCandidates;
11525   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
11526                                     ArgCopyElisionCandidates);
11527 
11528   // Set up the incoming argument description vector.
11529   for (const Argument &Arg : F.args()) {
11530     unsigned ArgNo = Arg.getArgNo();
11531     SmallVector<EVT, 4> ValueVTs;
11532     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
11533     bool isArgValueUsed = !Arg.use_empty();
11534     unsigned PartBase = 0;
11535     Type *FinalType = Arg.getType();
11536     if (Arg.hasAttribute(Attribute::ByVal))
11537       FinalType = Arg.getParamByValType();
11538     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
11539         FinalType, F.getCallingConv(), F.isVarArg(), DL);
11540     for (unsigned Value = 0, NumValues = ValueVTs.size();
11541          Value != NumValues; ++Value) {
11542       EVT VT = ValueVTs[Value];
11543       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
11544       ISD::ArgFlagsTy Flags;
11545 
11546 
11547       if (Arg.getType()->isPointerTy()) {
11548         Flags.setPointer();
11549         Flags.setPointerAddrSpace(
11550             cast<PointerType>(Arg.getType())->getAddressSpace());
11551       }
11552       if (Arg.hasAttribute(Attribute::ZExt))
11553         Flags.setZExt();
11554       if (Arg.hasAttribute(Attribute::SExt))
11555         Flags.setSExt();
11556       if (Arg.hasAttribute(Attribute::InReg)) {
11557         // If we are using vectorcall calling convention, a structure that is
11558         // passed InReg - is surely an HVA
11559         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
11560             isa<StructType>(Arg.getType())) {
11561           // The first value of a structure is marked
11562           if (0 == Value)
11563             Flags.setHvaStart();
11564           Flags.setHva();
11565         }
11566         // Set InReg Flag
11567         Flags.setInReg();
11568       }
11569       if (Arg.hasAttribute(Attribute::StructRet))
11570         Flags.setSRet();
11571       if (Arg.hasAttribute(Attribute::SwiftSelf))
11572         Flags.setSwiftSelf();
11573       if (Arg.hasAttribute(Attribute::SwiftAsync))
11574         Flags.setSwiftAsync();
11575       if (Arg.hasAttribute(Attribute::SwiftError))
11576         Flags.setSwiftError();
11577       if (Arg.hasAttribute(Attribute::ByVal))
11578         Flags.setByVal();
11579       if (Arg.hasAttribute(Attribute::ByRef))
11580         Flags.setByRef();
11581       if (Arg.hasAttribute(Attribute::InAlloca)) {
11582         Flags.setInAlloca();
11583         // Set the byval flag for CCAssignFn callbacks that don't know about
11584         // inalloca.  This way we can know how many bytes we should've allocated
11585         // and how many bytes a callee cleanup function will pop.  If we port
11586         // inalloca to more targets, we'll have to add custom inalloca handling
11587         // in the various CC lowering callbacks.
11588         Flags.setByVal();
11589       }
11590       if (Arg.hasAttribute(Attribute::Preallocated)) {
11591         Flags.setPreallocated();
11592         // Set the byval flag for CCAssignFn callbacks that don't know about
11593         // preallocated.  This way we can know how many bytes we should've
11594         // allocated and how many bytes a callee cleanup function will pop.  If
11595         // we port preallocated to more targets, we'll have to add custom
11596         // preallocated handling in the various CC lowering callbacks.
11597         Flags.setByVal();
11598       }
11599 
11600       // Certain targets (such as MIPS), may have a different ABI alignment
11601       // for a type depending on the context. Give the target a chance to
11602       // specify the alignment it wants.
11603       const Align OriginalAlignment(
11604           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
11605       Flags.setOrigAlign(OriginalAlignment);
11606 
11607       Align MemAlign;
11608       Type *ArgMemTy = nullptr;
11609       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
11610           Flags.isByRef()) {
11611         if (!ArgMemTy)
11612           ArgMemTy = Arg.getPointeeInMemoryValueType();
11613 
11614         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
11615 
11616         // For in-memory arguments, size and alignment should be passed from FE.
11617         // BE will guess if this info is not there but there are cases it cannot
11618         // get right.
11619         if (auto ParamAlign = Arg.getParamStackAlign())
11620           MemAlign = *ParamAlign;
11621         else if ((ParamAlign = Arg.getParamAlign()))
11622           MemAlign = *ParamAlign;
11623         else
11624           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
11625         if (Flags.isByRef())
11626           Flags.setByRefSize(MemSize);
11627         else
11628           Flags.setByValSize(MemSize);
11629       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
11630         MemAlign = *ParamAlign;
11631       } else {
11632         MemAlign = OriginalAlignment;
11633       }
11634       Flags.setMemAlign(MemAlign);
11635 
11636       if (Arg.hasAttribute(Attribute::Nest))
11637         Flags.setNest();
11638       if (NeedsRegBlock)
11639         Flags.setInConsecutiveRegs();
11640       if (ArgCopyElisionCandidates.count(&Arg))
11641         Flags.setCopyElisionCandidate();
11642       if (Arg.hasAttribute(Attribute::Returned))
11643         Flags.setReturned();
11644 
11645       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
11646           *CurDAG->getContext(), F.getCallingConv(), VT);
11647       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
11648           *CurDAG->getContext(), F.getCallingConv(), VT);
11649       for (unsigned i = 0; i != NumRegs; ++i) {
11650         // For scalable vectors, use the minimum size; individual targets
11651         // are responsible for handling scalable vector arguments and
11652         // return values.
11653         ISD::InputArg MyFlags(
11654             Flags, RegisterVT, VT, isArgValueUsed, ArgNo,
11655             PartBase + i * RegisterVT.getStoreSize().getKnownMinValue());
11656         if (NumRegs > 1 && i == 0)
11657           MyFlags.Flags.setSplit();
11658         // if it isn't first piece, alignment must be 1
11659         else if (i > 0) {
11660           MyFlags.Flags.setOrigAlign(Align(1));
11661           if (i == NumRegs - 1)
11662             MyFlags.Flags.setSplitEnd();
11663         }
11664         Ins.push_back(MyFlags);
11665       }
11666       if (NeedsRegBlock && Value == NumValues - 1)
11667         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
11668       PartBase += VT.getStoreSize().getKnownMinValue();
11669     }
11670   }
11671 
11672   // Call the target to set up the argument values.
11673   SmallVector<SDValue, 8> InVals;
11674   SDValue NewRoot = TLI->LowerFormalArguments(
11675       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
11676 
11677   // Verify that the target's LowerFormalArguments behaved as expected.
11678   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
11679          "LowerFormalArguments didn't return a valid chain!");
11680   assert(InVals.size() == Ins.size() &&
11681          "LowerFormalArguments didn't emit the correct number of values!");
11682   LLVM_DEBUG({
11683     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
11684       assert(InVals[i].getNode() &&
11685              "LowerFormalArguments emitted a null value!");
11686       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
11687              "LowerFormalArguments emitted a value with the wrong type!");
11688     }
11689   });
11690 
11691   // Update the DAG with the new chain value resulting from argument lowering.
11692   DAG.setRoot(NewRoot);
11693 
11694   // Set up the argument values.
11695   unsigned i = 0;
11696   if (!FuncInfo->CanLowerReturn) {
11697     // Create a virtual register for the sret pointer, and put in a copy
11698     // from the sret argument into it.
11699     SmallVector<EVT, 1> ValueVTs;
11700     ComputeValueVTs(*TLI, DAG.getDataLayout(),
11701                     PointerType::get(F.getContext(),
11702                                      DAG.getDataLayout().getAllocaAddrSpace()),
11703                     ValueVTs);
11704     MVT VT = ValueVTs[0].getSimpleVT();
11705     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
11706     std::optional<ISD::NodeType> AssertOp;
11707     SDValue ArgValue =
11708         getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, nullptr, NewRoot,
11709                          F.getCallingConv(), AssertOp);
11710 
11711     MachineFunction& MF = SDB->DAG.getMachineFunction();
11712     MachineRegisterInfo& RegInfo = MF.getRegInfo();
11713     Register SRetReg =
11714         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
11715     FuncInfo->DemoteRegister = SRetReg;
11716     NewRoot =
11717         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
11718     DAG.setRoot(NewRoot);
11719 
11720     // i indexes lowered arguments.  Bump it past the hidden sret argument.
11721     ++i;
11722   }
11723 
11724   SmallVector<SDValue, 4> Chains;
11725   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
11726   for (const Argument &Arg : F.args()) {
11727     SmallVector<SDValue, 4> ArgValues;
11728     SmallVector<EVT, 4> ValueVTs;
11729     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
11730     unsigned NumValues = ValueVTs.size();
11731     if (NumValues == 0)
11732       continue;
11733 
11734     bool ArgHasUses = !Arg.use_empty();
11735 
11736     // Elide the copying store if the target loaded this argument from a
11737     // suitable fixed stack object.
11738     if (Ins[i].Flags.isCopyElisionCandidate()) {
11739       unsigned NumParts = 0;
11740       for (EVT VT : ValueVTs)
11741         NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(),
11742                                                        F.getCallingConv(), VT);
11743 
11744       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
11745                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
11746                              ArrayRef(&InVals[i], NumParts), ArgHasUses);
11747     }
11748 
11749     // If this argument is unused then remember its value. It is used to generate
11750     // debugging information.
11751     bool isSwiftErrorArg =
11752         TLI->supportSwiftError() &&
11753         Arg.hasAttribute(Attribute::SwiftError);
11754     if (!ArgHasUses && !isSwiftErrorArg) {
11755       SDB->setUnusedArgValue(&Arg, InVals[i]);
11756 
11757       // Also remember any frame index for use in FastISel.
11758       if (FrameIndexSDNode *FI =
11759           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
11760         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11761     }
11762 
11763     for (unsigned Val = 0; Val != NumValues; ++Val) {
11764       EVT VT = ValueVTs[Val];
11765       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
11766                                                       F.getCallingConv(), VT);
11767       unsigned NumParts = TLI->getNumRegistersForCallingConv(
11768           *CurDAG->getContext(), F.getCallingConv(), VT);
11769 
11770       // Even an apparent 'unused' swifterror argument needs to be returned. So
11771       // we do generate a copy for it that can be used on return from the
11772       // function.
11773       if (ArgHasUses || isSwiftErrorArg) {
11774         std::optional<ISD::NodeType> AssertOp;
11775         if (Arg.hasAttribute(Attribute::SExt))
11776           AssertOp = ISD::AssertSext;
11777         else if (Arg.hasAttribute(Attribute::ZExt))
11778           AssertOp = ISD::AssertZext;
11779 
11780         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
11781                                              PartVT, VT, nullptr, NewRoot,
11782                                              F.getCallingConv(), AssertOp));
11783       }
11784 
11785       i += NumParts;
11786     }
11787 
11788     // We don't need to do anything else for unused arguments.
11789     if (ArgValues.empty())
11790       continue;
11791 
11792     // Note down frame index.
11793     if (FrameIndexSDNode *FI =
11794         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
11795       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11796 
11797     SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues),
11798                                      SDB->getCurSDLoc());
11799 
11800     SDB->setValue(&Arg, Res);
11801     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
11802       // We want to associate the argument with the frame index, among
11803       // involved operands, that correspond to the lowest address. The
11804       // getCopyFromParts function, called earlier, is swapping the order of
11805       // the operands to BUILD_PAIR depending on endianness. The result of
11806       // that swapping is that the least significant bits of the argument will
11807       // be in the first operand of the BUILD_PAIR node, and the most
11808       // significant bits will be in the second operand.
11809       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
11810       if (LoadSDNode *LNode =
11811           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
11812         if (FrameIndexSDNode *FI =
11813             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
11814           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11815     }
11816 
11817     // Analyses past this point are naive and don't expect an assertion.
11818     if (Res.getOpcode() == ISD::AssertZext)
11819       Res = Res.getOperand(0);
11820 
11821     // Update the SwiftErrorVRegDefMap.
11822     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
11823       Register Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11824       if (Reg.isVirtual())
11825         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
11826                                    Reg);
11827     }
11828 
11829     // If this argument is live outside of the entry block, insert a copy from
11830     // wherever we got it to the vreg that other BB's will reference it as.
11831     if (Res.getOpcode() == ISD::CopyFromReg) {
11832       // If we can, though, try to skip creating an unnecessary vreg.
11833       // FIXME: This isn't very clean... it would be nice to make this more
11834       // general.
11835       Register Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11836       if (Reg.isVirtual()) {
11837         FuncInfo->ValueMap[&Arg] = Reg;
11838         continue;
11839       }
11840     }
11841     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
11842       FuncInfo->InitializeRegForValue(&Arg);
11843       SDB->CopyToExportRegsIfNeeded(&Arg);
11844     }
11845   }
11846 
11847   if (!Chains.empty()) {
11848     Chains.push_back(NewRoot);
11849     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
11850   }
11851 
11852   DAG.setRoot(NewRoot);
11853 
11854   assert(i == InVals.size() && "Argument register count mismatch!");
11855 
11856   // If any argument copy elisions occurred and we have debug info, update the
11857   // stale frame indices used in the dbg.declare variable info table.
11858   if (!ArgCopyElisionFrameIndexMap.empty()) {
11859     for (MachineFunction::VariableDbgInfo &VI :
11860          MF->getInStackSlotVariableDbgInfo()) {
11861       auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot());
11862       if (I != ArgCopyElisionFrameIndexMap.end())
11863         VI.updateStackSlot(I->second);
11864     }
11865   }
11866 
11867   // Finally, if the target has anything special to do, allow it to do so.
11868   emitFunctionEntryCode();
11869 }
11870 
11871 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
11872 /// ensure constants are generated when needed.  Remember the virtual registers
11873 /// that need to be added to the Machine PHI nodes as input.  We cannot just
11874 /// directly add them, because expansion might result in multiple MBB's for one
11875 /// BB.  As such, the start of the BB might correspond to a different MBB than
11876 /// the end.
11877 void
11878 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
11879   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11880 
11881   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
11882 
11883   // Check PHI nodes in successors that expect a value to be available from this
11884   // block.
11885   for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
11886     if (!isa<PHINode>(SuccBB->begin())) continue;
11887     MachineBasicBlock *SuccMBB = FuncInfo.getMBB(SuccBB);
11888 
11889     // If this terminator has multiple identical successors (common for
11890     // switches), only handle each succ once.
11891     if (!SuccsHandled.insert(SuccMBB).second)
11892       continue;
11893 
11894     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
11895 
11896     // At this point we know that there is a 1-1 correspondence between LLVM PHI
11897     // nodes and Machine PHI nodes, but the incoming operands have not been
11898     // emitted yet.
11899     for (const PHINode &PN : SuccBB->phis()) {
11900       // Ignore dead phi's.
11901       if (PN.use_empty())
11902         continue;
11903 
11904       // Skip empty types
11905       if (PN.getType()->isEmptyTy())
11906         continue;
11907 
11908       unsigned Reg;
11909       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
11910 
11911       if (const auto *C = dyn_cast<Constant>(PHIOp)) {
11912         unsigned &RegOut = ConstantsOut[C];
11913         if (RegOut == 0) {
11914           RegOut = FuncInfo.CreateRegs(C);
11915           // We need to zero/sign extend ConstantInt phi operands to match
11916           // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
11917           ISD::NodeType ExtendType = ISD::ANY_EXTEND;
11918           if (auto *CI = dyn_cast<ConstantInt>(C))
11919             ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
11920                                                     : ISD::ZERO_EXTEND;
11921           CopyValueToVirtualRegister(C, RegOut, ExtendType);
11922         }
11923         Reg = RegOut;
11924       } else {
11925         DenseMap<const Value *, Register>::iterator I =
11926           FuncInfo.ValueMap.find(PHIOp);
11927         if (I != FuncInfo.ValueMap.end())
11928           Reg = I->second;
11929         else {
11930           assert(isa<AllocaInst>(PHIOp) &&
11931                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
11932                  "Didn't codegen value into a register!??");
11933           Reg = FuncInfo.CreateRegs(PHIOp);
11934           CopyValueToVirtualRegister(PHIOp, Reg);
11935         }
11936       }
11937 
11938       // Remember that this register needs to added to the machine PHI node as
11939       // the input for this MBB.
11940       SmallVector<EVT, 4> ValueVTs;
11941       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
11942       for (EVT VT : ValueVTs) {
11943         const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
11944         for (unsigned i = 0; i != NumRegisters; ++i)
11945           FuncInfo.PHINodesToUpdate.push_back(
11946               std::make_pair(&*MBBI++, Reg + i));
11947         Reg += NumRegisters;
11948       }
11949     }
11950   }
11951 
11952   ConstantsOut.clear();
11953 }
11954 
11955 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
11956   MachineFunction::iterator I(MBB);
11957   if (++I == FuncInfo.MF->end())
11958     return nullptr;
11959   return &*I;
11960 }
11961 
11962 /// During lowering new call nodes can be created (such as memset, etc.).
11963 /// Those will become new roots of the current DAG, but complications arise
11964 /// when they are tail calls. In such cases, the call lowering will update
11965 /// the root, but the builder still needs to know that a tail call has been
11966 /// lowered in order to avoid generating an additional return.
11967 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
11968   // If the node is null, we do have a tail call.
11969   if (MaybeTC.getNode() != nullptr)
11970     DAG.setRoot(MaybeTC);
11971   else
11972     HasTailCall = true;
11973 }
11974 
11975 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
11976                                         MachineBasicBlock *SwitchMBB,
11977                                         MachineBasicBlock *DefaultMBB) {
11978   MachineFunction *CurMF = FuncInfo.MF;
11979   MachineBasicBlock *NextMBB = nullptr;
11980   MachineFunction::iterator BBI(W.MBB);
11981   if (++BBI != FuncInfo.MF->end())
11982     NextMBB = &*BBI;
11983 
11984   unsigned Size = W.LastCluster - W.FirstCluster + 1;
11985 
11986   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11987 
11988   if (Size == 2 && W.MBB == SwitchMBB) {
11989     // If any two of the cases has the same destination, and if one value
11990     // is the same as the other, but has one bit unset that the other has set,
11991     // use bit manipulation to do two compares at once.  For example:
11992     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
11993     // TODO: This could be extended to merge any 2 cases in switches with 3
11994     // cases.
11995     // TODO: Handle cases where W.CaseBB != SwitchBB.
11996     CaseCluster &Small = *W.FirstCluster;
11997     CaseCluster &Big = *W.LastCluster;
11998 
11999     if (Small.Low == Small.High && Big.Low == Big.High &&
12000         Small.MBB == Big.MBB) {
12001       const APInt &SmallValue = Small.Low->getValue();
12002       const APInt &BigValue = Big.Low->getValue();
12003 
12004       // Check that there is only one bit different.
12005       APInt CommonBit = BigValue ^ SmallValue;
12006       if (CommonBit.isPowerOf2()) {
12007         SDValue CondLHS = getValue(Cond);
12008         EVT VT = CondLHS.getValueType();
12009         SDLoc DL = getCurSDLoc();
12010 
12011         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
12012                                  DAG.getConstant(CommonBit, DL, VT));
12013         SDValue Cond = DAG.getSetCC(
12014             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
12015             ISD::SETEQ);
12016 
12017         // Update successor info.
12018         // Both Small and Big will jump to Small.BB, so we sum up the
12019         // probabilities.
12020         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
12021         if (BPI)
12022           addSuccessorWithProb(
12023               SwitchMBB, DefaultMBB,
12024               // The default destination is the first successor in IR.
12025               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
12026         else
12027           addSuccessorWithProb(SwitchMBB, DefaultMBB);
12028 
12029         // Insert the true branch.
12030         SDValue BrCond =
12031             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
12032                         DAG.getBasicBlock(Small.MBB));
12033         // Insert the false branch.
12034         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
12035                              DAG.getBasicBlock(DefaultMBB));
12036 
12037         DAG.setRoot(BrCond);
12038         return;
12039       }
12040     }
12041   }
12042 
12043   if (TM.getOptLevel() != CodeGenOptLevel::None) {
12044     // Here, we order cases by probability so the most likely case will be
12045     // checked first. However, two clusters can have the same probability in
12046     // which case their relative ordering is non-deterministic. So we use Low
12047     // as a tie-breaker as clusters are guaranteed to never overlap.
12048     llvm::sort(W.FirstCluster, W.LastCluster + 1,
12049                [](const CaseCluster &a, const CaseCluster &b) {
12050       return a.Prob != b.Prob ?
12051              a.Prob > b.Prob :
12052              a.Low->getValue().slt(b.Low->getValue());
12053     });
12054 
12055     // Rearrange the case blocks so that the last one falls through if possible
12056     // without changing the order of probabilities.
12057     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
12058       --I;
12059       if (I->Prob > W.LastCluster->Prob)
12060         break;
12061       if (I->Kind == CC_Range && I->MBB == NextMBB) {
12062         std::swap(*I, *W.LastCluster);
12063         break;
12064       }
12065     }
12066   }
12067 
12068   // Compute total probability.
12069   BranchProbability DefaultProb = W.DefaultProb;
12070   BranchProbability UnhandledProbs = DefaultProb;
12071   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
12072     UnhandledProbs += I->Prob;
12073 
12074   MachineBasicBlock *CurMBB = W.MBB;
12075   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
12076     bool FallthroughUnreachable = false;
12077     MachineBasicBlock *Fallthrough;
12078     if (I == W.LastCluster) {
12079       // For the last cluster, fall through to the default destination.
12080       Fallthrough = DefaultMBB;
12081       FallthroughUnreachable = isa<UnreachableInst>(
12082           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
12083     } else {
12084       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
12085       CurMF->insert(BBI, Fallthrough);
12086       // Put Cond in a virtual register to make it available from the new blocks.
12087       ExportFromCurrentBlock(Cond);
12088     }
12089     UnhandledProbs -= I->Prob;
12090 
12091     switch (I->Kind) {
12092       case CC_JumpTable: {
12093         // FIXME: Optimize away range check based on pivot comparisons.
12094         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
12095         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
12096 
12097         // The jump block hasn't been inserted yet; insert it here.
12098         MachineBasicBlock *JumpMBB = JT->MBB;
12099         CurMF->insert(BBI, JumpMBB);
12100 
12101         auto JumpProb = I->Prob;
12102         auto FallthroughProb = UnhandledProbs;
12103 
12104         // If the default statement is a target of the jump table, we evenly
12105         // distribute the default probability to successors of CurMBB. Also
12106         // update the probability on the edge from JumpMBB to Fallthrough.
12107         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
12108                                               SE = JumpMBB->succ_end();
12109              SI != SE; ++SI) {
12110           if (*SI == DefaultMBB) {
12111             JumpProb += DefaultProb / 2;
12112             FallthroughProb -= DefaultProb / 2;
12113             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
12114             JumpMBB->normalizeSuccProbs();
12115             break;
12116           }
12117         }
12118 
12119         // If the default clause is unreachable, propagate that knowledge into
12120         // JTH->FallthroughUnreachable which will use it to suppress the range
12121         // check.
12122         //
12123         // However, don't do this if we're doing branch target enforcement,
12124         // because a table branch _without_ a range check can be a tempting JOP
12125         // gadget - out-of-bounds inputs that are impossible in correct
12126         // execution become possible again if an attacker can influence the
12127         // control flow. So if an attacker doesn't already have a BTI bypass
12128         // available, we don't want them to be able to get one out of this
12129         // table branch.
12130         if (FallthroughUnreachable) {
12131           Function &CurFunc = CurMF->getFunction();
12132           if (!CurFunc.hasFnAttribute("branch-target-enforcement"))
12133             JTH->FallthroughUnreachable = true;
12134         }
12135 
12136         if (!JTH->FallthroughUnreachable)
12137           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
12138         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
12139         CurMBB->normalizeSuccProbs();
12140 
12141         // The jump table header will be inserted in our current block, do the
12142         // range check, and fall through to our fallthrough block.
12143         JTH->HeaderBB = CurMBB;
12144         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
12145 
12146         // If we're in the right place, emit the jump table header right now.
12147         if (CurMBB == SwitchMBB) {
12148           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
12149           JTH->Emitted = true;
12150         }
12151         break;
12152       }
12153       case CC_BitTests: {
12154         // FIXME: Optimize away range check based on pivot comparisons.
12155         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
12156 
12157         // The bit test blocks haven't been inserted yet; insert them here.
12158         for (BitTestCase &BTC : BTB->Cases)
12159           CurMF->insert(BBI, BTC.ThisBB);
12160 
12161         // Fill in fields of the BitTestBlock.
12162         BTB->Parent = CurMBB;
12163         BTB->Default = Fallthrough;
12164 
12165         BTB->DefaultProb = UnhandledProbs;
12166         // If the cases in bit test don't form a contiguous range, we evenly
12167         // distribute the probability on the edge to Fallthrough to two
12168         // successors of CurMBB.
12169         if (!BTB->ContiguousRange) {
12170           BTB->Prob += DefaultProb / 2;
12171           BTB->DefaultProb -= DefaultProb / 2;
12172         }
12173 
12174         if (FallthroughUnreachable)
12175           BTB->FallthroughUnreachable = true;
12176 
12177         // If we're in the right place, emit the bit test header right now.
12178         if (CurMBB == SwitchMBB) {
12179           visitBitTestHeader(*BTB, SwitchMBB);
12180           BTB->Emitted = true;
12181         }
12182         break;
12183       }
12184       case CC_Range: {
12185         const Value *RHS, *LHS, *MHS;
12186         ISD::CondCode CC;
12187         if (I->Low == I->High) {
12188           // Check Cond == I->Low.
12189           CC = ISD::SETEQ;
12190           LHS = Cond;
12191           RHS=I->Low;
12192           MHS = nullptr;
12193         } else {
12194           // Check I->Low <= Cond <= I->High.
12195           CC = ISD::SETLE;
12196           LHS = I->Low;
12197           MHS = Cond;
12198           RHS = I->High;
12199         }
12200 
12201         // If Fallthrough is unreachable, fold away the comparison.
12202         if (FallthroughUnreachable)
12203           CC = ISD::SETTRUE;
12204 
12205         // The false probability is the sum of all unhandled cases.
12206         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
12207                      getCurSDLoc(), I->Prob, UnhandledProbs);
12208 
12209         if (CurMBB == SwitchMBB)
12210           visitSwitchCase(CB, SwitchMBB);
12211         else
12212           SL->SwitchCases.push_back(CB);
12213 
12214         break;
12215       }
12216     }
12217     CurMBB = Fallthrough;
12218   }
12219 }
12220 
12221 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
12222                                         const SwitchWorkListItem &W,
12223                                         Value *Cond,
12224                                         MachineBasicBlock *SwitchMBB) {
12225   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
12226          "Clusters not sorted?");
12227   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
12228 
12229   auto [LastLeft, FirstRight, LeftProb, RightProb] =
12230       SL->computeSplitWorkItemInfo(W);
12231 
12232   // Use the first element on the right as pivot since we will make less-than
12233   // comparisons against it.
12234   CaseClusterIt PivotCluster = FirstRight;
12235   assert(PivotCluster > W.FirstCluster);
12236   assert(PivotCluster <= W.LastCluster);
12237 
12238   CaseClusterIt FirstLeft = W.FirstCluster;
12239   CaseClusterIt LastRight = W.LastCluster;
12240 
12241   const ConstantInt *Pivot = PivotCluster->Low;
12242 
12243   // New blocks will be inserted immediately after the current one.
12244   MachineFunction::iterator BBI(W.MBB);
12245   ++BBI;
12246 
12247   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
12248   // we can branch to its destination directly if it's squeezed exactly in
12249   // between the known lower bound and Pivot - 1.
12250   MachineBasicBlock *LeftMBB;
12251   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
12252       FirstLeft->Low == W.GE &&
12253       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
12254     LeftMBB = FirstLeft->MBB;
12255   } else {
12256     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12257     FuncInfo.MF->insert(BBI, LeftMBB);
12258     WorkList.push_back(
12259         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
12260     // Put Cond in a virtual register to make it available from the new blocks.
12261     ExportFromCurrentBlock(Cond);
12262   }
12263 
12264   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
12265   // single cluster, RHS.Low == Pivot, and we can branch to its destination
12266   // directly if RHS.High equals the current upper bound.
12267   MachineBasicBlock *RightMBB;
12268   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
12269       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
12270     RightMBB = FirstRight->MBB;
12271   } else {
12272     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12273     FuncInfo.MF->insert(BBI, RightMBB);
12274     WorkList.push_back(
12275         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
12276     // Put Cond in a virtual register to make it available from the new blocks.
12277     ExportFromCurrentBlock(Cond);
12278   }
12279 
12280   // Create the CaseBlock record that will be used to lower the branch.
12281   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
12282                getCurSDLoc(), LeftProb, RightProb);
12283 
12284   if (W.MBB == SwitchMBB)
12285     visitSwitchCase(CB, SwitchMBB);
12286   else
12287     SL->SwitchCases.push_back(CB);
12288 }
12289 
12290 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
12291 // from the swith statement.
12292 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
12293                                             BranchProbability PeeledCaseProb) {
12294   if (PeeledCaseProb == BranchProbability::getOne())
12295     return BranchProbability::getZero();
12296   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
12297 
12298   uint32_t Numerator = CaseProb.getNumerator();
12299   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
12300   return BranchProbability(Numerator, std::max(Numerator, Denominator));
12301 }
12302 
12303 // Try to peel the top probability case if it exceeds the threshold.
12304 // Return current MachineBasicBlock for the switch statement if the peeling
12305 // does not occur.
12306 // If the peeling is performed, return the newly created MachineBasicBlock
12307 // for the peeled switch statement. Also update Clusters to remove the peeled
12308 // case. PeeledCaseProb is the BranchProbability for the peeled case.
12309 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
12310     const SwitchInst &SI, CaseClusterVector &Clusters,
12311     BranchProbability &PeeledCaseProb) {
12312   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12313   // Don't perform if there is only one cluster or optimizing for size.
12314   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
12315       TM.getOptLevel() == CodeGenOptLevel::None ||
12316       SwitchMBB->getParent()->getFunction().hasMinSize())
12317     return SwitchMBB;
12318 
12319   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
12320   unsigned PeeledCaseIndex = 0;
12321   bool SwitchPeeled = false;
12322   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
12323     CaseCluster &CC = Clusters[Index];
12324     if (CC.Prob < TopCaseProb)
12325       continue;
12326     TopCaseProb = CC.Prob;
12327     PeeledCaseIndex = Index;
12328     SwitchPeeled = true;
12329   }
12330   if (!SwitchPeeled)
12331     return SwitchMBB;
12332 
12333   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
12334                     << TopCaseProb << "\n");
12335 
12336   // Record the MBB for the peeled switch statement.
12337   MachineFunction::iterator BBI(SwitchMBB);
12338   ++BBI;
12339   MachineBasicBlock *PeeledSwitchMBB =
12340       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
12341   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
12342 
12343   ExportFromCurrentBlock(SI.getCondition());
12344   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
12345   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
12346                           nullptr,   nullptr,      TopCaseProb.getCompl()};
12347   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
12348 
12349   Clusters.erase(PeeledCaseIt);
12350   for (CaseCluster &CC : Clusters) {
12351     LLVM_DEBUG(
12352         dbgs() << "Scale the probablity for one cluster, before scaling: "
12353                << CC.Prob << "\n");
12354     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
12355     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
12356   }
12357   PeeledCaseProb = TopCaseProb;
12358   return PeeledSwitchMBB;
12359 }
12360 
12361 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
12362   // Extract cases from the switch.
12363   BranchProbabilityInfo *BPI = FuncInfo.BPI;
12364   CaseClusterVector Clusters;
12365   Clusters.reserve(SI.getNumCases());
12366   for (auto I : SI.cases()) {
12367     MachineBasicBlock *Succ = FuncInfo.getMBB(I.getCaseSuccessor());
12368     const ConstantInt *CaseVal = I.getCaseValue();
12369     BranchProbability Prob =
12370         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
12371             : BranchProbability(1, SI.getNumCases() + 1);
12372     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
12373   }
12374 
12375   MachineBasicBlock *DefaultMBB = FuncInfo.getMBB(SI.getDefaultDest());
12376 
12377   // Cluster adjacent cases with the same destination. We do this at all
12378   // optimization levels because it's cheap to do and will make codegen faster
12379   // if there are many clusters.
12380   sortAndRangeify(Clusters);
12381 
12382   // The branch probablity of the peeled case.
12383   BranchProbability PeeledCaseProb = BranchProbability::getZero();
12384   MachineBasicBlock *PeeledSwitchMBB =
12385       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
12386 
12387   // If there is only the default destination, jump there directly.
12388   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12389   if (Clusters.empty()) {
12390     assert(PeeledSwitchMBB == SwitchMBB);
12391     SwitchMBB->addSuccessor(DefaultMBB);
12392     if (DefaultMBB != NextBlock(SwitchMBB)) {
12393       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
12394                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
12395     }
12396     return;
12397   }
12398 
12399   SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(),
12400                      DAG.getBFI());
12401   SL->findBitTestClusters(Clusters, &SI);
12402 
12403   LLVM_DEBUG({
12404     dbgs() << "Case clusters: ";
12405     for (const CaseCluster &C : Clusters) {
12406       if (C.Kind == CC_JumpTable)
12407         dbgs() << "JT:";
12408       if (C.Kind == CC_BitTests)
12409         dbgs() << "BT:";
12410 
12411       C.Low->getValue().print(dbgs(), true);
12412       if (C.Low != C.High) {
12413         dbgs() << '-';
12414         C.High->getValue().print(dbgs(), true);
12415       }
12416       dbgs() << ' ';
12417     }
12418     dbgs() << '\n';
12419   });
12420 
12421   assert(!Clusters.empty());
12422   SwitchWorkList WorkList;
12423   CaseClusterIt First = Clusters.begin();
12424   CaseClusterIt Last = Clusters.end() - 1;
12425   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
12426   // Scale the branchprobability for DefaultMBB if the peel occurs and
12427   // DefaultMBB is not replaced.
12428   if (PeeledCaseProb != BranchProbability::getZero() &&
12429       DefaultMBB == FuncInfo.getMBB(SI.getDefaultDest()))
12430     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
12431   WorkList.push_back(
12432       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
12433 
12434   while (!WorkList.empty()) {
12435     SwitchWorkListItem W = WorkList.pop_back_val();
12436     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
12437 
12438     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None &&
12439         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
12440       // For optimized builds, lower large range as a balanced binary tree.
12441       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
12442       continue;
12443     }
12444 
12445     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
12446   }
12447 }
12448 
12449 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
12450   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12451   auto DL = getCurSDLoc();
12452   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12453   setValue(&I, DAG.getStepVector(DL, ResultVT));
12454 }
12455 
12456 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
12457   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12458   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12459 
12460   SDLoc DL = getCurSDLoc();
12461   SDValue V = getValue(I.getOperand(0));
12462   assert(VT == V.getValueType() && "Malformed vector.reverse!");
12463 
12464   if (VT.isScalableVector()) {
12465     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
12466     return;
12467   }
12468 
12469   // Use VECTOR_SHUFFLE for the fixed-length vector
12470   // to maintain existing behavior.
12471   SmallVector<int, 8> Mask;
12472   unsigned NumElts = VT.getVectorMinNumElements();
12473   for (unsigned i = 0; i != NumElts; ++i)
12474     Mask.push_back(NumElts - 1 - i);
12475 
12476   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
12477 }
12478 
12479 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) {
12480   auto DL = getCurSDLoc();
12481   SDValue InVec = getValue(I.getOperand(0));
12482   EVT OutVT =
12483       InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
12484 
12485   unsigned OutNumElts = OutVT.getVectorMinNumElements();
12486 
12487   // ISD Node needs the input vectors split into two equal parts
12488   SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
12489                            DAG.getVectorIdxConstant(0, DL));
12490   SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
12491                            DAG.getVectorIdxConstant(OutNumElts, DL));
12492 
12493   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
12494   // legalisation and combines.
12495   if (OutVT.isFixedLengthVector()) {
12496     SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
12497                                         createStrideMask(0, 2, OutNumElts));
12498     SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
12499                                        createStrideMask(1, 2, OutNumElts));
12500     SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc());
12501     setValue(&I, Res);
12502     return;
12503   }
12504 
12505   SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL,
12506                             DAG.getVTList(OutVT, OutVT), Lo, Hi);
12507   setValue(&I, Res);
12508 }
12509 
12510 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) {
12511   auto DL = getCurSDLoc();
12512   EVT InVT = getValue(I.getOperand(0)).getValueType();
12513   SDValue InVec0 = getValue(I.getOperand(0));
12514   SDValue InVec1 = getValue(I.getOperand(1));
12515   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12516   EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12517 
12518   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
12519   // legalisation and combines.
12520   if (OutVT.isFixedLengthVector()) {
12521     unsigned NumElts = InVT.getVectorMinNumElements();
12522     SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1);
12523     setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT),
12524                                       createInterleaveMask(NumElts, 2)));
12525     return;
12526   }
12527 
12528   SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL,
12529                             DAG.getVTList(InVT, InVT), InVec0, InVec1);
12530   Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0),
12531                     Res.getValue(1));
12532   setValue(&I, Res);
12533 }
12534 
12535 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
12536   SmallVector<EVT, 4> ValueVTs;
12537   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
12538                   ValueVTs);
12539   unsigned NumValues = ValueVTs.size();
12540   if (NumValues == 0) return;
12541 
12542   SmallVector<SDValue, 4> Values(NumValues);
12543   SDValue Op = getValue(I.getOperand(0));
12544 
12545   for (unsigned i = 0; i != NumValues; ++i)
12546     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
12547                             SDValue(Op.getNode(), Op.getResNo() + i));
12548 
12549   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12550                            DAG.getVTList(ValueVTs), Values));
12551 }
12552 
12553 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
12554   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12555   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12556 
12557   SDLoc DL = getCurSDLoc();
12558   SDValue V1 = getValue(I.getOperand(0));
12559   SDValue V2 = getValue(I.getOperand(1));
12560   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
12561 
12562   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
12563   if (VT.isScalableVector()) {
12564     setValue(
12565         &I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
12566                         DAG.getSignedConstant(
12567                             Imm, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))));
12568     return;
12569   }
12570 
12571   unsigned NumElts = VT.getVectorNumElements();
12572 
12573   uint64_t Idx = (NumElts + Imm) % NumElts;
12574 
12575   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
12576   SmallVector<int, 8> Mask;
12577   for (unsigned i = 0; i < NumElts; ++i)
12578     Mask.push_back(Idx + i);
12579   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
12580 }
12581 
12582 // Consider the following MIR after SelectionDAG, which produces output in
12583 // phyregs in the first case or virtregs in the second case.
12584 //
12585 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx
12586 // %5:gr32 = COPY $ebx
12587 // %6:gr32 = COPY $edx
12588 // %1:gr32 = COPY %6:gr32
12589 // %0:gr32 = COPY %5:gr32
12590 //
12591 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32
12592 // %1:gr32 = COPY %6:gr32
12593 // %0:gr32 = COPY %5:gr32
12594 //
12595 // Given %0, we'd like to return $ebx in the first case and %5 in the second.
12596 // Given %1, we'd like to return $edx in the first case and %6 in the second.
12597 //
12598 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap
12599 // to a single virtreg (such as %0). The remaining outputs monotonically
12600 // increase in virtreg number from there. If a callbr has no outputs, then it
12601 // should not have a corresponding callbr landingpad; in fact, the callbr
12602 // landingpad would not even be able to refer to such a callbr.
12603 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) {
12604   MachineInstr *MI = MRI.def_begin(Reg)->getParent();
12605   // There is definitely at least one copy.
12606   assert(MI->getOpcode() == TargetOpcode::COPY &&
12607          "start of copy chain MUST be COPY");
12608   Reg = MI->getOperand(1).getReg();
12609   MI = MRI.def_begin(Reg)->getParent();
12610   // There may be an optional second copy.
12611   if (MI->getOpcode() == TargetOpcode::COPY) {
12612     assert(Reg.isVirtual() && "expected COPY of virtual register");
12613     Reg = MI->getOperand(1).getReg();
12614     assert(Reg.isPhysical() && "expected COPY of physical register");
12615     MI = MRI.def_begin(Reg)->getParent();
12616   }
12617   // The start of the chain must be an INLINEASM_BR.
12618   assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR &&
12619          "end of copy chain MUST be INLINEASM_BR");
12620   return Reg;
12621 }
12622 
12623 // We must do this walk rather than the simpler
12624 //   setValue(&I, getCopyFromRegs(CBR, CBR->getType()));
12625 // otherwise we will end up with copies of virtregs only valid along direct
12626 // edges.
12627 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) {
12628   SmallVector<EVT, 8> ResultVTs;
12629   SmallVector<SDValue, 8> ResultValues;
12630   const auto *CBR =
12631       cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator());
12632 
12633   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12634   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
12635   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
12636 
12637   unsigned InitialDef = FuncInfo.ValueMap[CBR];
12638   SDValue Chain = DAG.getRoot();
12639 
12640   // Re-parse the asm constraints string.
12641   TargetLowering::AsmOperandInfoVector TargetConstraints =
12642       TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR);
12643   for (auto &T : TargetConstraints) {
12644     SDISelAsmOperandInfo OpInfo(T);
12645     if (OpInfo.Type != InlineAsm::isOutput)
12646       continue;
12647 
12648     // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the
12649     // individual constraint.
12650     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
12651 
12652     switch (OpInfo.ConstraintType) {
12653     case TargetLowering::C_Register:
12654     case TargetLowering::C_RegisterClass: {
12655       // Fill in OpInfo.AssignedRegs.Regs.
12656       getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo);
12657 
12658       // getRegistersForValue may produce 1 to many registers based on whether
12659       // the OpInfo.ConstraintVT is legal on the target or not.
12660       for (Register &Reg : OpInfo.AssignedRegs.Regs) {
12661         Register OriginalDef = FollowCopyChain(MRI, InitialDef++);
12662         if (Register::isPhysicalRegister(OriginalDef))
12663           FuncInfo.MBB->addLiveIn(OriginalDef);
12664         // Update the assigned registers to use the original defs.
12665         Reg = OriginalDef;
12666       }
12667 
12668       SDValue V = OpInfo.AssignedRegs.getCopyFromRegs(
12669           DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR);
12670       ResultValues.push_back(V);
12671       ResultVTs.push_back(OpInfo.ConstraintVT);
12672       break;
12673     }
12674     case TargetLowering::C_Other: {
12675       SDValue Flag;
12676       SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
12677                                                   OpInfo, DAG);
12678       ++InitialDef;
12679       ResultValues.push_back(V);
12680       ResultVTs.push_back(OpInfo.ConstraintVT);
12681       break;
12682     }
12683     default:
12684       break;
12685     }
12686   }
12687   SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12688                           DAG.getVTList(ResultVTs), ResultValues);
12689   setValue(&I, V);
12690 }
12691