xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 292ee93a87018bfef519ceff7de676e4792aa8d9)
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 
2288         for (unsigned i = 0; i < NumParts; ++i) {
2289           Outs.push_back(ISD::OutputArg(Flags,
2290                                         Parts[i].getValueType().getSimpleVT(),
2291                                         VT, /*isfixed=*/true, 0, 0));
2292           OutVals.push_back(Parts[i]);
2293         }
2294       }
2295     }
2296   }
2297 
2298   // Push in swifterror virtual register as the last element of Outs. This makes
2299   // sure swifterror virtual register will be returned in the swifterror
2300   // physical register.
2301   const Function *F = I.getParent()->getParent();
2302   if (TLI.supportSwiftError() &&
2303       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2304     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2305     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2306     Flags.setSwiftError();
2307     Outs.push_back(ISD::OutputArg(
2308         Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
2309         /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
2310     // Create SDNode for the swifterror virtual register.
2311     OutVals.push_back(
2312         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2313                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2314                         EVT(TLI.getPointerTy(DL))));
2315   }
2316 
2317   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2318   CallingConv::ID CallConv =
2319     DAG.getMachineFunction().getFunction().getCallingConv();
2320   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2321       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2322 
2323   // Verify that the target's LowerReturn behaved as expected.
2324   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2325          "LowerReturn didn't return a valid chain!");
2326 
2327   // Update the DAG with the new chain value resulting from return lowering.
2328   DAG.setRoot(Chain);
2329 }
2330 
2331 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2332 /// created for it, emit nodes to copy the value into the virtual
2333 /// registers.
2334 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2335   // Skip empty types
2336   if (V->getType()->isEmptyTy())
2337     return;
2338 
2339   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2340   if (VMI != FuncInfo.ValueMap.end()) {
2341     assert((!V->use_empty() || isa<CallBrInst>(V)) &&
2342            "Unused value assigned virtual registers!");
2343     CopyValueToVirtualRegister(V, VMI->second);
2344   }
2345 }
2346 
2347 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2348 /// the current basic block, add it to ValueMap now so that we'll get a
2349 /// CopyTo/FromReg.
2350 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2351   // No need to export constants.
2352   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2353 
2354   // Already exported?
2355   if (FuncInfo.isExportedInst(V)) return;
2356 
2357   Register Reg = FuncInfo.InitializeRegForValue(V);
2358   CopyValueToVirtualRegister(V, Reg);
2359 }
2360 
2361 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2362                                                      const BasicBlock *FromBB) {
2363   // The operands of the setcc have to be in this block.  We don't know
2364   // how to export them from some other block.
2365   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2366     // Can export from current BB.
2367     if (VI->getParent() == FromBB)
2368       return true;
2369 
2370     // Is already exported, noop.
2371     return FuncInfo.isExportedInst(V);
2372   }
2373 
2374   // If this is an argument, we can export it if the BB is the entry block or
2375   // if it is already exported.
2376   if (isa<Argument>(V)) {
2377     if (FromBB->isEntryBlock())
2378       return true;
2379 
2380     // Otherwise, can only export this if it is already exported.
2381     return FuncInfo.isExportedInst(V);
2382   }
2383 
2384   // Otherwise, constants can always be exported.
2385   return true;
2386 }
2387 
2388 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2389 BranchProbability
2390 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2391                                         const MachineBasicBlock *Dst) const {
2392   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2393   const BasicBlock *SrcBB = Src->getBasicBlock();
2394   const BasicBlock *DstBB = Dst->getBasicBlock();
2395   if (!BPI) {
2396     // If BPI is not available, set the default probability as 1 / N, where N is
2397     // the number of successors.
2398     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2399     return BranchProbability(1, SuccSize);
2400   }
2401   return BPI->getEdgeProbability(SrcBB, DstBB);
2402 }
2403 
2404 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2405                                                MachineBasicBlock *Dst,
2406                                                BranchProbability Prob) {
2407   if (!FuncInfo.BPI)
2408     Src->addSuccessorWithoutProb(Dst);
2409   else {
2410     if (Prob.isUnknown())
2411       Prob = getEdgeProbability(Src, Dst);
2412     Src->addSuccessor(Dst, Prob);
2413   }
2414 }
2415 
2416 static bool InBlock(const Value *V, const BasicBlock *BB) {
2417   if (const Instruction *I = dyn_cast<Instruction>(V))
2418     return I->getParent() == BB;
2419   return true;
2420 }
2421 
2422 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2423 /// This function emits a branch and is used at the leaves of an OR or an
2424 /// AND operator tree.
2425 void
2426 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2427                                                   MachineBasicBlock *TBB,
2428                                                   MachineBasicBlock *FBB,
2429                                                   MachineBasicBlock *CurBB,
2430                                                   MachineBasicBlock *SwitchBB,
2431                                                   BranchProbability TProb,
2432                                                   BranchProbability FProb,
2433                                                   bool InvertCond) {
2434   const BasicBlock *BB = CurBB->getBasicBlock();
2435 
2436   // If the leaf of the tree is a comparison, merge the condition into
2437   // the caseblock.
2438   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2439     // The operands of the cmp have to be in this block.  We don't know
2440     // how to export them from some other block.  If this is the first block
2441     // of the sequence, no exporting is needed.
2442     if (CurBB == SwitchBB ||
2443         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2444          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2445       ISD::CondCode Condition;
2446       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2447         ICmpInst::Predicate Pred =
2448             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2449         Condition = getICmpCondCode(Pred);
2450       } else {
2451         const FCmpInst *FC = cast<FCmpInst>(Cond);
2452         FCmpInst::Predicate Pred =
2453             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2454         Condition = getFCmpCondCode(Pred);
2455         if (TM.Options.NoNaNsFPMath)
2456           Condition = getFCmpCodeWithoutNaN(Condition);
2457       }
2458 
2459       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2460                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2461       SL->SwitchCases.push_back(CB);
2462       return;
2463     }
2464   }
2465 
2466   // Create a CaseBlock record representing this branch.
2467   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2468   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2469                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2470   SL->SwitchCases.push_back(CB);
2471 }
2472 
2473 // Collect dependencies on V recursively. This is used for the cost analysis in
2474 // `shouldKeepJumpConditionsTogether`.
2475 static bool collectInstructionDeps(
2476     SmallMapVector<const Instruction *, bool, 8> *Deps, const Value *V,
2477     SmallMapVector<const Instruction *, bool, 8> *Necessary = nullptr,
2478     unsigned Depth = 0) {
2479   // Return false if we have an incomplete count.
2480   if (Depth >= SelectionDAG::MaxRecursionDepth)
2481     return false;
2482 
2483   auto *I = dyn_cast<Instruction>(V);
2484   if (I == nullptr)
2485     return true;
2486 
2487   if (Necessary != nullptr) {
2488     // This instruction is necessary for the other side of the condition so
2489     // don't count it.
2490     if (Necessary->contains(I))
2491       return true;
2492   }
2493 
2494   // Already added this dep.
2495   if (!Deps->try_emplace(I, false).second)
2496     return true;
2497 
2498   for (unsigned OpIdx = 0, E = I->getNumOperands(); OpIdx < E; ++OpIdx)
2499     if (!collectInstructionDeps(Deps, I->getOperand(OpIdx), Necessary,
2500                                 Depth + 1))
2501       return false;
2502   return true;
2503 }
2504 
2505 bool SelectionDAGBuilder::shouldKeepJumpConditionsTogether(
2506     const FunctionLoweringInfo &FuncInfo, const BranchInst &I,
2507     Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs,
2508     TargetLoweringBase::CondMergingParams Params) const {
2509   if (I.getNumSuccessors() != 2)
2510     return false;
2511 
2512   if (!I.isConditional())
2513     return false;
2514 
2515   if (Params.BaseCost < 0)
2516     return false;
2517 
2518   // Baseline cost.
2519   InstructionCost CostThresh = Params.BaseCost;
2520 
2521   BranchProbabilityInfo *BPI = nullptr;
2522   if (Params.LikelyBias || Params.UnlikelyBias)
2523     BPI = FuncInfo.BPI;
2524   if (BPI != nullptr) {
2525     // See if we are either likely to get an early out or compute both lhs/rhs
2526     // of the condition.
2527     BasicBlock *IfFalse = I.getSuccessor(0);
2528     BasicBlock *IfTrue = I.getSuccessor(1);
2529 
2530     std::optional<bool> Likely;
2531     if (BPI->isEdgeHot(I.getParent(), IfTrue))
2532       Likely = true;
2533     else if (BPI->isEdgeHot(I.getParent(), IfFalse))
2534       Likely = false;
2535 
2536     if (Likely) {
2537       if (Opc == (*Likely ? Instruction::And : Instruction::Or))
2538         // Its likely we will have to compute both lhs and rhs of condition
2539         CostThresh += Params.LikelyBias;
2540       else {
2541         if (Params.UnlikelyBias < 0)
2542           return false;
2543         // Its likely we will get an early out.
2544         CostThresh -= Params.UnlikelyBias;
2545       }
2546     }
2547   }
2548 
2549   if (CostThresh <= 0)
2550     return false;
2551 
2552   // Collect "all" instructions that lhs condition is dependent on.
2553   // Use map for stable iteration (to avoid non-determanism of iteration of
2554   // SmallPtrSet). The `bool` value is just a dummy.
2555   SmallMapVector<const Instruction *, bool, 8> LhsDeps, RhsDeps;
2556   collectInstructionDeps(&LhsDeps, Lhs);
2557   // Collect "all" instructions that rhs condition is dependent on AND are
2558   // dependencies of lhs. This gives us an estimate on which instructions we
2559   // stand to save by splitting the condition.
2560   if (!collectInstructionDeps(&RhsDeps, Rhs, &LhsDeps))
2561     return false;
2562   // Add the compare instruction itself unless its a dependency on the LHS.
2563   if (const auto *RhsI = dyn_cast<Instruction>(Rhs))
2564     if (!LhsDeps.contains(RhsI))
2565       RhsDeps.try_emplace(RhsI, false);
2566 
2567   const auto &TLI = DAG.getTargetLoweringInfo();
2568   const auto &TTI =
2569       TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction());
2570 
2571   InstructionCost CostOfIncluding = 0;
2572   // See if this instruction will need to computed independently of whether RHS
2573   // is.
2574   Value *BrCond = I.getCondition();
2575   auto ShouldCountInsn = [&RhsDeps, &BrCond](const Instruction *Ins) {
2576     for (const auto *U : Ins->users()) {
2577       // If user is independent of RHS calculation we don't need to count it.
2578       if (auto *UIns = dyn_cast<Instruction>(U))
2579         if (UIns != BrCond && !RhsDeps.contains(UIns))
2580           return false;
2581     }
2582     return true;
2583   };
2584 
2585   // Prune instructions from RHS Deps that are dependencies of unrelated
2586   // instructions. The value (SelectionDAG::MaxRecursionDepth) is fairly
2587   // arbitrary and just meant to cap the how much time we spend in the pruning
2588   // loop. Its highly unlikely to come into affect.
2589   const unsigned MaxPruneIters = SelectionDAG::MaxRecursionDepth;
2590   // Stop after a certain point. No incorrectness from including too many
2591   // instructions.
2592   for (unsigned PruneIters = 0; PruneIters < MaxPruneIters; ++PruneIters) {
2593     const Instruction *ToDrop = nullptr;
2594     for (const auto &InsPair : RhsDeps) {
2595       if (!ShouldCountInsn(InsPair.first)) {
2596         ToDrop = InsPair.first;
2597         break;
2598       }
2599     }
2600     if (ToDrop == nullptr)
2601       break;
2602     RhsDeps.erase(ToDrop);
2603   }
2604 
2605   for (const auto &InsPair : RhsDeps) {
2606     // Finally accumulate latency that we can only attribute to computing the
2607     // RHS condition. Use latency because we are essentially trying to calculate
2608     // the cost of the dependency chain.
2609     // Possible TODO: We could try to estimate ILP and make this more precise.
2610     CostOfIncluding +=
2611         TTI.getInstructionCost(InsPair.first, TargetTransformInfo::TCK_Latency);
2612 
2613     if (CostOfIncluding > CostThresh)
2614       return false;
2615   }
2616   return true;
2617 }
2618 
2619 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2620                                                MachineBasicBlock *TBB,
2621                                                MachineBasicBlock *FBB,
2622                                                MachineBasicBlock *CurBB,
2623                                                MachineBasicBlock *SwitchBB,
2624                                                Instruction::BinaryOps Opc,
2625                                                BranchProbability TProb,
2626                                                BranchProbability FProb,
2627                                                bool InvertCond) {
2628   // Skip over not part of the tree and remember to invert op and operands at
2629   // next level.
2630   Value *NotCond;
2631   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2632       InBlock(NotCond, CurBB->getBasicBlock())) {
2633     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2634                          !InvertCond);
2635     return;
2636   }
2637 
2638   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2639   const Value *BOpOp0, *BOpOp1;
2640   // Compute the effective opcode for Cond, taking into account whether it needs
2641   // to be inverted, e.g.
2642   //   and (not (or A, B)), C
2643   // gets lowered as
2644   //   and (and (not A, not B), C)
2645   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2646   if (BOp) {
2647     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2648                ? Instruction::And
2649                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2650                       ? Instruction::Or
2651                       : (Instruction::BinaryOps)0);
2652     if (InvertCond) {
2653       if (BOpc == Instruction::And)
2654         BOpc = Instruction::Or;
2655       else if (BOpc == Instruction::Or)
2656         BOpc = Instruction::And;
2657     }
2658   }
2659 
2660   // If this node is not part of the or/and tree, emit it as a branch.
2661   // Note that all nodes in the tree should have same opcode.
2662   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2663   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2664       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2665       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2666     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2667                                  TProb, FProb, InvertCond);
2668     return;
2669   }
2670 
2671   //  Create TmpBB after CurBB.
2672   MachineFunction::iterator BBI(CurBB);
2673   MachineFunction &MF = DAG.getMachineFunction();
2674   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2675   CurBB->getParent()->insert(++BBI, TmpBB);
2676 
2677   if (Opc == Instruction::Or) {
2678     // Codegen X | Y as:
2679     // BB1:
2680     //   jmp_if_X TBB
2681     //   jmp TmpBB
2682     // TmpBB:
2683     //   jmp_if_Y TBB
2684     //   jmp FBB
2685     //
2686 
2687     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2688     // The requirement is that
2689     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2690     //     = TrueProb for original BB.
2691     // Assuming the original probabilities are A and B, one choice is to set
2692     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2693     // A/(1+B) and 2B/(1+B). This choice assumes that
2694     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2695     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2696     // TmpBB, but the math is more complicated.
2697 
2698     auto NewTrueProb = TProb / 2;
2699     auto NewFalseProb = TProb / 2 + FProb;
2700     // Emit the LHS condition.
2701     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2702                          NewFalseProb, InvertCond);
2703 
2704     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2705     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2706     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2707     // Emit the RHS condition into TmpBB.
2708     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2709                          Probs[1], InvertCond);
2710   } else {
2711     assert(Opc == Instruction::And && "Unknown merge op!");
2712     // Codegen X & Y as:
2713     // BB1:
2714     //   jmp_if_X TmpBB
2715     //   jmp FBB
2716     // TmpBB:
2717     //   jmp_if_Y TBB
2718     //   jmp FBB
2719     //
2720     //  This requires creation of TmpBB after CurBB.
2721 
2722     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2723     // The requirement is that
2724     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2725     //     = FalseProb for original BB.
2726     // Assuming the original probabilities are A and B, one choice is to set
2727     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2728     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2729     // TrueProb for BB1 * FalseProb for TmpBB.
2730 
2731     auto NewTrueProb = TProb + FProb / 2;
2732     auto NewFalseProb = FProb / 2;
2733     // Emit the LHS condition.
2734     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2735                          NewFalseProb, InvertCond);
2736 
2737     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2738     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2739     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2740     // Emit the RHS condition into TmpBB.
2741     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2742                          Probs[1], InvertCond);
2743   }
2744 }
2745 
2746 /// If the set of cases should be emitted as a series of branches, return true.
2747 /// If we should emit this as a bunch of and/or'd together conditions, return
2748 /// false.
2749 bool
2750 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2751   if (Cases.size() != 2) return true;
2752 
2753   // If this is two comparisons of the same values or'd or and'd together, they
2754   // will get folded into a single comparison, so don't emit two blocks.
2755   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2756        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2757       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2758        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2759     return false;
2760   }
2761 
2762   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2763   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2764   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2765       Cases[0].CC == Cases[1].CC &&
2766       isa<Constant>(Cases[0].CmpRHS) &&
2767       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2768     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2769       return false;
2770     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2771       return false;
2772   }
2773 
2774   return true;
2775 }
2776 
2777 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2778   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2779 
2780   // Update machine-CFG edges.
2781   MachineBasicBlock *Succ0MBB = FuncInfo.getMBB(I.getSuccessor(0));
2782 
2783   if (I.isUnconditional()) {
2784     // Update machine-CFG edges.
2785     BrMBB->addSuccessor(Succ0MBB);
2786 
2787     // If this is not a fall-through branch or optimizations are switched off,
2788     // emit the branch.
2789     if (Succ0MBB != NextBlock(BrMBB) ||
2790         TM.getOptLevel() == CodeGenOptLevel::None) {
2791       auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
2792                             getControlRoot(), DAG.getBasicBlock(Succ0MBB));
2793       setValue(&I, Br);
2794       DAG.setRoot(Br);
2795     }
2796 
2797     return;
2798   }
2799 
2800   // If this condition is one of the special cases we handle, do special stuff
2801   // now.
2802   const Value *CondVal = I.getCondition();
2803   MachineBasicBlock *Succ1MBB = FuncInfo.getMBB(I.getSuccessor(1));
2804 
2805   // If this is a series of conditions that are or'd or and'd together, emit
2806   // this as a sequence of branches instead of setcc's with and/or operations.
2807   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2808   // unpredictable branches, and vector extracts because those jumps are likely
2809   // expensive for any target), this should improve performance.
2810   // For example, instead of something like:
2811   //     cmp A, B
2812   //     C = seteq
2813   //     cmp D, E
2814   //     F = setle
2815   //     or C, F
2816   //     jnz foo
2817   // Emit:
2818   //     cmp A, B
2819   //     je foo
2820   //     cmp D, E
2821   //     jle foo
2822   bool IsUnpredictable = I.hasMetadata(LLVMContext::MD_unpredictable);
2823   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2824   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2825       BOp->hasOneUse() && !IsUnpredictable) {
2826     Value *Vec;
2827     const Value *BOp0, *BOp1;
2828     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2829     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2830       Opcode = Instruction::And;
2831     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2832       Opcode = Instruction::Or;
2833 
2834     if (Opcode &&
2835         !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2836           match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value()))) &&
2837         !shouldKeepJumpConditionsTogether(
2838             FuncInfo, I, Opcode, BOp0, BOp1,
2839             DAG.getTargetLoweringInfo().getJumpConditionMergingParams(
2840                 Opcode, BOp0, BOp1))) {
2841       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2842                            getEdgeProbability(BrMBB, Succ0MBB),
2843                            getEdgeProbability(BrMBB, Succ1MBB),
2844                            /*InvertCond=*/false);
2845       // If the compares in later blocks need to use values not currently
2846       // exported from this block, export them now.  This block should always
2847       // be the first entry.
2848       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2849 
2850       // Allow some cases to be rejected.
2851       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2852         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2853           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2854           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2855         }
2856 
2857         // Emit the branch for this block.
2858         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2859         SL->SwitchCases.erase(SL->SwitchCases.begin());
2860         return;
2861       }
2862 
2863       // Okay, we decided not to do this, remove any inserted MBB's and clear
2864       // SwitchCases.
2865       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2866         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2867 
2868       SL->SwitchCases.clear();
2869     }
2870   }
2871 
2872   // Create a CaseBlock record representing this branch.
2873   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2874                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc(),
2875                BranchProbability::getUnknown(), BranchProbability::getUnknown(),
2876                IsUnpredictable);
2877 
2878   // Use visitSwitchCase to actually insert the fast branch sequence for this
2879   // cond branch.
2880   visitSwitchCase(CB, BrMBB);
2881 }
2882 
2883 /// visitSwitchCase - Emits the necessary code to represent a single node in
2884 /// the binary search tree resulting from lowering a switch instruction.
2885 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2886                                           MachineBasicBlock *SwitchBB) {
2887   SDValue Cond;
2888   SDValue CondLHS = getValue(CB.CmpLHS);
2889   SDLoc dl = CB.DL;
2890 
2891   if (CB.CC == ISD::SETTRUE) {
2892     // Branch or fall through to TrueBB.
2893     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2894     SwitchBB->normalizeSuccProbs();
2895     if (CB.TrueBB != NextBlock(SwitchBB)) {
2896       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2897                               DAG.getBasicBlock(CB.TrueBB)));
2898     }
2899     return;
2900   }
2901 
2902   auto &TLI = DAG.getTargetLoweringInfo();
2903   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2904 
2905   // Build the setcc now.
2906   if (!CB.CmpMHS) {
2907     // Fold "(X == true)" to X and "(X == false)" to !X to
2908     // handle common cases produced by branch lowering.
2909     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2910         CB.CC == ISD::SETEQ)
2911       Cond = CondLHS;
2912     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2913              CB.CC == ISD::SETEQ) {
2914       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2915       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2916     } else {
2917       SDValue CondRHS = getValue(CB.CmpRHS);
2918 
2919       // If a pointer's DAG type is larger than its memory type then the DAG
2920       // values are zero-extended. This breaks signed comparisons so truncate
2921       // back to the underlying type before doing the compare.
2922       if (CondLHS.getValueType() != MemVT) {
2923         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2924         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2925       }
2926       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2927     }
2928   } else {
2929     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2930 
2931     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2932     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2933 
2934     SDValue CmpOp = getValue(CB.CmpMHS);
2935     EVT VT = CmpOp.getValueType();
2936 
2937     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2938       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2939                           ISD::SETLE);
2940     } else {
2941       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2942                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2943       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2944                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2945     }
2946   }
2947 
2948   // Update successor info
2949   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2950   // TrueBB and FalseBB are always different unless the incoming IR is
2951   // degenerate. This only happens when running llc on weird IR.
2952   if (CB.TrueBB != CB.FalseBB)
2953     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2954   SwitchBB->normalizeSuccProbs();
2955 
2956   // If the lhs block is the next block, invert the condition so that we can
2957   // fall through to the lhs instead of the rhs block.
2958   if (CB.TrueBB == NextBlock(SwitchBB)) {
2959     std::swap(CB.TrueBB, CB.FalseBB);
2960     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2961     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2962   }
2963 
2964   SDNodeFlags Flags;
2965   Flags.setUnpredictable(CB.IsUnpredictable);
2966   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, MVT::Other, getControlRoot(),
2967                                Cond, DAG.getBasicBlock(CB.TrueBB), Flags);
2968 
2969   setValue(CurInst, BrCond);
2970 
2971   // Insert the false branch. Do this even if it's a fall through branch,
2972   // this makes it easier to do DAG optimizations which require inverting
2973   // the branch condition.
2974   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2975                        DAG.getBasicBlock(CB.FalseBB));
2976 
2977   DAG.setRoot(BrCond);
2978 }
2979 
2980 /// visitJumpTable - Emit JumpTable node in the current MBB
2981 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2982   // Emit the code for the jump table
2983   assert(JT.SL && "Should set SDLoc for SelectionDAG!");
2984   assert(JT.Reg && "Should lower JT Header first!");
2985   EVT PTy = DAG.getTargetLoweringInfo().getJumpTableRegTy(DAG.getDataLayout());
2986   SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy);
2987   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2988   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other,
2989                                     Index.getValue(1), Table, Index);
2990   DAG.setRoot(BrJumpTable);
2991 }
2992 
2993 /// visitJumpTableHeader - This function emits necessary code to produce index
2994 /// in the JumpTable from switch case.
2995 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2996                                                JumpTableHeader &JTH,
2997                                                MachineBasicBlock *SwitchBB) {
2998   assert(JT.SL && "Should set SDLoc for SelectionDAG!");
2999   const SDLoc &dl = *JT.SL;
3000 
3001   // Subtract the lowest switch case value from the value being switched on.
3002   SDValue SwitchOp = getValue(JTH.SValue);
3003   EVT VT = SwitchOp.getValueType();
3004   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
3005                             DAG.getConstant(JTH.First, dl, VT));
3006 
3007   // The SDNode we just created, which holds the value being switched on minus
3008   // the smallest case value, needs to be copied to a virtual register so it
3009   // can be used as an index into the jump table in a subsequent basic block.
3010   // This value may be smaller or larger than the target's pointer type, and
3011   // therefore require extension or truncating.
3012   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3013   SwitchOp =
3014       DAG.getZExtOrTrunc(Sub, dl, TLI.getJumpTableRegTy(DAG.getDataLayout()));
3015 
3016   Register JumpTableReg =
3017       FuncInfo.CreateReg(TLI.getJumpTableRegTy(DAG.getDataLayout()));
3018   SDValue CopyTo =
3019       DAG.getCopyToReg(getControlRoot(), dl, JumpTableReg, SwitchOp);
3020   JT.Reg = JumpTableReg;
3021 
3022   if (!JTH.FallthroughUnreachable) {
3023     // Emit the range check for the jump table, and branch to the default block
3024     // for the switch statement if the value being switched on exceeds the
3025     // largest case in the switch.
3026     SDValue CMP = DAG.getSetCC(
3027         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3028                                    Sub.getValueType()),
3029         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
3030 
3031     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
3032                                  MVT::Other, CopyTo, CMP,
3033                                  DAG.getBasicBlock(JT.Default));
3034 
3035     // Avoid emitting unnecessary branches to the next block.
3036     if (JT.MBB != NextBlock(SwitchBB))
3037       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
3038                            DAG.getBasicBlock(JT.MBB));
3039 
3040     DAG.setRoot(BrCond);
3041   } else {
3042     // Avoid emitting unnecessary branches to the next block.
3043     if (JT.MBB != NextBlock(SwitchBB))
3044       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
3045                               DAG.getBasicBlock(JT.MBB)));
3046     else
3047       DAG.setRoot(CopyTo);
3048   }
3049 }
3050 
3051 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
3052 /// variable if there exists one.
3053 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
3054                                  SDValue &Chain) {
3055   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3056   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
3057   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
3058   MachineFunction &MF = DAG.getMachineFunction();
3059   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
3060   MachineSDNode *Node =
3061       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
3062   if (Global) {
3063     MachinePointerInfo MPInfo(Global);
3064     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
3065                  MachineMemOperand::MODereferenceable;
3066     MachineMemOperand *MemRef = MF.getMachineMemOperand(
3067         MPInfo, Flags, LocationSize::precise(PtrTy.getSizeInBits() / 8),
3068         DAG.getEVTAlign(PtrTy));
3069     DAG.setNodeMemRefs(Node, {MemRef});
3070   }
3071   if (PtrTy != PtrMemTy)
3072     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
3073   return SDValue(Node, 0);
3074 }
3075 
3076 /// Codegen a new tail for a stack protector check ParentMBB which has had its
3077 /// tail spliced into a stack protector check success bb.
3078 ///
3079 /// For a high level explanation of how this fits into the stack protector
3080 /// generation see the comment on the declaration of class
3081 /// StackProtectorDescriptor.
3082 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
3083                                                   MachineBasicBlock *ParentBB) {
3084 
3085   // First create the loads to the guard/stack slot for the comparison.
3086   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3087   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
3088   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
3089 
3090   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3091   int FI = MFI.getStackProtectorIndex();
3092 
3093   SDValue Guard;
3094   SDLoc dl = getCurSDLoc();
3095   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
3096   const Module &M = *ParentBB->getParent()->getFunction().getParent();
3097   Align Align =
3098       DAG.getDataLayout().getPrefTypeAlign(PointerType::get(M.getContext(), 0));
3099 
3100   // Generate code to load the content of the guard slot.
3101   SDValue GuardVal = DAG.getLoad(
3102       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
3103       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
3104       MachineMemOperand::MOVolatile);
3105 
3106   if (TLI.useStackGuardXorFP())
3107     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
3108 
3109   // Retrieve guard check function, nullptr if instrumentation is inlined.
3110   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
3111     // The target provides a guard check function to validate the guard value.
3112     // Generate a call to that function with the content of the guard slot as
3113     // argument.
3114     FunctionType *FnTy = GuardCheckFn->getFunctionType();
3115     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3116 
3117     TargetLowering::ArgListTy Args;
3118     TargetLowering::ArgListEntry Entry;
3119     Entry.Node = GuardVal;
3120     Entry.Ty = FnTy->getParamType(0);
3121     if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
3122       Entry.IsInReg = true;
3123     Args.push_back(Entry);
3124 
3125     TargetLowering::CallLoweringInfo CLI(DAG);
3126     CLI.setDebugLoc(getCurSDLoc())
3127         .setChain(DAG.getEntryNode())
3128         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
3129                    getValue(GuardCheckFn), std::move(Args));
3130 
3131     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
3132     DAG.setRoot(Result.second);
3133     return;
3134   }
3135 
3136   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
3137   // Otherwise, emit a volatile load to retrieve the stack guard value.
3138   SDValue Chain = DAG.getEntryNode();
3139   if (TLI.useLoadStackGuardNode()) {
3140     Guard = getLoadStackGuard(DAG, dl, Chain);
3141   } else {
3142     const Value *IRGuard = TLI.getSDagStackGuard(M);
3143     SDValue GuardPtr = getValue(IRGuard);
3144 
3145     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
3146                         MachinePointerInfo(IRGuard, 0), Align,
3147                         MachineMemOperand::MOVolatile);
3148   }
3149 
3150   // Perform the comparison via a getsetcc.
3151   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
3152                                                         *DAG.getContext(),
3153                                                         Guard.getValueType()),
3154                              Guard, GuardVal, ISD::SETNE);
3155 
3156   // If the guard/stackslot do not equal, branch to failure MBB.
3157   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
3158                                MVT::Other, GuardVal.getOperand(0),
3159                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
3160   // Otherwise branch to success MBB.
3161   SDValue Br = DAG.getNode(ISD::BR, dl,
3162                            MVT::Other, BrCond,
3163                            DAG.getBasicBlock(SPD.getSuccessMBB()));
3164 
3165   DAG.setRoot(Br);
3166 }
3167 
3168 /// Codegen the failure basic block for a stack protector check.
3169 ///
3170 /// A failure stack protector machine basic block consists simply of a call to
3171 /// __stack_chk_fail().
3172 ///
3173 /// For a high level explanation of how this fits into the stack protector
3174 /// generation see the comment on the declaration of class
3175 /// StackProtectorDescriptor.
3176 void
3177 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
3178   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3179   TargetLowering::MakeLibCallOptions CallOptions;
3180   CallOptions.setDiscardResult(true);
3181   SDValue Chain =
3182       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
3183                       std::nullopt, CallOptions, getCurSDLoc())
3184           .second;
3185   // On PS4/PS5, the "return address" must still be within the calling
3186   // function, even if it's at the very end, so emit an explicit TRAP here.
3187   // Passing 'true' for doesNotReturn above won't generate the trap for us.
3188   if (TM.getTargetTriple().isPS())
3189     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
3190   // WebAssembly needs an unreachable instruction after a non-returning call,
3191   // because the function return type can be different from __stack_chk_fail's
3192   // return type (void).
3193   if (TM.getTargetTriple().isWasm())
3194     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
3195 
3196   DAG.setRoot(Chain);
3197 }
3198 
3199 /// visitBitTestHeader - This function emits necessary code to produce value
3200 /// suitable for "bit tests"
3201 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
3202                                              MachineBasicBlock *SwitchBB) {
3203   SDLoc dl = getCurSDLoc();
3204 
3205   // Subtract the minimum value.
3206   SDValue SwitchOp = getValue(B.SValue);
3207   EVT VT = SwitchOp.getValueType();
3208   SDValue RangeSub =
3209       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
3210 
3211   // Determine the type of the test operands.
3212   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3213   bool UsePtrType = false;
3214   if (!TLI.isTypeLegal(VT)) {
3215     UsePtrType = true;
3216   } else {
3217     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
3218       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
3219         // Switch table case range are encoded into series of masks.
3220         // Just use pointer type, it's guaranteed to fit.
3221         UsePtrType = true;
3222         break;
3223       }
3224   }
3225   SDValue Sub = RangeSub;
3226   if (UsePtrType) {
3227     VT = TLI.getPointerTy(DAG.getDataLayout());
3228     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
3229   }
3230 
3231   B.RegVT = VT.getSimpleVT();
3232   B.Reg = FuncInfo.CreateReg(B.RegVT);
3233   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
3234 
3235   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
3236 
3237   if (!B.FallthroughUnreachable)
3238     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
3239   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
3240   SwitchBB->normalizeSuccProbs();
3241 
3242   SDValue Root = CopyTo;
3243   if (!B.FallthroughUnreachable) {
3244     // Conditional branch to the default block.
3245     SDValue RangeCmp = DAG.getSetCC(dl,
3246         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3247                                RangeSub.getValueType()),
3248         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
3249         ISD::SETUGT);
3250 
3251     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
3252                        DAG.getBasicBlock(B.Default));
3253   }
3254 
3255   // Avoid emitting unnecessary branches to the next block.
3256   if (MBB != NextBlock(SwitchBB))
3257     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
3258 
3259   DAG.setRoot(Root);
3260 }
3261 
3262 /// visitBitTestCase - this function produces one "bit test"
3263 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
3264                                            MachineBasicBlock *NextMBB,
3265                                            BranchProbability BranchProbToNext,
3266                                            Register Reg, BitTestCase &B,
3267                                            MachineBasicBlock *SwitchBB) {
3268   SDLoc dl = getCurSDLoc();
3269   MVT VT = BB.RegVT;
3270   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
3271   SDValue Cmp;
3272   unsigned PopCount = llvm::popcount(B.Mask);
3273   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3274   if (PopCount == 1) {
3275     // Testing for a single bit; just compare the shift count with what it
3276     // would need to be to shift a 1 bit in that position.
3277     Cmp = DAG.getSetCC(
3278         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3279         ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT),
3280         ISD::SETEQ);
3281   } else if (PopCount == BB.Range) {
3282     // There is only one zero bit in the range, test for it directly.
3283     Cmp = DAG.getSetCC(
3284         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3285         ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE);
3286   } else {
3287     // Make desired shift
3288     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
3289                                     DAG.getConstant(1, dl, VT), ShiftOp);
3290 
3291     // Emit bit tests and jumps
3292     SDValue AndOp = DAG.getNode(ISD::AND, dl,
3293                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
3294     Cmp = DAG.getSetCC(
3295         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3296         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
3297   }
3298 
3299   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
3300   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
3301   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
3302   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
3303   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
3304   // one as they are relative probabilities (and thus work more like weights),
3305   // and hence we need to normalize them to let the sum of them become one.
3306   SwitchBB->normalizeSuccProbs();
3307 
3308   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
3309                               MVT::Other, getControlRoot(),
3310                               Cmp, DAG.getBasicBlock(B.TargetBB));
3311 
3312   // Avoid emitting unnecessary branches to the next block.
3313   if (NextMBB != NextBlock(SwitchBB))
3314     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
3315                         DAG.getBasicBlock(NextMBB));
3316 
3317   DAG.setRoot(BrAnd);
3318 }
3319 
3320 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
3321   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
3322 
3323   // Retrieve successors. Look through artificial IR level blocks like
3324   // catchswitch for successors.
3325   MachineBasicBlock *Return = FuncInfo.getMBB(I.getSuccessor(0));
3326   const BasicBlock *EHPadBB = I.getSuccessor(1);
3327   MachineBasicBlock *EHPadMBB = FuncInfo.getMBB(EHPadBB);
3328 
3329   // Deopt and ptrauth bundles are lowered in helper functions, and we don't
3330   // have to do anything here to lower funclet bundles.
3331   assert(!I.hasOperandBundlesOtherThan(
3332              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
3333               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
3334               LLVMContext::OB_cfguardtarget, LLVMContext::OB_ptrauth,
3335               LLVMContext::OB_clang_arc_attachedcall}) &&
3336          "Cannot lower invokes with arbitrary operand bundles yet!");
3337 
3338   const Value *Callee(I.getCalledOperand());
3339   const Function *Fn = dyn_cast<Function>(Callee);
3340   if (isa<InlineAsm>(Callee))
3341     visitInlineAsm(I, EHPadBB);
3342   else if (Fn && Fn->isIntrinsic()) {
3343     switch (Fn->getIntrinsicID()) {
3344     default:
3345       llvm_unreachable("Cannot invoke this intrinsic");
3346     case Intrinsic::donothing:
3347       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
3348     case Intrinsic::seh_try_begin:
3349     case Intrinsic::seh_scope_begin:
3350     case Intrinsic::seh_try_end:
3351     case Intrinsic::seh_scope_end:
3352       if (EHPadMBB)
3353           // a block referenced by EH table
3354           // so dtor-funclet not removed by opts
3355           EHPadMBB->setMachineBlockAddressTaken();
3356       break;
3357     case Intrinsic::experimental_patchpoint_void:
3358     case Intrinsic::experimental_patchpoint:
3359       visitPatchpoint(I, EHPadBB);
3360       break;
3361     case Intrinsic::experimental_gc_statepoint:
3362       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
3363       break;
3364     case Intrinsic::wasm_rethrow: {
3365       // This is usually done in visitTargetIntrinsic, but this intrinsic is
3366       // special because it can be invoked, so we manually lower it to a DAG
3367       // node here.
3368       SmallVector<SDValue, 8> Ops;
3369       Ops.push_back(getControlRoot()); // inchain for the terminator node
3370       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3371       Ops.push_back(
3372           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
3373                                 TLI.getPointerTy(DAG.getDataLayout())));
3374       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3375       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3376       break;
3377     }
3378     }
3379   } else if (I.hasDeoptState()) {
3380     // Currently we do not lower any intrinsic calls with deopt operand bundles.
3381     // Eventually we will support lowering the @llvm.experimental.deoptimize
3382     // intrinsic, and right now there are no plans to support other intrinsics
3383     // with deopt state.
3384     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
3385   } else if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
3386     LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), EHPadBB);
3387   } else {
3388     LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
3389   }
3390 
3391   // If the value of the invoke is used outside of its defining block, make it
3392   // available as a virtual register.
3393   // We already took care of the exported value for the statepoint instruction
3394   // during call to the LowerStatepoint.
3395   if (!isa<GCStatepointInst>(I)) {
3396     CopyToExportRegsIfNeeded(&I);
3397   }
3398 
3399   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
3400   BranchProbabilityInfo *BPI = FuncInfo.BPI;
3401   BranchProbability EHPadBBProb =
3402       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3403           : BranchProbability::getZero();
3404   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
3405 
3406   // Update successor info.
3407   addSuccessorWithProb(InvokeMBB, Return);
3408   for (auto &UnwindDest : UnwindDests) {
3409     UnwindDest.first->setIsEHPad();
3410     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3411   }
3412   InvokeMBB->normalizeSuccProbs();
3413 
3414   // Drop into normal successor.
3415   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
3416                           DAG.getBasicBlock(Return)));
3417 }
3418 
3419 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3420   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3421 
3422   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3423   // have to do anything here to lower funclet bundles.
3424   assert(!I.hasOperandBundlesOtherThan(
3425              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
3426          "Cannot lower callbrs with arbitrary operand bundles yet!");
3427 
3428   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
3429   visitInlineAsm(I);
3430   CopyToExportRegsIfNeeded(&I);
3431 
3432   // Retrieve successors.
3433   SmallPtrSet<BasicBlock *, 8> Dests;
3434   Dests.insert(I.getDefaultDest());
3435   MachineBasicBlock *Return = FuncInfo.getMBB(I.getDefaultDest());
3436 
3437   // Update successor info.
3438   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3439   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
3440     BasicBlock *Dest = I.getIndirectDest(i);
3441     MachineBasicBlock *Target = FuncInfo.getMBB(Dest);
3442     Target->setIsInlineAsmBrIndirectTarget();
3443     Target->setMachineBlockAddressTaken();
3444     Target->setLabelMustBeEmitted();
3445     // Don't add duplicate machine successors.
3446     if (Dests.insert(Dest).second)
3447       addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3448   }
3449   CallBrMBB->normalizeSuccProbs();
3450 
3451   // Drop into default successor.
3452   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3453                           MVT::Other, getControlRoot(),
3454                           DAG.getBasicBlock(Return)));
3455 }
3456 
3457 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3458   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3459 }
3460 
3461 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3462   assert(FuncInfo.MBB->isEHPad() &&
3463          "Call to landingpad not in landing pad!");
3464 
3465   // If there aren't registers to copy the values into (e.g., during SjLj
3466   // exceptions), then don't bother to create these DAG nodes.
3467   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3468   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3469   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3470       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3471     return;
3472 
3473   // If landingpad's return type is token type, we don't create DAG nodes
3474   // for its exception pointer and selector value. The extraction of exception
3475   // pointer or selector value from token type landingpads is not currently
3476   // supported.
3477   if (LP.getType()->isTokenTy())
3478     return;
3479 
3480   SmallVector<EVT, 2> ValueVTs;
3481   SDLoc dl = getCurSDLoc();
3482   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3483   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3484 
3485   // Get the two live-in registers as SDValues. The physregs have already been
3486   // copied into virtual registers.
3487   SDValue Ops[2];
3488   if (FuncInfo.ExceptionPointerVirtReg) {
3489     Ops[0] = DAG.getZExtOrTrunc(
3490         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3491                            FuncInfo.ExceptionPointerVirtReg,
3492                            TLI.getPointerTy(DAG.getDataLayout())),
3493         dl, ValueVTs[0]);
3494   } else {
3495     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3496   }
3497   Ops[1] = DAG.getZExtOrTrunc(
3498       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3499                          FuncInfo.ExceptionSelectorVirtReg,
3500                          TLI.getPointerTy(DAG.getDataLayout())),
3501       dl, ValueVTs[1]);
3502 
3503   // Merge into one.
3504   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3505                             DAG.getVTList(ValueVTs), Ops);
3506   setValue(&LP, Res);
3507 }
3508 
3509 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3510                                            MachineBasicBlock *Last) {
3511   // Update JTCases.
3512   for (JumpTableBlock &JTB : SL->JTCases)
3513     if (JTB.first.HeaderBB == First)
3514       JTB.first.HeaderBB = Last;
3515 
3516   // Update BitTestCases.
3517   for (BitTestBlock &BTB : SL->BitTestCases)
3518     if (BTB.Parent == First)
3519       BTB.Parent = Last;
3520 }
3521 
3522 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3523   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3524 
3525   // Update machine-CFG edges with unique successors.
3526   SmallSet<BasicBlock*, 32> Done;
3527   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3528     BasicBlock *BB = I.getSuccessor(i);
3529     bool Inserted = Done.insert(BB).second;
3530     if (!Inserted)
3531         continue;
3532 
3533     MachineBasicBlock *Succ = FuncInfo.getMBB(BB);
3534     addSuccessorWithProb(IndirectBrMBB, Succ);
3535   }
3536   IndirectBrMBB->normalizeSuccProbs();
3537 
3538   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3539                           MVT::Other, getControlRoot(),
3540                           getValue(I.getAddress())));
3541 }
3542 
3543 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3544   if (!DAG.getTarget().Options.TrapUnreachable)
3545     return;
3546 
3547   // We may be able to ignore unreachable behind a noreturn call.
3548   if (const CallInst *Call = dyn_cast_or_null<CallInst>(I.getPrevNode());
3549       Call && Call->doesNotReturn()) {
3550     if (DAG.getTarget().Options.NoTrapAfterNoreturn)
3551       return;
3552     // Do not emit an additional trap instruction.
3553     if (Call->isNonContinuableTrap())
3554       return;
3555   }
3556 
3557   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3558 }
3559 
3560 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3561   SDNodeFlags Flags;
3562   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3563     Flags.copyFMF(*FPOp);
3564 
3565   SDValue Op = getValue(I.getOperand(0));
3566   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3567                                     Op, Flags);
3568   setValue(&I, UnNodeValue);
3569 }
3570 
3571 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3572   SDNodeFlags Flags;
3573   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3574     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3575     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3576   }
3577   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3578     Flags.setExact(ExactOp->isExact());
3579   if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&I))
3580     Flags.setDisjoint(DisjointOp->isDisjoint());
3581   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3582     Flags.copyFMF(*FPOp);
3583 
3584   SDValue Op1 = getValue(I.getOperand(0));
3585   SDValue Op2 = getValue(I.getOperand(1));
3586   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3587                                      Op1, Op2, Flags);
3588   setValue(&I, BinNodeValue);
3589 }
3590 
3591 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3592   SDValue Op1 = getValue(I.getOperand(0));
3593   SDValue Op2 = getValue(I.getOperand(1));
3594 
3595   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3596       Op1.getValueType(), DAG.getDataLayout());
3597 
3598   // Coerce the shift amount to the right type if we can. This exposes the
3599   // truncate or zext to optimization early.
3600   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3601     assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) &&
3602            "Unexpected shift type");
3603     Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3604   }
3605 
3606   bool nuw = false;
3607   bool nsw = false;
3608   bool exact = false;
3609 
3610   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3611 
3612     if (const OverflowingBinaryOperator *OFBinOp =
3613             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3614       nuw = OFBinOp->hasNoUnsignedWrap();
3615       nsw = OFBinOp->hasNoSignedWrap();
3616     }
3617     if (const PossiblyExactOperator *ExactOp =
3618             dyn_cast<const PossiblyExactOperator>(&I))
3619       exact = ExactOp->isExact();
3620   }
3621   SDNodeFlags Flags;
3622   Flags.setExact(exact);
3623   Flags.setNoSignedWrap(nsw);
3624   Flags.setNoUnsignedWrap(nuw);
3625   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3626                             Flags);
3627   setValue(&I, Res);
3628 }
3629 
3630 void SelectionDAGBuilder::visitSDiv(const User &I) {
3631   SDValue Op1 = getValue(I.getOperand(0));
3632   SDValue Op2 = getValue(I.getOperand(1));
3633 
3634   SDNodeFlags Flags;
3635   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3636                  cast<PossiblyExactOperator>(&I)->isExact());
3637   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3638                            Op2, Flags));
3639 }
3640 
3641 void SelectionDAGBuilder::visitICmp(const ICmpInst &I) {
3642   ICmpInst::Predicate predicate = I.getPredicate();
3643   SDValue Op1 = getValue(I.getOperand(0));
3644   SDValue Op2 = getValue(I.getOperand(1));
3645   ISD::CondCode Opcode = getICmpCondCode(predicate);
3646 
3647   auto &TLI = DAG.getTargetLoweringInfo();
3648   EVT MemVT =
3649       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3650 
3651   // If a pointer's DAG type is larger than its memory type then the DAG values
3652   // are zero-extended. This breaks signed comparisons so truncate back to the
3653   // underlying type before doing the compare.
3654   if (Op1.getValueType() != MemVT) {
3655     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3656     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3657   }
3658 
3659   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3660                                                         I.getType());
3661   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3662 }
3663 
3664 void SelectionDAGBuilder::visitFCmp(const FCmpInst &I) {
3665   FCmpInst::Predicate predicate = I.getPredicate();
3666   SDValue Op1 = getValue(I.getOperand(0));
3667   SDValue Op2 = getValue(I.getOperand(1));
3668 
3669   ISD::CondCode Condition = getFCmpCondCode(predicate);
3670   auto *FPMO = cast<FPMathOperator>(&I);
3671   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3672     Condition = getFCmpCodeWithoutNaN(Condition);
3673 
3674   SDNodeFlags Flags;
3675   Flags.copyFMF(*FPMO);
3676   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3677 
3678   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3679                                                         I.getType());
3680   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3681 }
3682 
3683 // Check if the condition of the select has one use or two users that are both
3684 // selects with the same condition.
3685 static bool hasOnlySelectUsers(const Value *Cond) {
3686   return llvm::all_of(Cond->users(), [](const Value *V) {
3687     return isa<SelectInst>(V);
3688   });
3689 }
3690 
3691 void SelectionDAGBuilder::visitSelect(const User &I) {
3692   SmallVector<EVT, 4> ValueVTs;
3693   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3694                   ValueVTs);
3695   unsigned NumValues = ValueVTs.size();
3696   if (NumValues == 0) return;
3697 
3698   SmallVector<SDValue, 4> Values(NumValues);
3699   SDValue Cond     = getValue(I.getOperand(0));
3700   SDValue LHSVal   = getValue(I.getOperand(1));
3701   SDValue RHSVal   = getValue(I.getOperand(2));
3702   SmallVector<SDValue, 1> BaseOps(1, Cond);
3703   ISD::NodeType OpCode =
3704       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3705 
3706   bool IsUnaryAbs = false;
3707   bool Negate = false;
3708 
3709   SDNodeFlags Flags;
3710   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3711     Flags.copyFMF(*FPOp);
3712 
3713   Flags.setUnpredictable(
3714       cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable));
3715 
3716   // Min/max matching is only viable if all output VTs are the same.
3717   if (all_equal(ValueVTs)) {
3718     EVT VT = ValueVTs[0];
3719     LLVMContext &Ctx = *DAG.getContext();
3720     auto &TLI = DAG.getTargetLoweringInfo();
3721 
3722     // We care about the legality of the operation after it has been type
3723     // legalized.
3724     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3725       VT = TLI.getTypeToTransformTo(Ctx, VT);
3726 
3727     // If the vselect is legal, assume we want to leave this as a vector setcc +
3728     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3729     // min/max is legal on the scalar type.
3730     bool UseScalarMinMax = VT.isVector() &&
3731       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3732 
3733     // ValueTracking's select pattern matching does not account for -0.0,
3734     // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that
3735     // -0.0 is less than +0.0.
3736     const Value *LHS, *RHS;
3737     auto SPR = matchSelectPattern(&I, LHS, RHS);
3738     ISD::NodeType Opc = ISD::DELETED_NODE;
3739     switch (SPR.Flavor) {
3740     case SPF_UMAX:    Opc = ISD::UMAX; break;
3741     case SPF_UMIN:    Opc = ISD::UMIN; break;
3742     case SPF_SMAX:    Opc = ISD::SMAX; break;
3743     case SPF_SMIN:    Opc = ISD::SMIN; break;
3744     case SPF_FMINNUM:
3745       switch (SPR.NaNBehavior) {
3746       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3747       case SPNB_RETURNS_NAN: break;
3748       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3749       case SPNB_RETURNS_ANY:
3750         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) ||
3751             (UseScalarMinMax &&
3752              TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType())))
3753           Opc = ISD::FMINNUM;
3754         break;
3755       }
3756       break;
3757     case SPF_FMAXNUM:
3758       switch (SPR.NaNBehavior) {
3759       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3760       case SPNB_RETURNS_NAN: break;
3761       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3762       case SPNB_RETURNS_ANY:
3763         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) ||
3764             (UseScalarMinMax &&
3765              TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType())))
3766           Opc = ISD::FMAXNUM;
3767         break;
3768       }
3769       break;
3770     case SPF_NABS:
3771       Negate = true;
3772       [[fallthrough]];
3773     case SPF_ABS:
3774       IsUnaryAbs = true;
3775       Opc = ISD::ABS;
3776       break;
3777     default: break;
3778     }
3779 
3780     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3781         (TLI.isOperationLegalOrCustomOrPromote(Opc, VT) ||
3782          (UseScalarMinMax &&
3783           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3784         // If the underlying comparison instruction is used by any other
3785         // instruction, the consumed instructions won't be destroyed, so it is
3786         // not profitable to convert to a min/max.
3787         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3788       OpCode = Opc;
3789       LHSVal = getValue(LHS);
3790       RHSVal = getValue(RHS);
3791       BaseOps.clear();
3792     }
3793 
3794     if (IsUnaryAbs) {
3795       OpCode = Opc;
3796       LHSVal = getValue(LHS);
3797       BaseOps.clear();
3798     }
3799   }
3800 
3801   if (IsUnaryAbs) {
3802     for (unsigned i = 0; i != NumValues; ++i) {
3803       SDLoc dl = getCurSDLoc();
3804       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3805       Values[i] =
3806           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3807       if (Negate)
3808         Values[i] = DAG.getNegative(Values[i], dl, VT);
3809     }
3810   } else {
3811     for (unsigned i = 0; i != NumValues; ++i) {
3812       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3813       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3814       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3815       Values[i] = DAG.getNode(
3816           OpCode, getCurSDLoc(),
3817           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3818     }
3819   }
3820 
3821   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3822                            DAG.getVTList(ValueVTs), Values));
3823 }
3824 
3825 void SelectionDAGBuilder::visitTrunc(const User &I) {
3826   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3827   SDValue N = getValue(I.getOperand(0));
3828   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3829                                                         I.getType());
3830   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3831 }
3832 
3833 void SelectionDAGBuilder::visitZExt(const User &I) {
3834   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3835   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3836   SDValue N = getValue(I.getOperand(0));
3837   auto &TLI = DAG.getTargetLoweringInfo();
3838   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3839 
3840   SDNodeFlags Flags;
3841   if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
3842     Flags.setNonNeg(PNI->hasNonNeg());
3843 
3844   // Eagerly use nonneg information to canonicalize towards sign_extend if
3845   // that is the target's preference.
3846   // TODO: Let the target do this later.
3847   if (Flags.hasNonNeg() &&
3848       TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) {
3849     setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3850     return;
3851   }
3852 
3853   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags));
3854 }
3855 
3856 void SelectionDAGBuilder::visitSExt(const User &I) {
3857   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3858   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3859   SDValue N = getValue(I.getOperand(0));
3860   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3861                                                         I.getType());
3862   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3863 }
3864 
3865 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3866   // FPTrunc is never a no-op cast, no need to check
3867   SDValue N = getValue(I.getOperand(0));
3868   SDLoc dl = getCurSDLoc();
3869   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3870   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3871   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3872                            DAG.getTargetConstant(
3873                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3874 }
3875 
3876 void SelectionDAGBuilder::visitFPExt(const User &I) {
3877   // FPExt is never a no-op cast, no need to check
3878   SDValue N = getValue(I.getOperand(0));
3879   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3880                                                         I.getType());
3881   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3882 }
3883 
3884 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3885   // FPToUI is never a no-op cast, no need to check
3886   SDValue N = getValue(I.getOperand(0));
3887   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3888                                                         I.getType());
3889   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3890 }
3891 
3892 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3893   // FPToSI is never a no-op cast, no need to check
3894   SDValue N = getValue(I.getOperand(0));
3895   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3896                                                         I.getType());
3897   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3898 }
3899 
3900 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3901   // UIToFP is never a no-op cast, no need to check
3902   SDValue N = getValue(I.getOperand(0));
3903   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3904                                                         I.getType());
3905   SDNodeFlags Flags;
3906   if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
3907     Flags.setNonNeg(PNI->hasNonNeg());
3908 
3909   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N, Flags));
3910 }
3911 
3912 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3913   // SIToFP is never a no-op cast, no need to check
3914   SDValue N = getValue(I.getOperand(0));
3915   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3916                                                         I.getType());
3917   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3918 }
3919 
3920 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3921   // What to do depends on the size of the integer and the size of the pointer.
3922   // We can either truncate, zero extend, or no-op, accordingly.
3923   SDValue N = getValue(I.getOperand(0));
3924   auto &TLI = DAG.getTargetLoweringInfo();
3925   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3926                                                         I.getType());
3927   EVT PtrMemVT =
3928       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3929   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3930   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3931   setValue(&I, N);
3932 }
3933 
3934 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3935   // What to do depends on the size of the integer and the size of the pointer.
3936   // We can either truncate, zero extend, or no-op, accordingly.
3937   SDValue N = getValue(I.getOperand(0));
3938   auto &TLI = DAG.getTargetLoweringInfo();
3939   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3940   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3941   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3942   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3943   setValue(&I, N);
3944 }
3945 
3946 void SelectionDAGBuilder::visitBitCast(const User &I) {
3947   SDValue N = getValue(I.getOperand(0));
3948   SDLoc dl = getCurSDLoc();
3949   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3950                                                         I.getType());
3951 
3952   // BitCast assures us that source and destination are the same size so this is
3953   // either a BITCAST or a no-op.
3954   if (DestVT != N.getValueType())
3955     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3956                              DestVT, N)); // convert types.
3957   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3958   // might fold any kind of constant expression to an integer constant and that
3959   // is not what we are looking for. Only recognize a bitcast of a genuine
3960   // constant integer as an opaque constant.
3961   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3962     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3963                                  /*isOpaque*/true));
3964   else
3965     setValue(&I, N);            // noop cast.
3966 }
3967 
3968 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3969   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3970   const Value *SV = I.getOperand(0);
3971   SDValue N = getValue(SV);
3972   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3973 
3974   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3975   unsigned DestAS = I.getType()->getPointerAddressSpace();
3976 
3977   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3978     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3979 
3980   setValue(&I, N);
3981 }
3982 
3983 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3984   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3985   SDValue InVec = getValue(I.getOperand(0));
3986   SDValue InVal = getValue(I.getOperand(1));
3987   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3988                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3989   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3990                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3991                            InVec, InVal, InIdx));
3992 }
3993 
3994 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3995   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3996   SDValue InVec = getValue(I.getOperand(0));
3997   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3998                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3999   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
4000                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
4001                            InVec, InIdx));
4002 }
4003 
4004 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
4005   SDValue Src1 = getValue(I.getOperand(0));
4006   SDValue Src2 = getValue(I.getOperand(1));
4007   ArrayRef<int> Mask;
4008   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
4009     Mask = SVI->getShuffleMask();
4010   else
4011     Mask = cast<ConstantExpr>(I).getShuffleMask();
4012   SDLoc DL = getCurSDLoc();
4013   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4014   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4015   EVT SrcVT = Src1.getValueType();
4016 
4017   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
4018       VT.isScalableVector()) {
4019     // Canonical splat form of first element of first input vector.
4020     SDValue FirstElt =
4021         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
4022                     DAG.getVectorIdxConstant(0, DL));
4023     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
4024     return;
4025   }
4026 
4027   // For now, we only handle splats for scalable vectors.
4028   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
4029   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
4030   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
4031 
4032   unsigned SrcNumElts = SrcVT.getVectorNumElements();
4033   unsigned MaskNumElts = Mask.size();
4034 
4035   if (SrcNumElts == MaskNumElts) {
4036     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
4037     return;
4038   }
4039 
4040   // Normalize the shuffle vector since mask and vector length don't match.
4041   if (SrcNumElts < MaskNumElts) {
4042     // Mask is longer than the source vectors. We can use concatenate vector to
4043     // make the mask and vectors lengths match.
4044 
4045     if (MaskNumElts % SrcNumElts == 0) {
4046       // Mask length is a multiple of the source vector length.
4047       // Check if the shuffle is some kind of concatenation of the input
4048       // vectors.
4049       unsigned NumConcat = MaskNumElts / SrcNumElts;
4050       bool IsConcat = true;
4051       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
4052       for (unsigned i = 0; i != MaskNumElts; ++i) {
4053         int Idx = Mask[i];
4054         if (Idx < 0)
4055           continue;
4056         // Ensure the indices in each SrcVT sized piece are sequential and that
4057         // the same source is used for the whole piece.
4058         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
4059             (ConcatSrcs[i / SrcNumElts] >= 0 &&
4060              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
4061           IsConcat = false;
4062           break;
4063         }
4064         // Remember which source this index came from.
4065         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
4066       }
4067 
4068       // The shuffle is concatenating multiple vectors together. Just emit
4069       // a CONCAT_VECTORS operation.
4070       if (IsConcat) {
4071         SmallVector<SDValue, 8> ConcatOps;
4072         for (auto Src : ConcatSrcs) {
4073           if (Src < 0)
4074             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
4075           else if (Src == 0)
4076             ConcatOps.push_back(Src1);
4077           else
4078             ConcatOps.push_back(Src2);
4079         }
4080         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
4081         return;
4082       }
4083     }
4084 
4085     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
4086     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
4087     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
4088                                     PaddedMaskNumElts);
4089 
4090     // Pad both vectors with undefs to make them the same length as the mask.
4091     SDValue UndefVal = DAG.getUNDEF(SrcVT);
4092 
4093     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
4094     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
4095     MOps1[0] = Src1;
4096     MOps2[0] = Src2;
4097 
4098     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
4099     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
4100 
4101     // Readjust mask for new input vector length.
4102     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
4103     for (unsigned i = 0; i != MaskNumElts; ++i) {
4104       int Idx = Mask[i];
4105       if (Idx >= (int)SrcNumElts)
4106         Idx -= SrcNumElts - PaddedMaskNumElts;
4107       MappedOps[i] = Idx;
4108     }
4109 
4110     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
4111 
4112     // If the concatenated vector was padded, extract a subvector with the
4113     // correct number of elements.
4114     if (MaskNumElts != PaddedMaskNumElts)
4115       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
4116                            DAG.getVectorIdxConstant(0, DL));
4117 
4118     setValue(&I, Result);
4119     return;
4120   }
4121 
4122   if (SrcNumElts > MaskNumElts) {
4123     // Analyze the access pattern of the vector to see if we can extract
4124     // two subvectors and do the shuffle.
4125     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
4126     bool CanExtract = true;
4127     for (int Idx : Mask) {
4128       unsigned Input = 0;
4129       if (Idx < 0)
4130         continue;
4131 
4132       if (Idx >= (int)SrcNumElts) {
4133         Input = 1;
4134         Idx -= SrcNumElts;
4135       }
4136 
4137       // If all the indices come from the same MaskNumElts sized portion of
4138       // the sources we can use extract. Also make sure the extract wouldn't
4139       // extract past the end of the source.
4140       int NewStartIdx = alignDown(Idx, MaskNumElts);
4141       if (NewStartIdx + MaskNumElts > SrcNumElts ||
4142           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
4143         CanExtract = false;
4144       // Make sure we always update StartIdx as we use it to track if all
4145       // elements are undef.
4146       StartIdx[Input] = NewStartIdx;
4147     }
4148 
4149     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
4150       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
4151       return;
4152     }
4153     if (CanExtract) {
4154       // Extract appropriate subvector and generate a vector shuffle
4155       for (unsigned Input = 0; Input < 2; ++Input) {
4156         SDValue &Src = Input == 0 ? Src1 : Src2;
4157         if (StartIdx[Input] < 0)
4158           Src = DAG.getUNDEF(VT);
4159         else {
4160           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
4161                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
4162         }
4163       }
4164 
4165       // Calculate new mask.
4166       SmallVector<int, 8> MappedOps(Mask);
4167       for (int &Idx : MappedOps) {
4168         if (Idx >= (int)SrcNumElts)
4169           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
4170         else if (Idx >= 0)
4171           Idx -= StartIdx[0];
4172       }
4173 
4174       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
4175       return;
4176     }
4177   }
4178 
4179   // We can't use either concat vectors or extract subvectors so fall back to
4180   // replacing the shuffle with extract and build vector.
4181   // to insert and build vector.
4182   EVT EltVT = VT.getVectorElementType();
4183   SmallVector<SDValue,8> Ops;
4184   for (int Idx : Mask) {
4185     SDValue Res;
4186 
4187     if (Idx < 0) {
4188       Res = DAG.getUNDEF(EltVT);
4189     } else {
4190       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
4191       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
4192 
4193       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
4194                         DAG.getVectorIdxConstant(Idx, DL));
4195     }
4196 
4197     Ops.push_back(Res);
4198   }
4199 
4200   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
4201 }
4202 
4203 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
4204   ArrayRef<unsigned> Indices = I.getIndices();
4205   const Value *Op0 = I.getOperand(0);
4206   const Value *Op1 = I.getOperand(1);
4207   Type *AggTy = I.getType();
4208   Type *ValTy = Op1->getType();
4209   bool IntoUndef = isa<UndefValue>(Op0);
4210   bool FromUndef = isa<UndefValue>(Op1);
4211 
4212   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4213 
4214   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4215   SmallVector<EVT, 4> AggValueVTs;
4216   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
4217   SmallVector<EVT, 4> ValValueVTs;
4218   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4219 
4220   unsigned NumAggValues = AggValueVTs.size();
4221   unsigned NumValValues = ValValueVTs.size();
4222   SmallVector<SDValue, 4> Values(NumAggValues);
4223 
4224   // Ignore an insertvalue that produces an empty object
4225   if (!NumAggValues) {
4226     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4227     return;
4228   }
4229 
4230   SDValue Agg = getValue(Op0);
4231   unsigned i = 0;
4232   // Copy the beginning value(s) from the original aggregate.
4233   for (; i != LinearIndex; ++i)
4234     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4235                 SDValue(Agg.getNode(), Agg.getResNo() + i);
4236   // Copy values from the inserted value(s).
4237   if (NumValValues) {
4238     SDValue Val = getValue(Op1);
4239     for (; i != LinearIndex + NumValValues; ++i)
4240       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4241                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
4242   }
4243   // Copy remaining value(s) from the original aggregate.
4244   for (; i != NumAggValues; ++i)
4245     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4246                 SDValue(Agg.getNode(), Agg.getResNo() + i);
4247 
4248   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
4249                            DAG.getVTList(AggValueVTs), Values));
4250 }
4251 
4252 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
4253   ArrayRef<unsigned> Indices = I.getIndices();
4254   const Value *Op0 = I.getOperand(0);
4255   Type *AggTy = Op0->getType();
4256   Type *ValTy = I.getType();
4257   bool OutOfUndef = isa<UndefValue>(Op0);
4258 
4259   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4260 
4261   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4262   SmallVector<EVT, 4> ValValueVTs;
4263   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4264 
4265   unsigned NumValValues = ValValueVTs.size();
4266 
4267   // Ignore a extractvalue that produces an empty object
4268   if (!NumValValues) {
4269     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4270     return;
4271   }
4272 
4273   SmallVector<SDValue, 4> Values(NumValValues);
4274 
4275   SDValue Agg = getValue(Op0);
4276   // Copy out the selected value(s).
4277   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
4278     Values[i - LinearIndex] =
4279       OutOfUndef ?
4280         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
4281         SDValue(Agg.getNode(), Agg.getResNo() + i);
4282 
4283   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
4284                            DAG.getVTList(ValValueVTs), Values));
4285 }
4286 
4287 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
4288   Value *Op0 = I.getOperand(0);
4289   // Note that the pointer operand may be a vector of pointers. Take the scalar
4290   // element which holds a pointer.
4291   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
4292   SDValue N = getValue(Op0);
4293   SDLoc dl = getCurSDLoc();
4294   auto &TLI = DAG.getTargetLoweringInfo();
4295   GEPNoWrapFlags NW = cast<GEPOperator>(I).getNoWrapFlags();
4296 
4297   // Normalize Vector GEP - all scalar operands should be converted to the
4298   // splat vector.
4299   bool IsVectorGEP = I.getType()->isVectorTy();
4300   ElementCount VectorElementCount =
4301       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
4302                   : ElementCount::getFixed(0);
4303 
4304   if (IsVectorGEP && !N.getValueType().isVector()) {
4305     LLVMContext &Context = *DAG.getContext();
4306     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
4307     N = DAG.getSplat(VT, dl, N);
4308   }
4309 
4310   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
4311        GTI != E; ++GTI) {
4312     const Value *Idx = GTI.getOperand();
4313     if (StructType *StTy = GTI.getStructTypeOrNull()) {
4314       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
4315       if (Field) {
4316         // N = N + Offset
4317         uint64_t Offset =
4318             DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
4319 
4320         // In an inbounds GEP with an offset that is nonnegative even when
4321         // interpreted as signed, assume there is no unsigned overflow.
4322         SDNodeFlags Flags;
4323         if (NW.hasNoUnsignedWrap() ||
4324             (int64_t(Offset) >= 0 && NW.hasNoUnsignedSignedWrap()))
4325           Flags.setNoUnsignedWrap(true);
4326 
4327         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
4328                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
4329       }
4330     } else {
4331       // IdxSize is the width of the arithmetic according to IR semantics.
4332       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
4333       // (and fix up the result later).
4334       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
4335       MVT IdxTy = MVT::getIntegerVT(IdxSize);
4336       TypeSize ElementSize =
4337           GTI.getSequentialElementStride(DAG.getDataLayout());
4338       // We intentionally mask away the high bits here; ElementSize may not
4339       // fit in IdxTy.
4340       APInt ElementMul(IdxSize, ElementSize.getKnownMinValue());
4341       bool ElementScalable = ElementSize.isScalable();
4342 
4343       // If this is a scalar constant or a splat vector of constants,
4344       // handle it quickly.
4345       const auto *C = dyn_cast<Constant>(Idx);
4346       if (C && isa<VectorType>(C->getType()))
4347         C = C->getSplatValue();
4348 
4349       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
4350       if (CI && CI->isZero())
4351         continue;
4352       if (CI && !ElementScalable) {
4353         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
4354         LLVMContext &Context = *DAG.getContext();
4355         SDValue OffsVal;
4356         if (IsVectorGEP)
4357           OffsVal = DAG.getConstant(
4358               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
4359         else
4360           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
4361 
4362         // In an inbounds GEP with an offset that is nonnegative even when
4363         // interpreted as signed, assume there is no unsigned overflow.
4364         SDNodeFlags Flags;
4365         if (NW.hasNoUnsignedWrap() ||
4366             (Offs.isNonNegative() && NW.hasNoUnsignedSignedWrap()))
4367           Flags.setNoUnsignedWrap(true);
4368 
4369         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
4370 
4371         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
4372         continue;
4373       }
4374 
4375       // N = N + Idx * ElementMul;
4376       SDValue IdxN = getValue(Idx);
4377 
4378       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
4379         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
4380                                   VectorElementCount);
4381         IdxN = DAG.getSplat(VT, dl, IdxN);
4382       }
4383 
4384       // If the index is smaller or larger than intptr_t, truncate or extend
4385       // it.
4386       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
4387 
4388       if (ElementScalable) {
4389         EVT VScaleTy = N.getValueType().getScalarType();
4390         SDValue VScale = DAG.getNode(
4391             ISD::VSCALE, dl, VScaleTy,
4392             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
4393         if (IsVectorGEP)
4394           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
4395         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
4396       } else {
4397         // If this is a multiply by a power of two, turn it into a shl
4398         // immediately.  This is a very common case.
4399         if (ElementMul != 1) {
4400           if (ElementMul.isPowerOf2()) {
4401             unsigned Amt = ElementMul.logBase2();
4402             IdxN = DAG.getNode(ISD::SHL, dl,
4403                                N.getValueType(), IdxN,
4404                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
4405           } else {
4406             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
4407                                             IdxN.getValueType());
4408             IdxN = DAG.getNode(ISD::MUL, dl,
4409                                N.getValueType(), IdxN, Scale);
4410           }
4411         }
4412       }
4413 
4414       N = DAG.getNode(ISD::ADD, dl,
4415                       N.getValueType(), N, IdxN);
4416     }
4417   }
4418 
4419   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4420   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4421   if (IsVectorGEP) {
4422     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4423     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4424   }
4425 
4426   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4427     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4428 
4429   setValue(&I, N);
4430 }
4431 
4432 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4433   // If this is a fixed sized alloca in the entry block of the function,
4434   // allocate it statically on the stack.
4435   if (FuncInfo.StaticAllocaMap.count(&I))
4436     return;   // getValue will auto-populate this.
4437 
4438   SDLoc dl = getCurSDLoc();
4439   Type *Ty = I.getAllocatedType();
4440   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4441   auto &DL = DAG.getDataLayout();
4442   TypeSize TySize = DL.getTypeAllocSize(Ty);
4443   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4444 
4445   SDValue AllocSize = getValue(I.getArraySize());
4446 
4447   EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace());
4448   if (AllocSize.getValueType() != IntPtr)
4449     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4450 
4451   if (TySize.isScalable())
4452     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4453                             DAG.getVScale(dl, IntPtr,
4454                                           APInt(IntPtr.getScalarSizeInBits(),
4455                                                 TySize.getKnownMinValue())));
4456   else {
4457     SDValue TySizeValue =
4458         DAG.getConstant(TySize.getFixedValue(), dl, MVT::getIntegerVT(64));
4459     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4460                             DAG.getZExtOrTrunc(TySizeValue, dl, IntPtr));
4461   }
4462 
4463   // Handle alignment.  If the requested alignment is less than or equal to
4464   // the stack alignment, ignore it.  If the size is greater than or equal to
4465   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4466   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4467   if (*Alignment <= StackAlign)
4468     Alignment = std::nullopt;
4469 
4470   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4471   // Round the size of the allocation up to the stack alignment size
4472   // by add SA-1 to the size. This doesn't overflow because we're computing
4473   // an address inside an alloca.
4474   SDNodeFlags Flags;
4475   Flags.setNoUnsignedWrap(true);
4476   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4477                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4478 
4479   // Mask out the low bits for alignment purposes.
4480   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4481                           DAG.getSignedConstant(~StackAlignMask, dl, IntPtr));
4482 
4483   SDValue Ops[] = {
4484       getRoot(), AllocSize,
4485       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4486   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4487   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4488   setValue(&I, DSA);
4489   DAG.setRoot(DSA.getValue(1));
4490 
4491   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4492 }
4493 
4494 static const MDNode *getRangeMetadata(const Instruction &I) {
4495   // If !noundef is not present, then !range violation results in a poison
4496   // value rather than immediate undefined behavior. In theory, transferring
4497   // these annotations to SDAG is fine, but in practice there are key SDAG
4498   // transforms that are known not to be poison-safe, such as folding logical
4499   // and/or to bitwise and/or. For now, only transfer !range if !noundef is
4500   // also present.
4501   if (!I.hasMetadata(LLVMContext::MD_noundef))
4502     return nullptr;
4503   return I.getMetadata(LLVMContext::MD_range);
4504 }
4505 
4506 static std::optional<ConstantRange> getRange(const Instruction &I) {
4507   if (const auto *CB = dyn_cast<CallBase>(&I)) {
4508     // see comment in getRangeMetadata about this check
4509     if (CB->hasRetAttr(Attribute::NoUndef))
4510       return CB->getRange();
4511   }
4512   if (const MDNode *Range = getRangeMetadata(I))
4513     return getConstantRangeFromMetadata(*Range);
4514   return std::nullopt;
4515 }
4516 
4517 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4518   if (I.isAtomic())
4519     return visitAtomicLoad(I);
4520 
4521   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4522   const Value *SV = I.getOperand(0);
4523   if (TLI.supportSwiftError()) {
4524     // Swifterror values can come from either a function parameter with
4525     // swifterror attribute or an alloca with swifterror attribute.
4526     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4527       if (Arg->hasSwiftErrorAttr())
4528         return visitLoadFromSwiftError(I);
4529     }
4530 
4531     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4532       if (Alloca->isSwiftError())
4533         return visitLoadFromSwiftError(I);
4534     }
4535   }
4536 
4537   SDValue Ptr = getValue(SV);
4538 
4539   Type *Ty = I.getType();
4540   SmallVector<EVT, 4> ValueVTs, MemVTs;
4541   SmallVector<TypeSize, 4> Offsets;
4542   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4543   unsigned NumValues = ValueVTs.size();
4544   if (NumValues == 0)
4545     return;
4546 
4547   Align Alignment = I.getAlign();
4548   AAMDNodes AAInfo = I.getAAMetadata();
4549   const MDNode *Ranges = getRangeMetadata(I);
4550   bool isVolatile = I.isVolatile();
4551   MachineMemOperand::Flags MMOFlags =
4552       TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4553 
4554   SDValue Root;
4555   bool ConstantMemory = false;
4556   if (isVolatile)
4557     // Serialize volatile loads with other side effects.
4558     Root = getRoot();
4559   else if (NumValues > MaxParallelChains)
4560     Root = getMemoryRoot();
4561   else if (AA &&
4562            AA->pointsToConstantMemory(MemoryLocation(
4563                SV,
4564                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4565                AAInfo))) {
4566     // Do not serialize (non-volatile) loads of constant memory with anything.
4567     Root = DAG.getEntryNode();
4568     ConstantMemory = true;
4569     MMOFlags |= MachineMemOperand::MOInvariant;
4570   } else {
4571     // Do not serialize non-volatile loads against each other.
4572     Root = DAG.getRoot();
4573   }
4574 
4575   SDLoc dl = getCurSDLoc();
4576 
4577   if (isVolatile)
4578     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4579 
4580   SmallVector<SDValue, 4> Values(NumValues);
4581   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4582 
4583   unsigned ChainI = 0;
4584   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4585     // Serializing loads here may result in excessive register pressure, and
4586     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4587     // could recover a bit by hoisting nodes upward in the chain by recognizing
4588     // they are side-effect free or do not alias. The optimizer should really
4589     // avoid this case by converting large object/array copies to llvm.memcpy
4590     // (MaxParallelChains should always remain as failsafe).
4591     if (ChainI == MaxParallelChains) {
4592       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4593       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4594                                   ArrayRef(Chains.data(), ChainI));
4595       Root = Chain;
4596       ChainI = 0;
4597     }
4598 
4599     // TODO: MachinePointerInfo only supports a fixed length offset.
4600     MachinePointerInfo PtrInfo =
4601         !Offsets[i].isScalable() || Offsets[i].isZero()
4602             ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue())
4603             : MachinePointerInfo();
4604 
4605     SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4606     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment,
4607                             MMOFlags, AAInfo, Ranges);
4608     Chains[ChainI] = L.getValue(1);
4609 
4610     if (MemVTs[i] != ValueVTs[i])
4611       L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]);
4612 
4613     Values[i] = L;
4614   }
4615 
4616   if (!ConstantMemory) {
4617     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4618                                 ArrayRef(Chains.data(), ChainI));
4619     if (isVolatile)
4620       DAG.setRoot(Chain);
4621     else
4622       PendingLoads.push_back(Chain);
4623   }
4624 
4625   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4626                            DAG.getVTList(ValueVTs), Values));
4627 }
4628 
4629 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4630   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4631          "call visitStoreToSwiftError when backend supports swifterror");
4632 
4633   SmallVector<EVT, 4> ValueVTs;
4634   SmallVector<uint64_t, 4> Offsets;
4635   const Value *SrcV = I.getOperand(0);
4636   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4637                   SrcV->getType(), ValueVTs, &Offsets, 0);
4638   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4639          "expect a single EVT for swifterror");
4640 
4641   SDValue Src = getValue(SrcV);
4642   // Create a virtual register, then update the virtual register.
4643   Register VReg =
4644       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4645   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4646   // Chain can be getRoot or getControlRoot.
4647   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4648                                       SDValue(Src.getNode(), Src.getResNo()));
4649   DAG.setRoot(CopyNode);
4650 }
4651 
4652 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4653   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4654          "call visitLoadFromSwiftError when backend supports swifterror");
4655 
4656   assert(!I.isVolatile() &&
4657          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4658          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4659          "Support volatile, non temporal, invariant for load_from_swift_error");
4660 
4661   const Value *SV = I.getOperand(0);
4662   Type *Ty = I.getType();
4663   assert(
4664       (!AA ||
4665        !AA->pointsToConstantMemory(MemoryLocation(
4666            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4667            I.getAAMetadata()))) &&
4668       "load_from_swift_error should not be constant memory");
4669 
4670   SmallVector<EVT, 4> ValueVTs;
4671   SmallVector<uint64_t, 4> Offsets;
4672   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4673                   ValueVTs, &Offsets, 0);
4674   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4675          "expect a single EVT for swifterror");
4676 
4677   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4678   SDValue L = DAG.getCopyFromReg(
4679       getRoot(), getCurSDLoc(),
4680       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4681 
4682   setValue(&I, L);
4683 }
4684 
4685 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4686   if (I.isAtomic())
4687     return visitAtomicStore(I);
4688 
4689   const Value *SrcV = I.getOperand(0);
4690   const Value *PtrV = I.getOperand(1);
4691 
4692   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4693   if (TLI.supportSwiftError()) {
4694     // Swifterror values can come from either a function parameter with
4695     // swifterror attribute or an alloca with swifterror attribute.
4696     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4697       if (Arg->hasSwiftErrorAttr())
4698         return visitStoreToSwiftError(I);
4699     }
4700 
4701     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4702       if (Alloca->isSwiftError())
4703         return visitStoreToSwiftError(I);
4704     }
4705   }
4706 
4707   SmallVector<EVT, 4> ValueVTs, MemVTs;
4708   SmallVector<TypeSize, 4> Offsets;
4709   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4710                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4711   unsigned NumValues = ValueVTs.size();
4712   if (NumValues == 0)
4713     return;
4714 
4715   // Get the lowered operands. Note that we do this after
4716   // checking if NumResults is zero, because with zero results
4717   // the operands won't have values in the map.
4718   SDValue Src = getValue(SrcV);
4719   SDValue Ptr = getValue(PtrV);
4720 
4721   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4722   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4723   SDLoc dl = getCurSDLoc();
4724   Align Alignment = I.getAlign();
4725   AAMDNodes AAInfo = I.getAAMetadata();
4726 
4727   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4728 
4729   unsigned ChainI = 0;
4730   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4731     // See visitLoad comments.
4732     if (ChainI == MaxParallelChains) {
4733       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4734                                   ArrayRef(Chains.data(), ChainI));
4735       Root = Chain;
4736       ChainI = 0;
4737     }
4738 
4739     // TODO: MachinePointerInfo only supports a fixed length offset.
4740     MachinePointerInfo PtrInfo =
4741         !Offsets[i].isScalable() || Offsets[i].isZero()
4742             ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue())
4743             : MachinePointerInfo();
4744 
4745     SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4746     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4747     if (MemVTs[i] != ValueVTs[i])
4748       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4749     SDValue St =
4750         DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags, AAInfo);
4751     Chains[ChainI] = St;
4752   }
4753 
4754   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4755                                   ArrayRef(Chains.data(), ChainI));
4756   setValue(&I, StoreNode);
4757   DAG.setRoot(StoreNode);
4758 }
4759 
4760 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4761                                            bool IsCompressing) {
4762   SDLoc sdl = getCurSDLoc();
4763 
4764   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4765                                Align &Alignment) {
4766     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4767     Src0 = I.getArgOperand(0);
4768     Ptr = I.getArgOperand(1);
4769     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getAlignValue();
4770     Mask = I.getArgOperand(3);
4771   };
4772   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4773                                     Align &Alignment) {
4774     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4775     Src0 = I.getArgOperand(0);
4776     Ptr = I.getArgOperand(1);
4777     Mask = I.getArgOperand(2);
4778     Alignment = I.getParamAlign(1).valueOrOne();
4779   };
4780 
4781   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4782   Align Alignment;
4783   if (IsCompressing)
4784     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4785   else
4786     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4787 
4788   SDValue Ptr = getValue(PtrOperand);
4789   SDValue Src0 = getValue(Src0Operand);
4790   SDValue Mask = getValue(MaskOperand);
4791   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4792 
4793   EVT VT = Src0.getValueType();
4794 
4795   auto MMOFlags = MachineMemOperand::MOStore;
4796   if (I.hasMetadata(LLVMContext::MD_nontemporal))
4797     MMOFlags |= MachineMemOperand::MONonTemporal;
4798 
4799   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4800       MachinePointerInfo(PtrOperand), MMOFlags,
4801       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata());
4802 
4803   const auto &TLI = DAG.getTargetLoweringInfo();
4804   const auto &TTI =
4805       TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction());
4806   SDValue StoreNode =
4807       !IsCompressing &&
4808               TTI.hasConditionalLoadStoreForType(I.getArgOperand(0)->getType())
4809           ? TLI.visitMaskedStore(DAG, sdl, getMemoryRoot(), MMO, Ptr, Src0,
4810                                  Mask)
4811           : DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask,
4812                                VT, MMO, ISD::UNINDEXED, /*Truncating=*/false,
4813                                IsCompressing);
4814   DAG.setRoot(StoreNode);
4815   setValue(&I, StoreNode);
4816 }
4817 
4818 // Get a uniform base for the Gather/Scatter intrinsic.
4819 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4820 // We try to represent it as a base pointer + vector of indices.
4821 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4822 // The first operand of the GEP may be a single pointer or a vector of pointers
4823 // Example:
4824 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4825 //  or
4826 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4827 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4828 //
4829 // When the first GEP operand is a single pointer - it is the uniform base we
4830 // are looking for. If first operand of the GEP is a splat vector - we
4831 // extract the splat value and use it as a uniform base.
4832 // In all other cases the function returns 'false'.
4833 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4834                            ISD::MemIndexType &IndexType, SDValue &Scale,
4835                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB,
4836                            uint64_t ElemSize) {
4837   SelectionDAG& DAG = SDB->DAG;
4838   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4839   const DataLayout &DL = DAG.getDataLayout();
4840 
4841   assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4842 
4843   // Handle splat constant pointer.
4844   if (auto *C = dyn_cast<Constant>(Ptr)) {
4845     C = C->getSplatValue();
4846     if (!C)
4847       return false;
4848 
4849     Base = SDB->getValue(C);
4850 
4851     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4852     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4853     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4854     IndexType = ISD::SIGNED_SCALED;
4855     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4856     return true;
4857   }
4858 
4859   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4860   if (!GEP || GEP->getParent() != CurBB)
4861     return false;
4862 
4863   if (GEP->getNumOperands() != 2)
4864     return false;
4865 
4866   const Value *BasePtr = GEP->getPointerOperand();
4867   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4868 
4869   // Make sure the base is scalar and the index is a vector.
4870   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4871     return false;
4872 
4873   TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
4874   if (ScaleVal.isScalable())
4875     return false;
4876 
4877   // Target may not support the required addressing mode.
4878   if (ScaleVal != 1 &&
4879       !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize))
4880     return false;
4881 
4882   Base = SDB->getValue(BasePtr);
4883   Index = SDB->getValue(IndexVal);
4884   IndexType = ISD::SIGNED_SCALED;
4885 
4886   Scale =
4887       DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4888   return true;
4889 }
4890 
4891 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4892   SDLoc sdl = getCurSDLoc();
4893 
4894   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4895   const Value *Ptr = I.getArgOperand(1);
4896   SDValue Src0 = getValue(I.getArgOperand(0));
4897   SDValue Mask = getValue(I.getArgOperand(3));
4898   EVT VT = Src0.getValueType();
4899   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4900                         ->getMaybeAlignValue()
4901                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4902   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4903 
4904   SDValue Base;
4905   SDValue Index;
4906   ISD::MemIndexType IndexType;
4907   SDValue Scale;
4908   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4909                                     I.getParent(), VT.getScalarStoreSize());
4910 
4911   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4912   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4913       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4914       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata());
4915   if (!UniformBase) {
4916     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4917     Index = getValue(Ptr);
4918     IndexType = ISD::SIGNED_SCALED;
4919     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4920   }
4921 
4922   EVT IdxVT = Index.getValueType();
4923   EVT EltTy = IdxVT.getVectorElementType();
4924   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4925     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4926     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4927   }
4928 
4929   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4930   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4931                                          Ops, MMO, IndexType, false);
4932   DAG.setRoot(Scatter);
4933   setValue(&I, Scatter);
4934 }
4935 
4936 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4937   SDLoc sdl = getCurSDLoc();
4938 
4939   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4940                               Align &Alignment) {
4941     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4942     Ptr = I.getArgOperand(0);
4943     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getAlignValue();
4944     Mask = I.getArgOperand(2);
4945     Src0 = I.getArgOperand(3);
4946   };
4947   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4948                                  Align &Alignment) {
4949     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4950     Ptr = I.getArgOperand(0);
4951     Alignment = I.getParamAlign(0).valueOrOne();
4952     Mask = I.getArgOperand(1);
4953     Src0 = I.getArgOperand(2);
4954   };
4955 
4956   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4957   Align Alignment;
4958   if (IsExpanding)
4959     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4960   else
4961     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4962 
4963   SDValue Ptr = getValue(PtrOperand);
4964   SDValue Src0 = getValue(Src0Operand);
4965   SDValue Mask = getValue(MaskOperand);
4966   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4967 
4968   EVT VT = Src0.getValueType();
4969   AAMDNodes AAInfo = I.getAAMetadata();
4970   const MDNode *Ranges = getRangeMetadata(I);
4971 
4972   // Do not serialize masked loads of constant memory with anything.
4973   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
4974   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4975 
4976   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4977 
4978   auto MMOFlags = MachineMemOperand::MOLoad;
4979   if (I.hasMetadata(LLVMContext::MD_nontemporal))
4980     MMOFlags |= MachineMemOperand::MONonTemporal;
4981 
4982   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4983       MachinePointerInfo(PtrOperand), MMOFlags,
4984       LocationSize::beforeOrAfterPointer(), Alignment, AAInfo, Ranges);
4985 
4986   const auto &TLI = DAG.getTargetLoweringInfo();
4987   const auto &TTI =
4988       TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction());
4989   // The Load/Res may point to different values and both of them are output
4990   // variables.
4991   SDValue Load;
4992   SDValue Res;
4993   if (!IsExpanding &&
4994       TTI.hasConditionalLoadStoreForType(Src0Operand->getType()))
4995     Res = TLI.visitMaskedLoad(DAG, sdl, InChain, MMO, Load, Ptr, Src0, Mask);
4996   else
4997     Res = Load =
4998         DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4999                           ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
5000   if (AddToChain)
5001     PendingLoads.push_back(Load.getValue(1));
5002   setValue(&I, Res);
5003 }
5004 
5005 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
5006   SDLoc sdl = getCurSDLoc();
5007 
5008   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
5009   const Value *Ptr = I.getArgOperand(0);
5010   SDValue Src0 = getValue(I.getArgOperand(3));
5011   SDValue Mask = getValue(I.getArgOperand(2));
5012 
5013   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5014   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5015   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
5016                         ->getMaybeAlignValue()
5017                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
5018 
5019   const MDNode *Ranges = getRangeMetadata(I);
5020 
5021   SDValue Root = DAG.getRoot();
5022   SDValue Base;
5023   SDValue Index;
5024   ISD::MemIndexType IndexType;
5025   SDValue Scale;
5026   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
5027                                     I.getParent(), VT.getScalarStoreSize());
5028   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
5029   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5030       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
5031       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata(),
5032       Ranges);
5033 
5034   if (!UniformBase) {
5035     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5036     Index = getValue(Ptr);
5037     IndexType = ISD::SIGNED_SCALED;
5038     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5039   }
5040 
5041   EVT IdxVT = Index.getValueType();
5042   EVT EltTy = IdxVT.getVectorElementType();
5043   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
5044     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
5045     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
5046   }
5047 
5048   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
5049   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
5050                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
5051 
5052   PendingLoads.push_back(Gather.getValue(1));
5053   setValue(&I, Gather);
5054 }
5055 
5056 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
5057   SDLoc dl = getCurSDLoc();
5058   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
5059   AtomicOrdering FailureOrdering = I.getFailureOrdering();
5060   SyncScope::ID SSID = I.getSyncScopeID();
5061 
5062   SDValue InChain = getRoot();
5063 
5064   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
5065   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
5066 
5067   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5068   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5069 
5070   MachineFunction &MF = DAG.getMachineFunction();
5071   MachineMemOperand *MMO = MF.getMachineMemOperand(
5072       MachinePointerInfo(I.getPointerOperand()), Flags,
5073       LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT),
5074       AAMDNodes(), nullptr, SSID, SuccessOrdering, FailureOrdering);
5075 
5076   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
5077                                    dl, MemVT, VTs, InChain,
5078                                    getValue(I.getPointerOperand()),
5079                                    getValue(I.getCompareOperand()),
5080                                    getValue(I.getNewValOperand()), MMO);
5081 
5082   SDValue OutChain = L.getValue(2);
5083 
5084   setValue(&I, L);
5085   DAG.setRoot(OutChain);
5086 }
5087 
5088 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
5089   SDLoc dl = getCurSDLoc();
5090   ISD::NodeType NT;
5091   switch (I.getOperation()) {
5092   default: llvm_unreachable("Unknown atomicrmw operation");
5093   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
5094   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
5095   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
5096   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
5097   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
5098   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
5099   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
5100   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
5101   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
5102   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
5103   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
5104   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
5105   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
5106   case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break;
5107   case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break;
5108   case AtomicRMWInst::UIncWrap:
5109     NT = ISD::ATOMIC_LOAD_UINC_WRAP;
5110     break;
5111   case AtomicRMWInst::UDecWrap:
5112     NT = ISD::ATOMIC_LOAD_UDEC_WRAP;
5113     break;
5114   case AtomicRMWInst::USubCond:
5115     NT = ISD::ATOMIC_LOAD_USUB_COND;
5116     break;
5117   case AtomicRMWInst::USubSat:
5118     NT = ISD::ATOMIC_LOAD_USUB_SAT;
5119     break;
5120   }
5121   AtomicOrdering Ordering = I.getOrdering();
5122   SyncScope::ID SSID = I.getSyncScopeID();
5123 
5124   SDValue InChain = getRoot();
5125 
5126   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
5127   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5128   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5129 
5130   MachineFunction &MF = DAG.getMachineFunction();
5131   MachineMemOperand *MMO = MF.getMachineMemOperand(
5132       MachinePointerInfo(I.getPointerOperand()), Flags,
5133       LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT),
5134       AAMDNodes(), nullptr, SSID, Ordering);
5135 
5136   SDValue L =
5137     DAG.getAtomic(NT, dl, MemVT, InChain,
5138                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
5139                   MMO);
5140 
5141   SDValue OutChain = L.getValue(1);
5142 
5143   setValue(&I, L);
5144   DAG.setRoot(OutChain);
5145 }
5146 
5147 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
5148   SDLoc dl = getCurSDLoc();
5149   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5150   SDValue Ops[3];
5151   Ops[0] = getRoot();
5152   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
5153                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
5154   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
5155                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
5156   SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
5157   setValue(&I, N);
5158   DAG.setRoot(N);
5159 }
5160 
5161 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
5162   SDLoc dl = getCurSDLoc();
5163   AtomicOrdering Order = I.getOrdering();
5164   SyncScope::ID SSID = I.getSyncScopeID();
5165 
5166   SDValue InChain = getRoot();
5167 
5168   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5169   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5170   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
5171 
5172   if (!TLI.supportsUnalignedAtomics() &&
5173       I.getAlign().value() < MemVT.getSizeInBits() / 8)
5174     report_fatal_error("Cannot generate unaligned atomic load");
5175 
5176   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
5177 
5178   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5179       MachinePointerInfo(I.getPointerOperand()), Flags,
5180       LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(),
5181       nullptr, SSID, Order);
5182 
5183   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
5184 
5185   SDValue Ptr = getValue(I.getPointerOperand());
5186   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
5187                             Ptr, MMO);
5188 
5189   SDValue OutChain = L.getValue(1);
5190   if (MemVT != VT)
5191     L = DAG.getPtrExtOrTrunc(L, dl, VT);
5192 
5193   setValue(&I, L);
5194   DAG.setRoot(OutChain);
5195 }
5196 
5197 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
5198   SDLoc dl = getCurSDLoc();
5199 
5200   AtomicOrdering Ordering = I.getOrdering();
5201   SyncScope::ID SSID = I.getSyncScopeID();
5202 
5203   SDValue InChain = getRoot();
5204 
5205   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5206   EVT MemVT =
5207       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
5208 
5209   if (!TLI.supportsUnalignedAtomics() &&
5210       I.getAlign().value() < MemVT.getSizeInBits() / 8)
5211     report_fatal_error("Cannot generate unaligned atomic store");
5212 
5213   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
5214 
5215   MachineFunction &MF = DAG.getMachineFunction();
5216   MachineMemOperand *MMO = MF.getMachineMemOperand(
5217       MachinePointerInfo(I.getPointerOperand()), Flags,
5218       LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(),
5219       nullptr, SSID, Ordering);
5220 
5221   SDValue Val = getValue(I.getValueOperand());
5222   if (Val.getValueType() != MemVT)
5223     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
5224   SDValue Ptr = getValue(I.getPointerOperand());
5225 
5226   SDValue OutChain =
5227       DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO);
5228 
5229   setValue(&I, OutChain);
5230   DAG.setRoot(OutChain);
5231 }
5232 
5233 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
5234 /// node.
5235 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
5236                                                unsigned Intrinsic) {
5237   // Ignore the callsite's attributes. A specific call site may be marked with
5238   // readnone, but the lowering code will expect the chain based on the
5239   // definition.
5240   const Function *F = I.getCalledFunction();
5241   bool HasChain = !F->doesNotAccessMemory();
5242   bool OnlyLoad =
5243       HasChain && F->onlyReadsMemory() && F->willReturn() && F->doesNotThrow();
5244 
5245   // Build the operand list.
5246   SmallVector<SDValue, 8> Ops;
5247   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
5248     if (OnlyLoad) {
5249       // We don't need to serialize loads against other loads.
5250       Ops.push_back(DAG.getRoot());
5251     } else {
5252       Ops.push_back(getRoot());
5253     }
5254   }
5255 
5256   // Info is set by getTgtMemIntrinsic
5257   TargetLowering::IntrinsicInfo Info;
5258   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5259   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
5260                                                DAG.getMachineFunction(),
5261                                                Intrinsic);
5262 
5263   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
5264   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
5265       Info.opc == ISD::INTRINSIC_W_CHAIN)
5266     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
5267                                         TLI.getPointerTy(DAG.getDataLayout())));
5268 
5269   // Add all operands of the call to the operand list.
5270   for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
5271     const Value *Arg = I.getArgOperand(i);
5272     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
5273       Ops.push_back(getValue(Arg));
5274       continue;
5275     }
5276 
5277     // Use TargetConstant instead of a regular constant for immarg.
5278     EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
5279     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
5280       assert(CI->getBitWidth() <= 64 &&
5281              "large intrinsic immediates not handled");
5282       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
5283     } else {
5284       Ops.push_back(
5285           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
5286     }
5287   }
5288 
5289   SmallVector<EVT, 4> ValueVTs;
5290   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
5291 
5292   if (HasChain)
5293     ValueVTs.push_back(MVT::Other);
5294 
5295   SDVTList VTs = DAG.getVTList(ValueVTs);
5296 
5297   // Propagate fast-math-flags from IR to node(s).
5298   SDNodeFlags Flags;
5299   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
5300     Flags.copyFMF(*FPMO);
5301   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
5302 
5303   // Create the node.
5304   SDValue Result;
5305 
5306   if (auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl)) {
5307     auto *Token = Bundle->Inputs[0].get();
5308     SDValue ConvControlToken = getValue(Token);
5309     assert(Ops.back().getValueType() != MVT::Glue &&
5310            "Did not expected another glue node here.");
5311     ConvControlToken =
5312         DAG.getNode(ISD::CONVERGENCECTRL_GLUE, {}, MVT::Glue, ConvControlToken);
5313     Ops.push_back(ConvControlToken);
5314   }
5315 
5316   // In some cases, custom collection of operands from CallInst I may be needed.
5317   TLI.CollectTargetIntrinsicOperands(I, Ops, DAG);
5318   if (IsTgtIntrinsic) {
5319     // This is target intrinsic that touches memory
5320     //
5321     // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic
5322     //       didn't yield anything useful.
5323     MachinePointerInfo MPI;
5324     if (Info.ptrVal)
5325       MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
5326     else if (Info.fallbackAddressSpace)
5327       MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
5328     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops,
5329                                      Info.memVT, MPI, Info.align, Info.flags,
5330                                      Info.size, I.getAAMetadata());
5331   } else if (!HasChain) {
5332     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
5333   } else if (!I.getType()->isVoidTy()) {
5334     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
5335   } else {
5336     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
5337   }
5338 
5339   if (HasChain) {
5340     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
5341     if (OnlyLoad)
5342       PendingLoads.push_back(Chain);
5343     else
5344       DAG.setRoot(Chain);
5345   }
5346 
5347   if (!I.getType()->isVoidTy()) {
5348     if (!isa<VectorType>(I.getType()))
5349       Result = lowerRangeToAssertZExt(DAG, I, Result);
5350 
5351     MaybeAlign Alignment = I.getRetAlign();
5352 
5353     // Insert `assertalign` node if there's an alignment.
5354     if (InsertAssertAlign && Alignment) {
5355       Result =
5356           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
5357     }
5358   }
5359 
5360   setValue(&I, Result);
5361 }
5362 
5363 /// GetSignificand - Get the significand and build it into a floating-point
5364 /// number with exponent of 1:
5365 ///
5366 ///   Op = (Op & 0x007fffff) | 0x3f800000;
5367 ///
5368 /// where Op is the hexadecimal representation of floating point value.
5369 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
5370   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5371                            DAG.getConstant(0x007fffff, dl, MVT::i32));
5372   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
5373                            DAG.getConstant(0x3f800000, dl, MVT::i32));
5374   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
5375 }
5376 
5377 /// GetExponent - Get the exponent:
5378 ///
5379 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
5380 ///
5381 /// where Op is the hexadecimal representation of floating point value.
5382 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
5383                            const TargetLowering &TLI, const SDLoc &dl) {
5384   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5385                            DAG.getConstant(0x7f800000, dl, MVT::i32));
5386   SDValue t1 = DAG.getNode(
5387       ISD::SRL, dl, MVT::i32, t0,
5388       DAG.getConstant(23, dl,
5389                       TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout())));
5390   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
5391                            DAG.getConstant(127, dl, MVT::i32));
5392   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
5393 }
5394 
5395 /// getF32Constant - Get 32-bit floating point constant.
5396 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
5397                               const SDLoc &dl) {
5398   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
5399                            MVT::f32);
5400 }
5401 
5402 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
5403                                        SelectionDAG &DAG) {
5404   // TODO: What fast-math-flags should be set on the floating-point nodes?
5405 
5406   //   IntegerPartOfX = ((int32_t)(t0);
5407   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
5408 
5409   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
5410   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
5411   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
5412 
5413   //   IntegerPartOfX <<= 23;
5414   IntegerPartOfX =
5415       DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
5416                   DAG.getConstant(23, dl,
5417                                   DAG.getTargetLoweringInfo().getShiftAmountTy(
5418                                       MVT::i32, DAG.getDataLayout())));
5419 
5420   SDValue TwoToFractionalPartOfX;
5421   if (LimitFloatPrecision <= 6) {
5422     // For floating-point precision of 6:
5423     //
5424     //   TwoToFractionalPartOfX =
5425     //     0.997535578f +
5426     //       (0.735607626f + 0.252464424f * x) * x;
5427     //
5428     // error 0.0144103317, which is 6 bits
5429     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5430                              getF32Constant(DAG, 0x3e814304, dl));
5431     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5432                              getF32Constant(DAG, 0x3f3c50c8, dl));
5433     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5434     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5435                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
5436   } else if (LimitFloatPrecision <= 12) {
5437     // For floating-point precision of 12:
5438     //
5439     //   TwoToFractionalPartOfX =
5440     //     0.999892986f +
5441     //       (0.696457318f +
5442     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
5443     //
5444     // error 0.000107046256, which is 13 to 14 bits
5445     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5446                              getF32Constant(DAG, 0x3da235e3, dl));
5447     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5448                              getF32Constant(DAG, 0x3e65b8f3, dl));
5449     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5450     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5451                              getF32Constant(DAG, 0x3f324b07, dl));
5452     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5453     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5454                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
5455   } else { // LimitFloatPrecision <= 18
5456     // For floating-point precision of 18:
5457     //
5458     //   TwoToFractionalPartOfX =
5459     //     0.999999982f +
5460     //       (0.693148872f +
5461     //         (0.240227044f +
5462     //           (0.554906021e-1f +
5463     //             (0.961591928e-2f +
5464     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5465     // error 2.47208000*10^(-7), which is better than 18 bits
5466     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5467                              getF32Constant(DAG, 0x3924b03e, dl));
5468     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5469                              getF32Constant(DAG, 0x3ab24b87, dl));
5470     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5471     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5472                              getF32Constant(DAG, 0x3c1d8c17, dl));
5473     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5474     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5475                              getF32Constant(DAG, 0x3d634a1d, dl));
5476     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5477     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5478                              getF32Constant(DAG, 0x3e75fe14, dl));
5479     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5480     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5481                               getF32Constant(DAG, 0x3f317234, dl));
5482     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5483     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5484                                          getF32Constant(DAG, 0x3f800000, dl));
5485   }
5486 
5487   // Add the exponent into the result in integer domain.
5488   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5489   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5490                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5491 }
5492 
5493 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5494 /// limited-precision mode.
5495 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5496                          const TargetLowering &TLI, SDNodeFlags Flags) {
5497   if (Op.getValueType() == MVT::f32 &&
5498       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5499 
5500     // Put the exponent in the right bit position for later addition to the
5501     // final result:
5502     //
5503     // t0 = Op * log2(e)
5504 
5505     // TODO: What fast-math-flags should be set here?
5506     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5507                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5508     return getLimitedPrecisionExp2(t0, dl, DAG);
5509   }
5510 
5511   // No special expansion.
5512   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5513 }
5514 
5515 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5516 /// limited-precision mode.
5517 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5518                          const TargetLowering &TLI, SDNodeFlags Flags) {
5519   // TODO: What fast-math-flags should be set on the floating-point nodes?
5520 
5521   if (Op.getValueType() == MVT::f32 &&
5522       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5523     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5524 
5525     // Scale the exponent by log(2).
5526     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5527     SDValue LogOfExponent =
5528         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5529                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5530 
5531     // Get the significand and build it into a floating-point number with
5532     // exponent of 1.
5533     SDValue X = GetSignificand(DAG, Op1, dl);
5534 
5535     SDValue LogOfMantissa;
5536     if (LimitFloatPrecision <= 6) {
5537       // For floating-point precision of 6:
5538       //
5539       //   LogofMantissa =
5540       //     -1.1609546f +
5541       //       (1.4034025f - 0.23903021f * x) * x;
5542       //
5543       // error 0.0034276066, which is better than 8 bits
5544       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5545                                getF32Constant(DAG, 0xbe74c456, dl));
5546       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5547                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5548       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5549       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5550                                   getF32Constant(DAG, 0x3f949a29, dl));
5551     } else if (LimitFloatPrecision <= 12) {
5552       // For floating-point precision of 12:
5553       //
5554       //   LogOfMantissa =
5555       //     -1.7417939f +
5556       //       (2.8212026f +
5557       //         (-1.4699568f +
5558       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5559       //
5560       // error 0.000061011436, which is 14 bits
5561       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5562                                getF32Constant(DAG, 0xbd67b6d6, dl));
5563       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5564                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5565       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5566       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5567                                getF32Constant(DAG, 0x3fbc278b, dl));
5568       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5569       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5570                                getF32Constant(DAG, 0x40348e95, dl));
5571       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5572       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5573                                   getF32Constant(DAG, 0x3fdef31a, dl));
5574     } else { // LimitFloatPrecision <= 18
5575       // For floating-point precision of 18:
5576       //
5577       //   LogOfMantissa =
5578       //     -2.1072184f +
5579       //       (4.2372794f +
5580       //         (-3.7029485f +
5581       //           (2.2781945f +
5582       //             (-0.87823314f +
5583       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5584       //
5585       // error 0.0000023660568, which is better than 18 bits
5586       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5587                                getF32Constant(DAG, 0xbc91e5ac, dl));
5588       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5589                                getF32Constant(DAG, 0x3e4350aa, dl));
5590       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5591       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5592                                getF32Constant(DAG, 0x3f60d3e3, dl));
5593       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5594       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5595                                getF32Constant(DAG, 0x4011cdf0, dl));
5596       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5597       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5598                                getF32Constant(DAG, 0x406cfd1c, dl));
5599       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5600       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5601                                getF32Constant(DAG, 0x408797cb, dl));
5602       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5603       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5604                                   getF32Constant(DAG, 0x4006dcab, dl));
5605     }
5606 
5607     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5608   }
5609 
5610   // No special expansion.
5611   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5612 }
5613 
5614 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5615 /// limited-precision mode.
5616 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5617                           const TargetLowering &TLI, SDNodeFlags Flags) {
5618   // TODO: What fast-math-flags should be set on the floating-point nodes?
5619 
5620   if (Op.getValueType() == MVT::f32 &&
5621       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5622     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5623 
5624     // Get the exponent.
5625     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5626 
5627     // Get the significand and build it into a floating-point number with
5628     // exponent of 1.
5629     SDValue X = GetSignificand(DAG, Op1, dl);
5630 
5631     // Different possible minimax approximations of significand in
5632     // floating-point for various degrees of accuracy over [1,2].
5633     SDValue Log2ofMantissa;
5634     if (LimitFloatPrecision <= 6) {
5635       // For floating-point precision of 6:
5636       //
5637       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5638       //
5639       // error 0.0049451742, which is more than 7 bits
5640       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5641                                getF32Constant(DAG, 0xbeb08fe0, dl));
5642       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5643                                getF32Constant(DAG, 0x40019463, dl));
5644       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5645       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5646                                    getF32Constant(DAG, 0x3fd6633d, dl));
5647     } else if (LimitFloatPrecision <= 12) {
5648       // For floating-point precision of 12:
5649       //
5650       //   Log2ofMantissa =
5651       //     -2.51285454f +
5652       //       (4.07009056f +
5653       //         (-2.12067489f +
5654       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5655       //
5656       // error 0.0000876136000, which is better than 13 bits
5657       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5658                                getF32Constant(DAG, 0xbda7262e, dl));
5659       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5660                                getF32Constant(DAG, 0x3f25280b, dl));
5661       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5662       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5663                                getF32Constant(DAG, 0x4007b923, dl));
5664       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5665       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5666                                getF32Constant(DAG, 0x40823e2f, dl));
5667       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5668       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5669                                    getF32Constant(DAG, 0x4020d29c, dl));
5670     } else { // LimitFloatPrecision <= 18
5671       // For floating-point precision of 18:
5672       //
5673       //   Log2ofMantissa =
5674       //     -3.0400495f +
5675       //       (6.1129976f +
5676       //         (-5.3420409f +
5677       //           (3.2865683f +
5678       //             (-1.2669343f +
5679       //               (0.27515199f -
5680       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5681       //
5682       // error 0.0000018516, which is better than 18 bits
5683       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5684                                getF32Constant(DAG, 0xbcd2769e, dl));
5685       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5686                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5687       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5688       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5689                                getF32Constant(DAG, 0x3fa22ae7, dl));
5690       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5691       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5692                                getF32Constant(DAG, 0x40525723, dl));
5693       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5694       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5695                                getF32Constant(DAG, 0x40aaf200, dl));
5696       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5697       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5698                                getF32Constant(DAG, 0x40c39dad, dl));
5699       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5700       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5701                                    getF32Constant(DAG, 0x4042902c, dl));
5702     }
5703 
5704     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5705   }
5706 
5707   // No special expansion.
5708   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5709 }
5710 
5711 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5712 /// limited-precision mode.
5713 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5714                            const TargetLowering &TLI, SDNodeFlags Flags) {
5715   // TODO: What fast-math-flags should be set on the floating-point nodes?
5716 
5717   if (Op.getValueType() == MVT::f32 &&
5718       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5719     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5720 
5721     // Scale the exponent by log10(2) [0.30102999f].
5722     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5723     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5724                                         getF32Constant(DAG, 0x3e9a209a, dl));
5725 
5726     // Get the significand and build it into a floating-point number with
5727     // exponent of 1.
5728     SDValue X = GetSignificand(DAG, Op1, dl);
5729 
5730     SDValue Log10ofMantissa;
5731     if (LimitFloatPrecision <= 6) {
5732       // For floating-point precision of 6:
5733       //
5734       //   Log10ofMantissa =
5735       //     -0.50419619f +
5736       //       (0.60948995f - 0.10380950f * x) * x;
5737       //
5738       // error 0.0014886165, which is 6 bits
5739       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5740                                getF32Constant(DAG, 0xbdd49a13, dl));
5741       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5742                                getF32Constant(DAG, 0x3f1c0789, dl));
5743       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5744       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5745                                     getF32Constant(DAG, 0x3f011300, dl));
5746     } else if (LimitFloatPrecision <= 12) {
5747       // For floating-point precision of 12:
5748       //
5749       //   Log10ofMantissa =
5750       //     -0.64831180f +
5751       //       (0.91751397f +
5752       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5753       //
5754       // error 0.00019228036, which is better than 12 bits
5755       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5756                                getF32Constant(DAG, 0x3d431f31, dl));
5757       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5758                                getF32Constant(DAG, 0x3ea21fb2, dl));
5759       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5760       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5761                                getF32Constant(DAG, 0x3f6ae232, dl));
5762       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5763       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5764                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5765     } else { // LimitFloatPrecision <= 18
5766       // For floating-point precision of 18:
5767       //
5768       //   Log10ofMantissa =
5769       //     -0.84299375f +
5770       //       (1.5327582f +
5771       //         (-1.0688956f +
5772       //           (0.49102474f +
5773       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5774       //
5775       // error 0.0000037995730, which is better than 18 bits
5776       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5777                                getF32Constant(DAG, 0x3c5d51ce, dl));
5778       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5779                                getF32Constant(DAG, 0x3e00685a, dl));
5780       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5781       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5782                                getF32Constant(DAG, 0x3efb6798, dl));
5783       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5784       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5785                                getF32Constant(DAG, 0x3f88d192, dl));
5786       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5787       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5788                                getF32Constant(DAG, 0x3fc4316c, dl));
5789       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5790       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5791                                     getF32Constant(DAG, 0x3f57ce70, dl));
5792     }
5793 
5794     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5795   }
5796 
5797   // No special expansion.
5798   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5799 }
5800 
5801 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5802 /// limited-precision mode.
5803 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5804                           const TargetLowering &TLI, SDNodeFlags Flags) {
5805   if (Op.getValueType() == MVT::f32 &&
5806       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5807     return getLimitedPrecisionExp2(Op, dl, DAG);
5808 
5809   // No special expansion.
5810   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5811 }
5812 
5813 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5814 /// limited-precision mode with x == 10.0f.
5815 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5816                          SelectionDAG &DAG, const TargetLowering &TLI,
5817                          SDNodeFlags Flags) {
5818   bool IsExp10 = false;
5819   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5820       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5821     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5822       APFloat Ten(10.0f);
5823       IsExp10 = LHSC->isExactlyValue(Ten);
5824     }
5825   }
5826 
5827   // TODO: What fast-math-flags should be set on the FMUL node?
5828   if (IsExp10) {
5829     // Put the exponent in the right bit position for later addition to the
5830     // final result:
5831     //
5832     //   #define LOG2OF10 3.3219281f
5833     //   t0 = Op * LOG2OF10;
5834     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5835                              getF32Constant(DAG, 0x40549a78, dl));
5836     return getLimitedPrecisionExp2(t0, dl, DAG);
5837   }
5838 
5839   // No special expansion.
5840   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5841 }
5842 
5843 /// ExpandPowI - Expand a llvm.powi intrinsic.
5844 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5845                           SelectionDAG &DAG) {
5846   // If RHS is a constant, we can expand this out to a multiplication tree if
5847   // it's beneficial on the target, otherwise we end up lowering to a call to
5848   // __powidf2 (for example).
5849   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5850     unsigned Val = RHSC->getSExtValue();
5851 
5852     // powi(x, 0) -> 1.0
5853     if (Val == 0)
5854       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5855 
5856     if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI(
5857             Val, DAG.shouldOptForSize())) {
5858       // Get the exponent as a positive value.
5859       if ((int)Val < 0)
5860         Val = -Val;
5861       // We use the simple binary decomposition method to generate the multiply
5862       // sequence.  There are more optimal ways to do this (for example,
5863       // powi(x,15) generates one more multiply than it should), but this has
5864       // the benefit of being both really simple and much better than a libcall.
5865       SDValue Res; // Logically starts equal to 1.0
5866       SDValue CurSquare = LHS;
5867       // TODO: Intrinsics should have fast-math-flags that propagate to these
5868       // nodes.
5869       while (Val) {
5870         if (Val & 1) {
5871           if (Res.getNode())
5872             Res =
5873                 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
5874           else
5875             Res = CurSquare; // 1.0*CurSquare.
5876         }
5877 
5878         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5879                                 CurSquare, CurSquare);
5880         Val >>= 1;
5881       }
5882 
5883       // If the original was negative, invert the result, producing 1/(x*x*x).
5884       if (RHSC->getSExtValue() < 0)
5885         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5886                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5887       return Res;
5888     }
5889   }
5890 
5891   // Otherwise, expand to a libcall.
5892   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5893 }
5894 
5895 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5896                             SDValue LHS, SDValue RHS, SDValue Scale,
5897                             SelectionDAG &DAG, const TargetLowering &TLI) {
5898   EVT VT = LHS.getValueType();
5899   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5900   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5901   LLVMContext &Ctx = *DAG.getContext();
5902 
5903   // If the type is legal but the operation isn't, this node might survive all
5904   // the way to operation legalization. If we end up there and we do not have
5905   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5906   // node.
5907 
5908   // Coax the legalizer into expanding the node during type legalization instead
5909   // by bumping the size by one bit. This will force it to Promote, enabling the
5910   // early expansion and avoiding the need to expand later.
5911 
5912   // We don't have to do this if Scale is 0; that can always be expanded, unless
5913   // it's a saturating signed operation. Those can experience true integer
5914   // division overflow, a case which we must avoid.
5915 
5916   // FIXME: We wouldn't have to do this (or any of the early
5917   // expansion/promotion) if it was possible to expand a libcall of an
5918   // illegal type during operation legalization. But it's not, so things
5919   // get a bit hacky.
5920   unsigned ScaleInt = Scale->getAsZExtVal();
5921   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5922       (TLI.isTypeLegal(VT) ||
5923        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5924     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5925         Opcode, VT, ScaleInt);
5926     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5927       EVT PromVT;
5928       if (VT.isScalarInteger())
5929         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5930       else if (VT.isVector()) {
5931         PromVT = VT.getVectorElementType();
5932         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5933         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5934       } else
5935         llvm_unreachable("Wrong VT for DIVFIX?");
5936       LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT);
5937       RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT);
5938       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5939       // For saturating operations, we need to shift up the LHS to get the
5940       // proper saturation width, and then shift down again afterwards.
5941       if (Saturating)
5942         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5943                           DAG.getConstant(1, DL, ShiftTy));
5944       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5945       if (Saturating)
5946         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5947                           DAG.getConstant(1, DL, ShiftTy));
5948       return DAG.getZExtOrTrunc(Res, DL, VT);
5949     }
5950   }
5951 
5952   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5953 }
5954 
5955 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5956 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5957 static void
5958 getUnderlyingArgRegs(SmallVectorImpl<std::pair<Register, TypeSize>> &Regs,
5959                      const SDValue &N) {
5960   switch (N.getOpcode()) {
5961   case ISD::CopyFromReg: {
5962     SDValue Op = N.getOperand(1);
5963     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5964                       Op.getValueType().getSizeInBits());
5965     return;
5966   }
5967   case ISD::BITCAST:
5968   case ISD::AssertZext:
5969   case ISD::AssertSext:
5970   case ISD::TRUNCATE:
5971     getUnderlyingArgRegs(Regs, N.getOperand(0));
5972     return;
5973   case ISD::BUILD_PAIR:
5974   case ISD::BUILD_VECTOR:
5975   case ISD::CONCAT_VECTORS:
5976     for (SDValue Op : N->op_values())
5977       getUnderlyingArgRegs(Regs, Op);
5978     return;
5979   default:
5980     return;
5981   }
5982 }
5983 
5984 /// If the DbgValueInst is a dbg_value of a function argument, create the
5985 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5986 /// instruction selection, they will be inserted to the entry BB.
5987 /// We don't currently support this for variadic dbg_values, as they shouldn't
5988 /// appear for function arguments or in the prologue.
5989 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5990     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5991     DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
5992   const Argument *Arg = dyn_cast<Argument>(V);
5993   if (!Arg)
5994     return false;
5995 
5996   MachineFunction &MF = DAG.getMachineFunction();
5997   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5998 
5999   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
6000   // we've been asked to pursue.
6001   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
6002                               bool Indirect) {
6003     if (Reg.isVirtual() && MF.useDebugInstrRef()) {
6004       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
6005       // pointing at the VReg, which will be patched up later.
6006       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
6007       SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg(
6008           /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
6009           /* isKill */ false, /* isDead */ false,
6010           /* isUndef */ false, /* isEarlyClobber */ false,
6011           /* SubReg */ 0, /* isDebug */ true)});
6012 
6013       auto *NewDIExpr = FragExpr;
6014       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
6015       // the DIExpression.
6016       if (Indirect)
6017         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
6018       SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0});
6019       NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops);
6020       return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr);
6021     } else {
6022       // Create a completely standard DBG_VALUE.
6023       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
6024       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
6025     }
6026   };
6027 
6028   if (Kind == FuncArgumentDbgValueKind::Value) {
6029     // ArgDbgValues are hoisted to the beginning of the entry block. So we
6030     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
6031     // the entry block.
6032     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
6033     if (!IsInEntryBlock)
6034       return false;
6035 
6036     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
6037     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
6038     // variable that also is a param.
6039     //
6040     // Although, if we are at the top of the entry block already, we can still
6041     // emit using ArgDbgValue. This might catch some situations when the
6042     // dbg.value refers to an argument that isn't used in the entry block, so
6043     // any CopyToReg node would be optimized out and the only way to express
6044     // this DBG_VALUE is by using the physical reg (or FI) as done in this
6045     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
6046     // we should only emit as ArgDbgValue if the Variable is an argument to the
6047     // current function, and the dbg.value intrinsic is found in the entry
6048     // block.
6049     bool VariableIsFunctionInputArg = Variable->isParameter() &&
6050         !DL->getInlinedAt();
6051     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
6052     if (!IsInPrologue && !VariableIsFunctionInputArg)
6053       return false;
6054 
6055     // Here we assume that a function argument on IR level only can be used to
6056     // describe one input parameter on source level. If we for example have
6057     // source code like this
6058     //
6059     //    struct A { long x, y; };
6060     //    void foo(struct A a, long b) {
6061     //      ...
6062     //      b = a.x;
6063     //      ...
6064     //    }
6065     //
6066     // and IR like this
6067     //
6068     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
6069     //  entry:
6070     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
6071     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
6072     //    call void @llvm.dbg.value(metadata i32 %b, "b",
6073     //    ...
6074     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
6075     //    ...
6076     //
6077     // then the last dbg.value is describing a parameter "b" using a value that
6078     // is an argument. But since we already has used %a1 to describe a parameter
6079     // we should not handle that last dbg.value here (that would result in an
6080     // incorrect hoisting of the DBG_VALUE to the function entry).
6081     // Notice that we allow one dbg.value per IR level argument, to accommodate
6082     // for the situation with fragments above.
6083     // If there is no node for the value being handled, we return true to skip
6084     // the normal generation of debug info, as it would kill existing debug
6085     // info for the parameter in case of duplicates.
6086     if (VariableIsFunctionInputArg) {
6087       unsigned ArgNo = Arg->getArgNo();
6088       if (ArgNo >= FuncInfo.DescribedArgs.size())
6089         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
6090       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
6091         return !NodeMap[V].getNode();
6092       FuncInfo.DescribedArgs.set(ArgNo);
6093     }
6094   }
6095 
6096   bool IsIndirect = false;
6097   std::optional<MachineOperand> Op;
6098   // Some arguments' frame index is recorded during argument lowering.
6099   int FI = FuncInfo.getArgumentFrameIndex(Arg);
6100   if (FI != std::numeric_limits<int>::max())
6101     Op = MachineOperand::CreateFI(FI);
6102 
6103   SmallVector<std::pair<Register, TypeSize>, 8> ArgRegsAndSizes;
6104   if (!Op && N.getNode()) {
6105     getUnderlyingArgRegs(ArgRegsAndSizes, N);
6106     Register Reg;
6107     if (ArgRegsAndSizes.size() == 1)
6108       Reg = ArgRegsAndSizes.front().first;
6109 
6110     if (Reg && Reg.isVirtual()) {
6111       MachineRegisterInfo &RegInfo = MF.getRegInfo();
6112       Register PR = RegInfo.getLiveInPhysReg(Reg);
6113       if (PR)
6114         Reg = PR;
6115     }
6116     if (Reg) {
6117       Op = MachineOperand::CreateReg(Reg, false);
6118       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6119     }
6120   }
6121 
6122   if (!Op && N.getNode()) {
6123     // Check if frame index is available.
6124     SDValue LCandidate = peekThroughBitcasts(N);
6125     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
6126       if (FrameIndexSDNode *FINode =
6127           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
6128         Op = MachineOperand::CreateFI(FINode->getIndex());
6129   }
6130 
6131   if (!Op) {
6132     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
6133     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<Register, TypeSize>>
6134                                          SplitRegs) {
6135       unsigned Offset = 0;
6136       for (const auto &RegAndSize : SplitRegs) {
6137         // If the expression is already a fragment, the current register
6138         // offset+size might extend beyond the fragment. In this case, only
6139         // the register bits that are inside the fragment are relevant.
6140         int RegFragmentSizeInBits = RegAndSize.second;
6141         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
6142           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
6143           // The register is entirely outside the expression fragment,
6144           // so is irrelevant for debug info.
6145           if (Offset >= ExprFragmentSizeInBits)
6146             break;
6147           // The register is partially outside the expression fragment, only
6148           // the low bits within the fragment are relevant for debug info.
6149           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
6150             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
6151           }
6152         }
6153 
6154         auto FragmentExpr = DIExpression::createFragmentExpression(
6155             Expr, Offset, RegFragmentSizeInBits);
6156         Offset += RegAndSize.second;
6157         // If a valid fragment expression cannot be created, the variable's
6158         // correct value cannot be determined and so it is set as Undef.
6159         if (!FragmentExpr) {
6160           SDDbgValue *SDV = DAG.getConstantDbgValue(
6161               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
6162           DAG.AddDbgValue(SDV, false);
6163           continue;
6164         }
6165         MachineInstr *NewMI =
6166             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr,
6167                              Kind != FuncArgumentDbgValueKind::Value);
6168         FuncInfo.ArgDbgValues.push_back(NewMI);
6169       }
6170     };
6171 
6172     // Check if ValueMap has reg number.
6173     DenseMap<const Value *, Register>::const_iterator
6174       VMI = FuncInfo.ValueMap.find(V);
6175     if (VMI != FuncInfo.ValueMap.end()) {
6176       const auto &TLI = DAG.getTargetLoweringInfo();
6177       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
6178                        V->getType(), std::nullopt);
6179       if (RFV.occupiesMultipleRegs()) {
6180         splitMultiRegDbgValue(RFV.getRegsAndSizes());
6181         return true;
6182       }
6183 
6184       Op = MachineOperand::CreateReg(VMI->second, false);
6185       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6186     } else if (ArgRegsAndSizes.size() > 1) {
6187       // This was split due to the calling convention, and no virtual register
6188       // mapping exists for the value.
6189       splitMultiRegDbgValue(ArgRegsAndSizes);
6190       return true;
6191     }
6192   }
6193 
6194   if (!Op)
6195     return false;
6196 
6197   assert(Variable->isValidLocationForIntrinsic(DL) &&
6198          "Expected inlined-at fields to agree");
6199   MachineInstr *NewMI = nullptr;
6200 
6201   if (Op->isReg())
6202     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
6203   else
6204     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
6205                     Variable, Expr);
6206 
6207   // Otherwise, use ArgDbgValues.
6208   FuncInfo.ArgDbgValues.push_back(NewMI);
6209   return true;
6210 }
6211 
6212 /// Return the appropriate SDDbgValue based on N.
6213 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
6214                                              DILocalVariable *Variable,
6215                                              DIExpression *Expr,
6216                                              const DebugLoc &dl,
6217                                              unsigned DbgSDNodeOrder) {
6218   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
6219     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
6220     // stack slot locations.
6221     //
6222     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
6223     // debug values here after optimization:
6224     //
6225     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
6226     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
6227     //
6228     // Both describe the direct values of their associated variables.
6229     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
6230                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6231   }
6232   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
6233                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6234 }
6235 
6236 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
6237   switch (Intrinsic) {
6238   case Intrinsic::smul_fix:
6239     return ISD::SMULFIX;
6240   case Intrinsic::umul_fix:
6241     return ISD::UMULFIX;
6242   case Intrinsic::smul_fix_sat:
6243     return ISD::SMULFIXSAT;
6244   case Intrinsic::umul_fix_sat:
6245     return ISD::UMULFIXSAT;
6246   case Intrinsic::sdiv_fix:
6247     return ISD::SDIVFIX;
6248   case Intrinsic::udiv_fix:
6249     return ISD::UDIVFIX;
6250   case Intrinsic::sdiv_fix_sat:
6251     return ISD::SDIVFIXSAT;
6252   case Intrinsic::udiv_fix_sat:
6253     return ISD::UDIVFIXSAT;
6254   default:
6255     llvm_unreachable("Unhandled fixed point intrinsic");
6256   }
6257 }
6258 
6259 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
6260                                            const char *FunctionName) {
6261   assert(FunctionName && "FunctionName must not be nullptr");
6262   SDValue Callee = DAG.getExternalSymbol(
6263       FunctionName,
6264       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6265   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
6266 }
6267 
6268 /// Given a @llvm.call.preallocated.setup, return the corresponding
6269 /// preallocated call.
6270 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
6271   assert(cast<CallBase>(PreallocatedSetup)
6272                  ->getCalledFunction()
6273                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
6274          "expected call_preallocated_setup Value");
6275   for (const auto *U : PreallocatedSetup->users()) {
6276     auto *UseCall = cast<CallBase>(U);
6277     const Function *Fn = UseCall->getCalledFunction();
6278     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
6279       return UseCall;
6280     }
6281   }
6282   llvm_unreachable("expected corresponding call to preallocated setup/arg");
6283 }
6284 
6285 /// If DI is a debug value with an EntryValue expression, lower it using the
6286 /// corresponding physical register of the associated Argument value
6287 /// (guaranteed to exist by the verifier).
6288 bool SelectionDAGBuilder::visitEntryValueDbgValue(
6289     ArrayRef<const Value *> Values, DILocalVariable *Variable,
6290     DIExpression *Expr, DebugLoc DbgLoc) {
6291   if (!Expr->isEntryValue() || !hasSingleElement(Values))
6292     return false;
6293 
6294   // These properties are guaranteed by the verifier.
6295   const Argument *Arg = cast<Argument>(Values[0]);
6296   assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync));
6297 
6298   auto ArgIt = FuncInfo.ValueMap.find(Arg);
6299   if (ArgIt == FuncInfo.ValueMap.end()) {
6300     LLVM_DEBUG(
6301         dbgs() << "Dropping dbg.value: expression is entry_value but "
6302                   "couldn't find an associated register for the Argument\n");
6303     return true;
6304   }
6305   Register ArgVReg = ArgIt->getSecond();
6306 
6307   for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
6308     if (ArgVReg == VirtReg || ArgVReg == PhysReg) {
6309       SDDbgValue *SDV = DAG.getVRegDbgValue(
6310           Variable, Expr, PhysReg, false /*IsIndidrect*/, DbgLoc, SDNodeOrder);
6311       DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/);
6312       return true;
6313     }
6314   LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but "
6315                        "couldn't find a physical register\n");
6316   return true;
6317 }
6318 
6319 /// Lower the call to the specified intrinsic function.
6320 void SelectionDAGBuilder::visitConvergenceControl(const CallInst &I,
6321                                                   unsigned Intrinsic) {
6322   SDLoc sdl = getCurSDLoc();
6323   switch (Intrinsic) {
6324   case Intrinsic::experimental_convergence_anchor:
6325     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ANCHOR, sdl, MVT::Untyped));
6326     break;
6327   case Intrinsic::experimental_convergence_entry:
6328     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ENTRY, sdl, MVT::Untyped));
6329     break;
6330   case Intrinsic::experimental_convergence_loop: {
6331     auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl);
6332     auto *Token = Bundle->Inputs[0].get();
6333     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_LOOP, sdl, MVT::Untyped,
6334                              getValue(Token)));
6335     break;
6336   }
6337   }
6338 }
6339 
6340 void SelectionDAGBuilder::visitVectorHistogram(const CallInst &I,
6341                                                unsigned IntrinsicID) {
6342   // For now, we're only lowering an 'add' histogram.
6343   // We can add others later, e.g. saturating adds, min/max.
6344   assert(IntrinsicID == Intrinsic::experimental_vector_histogram_add &&
6345          "Tried to lower unsupported histogram type");
6346   SDLoc sdl = getCurSDLoc();
6347   Value *Ptr = I.getOperand(0);
6348   SDValue Inc = getValue(I.getOperand(1));
6349   SDValue Mask = getValue(I.getOperand(2));
6350 
6351   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6352   DataLayout TargetDL = DAG.getDataLayout();
6353   EVT VT = Inc.getValueType();
6354   Align Alignment = DAG.getEVTAlign(VT);
6355 
6356   const MDNode *Ranges = getRangeMetadata(I);
6357 
6358   SDValue Root = DAG.getRoot();
6359   SDValue Base;
6360   SDValue Index;
6361   ISD::MemIndexType IndexType;
6362   SDValue Scale;
6363   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
6364                                     I.getParent(), VT.getScalarStoreSize());
6365 
6366   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
6367 
6368   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6369       MachinePointerInfo(AS),
6370       MachineMemOperand::MOLoad | MachineMemOperand::MOStore,
6371       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
6372 
6373   if (!UniformBase) {
6374     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6375     Index = getValue(Ptr);
6376     IndexType = ISD::SIGNED_SCALED;
6377     Scale =
6378         DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6379   }
6380 
6381   EVT IdxVT = Index.getValueType();
6382   EVT EltTy = IdxVT.getVectorElementType();
6383   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
6384     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
6385     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
6386   }
6387 
6388   SDValue ID = DAG.getTargetConstant(IntrinsicID, sdl, MVT::i32);
6389 
6390   SDValue Ops[] = {Root, Inc, Mask, Base, Index, Scale, ID};
6391   SDValue Histogram = DAG.getMaskedHistogram(DAG.getVTList(MVT::Other), VT, sdl,
6392                                              Ops, MMO, IndexType);
6393 
6394   setValue(&I, Histogram);
6395   DAG.setRoot(Histogram);
6396 }
6397 
6398 /// Lower the call to the specified intrinsic function.
6399 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
6400                                              unsigned Intrinsic) {
6401   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6402   SDLoc sdl = getCurSDLoc();
6403   DebugLoc dl = getCurDebugLoc();
6404   SDValue Res;
6405 
6406   SDNodeFlags Flags;
6407   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
6408     Flags.copyFMF(*FPOp);
6409 
6410   switch (Intrinsic) {
6411   default:
6412     // By default, turn this into a target intrinsic node.
6413     visitTargetIntrinsic(I, Intrinsic);
6414     return;
6415   case Intrinsic::vscale: {
6416     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6417     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
6418     return;
6419   }
6420   case Intrinsic::vastart:  visitVAStart(I); return;
6421   case Intrinsic::vaend:    visitVAEnd(I); return;
6422   case Intrinsic::vacopy:   visitVACopy(I); return;
6423   case Intrinsic::returnaddress:
6424     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
6425                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6426                              getValue(I.getArgOperand(0))));
6427     return;
6428   case Intrinsic::addressofreturnaddress:
6429     setValue(&I,
6430              DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
6431                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6432     return;
6433   case Intrinsic::sponentry:
6434     setValue(&I,
6435              DAG.getNode(ISD::SPONENTRY, sdl,
6436                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6437     return;
6438   case Intrinsic::frameaddress:
6439     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
6440                              TLI.getFrameIndexTy(DAG.getDataLayout()),
6441                              getValue(I.getArgOperand(0))));
6442     return;
6443   case Intrinsic::read_volatile_register:
6444   case Intrinsic::read_register: {
6445     Value *Reg = I.getArgOperand(0);
6446     SDValue Chain = getRoot();
6447     SDValue RegName =
6448         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6449     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6450     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
6451       DAG.getVTList(VT, MVT::Other), Chain, RegName);
6452     setValue(&I, Res);
6453     DAG.setRoot(Res.getValue(1));
6454     return;
6455   }
6456   case Intrinsic::write_register: {
6457     Value *Reg = I.getArgOperand(0);
6458     Value *RegValue = I.getArgOperand(1);
6459     SDValue Chain = getRoot();
6460     SDValue RegName =
6461         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6462     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
6463                             RegName, getValue(RegValue)));
6464     return;
6465   }
6466   case Intrinsic::memcpy: {
6467     const auto &MCI = cast<MemCpyInst>(I);
6468     SDValue Op1 = getValue(I.getArgOperand(0));
6469     SDValue Op2 = getValue(I.getArgOperand(1));
6470     SDValue Op3 = getValue(I.getArgOperand(2));
6471     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
6472     Align DstAlign = MCI.getDestAlign().valueOrOne();
6473     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6474     Align Alignment = std::min(DstAlign, SrcAlign);
6475     bool isVol = MCI.isVolatile();
6476     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6477     // node.
6478     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6479     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6480                                /* AlwaysInline */ false, &I, std::nullopt,
6481                                MachinePointerInfo(I.getArgOperand(0)),
6482                                MachinePointerInfo(I.getArgOperand(1)),
6483                                I.getAAMetadata(), AA);
6484     updateDAGForMaybeTailCall(MC);
6485     return;
6486   }
6487   case Intrinsic::memcpy_inline: {
6488     const auto &MCI = cast<MemCpyInlineInst>(I);
6489     SDValue Dst = getValue(I.getArgOperand(0));
6490     SDValue Src = getValue(I.getArgOperand(1));
6491     SDValue Size = getValue(I.getArgOperand(2));
6492     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
6493     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
6494     Align DstAlign = MCI.getDestAlign().valueOrOne();
6495     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6496     Align Alignment = std::min(DstAlign, SrcAlign);
6497     bool isVol = MCI.isVolatile();
6498     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6499     // node.
6500     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
6501                                /* AlwaysInline */ true, &I, std::nullopt,
6502                                MachinePointerInfo(I.getArgOperand(0)),
6503                                MachinePointerInfo(I.getArgOperand(1)),
6504                                I.getAAMetadata(), AA);
6505     updateDAGForMaybeTailCall(MC);
6506     return;
6507   }
6508   case Intrinsic::memset: {
6509     const auto &MSI = cast<MemSetInst>(I);
6510     SDValue Op1 = getValue(I.getArgOperand(0));
6511     SDValue Op2 = getValue(I.getArgOperand(1));
6512     SDValue Op3 = getValue(I.getArgOperand(2));
6513     // @llvm.memset defines 0 and 1 to both mean no alignment.
6514     Align Alignment = MSI.getDestAlign().valueOrOne();
6515     bool isVol = MSI.isVolatile();
6516     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6517     SDValue MS = DAG.getMemset(
6518         Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false,
6519         &I, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
6520     updateDAGForMaybeTailCall(MS);
6521     return;
6522   }
6523   case Intrinsic::memset_inline: {
6524     const auto &MSII = cast<MemSetInlineInst>(I);
6525     SDValue Dst = getValue(I.getArgOperand(0));
6526     SDValue Value = getValue(I.getArgOperand(1));
6527     SDValue Size = getValue(I.getArgOperand(2));
6528     assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size");
6529     // @llvm.memset defines 0 and 1 to both mean no alignment.
6530     Align DstAlign = MSII.getDestAlign().valueOrOne();
6531     bool isVol = MSII.isVolatile();
6532     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6533     SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol,
6534                                /* AlwaysInline */ true, &I,
6535                                MachinePointerInfo(I.getArgOperand(0)),
6536                                I.getAAMetadata());
6537     updateDAGForMaybeTailCall(MC);
6538     return;
6539   }
6540   case Intrinsic::memmove: {
6541     const auto &MMI = cast<MemMoveInst>(I);
6542     SDValue Op1 = getValue(I.getArgOperand(0));
6543     SDValue Op2 = getValue(I.getArgOperand(1));
6544     SDValue Op3 = getValue(I.getArgOperand(2));
6545     // @llvm.memmove defines 0 and 1 to both mean no alignment.
6546     Align DstAlign = MMI.getDestAlign().valueOrOne();
6547     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
6548     Align Alignment = std::min(DstAlign, SrcAlign);
6549     bool isVol = MMI.isVolatile();
6550     // FIXME: Support passing different dest/src alignments to the memmove DAG
6551     // node.
6552     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6553     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, &I,
6554                                 /* OverrideTailCall */ std::nullopt,
6555                                 MachinePointerInfo(I.getArgOperand(0)),
6556                                 MachinePointerInfo(I.getArgOperand(1)),
6557                                 I.getAAMetadata(), AA);
6558     updateDAGForMaybeTailCall(MM);
6559     return;
6560   }
6561   case Intrinsic::memcpy_element_unordered_atomic: {
6562     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
6563     SDValue Dst = getValue(MI.getRawDest());
6564     SDValue Src = getValue(MI.getRawSource());
6565     SDValue Length = getValue(MI.getLength());
6566 
6567     Type *LengthTy = MI.getLength()->getType();
6568     unsigned ElemSz = MI.getElementSizeInBytes();
6569     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6570     SDValue MC =
6571         DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6572                             isTC, MachinePointerInfo(MI.getRawDest()),
6573                             MachinePointerInfo(MI.getRawSource()));
6574     updateDAGForMaybeTailCall(MC);
6575     return;
6576   }
6577   case Intrinsic::memmove_element_unordered_atomic: {
6578     auto &MI = cast<AtomicMemMoveInst>(I);
6579     SDValue Dst = getValue(MI.getRawDest());
6580     SDValue Src = getValue(MI.getRawSource());
6581     SDValue Length = getValue(MI.getLength());
6582 
6583     Type *LengthTy = MI.getLength()->getType();
6584     unsigned ElemSz = MI.getElementSizeInBytes();
6585     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6586     SDValue MC =
6587         DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6588                              isTC, MachinePointerInfo(MI.getRawDest()),
6589                              MachinePointerInfo(MI.getRawSource()));
6590     updateDAGForMaybeTailCall(MC);
6591     return;
6592   }
6593   case Intrinsic::memset_element_unordered_atomic: {
6594     auto &MI = cast<AtomicMemSetInst>(I);
6595     SDValue Dst = getValue(MI.getRawDest());
6596     SDValue Val = getValue(MI.getValue());
6597     SDValue Length = getValue(MI.getLength());
6598 
6599     Type *LengthTy = MI.getLength()->getType();
6600     unsigned ElemSz = MI.getElementSizeInBytes();
6601     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6602     SDValue MC =
6603         DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
6604                             isTC, MachinePointerInfo(MI.getRawDest()));
6605     updateDAGForMaybeTailCall(MC);
6606     return;
6607   }
6608   case Intrinsic::call_preallocated_setup: {
6609     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
6610     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6611     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
6612                               getRoot(), SrcValue);
6613     setValue(&I, Res);
6614     DAG.setRoot(Res);
6615     return;
6616   }
6617   case Intrinsic::call_preallocated_arg: {
6618     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6619     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6620     SDValue Ops[3];
6621     Ops[0] = getRoot();
6622     Ops[1] = SrcValue;
6623     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6624                                    MVT::i32); // arg index
6625     SDValue Res = DAG.getNode(
6626         ISD::PREALLOCATED_ARG, sdl,
6627         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6628     setValue(&I, Res);
6629     DAG.setRoot(Res.getValue(1));
6630     return;
6631   }
6632   case Intrinsic::dbg_declare: {
6633     const auto &DI = cast<DbgDeclareInst>(I);
6634     // Debug intrinsics are handled separately in assignment tracking mode.
6635     // Some intrinsics are handled right after Argument lowering.
6636     if (AssignmentTrackingEnabled ||
6637         FuncInfo.PreprocessedDbgDeclares.count(&DI))
6638       return;
6639     LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DI << "\n");
6640     DILocalVariable *Variable = DI.getVariable();
6641     DIExpression *Expression = DI.getExpression();
6642     dropDanglingDebugInfo(Variable, Expression);
6643     // Assume dbg.declare can not currently use DIArgList, i.e.
6644     // it is non-variadic.
6645     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6646     handleDebugDeclare(DI.getVariableLocationOp(0), Variable, Expression,
6647                        DI.getDebugLoc());
6648     return;
6649   }
6650   case Intrinsic::dbg_label: {
6651     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6652     DILabel *Label = DI.getLabel();
6653     assert(Label && "Missing label");
6654 
6655     SDDbgLabel *SDV;
6656     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6657     DAG.AddDbgLabel(SDV);
6658     return;
6659   }
6660   case Intrinsic::dbg_assign: {
6661     // Debug intrinsics are handled separately in assignment tracking mode.
6662     if (AssignmentTrackingEnabled)
6663       return;
6664     // If assignment tracking hasn't been enabled then fall through and treat
6665     // the dbg.assign as a dbg.value.
6666     [[fallthrough]];
6667   }
6668   case Intrinsic::dbg_value: {
6669     // Debug intrinsics are handled separately in assignment tracking mode.
6670     if (AssignmentTrackingEnabled)
6671       return;
6672     const DbgValueInst &DI = cast<DbgValueInst>(I);
6673     assert(DI.getVariable() && "Missing variable");
6674 
6675     DILocalVariable *Variable = DI.getVariable();
6676     DIExpression *Expression = DI.getExpression();
6677     dropDanglingDebugInfo(Variable, Expression);
6678 
6679     if (DI.isKillLocation()) {
6680       handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder);
6681       return;
6682     }
6683 
6684     SmallVector<Value *, 4> Values(DI.getValues());
6685     if (Values.empty())
6686       return;
6687 
6688     bool IsVariadic = DI.hasArgList();
6689     if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(),
6690                           SDNodeOrder, IsVariadic))
6691       addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
6692                            DI.getDebugLoc(), SDNodeOrder);
6693     return;
6694   }
6695 
6696   case Intrinsic::eh_typeid_for: {
6697     // Find the type id for the given typeinfo.
6698     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6699     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6700     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6701     setValue(&I, Res);
6702     return;
6703   }
6704 
6705   case Intrinsic::eh_return_i32:
6706   case Intrinsic::eh_return_i64:
6707     DAG.getMachineFunction().setCallsEHReturn(true);
6708     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6709                             MVT::Other,
6710                             getControlRoot(),
6711                             getValue(I.getArgOperand(0)),
6712                             getValue(I.getArgOperand(1))));
6713     return;
6714   case Intrinsic::eh_unwind_init:
6715     DAG.getMachineFunction().setCallsUnwindInit(true);
6716     return;
6717   case Intrinsic::eh_dwarf_cfa:
6718     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6719                              TLI.getPointerTy(DAG.getDataLayout()),
6720                              getValue(I.getArgOperand(0))));
6721     return;
6722   case Intrinsic::eh_sjlj_callsite: {
6723     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
6724     assert(FuncInfo.getCurrentCallSite() == 0 && "Overlapping call sites!");
6725 
6726     FuncInfo.setCurrentCallSite(CI->getZExtValue());
6727     return;
6728   }
6729   case Intrinsic::eh_sjlj_functioncontext: {
6730     // Get and store the index of the function context.
6731     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6732     AllocaInst *FnCtx =
6733       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6734     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6735     MFI.setFunctionContextIndex(FI);
6736     return;
6737   }
6738   case Intrinsic::eh_sjlj_setjmp: {
6739     SDValue Ops[2];
6740     Ops[0] = getRoot();
6741     Ops[1] = getValue(I.getArgOperand(0));
6742     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6743                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6744     setValue(&I, Op.getValue(0));
6745     DAG.setRoot(Op.getValue(1));
6746     return;
6747   }
6748   case Intrinsic::eh_sjlj_longjmp:
6749     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6750                             getRoot(), getValue(I.getArgOperand(0))));
6751     return;
6752   case Intrinsic::eh_sjlj_setup_dispatch:
6753     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6754                             getRoot()));
6755     return;
6756   case Intrinsic::masked_gather:
6757     visitMaskedGather(I);
6758     return;
6759   case Intrinsic::masked_load:
6760     visitMaskedLoad(I);
6761     return;
6762   case Intrinsic::masked_scatter:
6763     visitMaskedScatter(I);
6764     return;
6765   case Intrinsic::masked_store:
6766     visitMaskedStore(I);
6767     return;
6768   case Intrinsic::masked_expandload:
6769     visitMaskedLoad(I, true /* IsExpanding */);
6770     return;
6771   case Intrinsic::masked_compressstore:
6772     visitMaskedStore(I, true /* IsCompressing */);
6773     return;
6774   case Intrinsic::powi:
6775     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6776                             getValue(I.getArgOperand(1)), DAG));
6777     return;
6778   case Intrinsic::log:
6779     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6780     return;
6781   case Intrinsic::log2:
6782     setValue(&I,
6783              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6784     return;
6785   case Intrinsic::log10:
6786     setValue(&I,
6787              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6788     return;
6789   case Intrinsic::exp:
6790     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6791     return;
6792   case Intrinsic::exp2:
6793     setValue(&I,
6794              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6795     return;
6796   case Intrinsic::pow:
6797     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6798                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6799     return;
6800   case Intrinsic::sqrt:
6801   case Intrinsic::fabs:
6802   case Intrinsic::sin:
6803   case Intrinsic::cos:
6804   case Intrinsic::tan:
6805   case Intrinsic::asin:
6806   case Intrinsic::acos:
6807   case Intrinsic::atan:
6808   case Intrinsic::sinh:
6809   case Intrinsic::cosh:
6810   case Intrinsic::tanh:
6811   case Intrinsic::exp10:
6812   case Intrinsic::floor:
6813   case Intrinsic::ceil:
6814   case Intrinsic::trunc:
6815   case Intrinsic::rint:
6816   case Intrinsic::nearbyint:
6817   case Intrinsic::round:
6818   case Intrinsic::roundeven:
6819   case Intrinsic::canonicalize: {
6820     unsigned Opcode;
6821     // clang-format off
6822     switch (Intrinsic) {
6823     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6824     case Intrinsic::sqrt:         Opcode = ISD::FSQRT;         break;
6825     case Intrinsic::fabs:         Opcode = ISD::FABS;          break;
6826     case Intrinsic::sin:          Opcode = ISD::FSIN;          break;
6827     case Intrinsic::cos:          Opcode = ISD::FCOS;          break;
6828     case Intrinsic::tan:          Opcode = ISD::FTAN;          break;
6829     case Intrinsic::asin:         Opcode = ISD::FASIN;         break;
6830     case Intrinsic::acos:         Opcode = ISD::FACOS;         break;
6831     case Intrinsic::atan:         Opcode = ISD::FATAN;         break;
6832     case Intrinsic::sinh:         Opcode = ISD::FSINH;         break;
6833     case Intrinsic::cosh:         Opcode = ISD::FCOSH;         break;
6834     case Intrinsic::tanh:         Opcode = ISD::FTANH;         break;
6835     case Intrinsic::exp10:        Opcode = ISD::FEXP10;        break;
6836     case Intrinsic::floor:        Opcode = ISD::FFLOOR;        break;
6837     case Intrinsic::ceil:         Opcode = ISD::FCEIL;         break;
6838     case Intrinsic::trunc:        Opcode = ISD::FTRUNC;        break;
6839     case Intrinsic::rint:         Opcode = ISD::FRINT;         break;
6840     case Intrinsic::nearbyint:    Opcode = ISD::FNEARBYINT;    break;
6841     case Intrinsic::round:        Opcode = ISD::FROUND;        break;
6842     case Intrinsic::roundeven:    Opcode = ISD::FROUNDEVEN;    break;
6843     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6844     }
6845     // clang-format on
6846 
6847     setValue(&I, DAG.getNode(Opcode, sdl,
6848                              getValue(I.getArgOperand(0)).getValueType(),
6849                              getValue(I.getArgOperand(0)), Flags));
6850     return;
6851   }
6852   case Intrinsic::lround:
6853   case Intrinsic::llround:
6854   case Intrinsic::lrint:
6855   case Intrinsic::llrint: {
6856     unsigned Opcode;
6857     // clang-format off
6858     switch (Intrinsic) {
6859     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6860     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6861     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6862     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6863     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6864     }
6865     // clang-format on
6866 
6867     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6868     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6869                              getValue(I.getArgOperand(0))));
6870     return;
6871   }
6872   case Intrinsic::minnum:
6873     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6874                              getValue(I.getArgOperand(0)).getValueType(),
6875                              getValue(I.getArgOperand(0)),
6876                              getValue(I.getArgOperand(1)), Flags));
6877     return;
6878   case Intrinsic::maxnum:
6879     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6880                              getValue(I.getArgOperand(0)).getValueType(),
6881                              getValue(I.getArgOperand(0)),
6882                              getValue(I.getArgOperand(1)), Flags));
6883     return;
6884   case Intrinsic::minimum:
6885     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6886                              getValue(I.getArgOperand(0)).getValueType(),
6887                              getValue(I.getArgOperand(0)),
6888                              getValue(I.getArgOperand(1)), Flags));
6889     return;
6890   case Intrinsic::maximum:
6891     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6892                              getValue(I.getArgOperand(0)).getValueType(),
6893                              getValue(I.getArgOperand(0)),
6894                              getValue(I.getArgOperand(1)), Flags));
6895     return;
6896   case Intrinsic::minimumnum:
6897     setValue(&I, DAG.getNode(ISD::FMINIMUMNUM, sdl,
6898                              getValue(I.getArgOperand(0)).getValueType(),
6899                              getValue(I.getArgOperand(0)),
6900                              getValue(I.getArgOperand(1)), Flags));
6901     return;
6902   case Intrinsic::maximumnum:
6903     setValue(&I, DAG.getNode(ISD::FMAXIMUMNUM, sdl,
6904                              getValue(I.getArgOperand(0)).getValueType(),
6905                              getValue(I.getArgOperand(0)),
6906                              getValue(I.getArgOperand(1)), Flags));
6907     return;
6908   case Intrinsic::copysign:
6909     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6910                              getValue(I.getArgOperand(0)).getValueType(),
6911                              getValue(I.getArgOperand(0)),
6912                              getValue(I.getArgOperand(1)), Flags));
6913     return;
6914   case Intrinsic::ldexp:
6915     setValue(&I, DAG.getNode(ISD::FLDEXP, sdl,
6916                              getValue(I.getArgOperand(0)).getValueType(),
6917                              getValue(I.getArgOperand(0)),
6918                              getValue(I.getArgOperand(1)), Flags));
6919     return;
6920   case Intrinsic::frexp: {
6921     SmallVector<EVT, 2> ValueVTs;
6922     ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
6923     SDVTList VTs = DAG.getVTList(ValueVTs);
6924     setValue(&I,
6925              DAG.getNode(ISD::FFREXP, sdl, VTs, getValue(I.getArgOperand(0))));
6926     return;
6927   }
6928   case Intrinsic::arithmetic_fence: {
6929     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6930                              getValue(I.getArgOperand(0)).getValueType(),
6931                              getValue(I.getArgOperand(0)), Flags));
6932     return;
6933   }
6934   case Intrinsic::fma:
6935     setValue(&I, DAG.getNode(
6936                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6937                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6938                      getValue(I.getArgOperand(2)), Flags));
6939     return;
6940 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6941   case Intrinsic::INTRINSIC:
6942 #include "llvm/IR/ConstrainedOps.def"
6943     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6944     return;
6945 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6946 #include "llvm/IR/VPIntrinsics.def"
6947     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6948     return;
6949   case Intrinsic::fptrunc_round: {
6950     // Get the last argument, the metadata and convert it to an integer in the
6951     // call
6952     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
6953     std::optional<RoundingMode> RoundMode =
6954         convertStrToRoundingMode(cast<MDString>(MD)->getString());
6955 
6956     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6957 
6958     // Propagate fast-math-flags from IR to node(s).
6959     SDNodeFlags Flags;
6960     Flags.copyFMF(*cast<FPMathOperator>(&I));
6961     SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
6962 
6963     SDValue Result;
6964     Result = DAG.getNode(
6965         ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
6966         DAG.getTargetConstant((int)*RoundMode, sdl, MVT::i32));
6967     setValue(&I, Result);
6968 
6969     return;
6970   }
6971   case Intrinsic::fmuladd: {
6972     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6973     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6974         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6975       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6976                                getValue(I.getArgOperand(0)).getValueType(),
6977                                getValue(I.getArgOperand(0)),
6978                                getValue(I.getArgOperand(1)),
6979                                getValue(I.getArgOperand(2)), Flags));
6980     } else {
6981       // TODO: Intrinsic calls should have fast-math-flags.
6982       SDValue Mul = DAG.getNode(
6983           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6984           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6985       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6986                                 getValue(I.getArgOperand(0)).getValueType(),
6987                                 Mul, getValue(I.getArgOperand(2)), Flags);
6988       setValue(&I, Add);
6989     }
6990     return;
6991   }
6992   case Intrinsic::convert_to_fp16:
6993     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6994                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6995                                          getValue(I.getArgOperand(0)),
6996                                          DAG.getTargetConstant(0, sdl,
6997                                                                MVT::i32))));
6998     return;
6999   case Intrinsic::convert_from_fp16:
7000     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
7001                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
7002                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
7003                                          getValue(I.getArgOperand(0)))));
7004     return;
7005   case Intrinsic::fptosi_sat: {
7006     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7007     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
7008                              getValue(I.getArgOperand(0)),
7009                              DAG.getValueType(VT.getScalarType())));
7010     return;
7011   }
7012   case Intrinsic::fptoui_sat: {
7013     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7014     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
7015                              getValue(I.getArgOperand(0)),
7016                              DAG.getValueType(VT.getScalarType())));
7017     return;
7018   }
7019   case Intrinsic::set_rounding:
7020     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
7021                       {getRoot(), getValue(I.getArgOperand(0))});
7022     setValue(&I, Res);
7023     DAG.setRoot(Res.getValue(0));
7024     return;
7025   case Intrinsic::is_fpclass: {
7026     const DataLayout DLayout = DAG.getDataLayout();
7027     EVT DestVT = TLI.getValueType(DLayout, I.getType());
7028     EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
7029     FPClassTest Test = static_cast<FPClassTest>(
7030         cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
7031     MachineFunction &MF = DAG.getMachineFunction();
7032     const Function &F = MF.getFunction();
7033     SDValue Op = getValue(I.getArgOperand(0));
7034     SDNodeFlags Flags;
7035     Flags.setNoFPExcept(
7036         !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
7037     // If ISD::IS_FPCLASS should be expanded, do it right now, because the
7038     // expansion can use illegal types. Making expansion early allows
7039     // legalizing these types prior to selection.
7040     if (!TLI.isOperationLegal(ISD::IS_FPCLASS, ArgVT) &&
7041         !TLI.isOperationCustom(ISD::IS_FPCLASS, ArgVT)) {
7042       SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
7043       setValue(&I, Result);
7044       return;
7045     }
7046 
7047     SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
7048     SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
7049     setValue(&I, V);
7050     return;
7051   }
7052   case Intrinsic::get_fpenv: {
7053     const DataLayout DLayout = DAG.getDataLayout();
7054     EVT EnvVT = TLI.getValueType(DLayout, I.getType());
7055     Align TempAlign = DAG.getEVTAlign(EnvVT);
7056     SDValue Chain = getRoot();
7057     // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node
7058     // and temporary storage in stack.
7059     if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) {
7060       Res = DAG.getNode(
7061           ISD::GET_FPENV, sdl,
7062           DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7063                         MVT::Other),
7064           Chain);
7065     } else {
7066       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7067       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7068       auto MPI =
7069           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7070       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7071           MPI, MachineMemOperand::MOStore, LocationSize::beforeOrAfterPointer(),
7072           TempAlign);
7073       Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7074       Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI);
7075     }
7076     setValue(&I, Res);
7077     DAG.setRoot(Res.getValue(1));
7078     return;
7079   }
7080   case Intrinsic::set_fpenv: {
7081     const DataLayout DLayout = DAG.getDataLayout();
7082     SDValue Env = getValue(I.getArgOperand(0));
7083     EVT EnvVT = Env.getValueType();
7084     Align TempAlign = DAG.getEVTAlign(EnvVT);
7085     SDValue Chain = getRoot();
7086     // If SET_FPENV is custom or legal, use it. Otherwise use loading
7087     // environment from memory.
7088     if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) {
7089       Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env);
7090     } else {
7091       // Allocate space in stack, copy environment bits into it and use this
7092       // memory in SET_FPENV_MEM.
7093       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7094       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7095       auto MPI =
7096           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7097       Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign,
7098                            MachineMemOperand::MOStore);
7099       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7100           MPI, MachineMemOperand::MOLoad, LocationSize::beforeOrAfterPointer(),
7101           TempAlign);
7102       Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7103     }
7104     DAG.setRoot(Chain);
7105     return;
7106   }
7107   case Intrinsic::reset_fpenv:
7108     DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot()));
7109     return;
7110   case Intrinsic::get_fpmode:
7111     Res = DAG.getNode(
7112         ISD::GET_FPMODE, sdl,
7113         DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7114                       MVT::Other),
7115         DAG.getRoot());
7116     setValue(&I, Res);
7117     DAG.setRoot(Res.getValue(1));
7118     return;
7119   case Intrinsic::set_fpmode:
7120     Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()},
7121                       getValue(I.getArgOperand(0)));
7122     DAG.setRoot(Res);
7123     return;
7124   case Intrinsic::reset_fpmode: {
7125     Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot());
7126     DAG.setRoot(Res);
7127     return;
7128   }
7129   case Intrinsic::pcmarker: {
7130     SDValue Tmp = getValue(I.getArgOperand(0));
7131     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
7132     return;
7133   }
7134   case Intrinsic::readcyclecounter: {
7135     SDValue Op = getRoot();
7136     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
7137                       DAG.getVTList(MVT::i64, MVT::Other), Op);
7138     setValue(&I, Res);
7139     DAG.setRoot(Res.getValue(1));
7140     return;
7141   }
7142   case Intrinsic::readsteadycounter: {
7143     SDValue Op = getRoot();
7144     Res = DAG.getNode(ISD::READSTEADYCOUNTER, sdl,
7145                       DAG.getVTList(MVT::i64, MVT::Other), Op);
7146     setValue(&I, Res);
7147     DAG.setRoot(Res.getValue(1));
7148     return;
7149   }
7150   case Intrinsic::bitreverse:
7151     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
7152                              getValue(I.getArgOperand(0)).getValueType(),
7153                              getValue(I.getArgOperand(0))));
7154     return;
7155   case Intrinsic::bswap:
7156     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
7157                              getValue(I.getArgOperand(0)).getValueType(),
7158                              getValue(I.getArgOperand(0))));
7159     return;
7160   case Intrinsic::cttz: {
7161     SDValue Arg = getValue(I.getArgOperand(0));
7162     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7163     EVT Ty = Arg.getValueType();
7164     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
7165                              sdl, Ty, Arg));
7166     return;
7167   }
7168   case Intrinsic::ctlz: {
7169     SDValue Arg = getValue(I.getArgOperand(0));
7170     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7171     EVT Ty = Arg.getValueType();
7172     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
7173                              sdl, Ty, Arg));
7174     return;
7175   }
7176   case Intrinsic::ctpop: {
7177     SDValue Arg = getValue(I.getArgOperand(0));
7178     EVT Ty = Arg.getValueType();
7179     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
7180     return;
7181   }
7182   case Intrinsic::fshl:
7183   case Intrinsic::fshr: {
7184     bool IsFSHL = Intrinsic == Intrinsic::fshl;
7185     SDValue X = getValue(I.getArgOperand(0));
7186     SDValue Y = getValue(I.getArgOperand(1));
7187     SDValue Z = getValue(I.getArgOperand(2));
7188     EVT VT = X.getValueType();
7189 
7190     if (X == Y) {
7191       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
7192       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
7193     } else {
7194       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
7195       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
7196     }
7197     return;
7198   }
7199   case Intrinsic::sadd_sat: {
7200     SDValue Op1 = getValue(I.getArgOperand(0));
7201     SDValue Op2 = getValue(I.getArgOperand(1));
7202     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7203     return;
7204   }
7205   case Intrinsic::uadd_sat: {
7206     SDValue Op1 = getValue(I.getArgOperand(0));
7207     SDValue Op2 = getValue(I.getArgOperand(1));
7208     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7209     return;
7210   }
7211   case Intrinsic::ssub_sat: {
7212     SDValue Op1 = getValue(I.getArgOperand(0));
7213     SDValue Op2 = getValue(I.getArgOperand(1));
7214     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7215     return;
7216   }
7217   case Intrinsic::usub_sat: {
7218     SDValue Op1 = getValue(I.getArgOperand(0));
7219     SDValue Op2 = getValue(I.getArgOperand(1));
7220     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7221     return;
7222   }
7223   case Intrinsic::sshl_sat: {
7224     SDValue Op1 = getValue(I.getArgOperand(0));
7225     SDValue Op2 = getValue(I.getArgOperand(1));
7226     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
7227     return;
7228   }
7229   case Intrinsic::ushl_sat: {
7230     SDValue Op1 = getValue(I.getArgOperand(0));
7231     SDValue Op2 = getValue(I.getArgOperand(1));
7232     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
7233     return;
7234   }
7235   case Intrinsic::smul_fix:
7236   case Intrinsic::umul_fix:
7237   case Intrinsic::smul_fix_sat:
7238   case Intrinsic::umul_fix_sat: {
7239     SDValue Op1 = getValue(I.getArgOperand(0));
7240     SDValue Op2 = getValue(I.getArgOperand(1));
7241     SDValue Op3 = getValue(I.getArgOperand(2));
7242     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7243                              Op1.getValueType(), Op1, Op2, Op3));
7244     return;
7245   }
7246   case Intrinsic::sdiv_fix:
7247   case Intrinsic::udiv_fix:
7248   case Intrinsic::sdiv_fix_sat:
7249   case Intrinsic::udiv_fix_sat: {
7250     SDValue Op1 = getValue(I.getArgOperand(0));
7251     SDValue Op2 = getValue(I.getArgOperand(1));
7252     SDValue Op3 = getValue(I.getArgOperand(2));
7253     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7254                               Op1, Op2, Op3, DAG, TLI));
7255     return;
7256   }
7257   case Intrinsic::smax: {
7258     SDValue Op1 = getValue(I.getArgOperand(0));
7259     SDValue Op2 = getValue(I.getArgOperand(1));
7260     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
7261     return;
7262   }
7263   case Intrinsic::smin: {
7264     SDValue Op1 = getValue(I.getArgOperand(0));
7265     SDValue Op2 = getValue(I.getArgOperand(1));
7266     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
7267     return;
7268   }
7269   case Intrinsic::umax: {
7270     SDValue Op1 = getValue(I.getArgOperand(0));
7271     SDValue Op2 = getValue(I.getArgOperand(1));
7272     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
7273     return;
7274   }
7275   case Intrinsic::umin: {
7276     SDValue Op1 = getValue(I.getArgOperand(0));
7277     SDValue Op2 = getValue(I.getArgOperand(1));
7278     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
7279     return;
7280   }
7281   case Intrinsic::abs: {
7282     // TODO: Preserve "int min is poison" arg in SDAG?
7283     SDValue Op1 = getValue(I.getArgOperand(0));
7284     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
7285     return;
7286   }
7287   case Intrinsic::scmp: {
7288     SDValue Op1 = getValue(I.getArgOperand(0));
7289     SDValue Op2 = getValue(I.getArgOperand(1));
7290     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7291     setValue(&I, DAG.getNode(ISD::SCMP, sdl, DestVT, Op1, Op2));
7292     break;
7293   }
7294   case Intrinsic::ucmp: {
7295     SDValue Op1 = getValue(I.getArgOperand(0));
7296     SDValue Op2 = getValue(I.getArgOperand(1));
7297     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7298     setValue(&I, DAG.getNode(ISD::UCMP, sdl, DestVT, Op1, Op2));
7299     break;
7300   }
7301   case Intrinsic::stacksave: {
7302     SDValue Op = getRoot();
7303     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7304     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
7305     setValue(&I, Res);
7306     DAG.setRoot(Res.getValue(1));
7307     return;
7308   }
7309   case Intrinsic::stackrestore:
7310     Res = getValue(I.getArgOperand(0));
7311     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
7312     return;
7313   case Intrinsic::get_dynamic_area_offset: {
7314     SDValue Op = getRoot();
7315     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7316     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7317     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
7318     // target.
7319     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
7320       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
7321                          " intrinsic!");
7322     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
7323                       Op);
7324     DAG.setRoot(Op);
7325     setValue(&I, Res);
7326     return;
7327   }
7328   case Intrinsic::stackguard: {
7329     MachineFunction &MF = DAG.getMachineFunction();
7330     const Module &M = *MF.getFunction().getParent();
7331     EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7332     SDValue Chain = getRoot();
7333     if (TLI.useLoadStackGuardNode()) {
7334       Res = getLoadStackGuard(DAG, sdl, Chain);
7335       Res = DAG.getPtrExtOrTrunc(Res, sdl, PtrTy);
7336     } else {
7337       const Value *Global = TLI.getSDagStackGuard(M);
7338       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
7339       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
7340                         MachinePointerInfo(Global, 0), Align,
7341                         MachineMemOperand::MOVolatile);
7342     }
7343     if (TLI.useStackGuardXorFP())
7344       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
7345     DAG.setRoot(Chain);
7346     setValue(&I, Res);
7347     return;
7348   }
7349   case Intrinsic::stackprotector: {
7350     // Emit code into the DAG to store the stack guard onto the stack.
7351     MachineFunction &MF = DAG.getMachineFunction();
7352     MachineFrameInfo &MFI = MF.getFrameInfo();
7353     SDValue Src, Chain = getRoot();
7354 
7355     if (TLI.useLoadStackGuardNode())
7356       Src = getLoadStackGuard(DAG, sdl, Chain);
7357     else
7358       Src = getValue(I.getArgOperand(0));   // The guard's value.
7359 
7360     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
7361 
7362     int FI = FuncInfo.StaticAllocaMap[Slot];
7363     MFI.setStackProtectorIndex(FI);
7364     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7365 
7366     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
7367 
7368     // Store the stack protector onto the stack.
7369     Res = DAG.getStore(
7370         Chain, sdl, Src, FIN,
7371         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
7372         MaybeAlign(), MachineMemOperand::MOVolatile);
7373     setValue(&I, Res);
7374     DAG.setRoot(Res);
7375     return;
7376   }
7377   case Intrinsic::objectsize:
7378     llvm_unreachable("llvm.objectsize.* should have been lowered already");
7379 
7380   case Intrinsic::is_constant:
7381     llvm_unreachable("llvm.is.constant.* should have been lowered already");
7382 
7383   case Intrinsic::annotation:
7384   case Intrinsic::ptr_annotation:
7385   case Intrinsic::launder_invariant_group:
7386   case Intrinsic::strip_invariant_group:
7387     // Drop the intrinsic, but forward the value
7388     setValue(&I, getValue(I.getOperand(0)));
7389     return;
7390 
7391   case Intrinsic::assume:
7392   case Intrinsic::experimental_noalias_scope_decl:
7393   case Intrinsic::var_annotation:
7394   case Intrinsic::sideeffect:
7395     // Discard annotate attributes, noalias scope declarations, assumptions, and
7396     // artificial side-effects.
7397     return;
7398 
7399   case Intrinsic::codeview_annotation: {
7400     // Emit a label associated with this metadata.
7401     MachineFunction &MF = DAG.getMachineFunction();
7402     MCSymbol *Label = MF.getContext().createTempSymbol("annotation", true);
7403     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
7404     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
7405     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
7406     DAG.setRoot(Res);
7407     return;
7408   }
7409 
7410   case Intrinsic::init_trampoline: {
7411     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
7412 
7413     SDValue Ops[6];
7414     Ops[0] = getRoot();
7415     Ops[1] = getValue(I.getArgOperand(0));
7416     Ops[2] = getValue(I.getArgOperand(1));
7417     Ops[3] = getValue(I.getArgOperand(2));
7418     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
7419     Ops[5] = DAG.getSrcValue(F);
7420 
7421     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
7422 
7423     DAG.setRoot(Res);
7424     return;
7425   }
7426   case Intrinsic::adjust_trampoline:
7427     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
7428                              TLI.getPointerTy(DAG.getDataLayout()),
7429                              getValue(I.getArgOperand(0))));
7430     return;
7431   case Intrinsic::gcroot: {
7432     assert(DAG.getMachineFunction().getFunction().hasGC() &&
7433            "only valid in functions with gc specified, enforced by Verifier");
7434     assert(GFI && "implied by previous");
7435     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
7436     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
7437 
7438     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
7439     GFI->addStackRoot(FI->getIndex(), TypeMap);
7440     return;
7441   }
7442   case Intrinsic::gcread:
7443   case Intrinsic::gcwrite:
7444     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
7445   case Intrinsic::get_rounding:
7446     Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot());
7447     setValue(&I, Res);
7448     DAG.setRoot(Res.getValue(1));
7449     return;
7450 
7451   case Intrinsic::expect:
7452     // Just replace __builtin_expect(exp, c) with EXP.
7453     setValue(&I, getValue(I.getArgOperand(0)));
7454     return;
7455 
7456   case Intrinsic::ubsantrap:
7457   case Intrinsic::debugtrap:
7458   case Intrinsic::trap: {
7459     StringRef TrapFuncName =
7460         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
7461     if (TrapFuncName.empty()) {
7462       switch (Intrinsic) {
7463       case Intrinsic::trap:
7464         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
7465         break;
7466       case Intrinsic::debugtrap:
7467         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
7468         break;
7469       case Intrinsic::ubsantrap:
7470         DAG.setRoot(DAG.getNode(
7471             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
7472             DAG.getTargetConstant(
7473                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
7474                 MVT::i32)));
7475         break;
7476       default: llvm_unreachable("unknown trap intrinsic");
7477       }
7478       DAG.addNoMergeSiteInfo(DAG.getRoot().getNode(),
7479                              I.hasFnAttr(Attribute::NoMerge));
7480       return;
7481     }
7482     TargetLowering::ArgListTy Args;
7483     if (Intrinsic == Intrinsic::ubsantrap) {
7484       Args.push_back(TargetLoweringBase::ArgListEntry());
7485       Args[0].Val = I.getArgOperand(0);
7486       Args[0].Node = getValue(Args[0].Val);
7487       Args[0].Ty = Args[0].Val->getType();
7488     }
7489 
7490     TargetLowering::CallLoweringInfo CLI(DAG);
7491     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
7492         CallingConv::C, I.getType(),
7493         DAG.getExternalSymbol(TrapFuncName.data(),
7494                               TLI.getPointerTy(DAG.getDataLayout())),
7495         std::move(Args));
7496     CLI.NoMerge = I.hasFnAttr(Attribute::NoMerge);
7497     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7498     DAG.setRoot(Result.second);
7499     return;
7500   }
7501 
7502   case Intrinsic::allow_runtime_check:
7503   case Intrinsic::allow_ubsan_check:
7504     setValue(&I, getValue(ConstantInt::getTrue(I.getType())));
7505     return;
7506 
7507   case Intrinsic::uadd_with_overflow:
7508   case Intrinsic::sadd_with_overflow:
7509   case Intrinsic::usub_with_overflow:
7510   case Intrinsic::ssub_with_overflow:
7511   case Intrinsic::umul_with_overflow:
7512   case Intrinsic::smul_with_overflow: {
7513     ISD::NodeType Op;
7514     switch (Intrinsic) {
7515     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7516     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
7517     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
7518     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
7519     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
7520     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
7521     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
7522     }
7523     SDValue Op1 = getValue(I.getArgOperand(0));
7524     SDValue Op2 = getValue(I.getArgOperand(1));
7525 
7526     EVT ResultVT = Op1.getValueType();
7527     EVT OverflowVT = MVT::i1;
7528     if (ResultVT.isVector())
7529       OverflowVT = EVT::getVectorVT(
7530           *Context, OverflowVT, ResultVT.getVectorElementCount());
7531 
7532     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
7533     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
7534     return;
7535   }
7536   case Intrinsic::prefetch: {
7537     SDValue Ops[5];
7538     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7539     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
7540     Ops[0] = DAG.getRoot();
7541     Ops[1] = getValue(I.getArgOperand(0));
7542     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
7543                                    MVT::i32);
7544     Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl,
7545                                    MVT::i32);
7546     Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl,
7547                                    MVT::i32);
7548     SDValue Result = DAG.getMemIntrinsicNode(
7549         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
7550         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
7551         /* align */ std::nullopt, Flags);
7552 
7553     // Chain the prefetch in parallel with any pending loads, to stay out of
7554     // the way of later optimizations.
7555     PendingLoads.push_back(Result);
7556     Result = getRoot();
7557     DAG.setRoot(Result);
7558     return;
7559   }
7560   case Intrinsic::lifetime_start:
7561   case Intrinsic::lifetime_end: {
7562     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
7563     // Stack coloring is not enabled in O0, discard region information.
7564     if (TM.getOptLevel() == CodeGenOptLevel::None)
7565       return;
7566 
7567     const int64_t ObjectSize =
7568         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
7569     Value *const ObjectPtr = I.getArgOperand(1);
7570     SmallVector<const Value *, 4> Allocas;
7571     getUnderlyingObjects(ObjectPtr, Allocas);
7572 
7573     for (const Value *Alloca : Allocas) {
7574       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
7575 
7576       // Could not find an Alloca.
7577       if (!LifetimeObject)
7578         continue;
7579 
7580       // First check that the Alloca is static, otherwise it won't have a
7581       // valid frame index.
7582       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
7583       if (SI == FuncInfo.StaticAllocaMap.end())
7584         return;
7585 
7586       const int FrameIndex = SI->second;
7587       int64_t Offset;
7588       if (GetPointerBaseWithConstantOffset(
7589               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
7590         Offset = -1; // Cannot determine offset from alloca to lifetime object.
7591       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
7592                                 Offset);
7593       DAG.setRoot(Res);
7594     }
7595     return;
7596   }
7597   case Intrinsic::pseudoprobe: {
7598     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
7599     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7600     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
7601     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
7602     DAG.setRoot(Res);
7603     return;
7604   }
7605   case Intrinsic::invariant_start:
7606     // Discard region information.
7607     setValue(&I,
7608              DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
7609     return;
7610   case Intrinsic::invariant_end:
7611     // Discard region information.
7612     return;
7613   case Intrinsic::clear_cache: {
7614     SDValue InputChain = DAG.getRoot();
7615     SDValue StartVal = getValue(I.getArgOperand(0));
7616     SDValue EndVal = getValue(I.getArgOperand(1));
7617     Res = DAG.getNode(ISD::CLEAR_CACHE, sdl, DAG.getVTList(MVT::Other),
7618                       {InputChain, StartVal, EndVal});
7619     setValue(&I, Res);
7620     DAG.setRoot(Res);
7621     return;
7622   }
7623   case Intrinsic::donothing:
7624   case Intrinsic::seh_try_begin:
7625   case Intrinsic::seh_scope_begin:
7626   case Intrinsic::seh_try_end:
7627   case Intrinsic::seh_scope_end:
7628     // ignore
7629     return;
7630   case Intrinsic::experimental_stackmap:
7631     visitStackmap(I);
7632     return;
7633   case Intrinsic::experimental_patchpoint_void:
7634   case Intrinsic::experimental_patchpoint:
7635     visitPatchpoint(I);
7636     return;
7637   case Intrinsic::experimental_gc_statepoint:
7638     LowerStatepoint(cast<GCStatepointInst>(I));
7639     return;
7640   case Intrinsic::experimental_gc_result:
7641     visitGCResult(cast<GCResultInst>(I));
7642     return;
7643   case Intrinsic::experimental_gc_relocate:
7644     visitGCRelocate(cast<GCRelocateInst>(I));
7645     return;
7646   case Intrinsic::instrprof_cover:
7647     llvm_unreachable("instrprof failed to lower a cover");
7648   case Intrinsic::instrprof_increment:
7649     llvm_unreachable("instrprof failed to lower an increment");
7650   case Intrinsic::instrprof_timestamp:
7651     llvm_unreachable("instrprof failed to lower a timestamp");
7652   case Intrinsic::instrprof_value_profile:
7653     llvm_unreachable("instrprof failed to lower a value profiling call");
7654   case Intrinsic::instrprof_mcdc_parameters:
7655     llvm_unreachable("instrprof failed to lower mcdc parameters");
7656   case Intrinsic::instrprof_mcdc_tvbitmap_update:
7657     llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update");
7658   case Intrinsic::localescape: {
7659     MachineFunction &MF = DAG.getMachineFunction();
7660     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
7661 
7662     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
7663     // is the same on all targets.
7664     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
7665       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
7666       if (isa<ConstantPointerNull>(Arg))
7667         continue; // Skip null pointers. They represent a hole in index space.
7668       AllocaInst *Slot = cast<AllocaInst>(Arg);
7669       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
7670              "can only escape static allocas");
7671       int FI = FuncInfo.StaticAllocaMap[Slot];
7672       MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
7673           GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
7674       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
7675               TII->get(TargetOpcode::LOCAL_ESCAPE))
7676           .addSym(FrameAllocSym)
7677           .addFrameIndex(FI);
7678     }
7679 
7680     return;
7681   }
7682 
7683   case Intrinsic::localrecover: {
7684     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
7685     MachineFunction &MF = DAG.getMachineFunction();
7686 
7687     // Get the symbol that defines the frame offset.
7688     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
7689     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
7690     unsigned IdxVal =
7691         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
7692     MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
7693         GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
7694 
7695     Value *FP = I.getArgOperand(1);
7696     SDValue FPVal = getValue(FP);
7697     EVT PtrVT = FPVal.getValueType();
7698 
7699     // Create a MCSymbol for the label to avoid any target lowering
7700     // that would make this PC relative.
7701     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
7702     SDValue OffsetVal =
7703         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
7704 
7705     // Add the offset to the FP.
7706     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
7707     setValue(&I, Add);
7708 
7709     return;
7710   }
7711 
7712   case Intrinsic::fake_use: {
7713     Value *V = I.getArgOperand(0);
7714     SDValue Ops[2];
7715     // For Values not declared or previously used in this basic block, the
7716     // NodeMap will not have an entry, and `getValue` will assert if V has no
7717     // valid register value.
7718     auto FakeUseValue = [&]() -> SDValue {
7719       SDValue &N = NodeMap[V];
7720       if (N.getNode())
7721         return N;
7722 
7723       // If there's a virtual register allocated and initialized for this
7724       // value, use it.
7725       if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
7726         return copyFromReg;
7727       // FIXME: Do we want to preserve constants? It seems pointless.
7728       if (isa<Constant>(V))
7729         return getValue(V);
7730       return SDValue();
7731     }();
7732     if (!FakeUseValue || FakeUseValue.isUndef())
7733       return;
7734     Ops[0] = getRoot();
7735     Ops[1] = FakeUseValue;
7736     // Also, do not translate a fake use with an undef operand, or any other
7737     // empty SDValues.
7738     if (!Ops[1] || Ops[1].isUndef())
7739       return;
7740     DAG.setRoot(DAG.getNode(ISD::FAKE_USE, sdl, MVT::Other, Ops));
7741     return;
7742   }
7743 
7744   case Intrinsic::eh_exceptionpointer:
7745   case Intrinsic::eh_exceptioncode: {
7746     // Get the exception pointer vreg, copy from it, and resize it to fit.
7747     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
7748     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
7749     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
7750     Register VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
7751     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
7752     if (Intrinsic == Intrinsic::eh_exceptioncode)
7753       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
7754     setValue(&I, N);
7755     return;
7756   }
7757   case Intrinsic::xray_customevent: {
7758     // Here we want to make sure that the intrinsic behaves as if it has a
7759     // specific calling convention.
7760     const auto &Triple = DAG.getTarget().getTargetTriple();
7761     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7762       return;
7763 
7764     SmallVector<SDValue, 8> Ops;
7765 
7766     // We want to say that we always want the arguments in registers.
7767     SDValue LogEntryVal = getValue(I.getArgOperand(0));
7768     SDValue StrSizeVal = getValue(I.getArgOperand(1));
7769     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7770     SDValue Chain = getRoot();
7771     Ops.push_back(LogEntryVal);
7772     Ops.push_back(StrSizeVal);
7773     Ops.push_back(Chain);
7774 
7775     // We need to enforce the calling convention for the callsite, so that
7776     // argument ordering is enforced correctly, and that register allocation can
7777     // see that some registers may be assumed clobbered and have to preserve
7778     // them across calls to the intrinsic.
7779     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
7780                                            sdl, NodeTys, Ops);
7781     SDValue patchableNode = SDValue(MN, 0);
7782     DAG.setRoot(patchableNode);
7783     setValue(&I, patchableNode);
7784     return;
7785   }
7786   case Intrinsic::xray_typedevent: {
7787     // Here we want to make sure that the intrinsic behaves as if it has a
7788     // specific calling convention.
7789     const auto &Triple = DAG.getTarget().getTargetTriple();
7790     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7791       return;
7792 
7793     SmallVector<SDValue, 8> Ops;
7794 
7795     // We want to say that we always want the arguments in registers.
7796     // It's unclear to me how manipulating the selection DAG here forces callers
7797     // to provide arguments in registers instead of on the stack.
7798     SDValue LogTypeId = getValue(I.getArgOperand(0));
7799     SDValue LogEntryVal = getValue(I.getArgOperand(1));
7800     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7801     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7802     SDValue Chain = getRoot();
7803     Ops.push_back(LogTypeId);
7804     Ops.push_back(LogEntryVal);
7805     Ops.push_back(StrSizeVal);
7806     Ops.push_back(Chain);
7807 
7808     // We need to enforce the calling convention for the callsite, so that
7809     // argument ordering is enforced correctly, and that register allocation can
7810     // see that some registers may be assumed clobbered and have to preserve
7811     // them across calls to the intrinsic.
7812     MachineSDNode *MN = DAG.getMachineNode(
7813         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7814     SDValue patchableNode = SDValue(MN, 0);
7815     DAG.setRoot(patchableNode);
7816     setValue(&I, patchableNode);
7817     return;
7818   }
7819   case Intrinsic::experimental_deoptimize:
7820     LowerDeoptimizeCall(&I);
7821     return;
7822   case Intrinsic::stepvector:
7823     visitStepVector(I);
7824     return;
7825   case Intrinsic::vector_reduce_fadd:
7826   case Intrinsic::vector_reduce_fmul:
7827   case Intrinsic::vector_reduce_add:
7828   case Intrinsic::vector_reduce_mul:
7829   case Intrinsic::vector_reduce_and:
7830   case Intrinsic::vector_reduce_or:
7831   case Intrinsic::vector_reduce_xor:
7832   case Intrinsic::vector_reduce_smax:
7833   case Intrinsic::vector_reduce_smin:
7834   case Intrinsic::vector_reduce_umax:
7835   case Intrinsic::vector_reduce_umin:
7836   case Intrinsic::vector_reduce_fmax:
7837   case Intrinsic::vector_reduce_fmin:
7838   case Intrinsic::vector_reduce_fmaximum:
7839   case Intrinsic::vector_reduce_fminimum:
7840     visitVectorReduce(I, Intrinsic);
7841     return;
7842 
7843   case Intrinsic::icall_branch_funnel: {
7844     SmallVector<SDValue, 16> Ops;
7845     Ops.push_back(getValue(I.getArgOperand(0)));
7846 
7847     int64_t Offset;
7848     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7849         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7850     if (!Base)
7851       report_fatal_error(
7852           "llvm.icall.branch.funnel operand must be a GlobalValue");
7853     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7854 
7855     struct BranchFunnelTarget {
7856       int64_t Offset;
7857       SDValue Target;
7858     };
7859     SmallVector<BranchFunnelTarget, 8> Targets;
7860 
7861     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7862       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7863           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7864       if (ElemBase != Base)
7865         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7866                            "to the same GlobalValue");
7867 
7868       SDValue Val = getValue(I.getArgOperand(Op + 1));
7869       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7870       if (!GA)
7871         report_fatal_error(
7872             "llvm.icall.branch.funnel operand must be a GlobalValue");
7873       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7874                                      GA->getGlobal(), sdl, Val.getValueType(),
7875                                      GA->getOffset())});
7876     }
7877     llvm::sort(Targets,
7878                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7879                  return T1.Offset < T2.Offset;
7880                });
7881 
7882     for (auto &T : Targets) {
7883       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7884       Ops.push_back(T.Target);
7885     }
7886 
7887     Ops.push_back(DAG.getRoot()); // Chain
7888     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7889                                  MVT::Other, Ops),
7890               0);
7891     DAG.setRoot(N);
7892     setValue(&I, N);
7893     HasTailCall = true;
7894     return;
7895   }
7896 
7897   case Intrinsic::wasm_landingpad_index:
7898     // Information this intrinsic contained has been transferred to
7899     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7900     // delete it now.
7901     return;
7902 
7903   case Intrinsic::aarch64_settag:
7904   case Intrinsic::aarch64_settag_zero: {
7905     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7906     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7907     SDValue Val = TSI.EmitTargetCodeForSetTag(
7908         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7909         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7910         ZeroMemory);
7911     DAG.setRoot(Val);
7912     setValue(&I, Val);
7913     return;
7914   }
7915   case Intrinsic::amdgcn_cs_chain: {
7916     assert(I.arg_size() == 5 && "Additional args not supported yet");
7917     assert(cast<ConstantInt>(I.getOperand(4))->isZero() &&
7918            "Non-zero flags not supported yet");
7919 
7920     // At this point we don't care if it's amdgpu_cs_chain or
7921     // amdgpu_cs_chain_preserve.
7922     CallingConv::ID CC = CallingConv::AMDGPU_CS_Chain;
7923 
7924     Type *RetTy = I.getType();
7925     assert(RetTy->isVoidTy() && "Should not return");
7926 
7927     SDValue Callee = getValue(I.getOperand(0));
7928 
7929     // We only have 2 actual args: one for the SGPRs and one for the VGPRs.
7930     // We'll also tack the value of the EXEC mask at the end.
7931     TargetLowering::ArgListTy Args;
7932     Args.reserve(3);
7933 
7934     for (unsigned Idx : {2, 3, 1}) {
7935       TargetLowering::ArgListEntry Arg;
7936       Arg.Node = getValue(I.getOperand(Idx));
7937       Arg.Ty = I.getOperand(Idx)->getType();
7938       Arg.setAttributes(&I, Idx);
7939       Args.push_back(Arg);
7940     }
7941 
7942     assert(Args[0].IsInReg && "SGPR args should be marked inreg");
7943     assert(!Args[1].IsInReg && "VGPR args should not be marked inreg");
7944     Args[2].IsInReg = true; // EXEC should be inreg
7945 
7946     TargetLowering::CallLoweringInfo CLI(DAG);
7947     CLI.setDebugLoc(getCurSDLoc())
7948         .setChain(getRoot())
7949         .setCallee(CC, RetTy, Callee, std::move(Args))
7950         .setNoReturn(true)
7951         .setTailCall(true)
7952         .setConvergent(I.isConvergent());
7953     CLI.CB = &I;
7954     std::pair<SDValue, SDValue> Result =
7955         lowerInvokable(CLI, /*EHPadBB*/ nullptr);
7956     (void)Result;
7957     assert(!Result.first.getNode() && !Result.second.getNode() &&
7958            "Should've lowered as tail call");
7959 
7960     HasTailCall = true;
7961     return;
7962   }
7963   case Intrinsic::ptrmask: {
7964     SDValue Ptr = getValue(I.getOperand(0));
7965     SDValue Mask = getValue(I.getOperand(1));
7966 
7967     // On arm64_32, pointers are 32 bits when stored in memory, but
7968     // zero-extended to 64 bits when in registers.  Thus the mask is 32 bits to
7969     // match the index type, but the pointer is 64 bits, so the the mask must be
7970     // zero-extended up to 64 bits to match the pointer.
7971     EVT PtrVT =
7972         TLI.getValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
7973     EVT MemVT =
7974         TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
7975     assert(PtrVT == Ptr.getValueType());
7976     assert(MemVT == Mask.getValueType());
7977     if (MemVT != PtrVT)
7978       Mask = DAG.getPtrExtOrTrunc(Mask, sdl, PtrVT);
7979 
7980     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask));
7981     return;
7982   }
7983   case Intrinsic::threadlocal_address: {
7984     setValue(&I, getValue(I.getOperand(0)));
7985     return;
7986   }
7987   case Intrinsic::get_active_lane_mask: {
7988     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7989     SDValue Index = getValue(I.getOperand(0));
7990     EVT ElementVT = Index.getValueType();
7991 
7992     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
7993       visitTargetIntrinsic(I, Intrinsic);
7994       return;
7995     }
7996 
7997     SDValue TripCount = getValue(I.getOperand(1));
7998     EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT,
7999                                  CCVT.getVectorElementCount());
8000 
8001     SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
8002     SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
8003     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
8004     SDValue VectorInduction = DAG.getNode(
8005         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
8006     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
8007                                  VectorTripCount, ISD::CondCode::SETULT);
8008     setValue(&I, SetCC);
8009     return;
8010   }
8011   case Intrinsic::experimental_get_vector_length: {
8012     assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 &&
8013            "Expected positive VF");
8014     unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue();
8015     bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne();
8016 
8017     SDValue Count = getValue(I.getOperand(0));
8018     EVT CountVT = Count.getValueType();
8019 
8020     if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) {
8021       visitTargetIntrinsic(I, Intrinsic);
8022       return;
8023     }
8024 
8025     // Expand to a umin between the trip count and the maximum elements the type
8026     // can hold.
8027     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8028 
8029     // Extend the trip count to at least the result VT.
8030     if (CountVT.bitsLT(VT)) {
8031       Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count);
8032       CountVT = VT;
8033     }
8034 
8035     SDValue MaxEVL = DAG.getElementCount(sdl, CountVT,
8036                                          ElementCount::get(VF, IsScalable));
8037 
8038     SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL);
8039     // Clip to the result type if needed.
8040     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin);
8041 
8042     setValue(&I, Trunc);
8043     return;
8044   }
8045   case Intrinsic::experimental_vector_partial_reduce_add: {
8046 
8047     if (!TLI.shouldExpandPartialReductionIntrinsic(cast<IntrinsicInst>(&I))) {
8048       visitTargetIntrinsic(I, Intrinsic);
8049       return;
8050     }
8051 
8052     setValue(&I, DAG.getPartialReduceAdd(sdl, EVT::getEVT(I.getType()),
8053                                          getValue(I.getOperand(0)),
8054                                          getValue(I.getOperand(1))));
8055     return;
8056   }
8057   case Intrinsic::experimental_cttz_elts: {
8058     auto DL = getCurSDLoc();
8059     SDValue Op = getValue(I.getOperand(0));
8060     EVT OpVT = Op.getValueType();
8061 
8062     if (!TLI.shouldExpandCttzElements(OpVT)) {
8063       visitTargetIntrinsic(I, Intrinsic);
8064       return;
8065     }
8066 
8067     if (OpVT.getScalarType() != MVT::i1) {
8068       // Compare the input vector elements to zero & use to count trailing zeros
8069       SDValue AllZero = DAG.getConstant(0, DL, OpVT);
8070       OpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
8071                               OpVT.getVectorElementCount());
8072       Op = DAG.getSetCC(DL, OpVT, Op, AllZero, ISD::SETNE);
8073     }
8074 
8075     // If the zero-is-poison flag is set, we can assume the upper limit
8076     // of the result is VF-1.
8077     bool ZeroIsPoison =
8078         !cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero();
8079     ConstantRange VScaleRange(1, true); // Dummy value.
8080     if (isa<ScalableVectorType>(I.getOperand(0)->getType()))
8081       VScaleRange = getVScaleRange(I.getCaller(), 64);
8082     unsigned EltWidth = TLI.getBitWidthForCttzElements(
8083         I.getType(), OpVT.getVectorElementCount(), ZeroIsPoison, &VScaleRange);
8084 
8085     MVT NewEltTy = MVT::getIntegerVT(EltWidth);
8086 
8087     // Create the new vector type & get the vector length
8088     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), NewEltTy,
8089                                  OpVT.getVectorElementCount());
8090 
8091     SDValue VL =
8092         DAG.getElementCount(DL, NewEltTy, OpVT.getVectorElementCount());
8093 
8094     SDValue StepVec = DAG.getStepVector(DL, NewVT);
8095     SDValue SplatVL = DAG.getSplat(NewVT, DL, VL);
8096     SDValue StepVL = DAG.getNode(ISD::SUB, DL, NewVT, SplatVL, StepVec);
8097     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, Op);
8098     SDValue And = DAG.getNode(ISD::AND, DL, NewVT, StepVL, Ext);
8099     SDValue Max = DAG.getNode(ISD::VECREDUCE_UMAX, DL, NewEltTy, And);
8100     SDValue Sub = DAG.getNode(ISD::SUB, DL, NewEltTy, VL, Max);
8101 
8102     EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
8103     SDValue Ret = DAG.getZExtOrTrunc(Sub, DL, RetTy);
8104 
8105     setValue(&I, Ret);
8106     return;
8107   }
8108   case Intrinsic::vector_insert: {
8109     SDValue Vec = getValue(I.getOperand(0));
8110     SDValue SubVec = getValue(I.getOperand(1));
8111     SDValue Index = getValue(I.getOperand(2));
8112 
8113     // The intrinsic's index type is i64, but the SDNode requires an index type
8114     // suitable for the target. Convert the index as required.
8115     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8116     if (Index.getValueType() != VectorIdxTy)
8117       Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8118 
8119     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8120     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
8121                              Index));
8122     return;
8123   }
8124   case Intrinsic::vector_extract: {
8125     SDValue Vec = getValue(I.getOperand(0));
8126     SDValue Index = getValue(I.getOperand(1));
8127     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8128 
8129     // The intrinsic's index type is i64, but the SDNode requires an index type
8130     // suitable for the target. Convert the index as required.
8131     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8132     if (Index.getValueType() != VectorIdxTy)
8133       Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8134 
8135     setValue(&I,
8136              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
8137     return;
8138   }
8139   case Intrinsic::vector_reverse:
8140     visitVectorReverse(I);
8141     return;
8142   case Intrinsic::vector_splice:
8143     visitVectorSplice(I);
8144     return;
8145   case Intrinsic::callbr_landingpad:
8146     visitCallBrLandingPad(I);
8147     return;
8148   case Intrinsic::vector_interleave2:
8149     visitVectorInterleave(I);
8150     return;
8151   case Intrinsic::vector_deinterleave2:
8152     visitVectorDeinterleave(I);
8153     return;
8154   case Intrinsic::experimental_vector_compress:
8155     setValue(&I, DAG.getNode(ISD::VECTOR_COMPRESS, sdl,
8156                              getValue(I.getArgOperand(0)).getValueType(),
8157                              getValue(I.getArgOperand(0)),
8158                              getValue(I.getArgOperand(1)),
8159                              getValue(I.getArgOperand(2)), Flags));
8160     return;
8161   case Intrinsic::experimental_convergence_anchor:
8162   case Intrinsic::experimental_convergence_entry:
8163   case Intrinsic::experimental_convergence_loop:
8164     visitConvergenceControl(I, Intrinsic);
8165     return;
8166   case Intrinsic::experimental_vector_histogram_add: {
8167     visitVectorHistogram(I, Intrinsic);
8168     return;
8169   }
8170   }
8171 }
8172 
8173 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
8174     const ConstrainedFPIntrinsic &FPI) {
8175   SDLoc sdl = getCurSDLoc();
8176 
8177   // We do not need to serialize constrained FP intrinsics against
8178   // each other or against (nonvolatile) loads, so they can be
8179   // chained like loads.
8180   SDValue Chain = DAG.getRoot();
8181   SmallVector<SDValue, 4> Opers;
8182   Opers.push_back(Chain);
8183   for (unsigned I = 0, E = FPI.getNonMetadataArgCount(); I != E; ++I)
8184     Opers.push_back(getValue(FPI.getArgOperand(I)));
8185 
8186   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
8187     assert(Result.getNode()->getNumValues() == 2);
8188 
8189     // Push node to the appropriate list so that future instructions can be
8190     // chained up correctly.
8191     SDValue OutChain = Result.getValue(1);
8192     switch (EB) {
8193     case fp::ExceptionBehavior::ebIgnore:
8194       // The only reason why ebIgnore nodes still need to be chained is that
8195       // they might depend on the current rounding mode, and therefore must
8196       // not be moved across instruction that may change that mode.
8197       [[fallthrough]];
8198     case fp::ExceptionBehavior::ebMayTrap:
8199       // These must not be moved across calls or instructions that may change
8200       // floating-point exception masks.
8201       PendingConstrainedFP.push_back(OutChain);
8202       break;
8203     case fp::ExceptionBehavior::ebStrict:
8204       // These must not be moved across calls or instructions that may change
8205       // floating-point exception masks or read floating-point exception flags.
8206       // In addition, they cannot be optimized out even if unused.
8207       PendingConstrainedFPStrict.push_back(OutChain);
8208       break;
8209     }
8210   };
8211 
8212   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8213   EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
8214   SDVTList VTs = DAG.getVTList(VT, MVT::Other);
8215   fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
8216 
8217   SDNodeFlags Flags;
8218   if (EB == fp::ExceptionBehavior::ebIgnore)
8219     Flags.setNoFPExcept(true);
8220 
8221   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
8222     Flags.copyFMF(*FPOp);
8223 
8224   unsigned Opcode;
8225   switch (FPI.getIntrinsicID()) {
8226   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
8227 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8228   case Intrinsic::INTRINSIC:                                                   \
8229     Opcode = ISD::STRICT_##DAGN;                                               \
8230     break;
8231 #include "llvm/IR/ConstrainedOps.def"
8232   case Intrinsic::experimental_constrained_fmuladd: {
8233     Opcode = ISD::STRICT_FMA;
8234     // Break fmuladd into fmul and fadd.
8235     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
8236         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
8237       Opers.pop_back();
8238       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
8239       pushOutChain(Mul, EB);
8240       Opcode = ISD::STRICT_FADD;
8241       Opers.clear();
8242       Opers.push_back(Mul.getValue(1));
8243       Opers.push_back(Mul.getValue(0));
8244       Opers.push_back(getValue(FPI.getArgOperand(2)));
8245     }
8246     break;
8247   }
8248   }
8249 
8250   // A few strict DAG nodes carry additional operands that are not
8251   // set up by the default code above.
8252   switch (Opcode) {
8253   default: break;
8254   case ISD::STRICT_FP_ROUND:
8255     Opers.push_back(
8256         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
8257     break;
8258   case ISD::STRICT_FSETCC:
8259   case ISD::STRICT_FSETCCS: {
8260     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
8261     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
8262     if (TM.Options.NoNaNsFPMath)
8263       Condition = getFCmpCodeWithoutNaN(Condition);
8264     Opers.push_back(DAG.getCondCode(Condition));
8265     break;
8266   }
8267   }
8268 
8269   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
8270   pushOutChain(Result, EB);
8271 
8272   SDValue FPResult = Result.getValue(0);
8273   setValue(&FPI, FPResult);
8274 }
8275 
8276 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
8277   std::optional<unsigned> ResOPC;
8278   switch (VPIntrin.getIntrinsicID()) {
8279   case Intrinsic::vp_ctlz: {
8280     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8281     ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ;
8282     break;
8283   }
8284   case Intrinsic::vp_cttz: {
8285     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8286     ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ;
8287     break;
8288   }
8289   case Intrinsic::vp_cttz_elts: {
8290     bool IsZeroPoison = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8291     ResOPC = IsZeroPoison ? ISD::VP_CTTZ_ELTS_ZERO_UNDEF : ISD::VP_CTTZ_ELTS;
8292     break;
8293   }
8294 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD)                                    \
8295   case Intrinsic::VPID:                                                        \
8296     ResOPC = ISD::VPSD;                                                        \
8297     break;
8298 #include "llvm/IR/VPIntrinsics.def"
8299   }
8300 
8301   if (!ResOPC)
8302     llvm_unreachable(
8303         "Inconsistency: no SDNode available for this VPIntrinsic!");
8304 
8305   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
8306       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
8307     if (VPIntrin.getFastMathFlags().allowReassoc())
8308       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
8309                                                 : ISD::VP_REDUCE_FMUL;
8310   }
8311 
8312   return *ResOPC;
8313 }
8314 
8315 void SelectionDAGBuilder::visitVPLoad(
8316     const VPIntrinsic &VPIntrin, EVT VT,
8317     const SmallVectorImpl<SDValue> &OpValues) {
8318   SDLoc DL = getCurSDLoc();
8319   Value *PtrOperand = VPIntrin.getArgOperand(0);
8320   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8321   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8322   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8323   SDValue LD;
8324   // Do not serialize variable-length loads of constant memory with
8325   // anything.
8326   if (!Alignment)
8327     Alignment = DAG.getEVTAlign(VT);
8328   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
8329   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
8330   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8331   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8332       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
8333       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8334   LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
8335                      MMO, false /*IsExpanding */);
8336   if (AddToChain)
8337     PendingLoads.push_back(LD.getValue(1));
8338   setValue(&VPIntrin, LD);
8339 }
8340 
8341 void SelectionDAGBuilder::visitVPGather(
8342     const VPIntrinsic &VPIntrin, EVT VT,
8343     const SmallVectorImpl<SDValue> &OpValues) {
8344   SDLoc DL = getCurSDLoc();
8345   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8346   Value *PtrOperand = VPIntrin.getArgOperand(0);
8347   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8348   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8349   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8350   SDValue LD;
8351   if (!Alignment)
8352     Alignment = DAG.getEVTAlign(VT.getScalarType());
8353   unsigned AS =
8354     PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8355   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8356       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
8357       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8358   SDValue Base, Index, Scale;
8359   ISD::MemIndexType IndexType;
8360   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
8361                                     this, VPIntrin.getParent(),
8362                                     VT.getScalarStoreSize());
8363   if (!UniformBase) {
8364     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
8365     Index = getValue(PtrOperand);
8366     IndexType = ISD::SIGNED_SCALED;
8367     Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
8368   }
8369   EVT IdxVT = Index.getValueType();
8370   EVT EltTy = IdxVT.getVectorElementType();
8371   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
8372     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
8373     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
8374   }
8375   LD = DAG.getGatherVP(
8376       DAG.getVTList(VT, MVT::Other), VT, DL,
8377       {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
8378       IndexType);
8379   PendingLoads.push_back(LD.getValue(1));
8380   setValue(&VPIntrin, LD);
8381 }
8382 
8383 void SelectionDAGBuilder::visitVPStore(
8384     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8385   SDLoc DL = getCurSDLoc();
8386   Value *PtrOperand = VPIntrin.getArgOperand(1);
8387   EVT VT = OpValues[0].getValueType();
8388   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8389   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8390   SDValue ST;
8391   if (!Alignment)
8392     Alignment = DAG.getEVTAlign(VT);
8393   SDValue Ptr = OpValues[1];
8394   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
8395   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8396       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
8397       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8398   ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
8399                       OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
8400                       /* IsTruncating */ false, /*IsCompressing*/ false);
8401   DAG.setRoot(ST);
8402   setValue(&VPIntrin, ST);
8403 }
8404 
8405 void SelectionDAGBuilder::visitVPScatter(
8406     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8407   SDLoc DL = getCurSDLoc();
8408   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8409   Value *PtrOperand = VPIntrin.getArgOperand(1);
8410   EVT VT = OpValues[0].getValueType();
8411   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8412   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8413   SDValue ST;
8414   if (!Alignment)
8415     Alignment = DAG.getEVTAlign(VT.getScalarType());
8416   unsigned AS =
8417       PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8418   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8419       MachinePointerInfo(AS), MachineMemOperand::MOStore,
8420       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8421   SDValue Base, Index, Scale;
8422   ISD::MemIndexType IndexType;
8423   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
8424                                     this, VPIntrin.getParent(),
8425                                     VT.getScalarStoreSize());
8426   if (!UniformBase) {
8427     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
8428     Index = getValue(PtrOperand);
8429     IndexType = ISD::SIGNED_SCALED;
8430     Scale =
8431       DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
8432   }
8433   EVT IdxVT = Index.getValueType();
8434   EVT EltTy = IdxVT.getVectorElementType();
8435   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
8436     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
8437     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
8438   }
8439   ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
8440                         {getMemoryRoot(), OpValues[0], Base, Index, Scale,
8441                          OpValues[2], OpValues[3]},
8442                         MMO, IndexType);
8443   DAG.setRoot(ST);
8444   setValue(&VPIntrin, ST);
8445 }
8446 
8447 void SelectionDAGBuilder::visitVPStridedLoad(
8448     const VPIntrinsic &VPIntrin, EVT VT,
8449     const SmallVectorImpl<SDValue> &OpValues) {
8450   SDLoc DL = getCurSDLoc();
8451   Value *PtrOperand = VPIntrin.getArgOperand(0);
8452   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8453   if (!Alignment)
8454     Alignment = DAG.getEVTAlign(VT.getScalarType());
8455   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8456   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8457   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
8458   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
8459   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8460   unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8461   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8462       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
8463       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8464 
8465   SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
8466                                     OpValues[2], OpValues[3], MMO,
8467                                     false /*IsExpanding*/);
8468 
8469   if (AddToChain)
8470     PendingLoads.push_back(LD.getValue(1));
8471   setValue(&VPIntrin, LD);
8472 }
8473 
8474 void SelectionDAGBuilder::visitVPStridedStore(
8475     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8476   SDLoc DL = getCurSDLoc();
8477   Value *PtrOperand = VPIntrin.getArgOperand(1);
8478   EVT VT = OpValues[0].getValueType();
8479   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8480   if (!Alignment)
8481     Alignment = DAG.getEVTAlign(VT.getScalarType());
8482   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8483   unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8484   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8485       MachinePointerInfo(AS), MachineMemOperand::MOStore,
8486       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8487 
8488   SDValue ST = DAG.getStridedStoreVP(
8489       getMemoryRoot(), DL, OpValues[0], OpValues[1],
8490       DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3],
8491       OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
8492       /*IsCompressing*/ false);
8493 
8494   DAG.setRoot(ST);
8495   setValue(&VPIntrin, ST);
8496 }
8497 
8498 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) {
8499   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8500   SDLoc DL = getCurSDLoc();
8501 
8502   ISD::CondCode Condition;
8503   CmpInst::Predicate CondCode = VPIntrin.getPredicate();
8504   bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy();
8505   if (IsFP) {
8506     // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan)
8507     // flags, but calls that don't return floating-point types can't be
8508     // FPMathOperators, like vp.fcmp. This affects constrained fcmp too.
8509     Condition = getFCmpCondCode(CondCode);
8510     if (TM.Options.NoNaNsFPMath)
8511       Condition = getFCmpCodeWithoutNaN(Condition);
8512   } else {
8513     Condition = getICmpCondCode(CondCode);
8514   }
8515 
8516   SDValue Op1 = getValue(VPIntrin.getOperand(0));
8517   SDValue Op2 = getValue(VPIntrin.getOperand(1));
8518   // #2 is the condition code
8519   SDValue MaskOp = getValue(VPIntrin.getOperand(3));
8520   SDValue EVL = getValue(VPIntrin.getOperand(4));
8521   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8522   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8523          "Unexpected target EVL type");
8524   EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL);
8525 
8526   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8527                                                         VPIntrin.getType());
8528   setValue(&VPIntrin,
8529            DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL));
8530 }
8531 
8532 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
8533     const VPIntrinsic &VPIntrin) {
8534   SDLoc DL = getCurSDLoc();
8535   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
8536 
8537   auto IID = VPIntrin.getIntrinsicID();
8538 
8539   if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin))
8540     return visitVPCmp(*CmpI);
8541 
8542   SmallVector<EVT, 4> ValueVTs;
8543   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8544   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
8545   SDVTList VTs = DAG.getVTList(ValueVTs);
8546 
8547   auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
8548 
8549   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8550   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8551          "Unexpected target EVL type");
8552 
8553   // Request operands.
8554   SmallVector<SDValue, 7> OpValues;
8555   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
8556     auto Op = getValue(VPIntrin.getArgOperand(I));
8557     if (I == EVLParamPos)
8558       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
8559     OpValues.push_back(Op);
8560   }
8561 
8562   switch (Opcode) {
8563   default: {
8564     SDNodeFlags SDFlags;
8565     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8566       SDFlags.copyFMF(*FPMO);
8567     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
8568     setValue(&VPIntrin, Result);
8569     break;
8570   }
8571   case ISD::VP_LOAD:
8572     visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
8573     break;
8574   case ISD::VP_GATHER:
8575     visitVPGather(VPIntrin, ValueVTs[0], OpValues);
8576     break;
8577   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
8578     visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
8579     break;
8580   case ISD::VP_STORE:
8581     visitVPStore(VPIntrin, OpValues);
8582     break;
8583   case ISD::VP_SCATTER:
8584     visitVPScatter(VPIntrin, OpValues);
8585     break;
8586   case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
8587     visitVPStridedStore(VPIntrin, OpValues);
8588     break;
8589   case ISD::VP_FMULADD: {
8590     assert(OpValues.size() == 5 && "Unexpected number of operands");
8591     SDNodeFlags SDFlags;
8592     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8593       SDFlags.copyFMF(*FPMO);
8594     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
8595         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) {
8596       setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags));
8597     } else {
8598       SDValue Mul = DAG.getNode(
8599           ISD::VP_FMUL, DL, VTs,
8600           {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags);
8601       SDValue Add =
8602           DAG.getNode(ISD::VP_FADD, DL, VTs,
8603                       {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags);
8604       setValue(&VPIntrin, Add);
8605     }
8606     break;
8607   }
8608   case ISD::VP_IS_FPCLASS: {
8609     const DataLayout DLayout = DAG.getDataLayout();
8610     EVT DestVT = TLI.getValueType(DLayout, VPIntrin.getType());
8611     auto Constant = OpValues[1]->getAsZExtVal();
8612     SDValue Check = DAG.getTargetConstant(Constant, DL, MVT::i32);
8613     SDValue V = DAG.getNode(ISD::VP_IS_FPCLASS, DL, DestVT,
8614                             {OpValues[0], Check, OpValues[2], OpValues[3]});
8615     setValue(&VPIntrin, V);
8616     return;
8617   }
8618   case ISD::VP_INTTOPTR: {
8619     SDValue N = OpValues[0];
8620     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType());
8621     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType());
8622     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8623                                OpValues[2]);
8624     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8625                              OpValues[2]);
8626     setValue(&VPIntrin, N);
8627     break;
8628   }
8629   case ISD::VP_PTRTOINT: {
8630     SDValue N = OpValues[0];
8631     EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8632                                                           VPIntrin.getType());
8633     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(),
8634                                        VPIntrin.getOperand(0)->getType());
8635     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8636                                OpValues[2]);
8637     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8638                              OpValues[2]);
8639     setValue(&VPIntrin, N);
8640     break;
8641   }
8642   case ISD::VP_ABS:
8643   case ISD::VP_CTLZ:
8644   case ISD::VP_CTLZ_ZERO_UNDEF:
8645   case ISD::VP_CTTZ:
8646   case ISD::VP_CTTZ_ZERO_UNDEF:
8647   case ISD::VP_CTTZ_ELTS_ZERO_UNDEF:
8648   case ISD::VP_CTTZ_ELTS: {
8649     SDValue Result =
8650         DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]});
8651     setValue(&VPIntrin, Result);
8652     break;
8653   }
8654   }
8655 }
8656 
8657 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
8658                                           const BasicBlock *EHPadBB,
8659                                           MCSymbol *&BeginLabel) {
8660   MachineFunction &MF = DAG.getMachineFunction();
8661 
8662   // Insert a label before the invoke call to mark the try range.  This can be
8663   // used to detect deletion of the invoke via the MachineModuleInfo.
8664   BeginLabel = MF.getContext().createTempSymbol();
8665 
8666   // For SjLj, keep track of which landing pads go with which invokes
8667   // so as to maintain the ordering of pads in the LSDA.
8668   unsigned CallSiteIndex = FuncInfo.getCurrentCallSite();
8669   if (CallSiteIndex) {
8670     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
8671     LPadToCallSiteMap[FuncInfo.getMBB(EHPadBB)].push_back(CallSiteIndex);
8672 
8673     // Now that the call site is handled, stop tracking it.
8674     FuncInfo.setCurrentCallSite(0);
8675   }
8676 
8677   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
8678 }
8679 
8680 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
8681                                         const BasicBlock *EHPadBB,
8682                                         MCSymbol *BeginLabel) {
8683   assert(BeginLabel && "BeginLabel should've been set");
8684 
8685   MachineFunction &MF = DAG.getMachineFunction();
8686 
8687   // Insert a label at the end of the invoke call to mark the try range.  This
8688   // can be used to detect deletion of the invoke via the MachineModuleInfo.
8689   MCSymbol *EndLabel = MF.getContext().createTempSymbol();
8690   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
8691 
8692   // Inform MachineModuleInfo of range.
8693   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
8694   // There is a platform (e.g. wasm) that uses funclet style IR but does not
8695   // actually use outlined funclets and their LSDA info style.
8696   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
8697     assert(II && "II should've been set");
8698     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
8699     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
8700   } else if (!isScopedEHPersonality(Pers)) {
8701     assert(EHPadBB);
8702     MF.addInvoke(FuncInfo.getMBB(EHPadBB), BeginLabel, EndLabel);
8703   }
8704 
8705   return Chain;
8706 }
8707 
8708 std::pair<SDValue, SDValue>
8709 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
8710                                     const BasicBlock *EHPadBB) {
8711   MCSymbol *BeginLabel = nullptr;
8712 
8713   if (EHPadBB) {
8714     // Both PendingLoads and PendingExports must be flushed here;
8715     // this call might not return.
8716     (void)getRoot();
8717     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
8718     CLI.setChain(getRoot());
8719   }
8720 
8721   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8722   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
8723 
8724   assert((CLI.IsTailCall || Result.second.getNode()) &&
8725          "Non-null chain expected with non-tail call!");
8726   assert((Result.second.getNode() || !Result.first.getNode()) &&
8727          "Null value expected with tail call!");
8728 
8729   if (!Result.second.getNode()) {
8730     // As a special case, a null chain means that a tail call has been emitted
8731     // and the DAG root is already updated.
8732     HasTailCall = true;
8733 
8734     // Since there's no actual continuation from this block, nothing can be
8735     // relying on us setting vregs for them.
8736     PendingExports.clear();
8737   } else {
8738     DAG.setRoot(Result.second);
8739   }
8740 
8741   if (EHPadBB) {
8742     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
8743                            BeginLabel));
8744     Result.second = getRoot();
8745   }
8746 
8747   return Result;
8748 }
8749 
8750 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
8751                                       bool isTailCall, bool isMustTailCall,
8752                                       const BasicBlock *EHPadBB,
8753                                       const TargetLowering::PtrAuthInfo *PAI) {
8754   auto &DL = DAG.getDataLayout();
8755   FunctionType *FTy = CB.getFunctionType();
8756   Type *RetTy = CB.getType();
8757 
8758   TargetLowering::ArgListTy Args;
8759   Args.reserve(CB.arg_size());
8760 
8761   const Value *SwiftErrorVal = nullptr;
8762   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8763 
8764   if (isTailCall) {
8765     // Avoid emitting tail calls in functions with the disable-tail-calls
8766     // attribute.
8767     auto *Caller = CB.getParent()->getParent();
8768     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
8769         "true" && !isMustTailCall)
8770       isTailCall = false;
8771 
8772     // We can't tail call inside a function with a swifterror argument. Lowering
8773     // does not support this yet. It would have to move into the swifterror
8774     // register before the call.
8775     if (TLI.supportSwiftError() &&
8776         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
8777       isTailCall = false;
8778   }
8779 
8780   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
8781     TargetLowering::ArgListEntry Entry;
8782     const Value *V = *I;
8783 
8784     // Skip empty types
8785     if (V->getType()->isEmptyTy())
8786       continue;
8787 
8788     SDValue ArgNode = getValue(V);
8789     Entry.Node = ArgNode; Entry.Ty = V->getType();
8790 
8791     Entry.setAttributes(&CB, I - CB.arg_begin());
8792 
8793     // Use swifterror virtual register as input to the call.
8794     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
8795       SwiftErrorVal = V;
8796       // We find the virtual register for the actual swifterror argument.
8797       // Instead of using the Value, we use the virtual register instead.
8798       Entry.Node =
8799           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
8800                           EVT(TLI.getPointerTy(DL)));
8801     }
8802 
8803     Args.push_back(Entry);
8804 
8805     // If we have an explicit sret argument that is an Instruction, (i.e., it
8806     // might point to function-local memory), we can't meaningfully tail-call.
8807     if (Entry.IsSRet && isa<Instruction>(V))
8808       isTailCall = false;
8809   }
8810 
8811   // If call site has a cfguardtarget operand bundle, create and add an
8812   // additional ArgListEntry.
8813   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
8814     TargetLowering::ArgListEntry Entry;
8815     Value *V = Bundle->Inputs[0];
8816     SDValue ArgNode = getValue(V);
8817     Entry.Node = ArgNode;
8818     Entry.Ty = V->getType();
8819     Entry.IsCFGuardTarget = true;
8820     Args.push_back(Entry);
8821   }
8822 
8823   // Check if target-independent constraints permit a tail call here.
8824   // Target-dependent constraints are checked within TLI->LowerCallTo.
8825   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
8826     isTailCall = false;
8827 
8828   // Disable tail calls if there is an swifterror argument. Targets have not
8829   // been updated to support tail calls.
8830   if (TLI.supportSwiftError() && SwiftErrorVal)
8831     isTailCall = false;
8832 
8833   ConstantInt *CFIType = nullptr;
8834   if (CB.isIndirectCall()) {
8835     if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
8836       if (!TLI.supportKCFIBundles())
8837         report_fatal_error(
8838             "Target doesn't support calls with kcfi operand bundles.");
8839       CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
8840       assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
8841     }
8842   }
8843 
8844   SDValue ConvControlToken;
8845   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_convergencectrl)) {
8846     auto *Token = Bundle->Inputs[0].get();
8847     ConvControlToken = getValue(Token);
8848   }
8849 
8850   TargetLowering::CallLoweringInfo CLI(DAG);
8851   CLI.setDebugLoc(getCurSDLoc())
8852       .setChain(getRoot())
8853       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
8854       .setTailCall(isTailCall)
8855       .setConvergent(CB.isConvergent())
8856       .setIsPreallocated(
8857           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
8858       .setCFIType(CFIType)
8859       .setConvergenceControlToken(ConvControlToken);
8860 
8861   // Set the pointer authentication info if we have it.
8862   if (PAI) {
8863     if (!TLI.supportPtrAuthBundles())
8864       report_fatal_error(
8865           "This target doesn't support calls with ptrauth operand bundles.");
8866     CLI.setPtrAuth(*PAI);
8867   }
8868 
8869   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8870 
8871   if (Result.first.getNode()) {
8872     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
8873     setValue(&CB, Result.first);
8874   }
8875 
8876   // The last element of CLI.InVals has the SDValue for swifterror return.
8877   // Here we copy it to a virtual register and update SwiftErrorMap for
8878   // book-keeping.
8879   if (SwiftErrorVal && TLI.supportSwiftError()) {
8880     // Get the last element of InVals.
8881     SDValue Src = CLI.InVals.back();
8882     Register VReg =
8883         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
8884     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
8885     DAG.setRoot(CopyNode);
8886   }
8887 }
8888 
8889 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
8890                              SelectionDAGBuilder &Builder) {
8891   // Check to see if this load can be trivially constant folded, e.g. if the
8892   // input is from a string literal.
8893   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
8894     // Cast pointer to the type we really want to load.
8895     Type *LoadTy =
8896         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
8897     if (LoadVT.isVector())
8898       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
8899 
8900     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
8901                                          PointerType::getUnqual(LoadTy));
8902 
8903     if (const Constant *LoadCst =
8904             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
8905                                          LoadTy, Builder.DAG.getDataLayout()))
8906       return Builder.getValue(LoadCst);
8907   }
8908 
8909   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
8910   // still constant memory, the input chain can be the entry node.
8911   SDValue Root;
8912   bool ConstantMemory = false;
8913 
8914   // Do not serialize (non-volatile) loads of constant memory with anything.
8915   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
8916     Root = Builder.DAG.getEntryNode();
8917     ConstantMemory = true;
8918   } else {
8919     // Do not serialize non-volatile loads against each other.
8920     Root = Builder.DAG.getRoot();
8921   }
8922 
8923   SDValue Ptr = Builder.getValue(PtrVal);
8924   SDValue LoadVal =
8925       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
8926                           MachinePointerInfo(PtrVal), Align(1));
8927 
8928   if (!ConstantMemory)
8929     Builder.PendingLoads.push_back(LoadVal.getValue(1));
8930   return LoadVal;
8931 }
8932 
8933 /// Record the value for an instruction that produces an integer result,
8934 /// converting the type where necessary.
8935 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
8936                                                   SDValue Value,
8937                                                   bool IsSigned) {
8938   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8939                                                     I.getType(), true);
8940   Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT);
8941   setValue(&I, Value);
8942 }
8943 
8944 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
8945 /// true and lower it. Otherwise return false, and it will be lowered like a
8946 /// normal call.
8947 /// The caller already checked that \p I calls the appropriate LibFunc with a
8948 /// correct prototype.
8949 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
8950   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
8951   const Value *Size = I.getArgOperand(2);
8952   const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
8953   if (CSize && CSize->getZExtValue() == 0) {
8954     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8955                                                           I.getType(), true);
8956     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
8957     return true;
8958   }
8959 
8960   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8961   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
8962       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
8963       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
8964   if (Res.first.getNode()) {
8965     processIntegerCallValue(I, Res.first, true);
8966     PendingLoads.push_back(Res.second);
8967     return true;
8968   }
8969 
8970   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
8971   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
8972   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
8973     return false;
8974 
8975   // If the target has a fast compare for the given size, it will return a
8976   // preferred load type for that size. Require that the load VT is legal and
8977   // that the target supports unaligned loads of that type. Otherwise, return
8978   // INVALID.
8979   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
8980     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8981     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
8982     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
8983       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
8984       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
8985       // TODO: Check alignment of src and dest ptrs.
8986       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
8987       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
8988       if (!TLI.isTypeLegal(LVT) ||
8989           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
8990           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
8991         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
8992     }
8993 
8994     return LVT;
8995   };
8996 
8997   // This turns into unaligned loads. We only do this if the target natively
8998   // supports the MVT we'll be loading or if it is small enough (<= 4) that
8999   // we'll only produce a small number of byte loads.
9000   MVT LoadVT;
9001   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
9002   switch (NumBitsToCompare) {
9003   default:
9004     return false;
9005   case 16:
9006     LoadVT = MVT::i16;
9007     break;
9008   case 32:
9009     LoadVT = MVT::i32;
9010     break;
9011   case 64:
9012   case 128:
9013   case 256:
9014     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
9015     break;
9016   }
9017 
9018   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
9019     return false;
9020 
9021   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
9022   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
9023 
9024   // Bitcast to a wide integer type if the loads are vectors.
9025   if (LoadVT.isVector()) {
9026     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
9027     LoadL = DAG.getBitcast(CmpVT, LoadL);
9028     LoadR = DAG.getBitcast(CmpVT, LoadR);
9029   }
9030 
9031   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
9032   processIntegerCallValue(I, Cmp, false);
9033   return true;
9034 }
9035 
9036 /// See if we can lower a memchr call into an optimized form. If so, return
9037 /// true and lower it. Otherwise return false, and it will be lowered like a
9038 /// normal call.
9039 /// The caller already checked that \p I calls the appropriate LibFunc with a
9040 /// correct prototype.
9041 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
9042   const Value *Src = I.getArgOperand(0);
9043   const Value *Char = I.getArgOperand(1);
9044   const Value *Length = I.getArgOperand(2);
9045 
9046   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9047   std::pair<SDValue, SDValue> Res =
9048     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
9049                                 getValue(Src), getValue(Char), getValue(Length),
9050                                 MachinePointerInfo(Src));
9051   if (Res.first.getNode()) {
9052     setValue(&I, Res.first);
9053     PendingLoads.push_back(Res.second);
9054     return true;
9055   }
9056 
9057   return false;
9058 }
9059 
9060 /// See if we can lower a mempcpy call into an optimized form. If so, return
9061 /// true and lower it. Otherwise return false, and it will be lowered like a
9062 /// normal call.
9063 /// The caller already checked that \p I calls the appropriate LibFunc with a
9064 /// correct prototype.
9065 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
9066   SDValue Dst = getValue(I.getArgOperand(0));
9067   SDValue Src = getValue(I.getArgOperand(1));
9068   SDValue Size = getValue(I.getArgOperand(2));
9069 
9070   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
9071   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
9072   // DAG::getMemcpy needs Alignment to be defined.
9073   Align Alignment = std::min(DstAlign, SrcAlign);
9074 
9075   SDLoc sdl = getCurSDLoc();
9076 
9077   // In the mempcpy context we need to pass in a false value for isTailCall
9078   // because the return pointer needs to be adjusted by the size of
9079   // the copied memory.
9080   SDValue Root = getMemoryRoot();
9081   SDValue MC = DAG.getMemcpy(
9082       Root, sdl, Dst, Src, Size, Alignment, false, false, /*CI=*/nullptr,
9083       std::nullopt, MachinePointerInfo(I.getArgOperand(0)),
9084       MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata());
9085   assert(MC.getNode() != nullptr &&
9086          "** memcpy should not be lowered as TailCall in mempcpy context **");
9087   DAG.setRoot(MC);
9088 
9089   // Check if Size needs to be truncated or extended.
9090   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
9091 
9092   // Adjust return pointer to point just past the last dst byte.
9093   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
9094                                     Dst, Size);
9095   setValue(&I, DstPlusSize);
9096   return true;
9097 }
9098 
9099 /// See if we can lower a strcpy call into an optimized form.  If so, return
9100 /// true and lower it, otherwise return false and it will be lowered like a
9101 /// normal call.
9102 /// The caller already checked that \p I calls the appropriate LibFunc with a
9103 /// correct prototype.
9104 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
9105   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9106 
9107   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9108   std::pair<SDValue, SDValue> Res =
9109     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
9110                                 getValue(Arg0), getValue(Arg1),
9111                                 MachinePointerInfo(Arg0),
9112                                 MachinePointerInfo(Arg1), isStpcpy);
9113   if (Res.first.getNode()) {
9114     setValue(&I, Res.first);
9115     DAG.setRoot(Res.second);
9116     return true;
9117   }
9118 
9119   return false;
9120 }
9121 
9122 /// See if we can lower a strcmp call into an optimized form.  If so, return
9123 /// true and lower it, otherwise return false and it will be lowered like a
9124 /// normal call.
9125 /// The caller already checked that \p I calls the appropriate LibFunc with a
9126 /// correct prototype.
9127 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
9128   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9129 
9130   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9131   std::pair<SDValue, SDValue> Res =
9132     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
9133                                 getValue(Arg0), getValue(Arg1),
9134                                 MachinePointerInfo(Arg0),
9135                                 MachinePointerInfo(Arg1));
9136   if (Res.first.getNode()) {
9137     processIntegerCallValue(I, Res.first, true);
9138     PendingLoads.push_back(Res.second);
9139     return true;
9140   }
9141 
9142   return false;
9143 }
9144 
9145 /// See if we can lower a strlen call into an optimized form.  If so, return
9146 /// true and lower it, otherwise return false and it will be lowered like a
9147 /// normal call.
9148 /// The caller already checked that \p I calls the appropriate LibFunc with a
9149 /// correct prototype.
9150 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
9151   const Value *Arg0 = I.getArgOperand(0);
9152 
9153   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9154   std::pair<SDValue, SDValue> Res =
9155     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
9156                                 getValue(Arg0), MachinePointerInfo(Arg0));
9157   if (Res.first.getNode()) {
9158     processIntegerCallValue(I, Res.first, false);
9159     PendingLoads.push_back(Res.second);
9160     return true;
9161   }
9162 
9163   return false;
9164 }
9165 
9166 /// See if we can lower a strnlen call into an optimized form.  If so, return
9167 /// true and lower it, otherwise return false and it will be lowered like a
9168 /// normal call.
9169 /// The caller already checked that \p I calls the appropriate LibFunc with a
9170 /// correct prototype.
9171 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
9172   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9173 
9174   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9175   std::pair<SDValue, SDValue> Res =
9176     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
9177                                  getValue(Arg0), getValue(Arg1),
9178                                  MachinePointerInfo(Arg0));
9179   if (Res.first.getNode()) {
9180     processIntegerCallValue(I, Res.first, false);
9181     PendingLoads.push_back(Res.second);
9182     return true;
9183   }
9184 
9185   return false;
9186 }
9187 
9188 /// See if we can lower a unary floating-point operation into an SDNode with
9189 /// the specified Opcode.  If so, return true and lower it, otherwise return
9190 /// false and it will be lowered like a normal call.
9191 /// The caller already checked that \p I calls the appropriate LibFunc with a
9192 /// correct prototype.
9193 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
9194                                               unsigned Opcode) {
9195   // We already checked this call's prototype; verify it doesn't modify errno.
9196   if (!I.onlyReadsMemory())
9197     return false;
9198 
9199   SDNodeFlags Flags;
9200   Flags.copyFMF(cast<FPMathOperator>(I));
9201 
9202   SDValue Tmp = getValue(I.getArgOperand(0));
9203   setValue(&I,
9204            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
9205   return true;
9206 }
9207 
9208 /// See if we can lower a binary floating-point operation into an SDNode with
9209 /// the specified Opcode. If so, return true and lower it. Otherwise return
9210 /// false, and it will be lowered like a normal call.
9211 /// The caller already checked that \p I calls the appropriate LibFunc with a
9212 /// correct prototype.
9213 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
9214                                                unsigned Opcode) {
9215   // We already checked this call's prototype; verify it doesn't modify errno.
9216   if (!I.onlyReadsMemory())
9217     return false;
9218 
9219   SDNodeFlags Flags;
9220   Flags.copyFMF(cast<FPMathOperator>(I));
9221 
9222   SDValue Tmp0 = getValue(I.getArgOperand(0));
9223   SDValue Tmp1 = getValue(I.getArgOperand(1));
9224   EVT VT = Tmp0.getValueType();
9225   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
9226   return true;
9227 }
9228 
9229 void SelectionDAGBuilder::visitCall(const CallInst &I) {
9230   // Handle inline assembly differently.
9231   if (I.isInlineAsm()) {
9232     visitInlineAsm(I);
9233     return;
9234   }
9235 
9236   diagnoseDontCall(I);
9237 
9238   if (Function *F = I.getCalledFunction()) {
9239     if (F->isDeclaration()) {
9240       // Is this an LLVM intrinsic or a target-specific intrinsic?
9241       unsigned IID = F->getIntrinsicID();
9242       if (!IID)
9243         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
9244           IID = II->getIntrinsicID(F);
9245 
9246       if (IID) {
9247         visitIntrinsicCall(I, IID);
9248         return;
9249       }
9250     }
9251 
9252     // Check for well-known libc/libm calls.  If the function is internal, it
9253     // can't be a library call.  Don't do the check if marked as nobuiltin for
9254     // some reason or the call site requires strict floating point semantics.
9255     LibFunc Func;
9256     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
9257         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
9258         LibInfo->hasOptimizedCodeGen(Func)) {
9259       switch (Func) {
9260       default: break;
9261       case LibFunc_bcmp:
9262         if (visitMemCmpBCmpCall(I))
9263           return;
9264         break;
9265       case LibFunc_copysign:
9266       case LibFunc_copysignf:
9267       case LibFunc_copysignl:
9268         // We already checked this call's prototype; verify it doesn't modify
9269         // errno.
9270         if (I.onlyReadsMemory()) {
9271           SDValue LHS = getValue(I.getArgOperand(0));
9272           SDValue RHS = getValue(I.getArgOperand(1));
9273           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
9274                                    LHS.getValueType(), LHS, RHS));
9275           return;
9276         }
9277         break;
9278       case LibFunc_fabs:
9279       case LibFunc_fabsf:
9280       case LibFunc_fabsl:
9281         if (visitUnaryFloatCall(I, ISD::FABS))
9282           return;
9283         break;
9284       case LibFunc_fmin:
9285       case LibFunc_fminf:
9286       case LibFunc_fminl:
9287         if (visitBinaryFloatCall(I, ISD::FMINNUM))
9288           return;
9289         break;
9290       case LibFunc_fmax:
9291       case LibFunc_fmaxf:
9292       case LibFunc_fmaxl:
9293         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
9294           return;
9295         break;
9296       case LibFunc_fminimum_num:
9297       case LibFunc_fminimum_numf:
9298       case LibFunc_fminimum_numl:
9299         if (visitBinaryFloatCall(I, ISD::FMINIMUMNUM))
9300           return;
9301         break;
9302       case LibFunc_fmaximum_num:
9303       case LibFunc_fmaximum_numf:
9304       case LibFunc_fmaximum_numl:
9305         if (visitBinaryFloatCall(I, ISD::FMAXIMUMNUM))
9306           return;
9307         break;
9308       case LibFunc_sin:
9309       case LibFunc_sinf:
9310       case LibFunc_sinl:
9311         if (visitUnaryFloatCall(I, ISD::FSIN))
9312           return;
9313         break;
9314       case LibFunc_cos:
9315       case LibFunc_cosf:
9316       case LibFunc_cosl:
9317         if (visitUnaryFloatCall(I, ISD::FCOS))
9318           return;
9319         break;
9320       case LibFunc_tan:
9321       case LibFunc_tanf:
9322       case LibFunc_tanl:
9323         if (visitUnaryFloatCall(I, ISD::FTAN))
9324           return;
9325         break;
9326       case LibFunc_asin:
9327       case LibFunc_asinf:
9328       case LibFunc_asinl:
9329         if (visitUnaryFloatCall(I, ISD::FASIN))
9330           return;
9331         break;
9332       case LibFunc_acos:
9333       case LibFunc_acosf:
9334       case LibFunc_acosl:
9335         if (visitUnaryFloatCall(I, ISD::FACOS))
9336           return;
9337         break;
9338       case LibFunc_atan:
9339       case LibFunc_atanf:
9340       case LibFunc_atanl:
9341         if (visitUnaryFloatCall(I, ISD::FATAN))
9342           return;
9343         break;
9344       case LibFunc_sinh:
9345       case LibFunc_sinhf:
9346       case LibFunc_sinhl:
9347         if (visitUnaryFloatCall(I, ISD::FSINH))
9348           return;
9349         break;
9350       case LibFunc_cosh:
9351       case LibFunc_coshf:
9352       case LibFunc_coshl:
9353         if (visitUnaryFloatCall(I, ISD::FCOSH))
9354           return;
9355         break;
9356       case LibFunc_tanh:
9357       case LibFunc_tanhf:
9358       case LibFunc_tanhl:
9359         if (visitUnaryFloatCall(I, ISD::FTANH))
9360           return;
9361         break;
9362       case LibFunc_sqrt:
9363       case LibFunc_sqrtf:
9364       case LibFunc_sqrtl:
9365       case LibFunc_sqrt_finite:
9366       case LibFunc_sqrtf_finite:
9367       case LibFunc_sqrtl_finite:
9368         if (visitUnaryFloatCall(I, ISD::FSQRT))
9369           return;
9370         break;
9371       case LibFunc_floor:
9372       case LibFunc_floorf:
9373       case LibFunc_floorl:
9374         if (visitUnaryFloatCall(I, ISD::FFLOOR))
9375           return;
9376         break;
9377       case LibFunc_nearbyint:
9378       case LibFunc_nearbyintf:
9379       case LibFunc_nearbyintl:
9380         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
9381           return;
9382         break;
9383       case LibFunc_ceil:
9384       case LibFunc_ceilf:
9385       case LibFunc_ceill:
9386         if (visitUnaryFloatCall(I, ISD::FCEIL))
9387           return;
9388         break;
9389       case LibFunc_rint:
9390       case LibFunc_rintf:
9391       case LibFunc_rintl:
9392         if (visitUnaryFloatCall(I, ISD::FRINT))
9393           return;
9394         break;
9395       case LibFunc_round:
9396       case LibFunc_roundf:
9397       case LibFunc_roundl:
9398         if (visitUnaryFloatCall(I, ISD::FROUND))
9399           return;
9400         break;
9401       case LibFunc_trunc:
9402       case LibFunc_truncf:
9403       case LibFunc_truncl:
9404         if (visitUnaryFloatCall(I, ISD::FTRUNC))
9405           return;
9406         break;
9407       case LibFunc_log2:
9408       case LibFunc_log2f:
9409       case LibFunc_log2l:
9410         if (visitUnaryFloatCall(I, ISD::FLOG2))
9411           return;
9412         break;
9413       case LibFunc_exp2:
9414       case LibFunc_exp2f:
9415       case LibFunc_exp2l:
9416         if (visitUnaryFloatCall(I, ISD::FEXP2))
9417           return;
9418         break;
9419       case LibFunc_exp10:
9420       case LibFunc_exp10f:
9421       case LibFunc_exp10l:
9422         if (visitUnaryFloatCall(I, ISD::FEXP10))
9423           return;
9424         break;
9425       case LibFunc_ldexp:
9426       case LibFunc_ldexpf:
9427       case LibFunc_ldexpl:
9428         if (visitBinaryFloatCall(I, ISD::FLDEXP))
9429           return;
9430         break;
9431       case LibFunc_memcmp:
9432         if (visitMemCmpBCmpCall(I))
9433           return;
9434         break;
9435       case LibFunc_mempcpy:
9436         if (visitMemPCpyCall(I))
9437           return;
9438         break;
9439       case LibFunc_memchr:
9440         if (visitMemChrCall(I))
9441           return;
9442         break;
9443       case LibFunc_strcpy:
9444         if (visitStrCpyCall(I, false))
9445           return;
9446         break;
9447       case LibFunc_stpcpy:
9448         if (visitStrCpyCall(I, true))
9449           return;
9450         break;
9451       case LibFunc_strcmp:
9452         if (visitStrCmpCall(I))
9453           return;
9454         break;
9455       case LibFunc_strlen:
9456         if (visitStrLenCall(I))
9457           return;
9458         break;
9459       case LibFunc_strnlen:
9460         if (visitStrNLenCall(I))
9461           return;
9462         break;
9463       }
9464     }
9465   }
9466 
9467   if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
9468     LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), /*EHPadBB=*/nullptr);
9469     return;
9470   }
9471 
9472   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
9473   // have to do anything here to lower funclet bundles.
9474   // CFGuardTarget bundles are lowered in LowerCallTo.
9475   assert(!I.hasOperandBundlesOtherThan(
9476              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
9477               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
9478               LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi,
9479               LLVMContext::OB_convergencectrl}) &&
9480          "Cannot lower calls with arbitrary operand bundles!");
9481 
9482   SDValue Callee = getValue(I.getCalledOperand());
9483 
9484   if (I.hasDeoptState())
9485     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
9486   else
9487     // Check if we can potentially perform a tail call. More detailed checking
9488     // is be done within LowerCallTo, after more information about the call is
9489     // known.
9490     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
9491 }
9492 
9493 void SelectionDAGBuilder::LowerCallSiteWithPtrAuthBundle(
9494     const CallBase &CB, const BasicBlock *EHPadBB) {
9495   auto PAB = CB.getOperandBundle("ptrauth");
9496   const Value *CalleeV = CB.getCalledOperand();
9497 
9498   // Gather the call ptrauth data from the operand bundle:
9499   //   [ i32 <key>, i64 <discriminator> ]
9500   const auto *Key = cast<ConstantInt>(PAB->Inputs[0]);
9501   const Value *Discriminator = PAB->Inputs[1];
9502 
9503   assert(Key->getType()->isIntegerTy(32) && "Invalid ptrauth key");
9504   assert(Discriminator->getType()->isIntegerTy(64) &&
9505          "Invalid ptrauth discriminator");
9506 
9507   // Look through ptrauth constants to find the raw callee.
9508   // Do a direct unauthenticated call if we found it and everything matches.
9509   if (const auto *CalleeCPA = dyn_cast<ConstantPtrAuth>(CalleeV))
9510     if (CalleeCPA->isKnownCompatibleWith(Key, Discriminator,
9511                                          DAG.getDataLayout()))
9512       return LowerCallTo(CB, getValue(CalleeCPA->getPointer()), CB.isTailCall(),
9513                          CB.isMustTailCall(), EHPadBB);
9514 
9515   // Functions should never be ptrauth-called directly.
9516   assert(!isa<Function>(CalleeV) && "invalid direct ptrauth call");
9517 
9518   // Otherwise, do an authenticated indirect call.
9519   TargetLowering::PtrAuthInfo PAI = {Key->getZExtValue(),
9520                                      getValue(Discriminator)};
9521 
9522   LowerCallTo(CB, getValue(CalleeV), CB.isTailCall(), CB.isMustTailCall(),
9523               EHPadBB, &PAI);
9524 }
9525 
9526 namespace {
9527 
9528 /// AsmOperandInfo - This contains information for each constraint that we are
9529 /// lowering.
9530 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
9531 public:
9532   /// CallOperand - If this is the result output operand or a clobber
9533   /// this is null, otherwise it is the incoming operand to the CallInst.
9534   /// This gets modified as the asm is processed.
9535   SDValue CallOperand;
9536 
9537   /// AssignedRegs - If this is a register or register class operand, this
9538   /// contains the set of register corresponding to the operand.
9539   RegsForValue AssignedRegs;
9540 
9541   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
9542     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
9543   }
9544 
9545   /// Whether or not this operand accesses memory
9546   bool hasMemory(const TargetLowering &TLI) const {
9547     // Indirect operand accesses access memory.
9548     if (isIndirect)
9549       return true;
9550 
9551     for (const auto &Code : Codes)
9552       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
9553         return true;
9554 
9555     return false;
9556   }
9557 };
9558 
9559 
9560 } // end anonymous namespace
9561 
9562 /// Make sure that the output operand \p OpInfo and its corresponding input
9563 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
9564 /// out).
9565 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
9566                                SDISelAsmOperandInfo &MatchingOpInfo,
9567                                SelectionDAG &DAG) {
9568   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
9569     return;
9570 
9571   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
9572   const auto &TLI = DAG.getTargetLoweringInfo();
9573 
9574   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
9575       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
9576                                        OpInfo.ConstraintVT);
9577   std::pair<unsigned, const TargetRegisterClass *> InputRC =
9578       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
9579                                        MatchingOpInfo.ConstraintVT);
9580   const bool OutOpIsIntOrFP =
9581       OpInfo.ConstraintVT.isInteger() || OpInfo.ConstraintVT.isFloatingPoint();
9582   const bool InOpIsIntOrFP = MatchingOpInfo.ConstraintVT.isInteger() ||
9583                              MatchingOpInfo.ConstraintVT.isFloatingPoint();
9584   if ((OutOpIsIntOrFP != InOpIsIntOrFP) || (MatchRC.second != InputRC.second)) {
9585     // FIXME: error out in a more elegant fashion
9586     report_fatal_error("Unsupported asm: input constraint"
9587                        " with a matching output constraint of"
9588                        " incompatible type!");
9589   }
9590   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
9591 }
9592 
9593 /// Get a direct memory input to behave well as an indirect operand.
9594 /// This may introduce stores, hence the need for a \p Chain.
9595 /// \return The (possibly updated) chain.
9596 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
9597                                         SDISelAsmOperandInfo &OpInfo,
9598                                         SelectionDAG &DAG) {
9599   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9600 
9601   // If we don't have an indirect input, put it in the constpool if we can,
9602   // otherwise spill it to a stack slot.
9603   // TODO: This isn't quite right. We need to handle these according to
9604   // the addressing mode that the constraint wants. Also, this may take
9605   // an additional register for the computation and we don't want that
9606   // either.
9607 
9608   // If the operand is a float, integer, or vector constant, spill to a
9609   // constant pool entry to get its address.
9610   const Value *OpVal = OpInfo.CallOperandVal;
9611   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
9612       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
9613     OpInfo.CallOperand = DAG.getConstantPool(
9614         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
9615     return Chain;
9616   }
9617 
9618   // Otherwise, create a stack slot and emit a store to it before the asm.
9619   Type *Ty = OpVal->getType();
9620   auto &DL = DAG.getDataLayout();
9621   TypeSize TySize = DL.getTypeAllocSize(Ty);
9622   MachineFunction &MF = DAG.getMachineFunction();
9623   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
9624   int StackID = 0;
9625   if (TySize.isScalable())
9626     StackID = TFI->getStackIDForScalableVectors();
9627   int SSFI = MF.getFrameInfo().CreateStackObject(TySize.getKnownMinValue(),
9628                                                  DL.getPrefTypeAlign(Ty), false,
9629                                                  nullptr, StackID);
9630   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
9631   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
9632                             MachinePointerInfo::getFixedStack(MF, SSFI),
9633                             TLI.getMemValueType(DL, Ty));
9634   OpInfo.CallOperand = StackSlot;
9635 
9636   return Chain;
9637 }
9638 
9639 /// GetRegistersForValue - Assign registers (virtual or physical) for the
9640 /// specified operand.  We prefer to assign virtual registers, to allow the
9641 /// register allocator to handle the assignment process.  However, if the asm
9642 /// uses features that we can't model on machineinstrs, we have SDISel do the
9643 /// allocation.  This produces generally horrible, but correct, code.
9644 ///
9645 ///   OpInfo describes the operand
9646 ///   RefOpInfo describes the matching operand if any, the operand otherwise
9647 static std::optional<unsigned>
9648 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
9649                      SDISelAsmOperandInfo &OpInfo,
9650                      SDISelAsmOperandInfo &RefOpInfo) {
9651   LLVMContext &Context = *DAG.getContext();
9652   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9653 
9654   MachineFunction &MF = DAG.getMachineFunction();
9655   SmallVector<Register, 4> Regs;
9656   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9657 
9658   // No work to do for memory/address operands.
9659   if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9660       OpInfo.ConstraintType == TargetLowering::C_Address)
9661     return std::nullopt;
9662 
9663   // If this is a constraint for a single physreg, or a constraint for a
9664   // register class, find it.
9665   unsigned AssignedReg;
9666   const TargetRegisterClass *RC;
9667   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
9668       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
9669   // RC is unset only on failure. Return immediately.
9670   if (!RC)
9671     return std::nullopt;
9672 
9673   // Get the actual register value type.  This is important, because the user
9674   // may have asked for (e.g.) the AX register in i32 type.  We need to
9675   // remember that AX is actually i16 to get the right extension.
9676   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
9677 
9678   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
9679     // If this is an FP operand in an integer register (or visa versa), or more
9680     // generally if the operand value disagrees with the register class we plan
9681     // to stick it in, fix the operand type.
9682     //
9683     // If this is an input value, the bitcast to the new type is done now.
9684     // Bitcast for output value is done at the end of visitInlineAsm().
9685     if ((OpInfo.Type == InlineAsm::isOutput ||
9686          OpInfo.Type == InlineAsm::isInput) &&
9687         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
9688       // Try to convert to the first EVT that the reg class contains.  If the
9689       // types are identical size, use a bitcast to convert (e.g. two differing
9690       // vector types).  Note: output bitcast is done at the end of
9691       // visitInlineAsm().
9692       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
9693         // Exclude indirect inputs while they are unsupported because the code
9694         // to perform the load is missing and thus OpInfo.CallOperand still
9695         // refers to the input address rather than the pointed-to value.
9696         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
9697           OpInfo.CallOperand =
9698               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
9699         OpInfo.ConstraintVT = RegVT;
9700         // If the operand is an FP value and we want it in integer registers,
9701         // use the corresponding integer type. This turns an f64 value into
9702         // i64, which can be passed with two i32 values on a 32-bit machine.
9703       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
9704         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
9705         if (OpInfo.Type == InlineAsm::isInput)
9706           OpInfo.CallOperand =
9707               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
9708         OpInfo.ConstraintVT = VT;
9709       }
9710     }
9711   }
9712 
9713   // No need to allocate a matching input constraint since the constraint it's
9714   // matching to has already been allocated.
9715   if (OpInfo.isMatchingInputConstraint())
9716     return std::nullopt;
9717 
9718   EVT ValueVT = OpInfo.ConstraintVT;
9719   if (OpInfo.ConstraintVT == MVT::Other)
9720     ValueVT = RegVT;
9721 
9722   // Initialize NumRegs.
9723   unsigned NumRegs = 1;
9724   if (OpInfo.ConstraintVT != MVT::Other)
9725     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
9726 
9727   // If this is a constraint for a specific physical register, like {r17},
9728   // assign it now.
9729 
9730   // If this associated to a specific register, initialize iterator to correct
9731   // place. If virtual, make sure we have enough registers
9732 
9733   // Initialize iterator if necessary
9734   TargetRegisterClass::iterator I = RC->begin();
9735   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9736 
9737   // Do not check for single registers.
9738   if (AssignedReg) {
9739     I = std::find(I, RC->end(), AssignedReg);
9740     if (I == RC->end()) {
9741       // RC does not contain the selected register, which indicates a
9742       // mismatch between the register and the required type/bitwidth.
9743       return {AssignedReg};
9744     }
9745   }
9746 
9747   for (; NumRegs; --NumRegs, ++I) {
9748     assert(I != RC->end() && "Ran out of registers to allocate!");
9749     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
9750     Regs.push_back(R);
9751   }
9752 
9753   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
9754   return std::nullopt;
9755 }
9756 
9757 static unsigned
9758 findMatchingInlineAsmOperand(unsigned OperandNo,
9759                              const std::vector<SDValue> &AsmNodeOperands) {
9760   // Scan until we find the definition we already emitted of this operand.
9761   unsigned CurOp = InlineAsm::Op_FirstOperand;
9762   for (; OperandNo; --OperandNo) {
9763     // Advance to the next operand.
9764     unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal();
9765     const InlineAsm::Flag F(OpFlag);
9766     assert(
9767         (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) &&
9768         "Skipped past definitions?");
9769     CurOp += F.getNumOperandRegisters() + 1;
9770   }
9771   return CurOp;
9772 }
9773 
9774 namespace {
9775 
9776 class ExtraFlags {
9777   unsigned Flags = 0;
9778 
9779 public:
9780   explicit ExtraFlags(const CallBase &Call) {
9781     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9782     if (IA->hasSideEffects())
9783       Flags |= InlineAsm::Extra_HasSideEffects;
9784     if (IA->isAlignStack())
9785       Flags |= InlineAsm::Extra_IsAlignStack;
9786     if (Call.isConvergent())
9787       Flags |= InlineAsm::Extra_IsConvergent;
9788     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
9789   }
9790 
9791   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
9792     // Ideally, we would only check against memory constraints.  However, the
9793     // meaning of an Other constraint can be target-specific and we can't easily
9794     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
9795     // for Other constraints as well.
9796     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9797         OpInfo.ConstraintType == TargetLowering::C_Other) {
9798       if (OpInfo.Type == InlineAsm::isInput)
9799         Flags |= InlineAsm::Extra_MayLoad;
9800       else if (OpInfo.Type == InlineAsm::isOutput)
9801         Flags |= InlineAsm::Extra_MayStore;
9802       else if (OpInfo.Type == InlineAsm::isClobber)
9803         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
9804     }
9805   }
9806 
9807   unsigned get() const { return Flags; }
9808 };
9809 
9810 } // end anonymous namespace
9811 
9812 static bool isFunction(SDValue Op) {
9813   if (Op && Op.getOpcode() == ISD::GlobalAddress) {
9814     if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
9815       auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
9816 
9817       // In normal "call dllimport func" instruction (non-inlineasm) it force
9818       // indirect access by specifing call opcode. And usually specially print
9819       // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
9820       // not do in this way now. (In fact, this is similar with "Data Access"
9821       // action). So here we ignore dllimport function.
9822       if (Fn && !Fn->hasDLLImportStorageClass())
9823         return true;
9824     }
9825   }
9826   return false;
9827 }
9828 
9829 /// visitInlineAsm - Handle a call to an InlineAsm object.
9830 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
9831                                          const BasicBlock *EHPadBB) {
9832   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9833 
9834   /// ConstraintOperands - Information about all of the constraints.
9835   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
9836 
9837   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9838   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
9839       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
9840 
9841   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
9842   // AsmDialect, MayLoad, MayStore).
9843   bool HasSideEffect = IA->hasSideEffects();
9844   ExtraFlags ExtraInfo(Call);
9845 
9846   for (auto &T : TargetConstraints) {
9847     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
9848     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
9849 
9850     if (OpInfo.CallOperandVal)
9851       OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
9852 
9853     if (!HasSideEffect)
9854       HasSideEffect = OpInfo.hasMemory(TLI);
9855 
9856     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
9857     // FIXME: Could we compute this on OpInfo rather than T?
9858 
9859     // Compute the constraint code and ConstraintType to use.
9860     TLI.ComputeConstraintToUse(T, SDValue());
9861 
9862     if (T.ConstraintType == TargetLowering::C_Immediate &&
9863         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
9864       // We've delayed emitting a diagnostic like the "n" constraint because
9865       // inlining could cause an integer showing up.
9866       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
9867                                           "' expects an integer constant "
9868                                           "expression");
9869 
9870     ExtraInfo.update(T);
9871   }
9872 
9873   // We won't need to flush pending loads if this asm doesn't touch
9874   // memory and is nonvolatile.
9875   SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
9876 
9877   bool EmitEHLabels = isa<InvokeInst>(Call);
9878   if (EmitEHLabels) {
9879     assert(EHPadBB && "InvokeInst must have an EHPadBB");
9880   }
9881   bool IsCallBr = isa<CallBrInst>(Call);
9882 
9883   if (IsCallBr || EmitEHLabels) {
9884     // If this is a callbr or invoke we need to flush pending exports since
9885     // inlineasm_br and invoke are terminators.
9886     // We need to do this before nodes are glued to the inlineasm_br node.
9887     Chain = getControlRoot();
9888   }
9889 
9890   MCSymbol *BeginLabel = nullptr;
9891   if (EmitEHLabels) {
9892     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
9893   }
9894 
9895   int OpNo = -1;
9896   SmallVector<StringRef> AsmStrs;
9897   IA->collectAsmStrs(AsmStrs);
9898 
9899   // Second pass over the constraints: compute which constraint option to use.
9900   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9901     if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
9902       OpNo++;
9903 
9904     // If this is an output operand with a matching input operand, look up the
9905     // matching input. If their types mismatch, e.g. one is an integer, the
9906     // other is floating point, or their sizes are different, flag it as an
9907     // error.
9908     if (OpInfo.hasMatchingInput()) {
9909       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
9910       patchMatchingInput(OpInfo, Input, DAG);
9911     }
9912 
9913     // Compute the constraint code and ConstraintType to use.
9914     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
9915 
9916     if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
9917          OpInfo.Type == InlineAsm::isClobber) ||
9918         OpInfo.ConstraintType == TargetLowering::C_Address)
9919       continue;
9920 
9921     // In Linux PIC model, there are 4 cases about value/label addressing:
9922     //
9923     // 1: Function call or Label jmp inside the module.
9924     // 2: Data access (such as global variable, static variable) inside module.
9925     // 3: Function call or Label jmp outside the module.
9926     // 4: Data access (such as global variable) outside the module.
9927     //
9928     // Due to current llvm inline asm architecture designed to not "recognize"
9929     // the asm code, there are quite troubles for us to treat mem addressing
9930     // differently for same value/adress used in different instuctions.
9931     // For example, in pic model, call a func may in plt way or direclty
9932     // pc-related, but lea/mov a function adress may use got.
9933     //
9934     // Here we try to "recognize" function call for the case 1 and case 3 in
9935     // inline asm. And try to adjust the constraint for them.
9936     //
9937     // TODO: Due to current inline asm didn't encourage to jmp to the outsider
9938     // label, so here we don't handle jmp function label now, but we need to
9939     // enhance it (especilly in PIC model) if we meet meaningful requirements.
9940     if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
9941         TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
9942         TM.getCodeModel() != CodeModel::Large) {
9943       OpInfo.isIndirect = false;
9944       OpInfo.ConstraintType = TargetLowering::C_Address;
9945     }
9946 
9947     // If this is a memory input, and if the operand is not indirect, do what we
9948     // need to provide an address for the memory input.
9949     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
9950         !OpInfo.isIndirect) {
9951       assert((OpInfo.isMultipleAlternative ||
9952               (OpInfo.Type == InlineAsm::isInput)) &&
9953              "Can only indirectify direct input operands!");
9954 
9955       // Memory operands really want the address of the value.
9956       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
9957 
9958       // There is no longer a Value* corresponding to this operand.
9959       OpInfo.CallOperandVal = nullptr;
9960 
9961       // It is now an indirect operand.
9962       OpInfo.isIndirect = true;
9963     }
9964 
9965   }
9966 
9967   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
9968   std::vector<SDValue> AsmNodeOperands;
9969   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
9970   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
9971       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
9972 
9973   // If we have a !srcloc metadata node associated with it, we want to attach
9974   // this to the ultimately generated inline asm machineinstr.  To do this, we
9975   // pass in the third operand as this (potentially null) inline asm MDNode.
9976   const MDNode *SrcLoc = Call.getMetadata("srcloc");
9977   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
9978 
9979   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
9980   // bits as operand 3.
9981   AsmNodeOperands.push_back(DAG.getTargetConstant(
9982       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9983 
9984   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
9985   // this, assign virtual and physical registers for inputs and otput.
9986   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9987     // Assign Registers.
9988     SDISelAsmOperandInfo &RefOpInfo =
9989         OpInfo.isMatchingInputConstraint()
9990             ? ConstraintOperands[OpInfo.getMatchedOperand()]
9991             : OpInfo;
9992     const auto RegError =
9993         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
9994     if (RegError) {
9995       const MachineFunction &MF = DAG.getMachineFunction();
9996       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9997       const char *RegName = TRI.getName(*RegError);
9998       emitInlineAsmError(Call, "register '" + Twine(RegName) +
9999                                    "' allocated for constraint '" +
10000                                    Twine(OpInfo.ConstraintCode) +
10001                                    "' does not match required type");
10002       return;
10003     }
10004 
10005     auto DetectWriteToReservedRegister = [&]() {
10006       const MachineFunction &MF = DAG.getMachineFunction();
10007       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
10008       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
10009         if (Register::isPhysicalRegister(Reg) &&
10010             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
10011           const char *RegName = TRI.getName(Reg);
10012           emitInlineAsmError(Call, "write to reserved register '" +
10013                                        Twine(RegName) + "'");
10014           return true;
10015         }
10016       }
10017       return false;
10018     };
10019     assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
10020             (OpInfo.Type == InlineAsm::isInput &&
10021              !OpInfo.isMatchingInputConstraint())) &&
10022            "Only address as input operand is allowed.");
10023 
10024     switch (OpInfo.Type) {
10025     case InlineAsm::isOutput:
10026       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10027         const InlineAsm::ConstraintCode ConstraintID =
10028             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10029         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10030                "Failed to convert memory constraint code to constraint id.");
10031 
10032         // Add information to the INLINEASM node to know about this output.
10033         InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1);
10034         OpFlags.setMemConstraint(ConstraintID);
10035         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
10036                                                         MVT::i32));
10037         AsmNodeOperands.push_back(OpInfo.CallOperand);
10038       } else {
10039         // Otherwise, this outputs to a register (directly for C_Register /
10040         // C_RegisterClass, and a target-defined fashion for
10041         // C_Immediate/C_Other). Find a register that we can use.
10042         if (OpInfo.AssignedRegs.Regs.empty()) {
10043           emitInlineAsmError(
10044               Call, "couldn't allocate output register for constraint '" +
10045                         Twine(OpInfo.ConstraintCode) + "'");
10046           return;
10047         }
10048 
10049         if (DetectWriteToReservedRegister())
10050           return;
10051 
10052         // Add information to the INLINEASM node to know that this register is
10053         // set.
10054         OpInfo.AssignedRegs.AddInlineAsmOperands(
10055             OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber
10056                                   : InlineAsm::Kind::RegDef,
10057             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
10058       }
10059       break;
10060 
10061     case InlineAsm::isInput:
10062     case InlineAsm::isLabel: {
10063       SDValue InOperandVal = OpInfo.CallOperand;
10064 
10065       if (OpInfo.isMatchingInputConstraint()) {
10066         // If this is required to match an output register we have already set,
10067         // just use its register.
10068         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
10069                                                   AsmNodeOperands);
10070         InlineAsm::Flag Flag(AsmNodeOperands[CurOp]->getAsZExtVal());
10071         if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) {
10072           if (OpInfo.isIndirect) {
10073             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
10074             emitInlineAsmError(Call, "inline asm not supported yet: "
10075                                      "don't know how to handle tied "
10076                                      "indirect register inputs");
10077             return;
10078           }
10079 
10080           SmallVector<Register, 4> Regs;
10081           MachineFunction &MF = DAG.getMachineFunction();
10082           MachineRegisterInfo &MRI = MF.getRegInfo();
10083           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
10084           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
10085           Register TiedReg = R->getReg();
10086           MVT RegVT = R->getSimpleValueType(0);
10087           const TargetRegisterClass *RC =
10088               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
10089               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
10090                                       : TRI.getMinimalPhysRegClass(TiedReg);
10091           for (unsigned i = 0, e = Flag.getNumOperandRegisters(); i != e; ++i)
10092             Regs.push_back(MRI.createVirtualRegister(RC));
10093 
10094           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
10095 
10096           SDLoc dl = getCurSDLoc();
10097           // Use the produced MatchedRegs object to
10098           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call);
10099           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, true,
10100                                            OpInfo.getMatchedOperand(), dl, DAG,
10101                                            AsmNodeOperands);
10102           break;
10103         }
10104 
10105         assert(Flag.isMemKind() && "Unknown matching constraint!");
10106         assert(Flag.getNumOperandRegisters() == 1 &&
10107                "Unexpected number of operands");
10108         // Add information to the INLINEASM node to know about this input.
10109         // See InlineAsm.h isUseOperandTiedToDef.
10110         Flag.clearMemConstraint();
10111         Flag.setMatchingOp(OpInfo.getMatchedOperand());
10112         AsmNodeOperands.push_back(DAG.getTargetConstant(
10113             Flag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
10114         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
10115         break;
10116       }
10117 
10118       // Treat indirect 'X' constraint as memory.
10119       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
10120           OpInfo.isIndirect)
10121         OpInfo.ConstraintType = TargetLowering::C_Memory;
10122 
10123       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
10124           OpInfo.ConstraintType == TargetLowering::C_Other) {
10125         std::vector<SDValue> Ops;
10126         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
10127                                           Ops, DAG);
10128         if (Ops.empty()) {
10129           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
10130             if (isa<ConstantSDNode>(InOperandVal)) {
10131               emitInlineAsmError(Call, "value out of range for constraint '" +
10132                                            Twine(OpInfo.ConstraintCode) + "'");
10133               return;
10134             }
10135 
10136           emitInlineAsmError(Call,
10137                              "invalid operand for inline asm constraint '" +
10138                                  Twine(OpInfo.ConstraintCode) + "'");
10139           return;
10140         }
10141 
10142         // Add information to the INLINEASM node to know about this input.
10143         InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size());
10144         AsmNodeOperands.push_back(DAG.getTargetConstant(
10145             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
10146         llvm::append_range(AsmNodeOperands, Ops);
10147         break;
10148       }
10149 
10150       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10151         assert((OpInfo.isIndirect ||
10152                 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
10153                "Operand must be indirect to be a mem!");
10154         assert(InOperandVal.getValueType() ==
10155                    TLI.getPointerTy(DAG.getDataLayout()) &&
10156                "Memory operands expect pointer values");
10157 
10158         const InlineAsm::ConstraintCode ConstraintID =
10159             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10160         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10161                "Failed to convert memory constraint code to constraint id.");
10162 
10163         // Add information to the INLINEASM node to know about this input.
10164         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
10165         ResOpType.setMemConstraint(ConstraintID);
10166         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
10167                                                         getCurSDLoc(),
10168                                                         MVT::i32));
10169         AsmNodeOperands.push_back(InOperandVal);
10170         break;
10171       }
10172 
10173       if (OpInfo.ConstraintType == TargetLowering::C_Address) {
10174         const InlineAsm::ConstraintCode ConstraintID =
10175             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10176         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10177                "Failed to convert memory constraint code to constraint id.");
10178 
10179         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
10180 
10181         SDValue AsmOp = InOperandVal;
10182         if (isFunction(InOperandVal)) {
10183           auto *GA = cast<GlobalAddressSDNode>(InOperandVal);
10184           ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1);
10185           AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(),
10186                                              InOperandVal.getValueType(),
10187                                              GA->getOffset());
10188         }
10189 
10190         // Add information to the INLINEASM node to know about this input.
10191         ResOpType.setMemConstraint(ConstraintID);
10192 
10193         AsmNodeOperands.push_back(
10194             DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32));
10195 
10196         AsmNodeOperands.push_back(AsmOp);
10197         break;
10198       }
10199 
10200       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
10201           OpInfo.ConstraintType != TargetLowering::C_Register) {
10202         emitInlineAsmError(Call, "unknown asm constraint '" +
10203                                      Twine(OpInfo.ConstraintCode) + "'");
10204         return;
10205       }
10206 
10207       // TODO: Support this.
10208       if (OpInfo.isIndirect) {
10209         emitInlineAsmError(
10210             Call, "Don't know how to handle indirect register inputs yet "
10211                   "for constraint '" +
10212                       Twine(OpInfo.ConstraintCode) + "'");
10213         return;
10214       }
10215 
10216       // Copy the input into the appropriate registers.
10217       if (OpInfo.AssignedRegs.Regs.empty()) {
10218         emitInlineAsmError(Call,
10219                            "couldn't allocate input reg for constraint '" +
10220                                Twine(OpInfo.ConstraintCode) + "'");
10221         return;
10222       }
10223 
10224       if (DetectWriteToReservedRegister())
10225         return;
10226 
10227       SDLoc dl = getCurSDLoc();
10228 
10229       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue,
10230                                         &Call);
10231 
10232       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, false,
10233                                                0, dl, DAG, AsmNodeOperands);
10234       break;
10235     }
10236     case InlineAsm::isClobber:
10237       // Add the clobbered value to the operand list, so that the register
10238       // allocator is aware that the physreg got clobbered.
10239       if (!OpInfo.AssignedRegs.Regs.empty())
10240         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::Clobber,
10241                                                  false, 0, getCurSDLoc(), DAG,
10242                                                  AsmNodeOperands);
10243       break;
10244     }
10245   }
10246 
10247   // Finish up input operands.  Set the input chain and add the flag last.
10248   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
10249   if (Glue.getNode()) AsmNodeOperands.push_back(Glue);
10250 
10251   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
10252   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
10253                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
10254   Glue = Chain.getValue(1);
10255 
10256   // Do additional work to generate outputs.
10257 
10258   SmallVector<EVT, 1> ResultVTs;
10259   SmallVector<SDValue, 1> ResultValues;
10260   SmallVector<SDValue, 8> OutChains;
10261 
10262   llvm::Type *CallResultType = Call.getType();
10263   ArrayRef<Type *> ResultTypes;
10264   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
10265     ResultTypes = StructResult->elements();
10266   else if (!CallResultType->isVoidTy())
10267     ResultTypes = ArrayRef(CallResultType);
10268 
10269   auto CurResultType = ResultTypes.begin();
10270   auto handleRegAssign = [&](SDValue V) {
10271     assert(CurResultType != ResultTypes.end() && "Unexpected value");
10272     assert((*CurResultType)->isSized() && "Unexpected unsized type");
10273     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
10274     ++CurResultType;
10275     // If the type of the inline asm call site return value is different but has
10276     // same size as the type of the asm output bitcast it.  One example of this
10277     // is for vectors with different width / number of elements.  This can
10278     // happen for register classes that can contain multiple different value
10279     // types.  The preg or vreg allocated may not have the same VT as was
10280     // expected.
10281     //
10282     // This can also happen for a return value that disagrees with the register
10283     // class it is put in, eg. a double in a general-purpose register on a
10284     // 32-bit machine.
10285     if (ResultVT != V.getValueType() &&
10286         ResultVT.getSizeInBits() == V.getValueSizeInBits())
10287       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
10288     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
10289              V.getValueType().isInteger()) {
10290       // If a result value was tied to an input value, the computed result
10291       // may have a wider width than the expected result.  Extract the
10292       // relevant portion.
10293       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
10294     }
10295     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
10296     ResultVTs.push_back(ResultVT);
10297     ResultValues.push_back(V);
10298   };
10299 
10300   // Deal with output operands.
10301   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
10302     if (OpInfo.Type == InlineAsm::isOutput) {
10303       SDValue Val;
10304       // Skip trivial output operands.
10305       if (OpInfo.AssignedRegs.Regs.empty())
10306         continue;
10307 
10308       switch (OpInfo.ConstraintType) {
10309       case TargetLowering::C_Register:
10310       case TargetLowering::C_RegisterClass:
10311         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
10312                                                   Chain, &Glue, &Call);
10313         break;
10314       case TargetLowering::C_Immediate:
10315       case TargetLowering::C_Other:
10316         Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(),
10317                                               OpInfo, DAG);
10318         break;
10319       case TargetLowering::C_Memory:
10320         break; // Already handled.
10321       case TargetLowering::C_Address:
10322         break; // Silence warning.
10323       case TargetLowering::C_Unknown:
10324         assert(false && "Unexpected unknown constraint");
10325       }
10326 
10327       // Indirect output manifest as stores. Record output chains.
10328       if (OpInfo.isIndirect) {
10329         const Value *Ptr = OpInfo.CallOperandVal;
10330         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
10331         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
10332                                      MachinePointerInfo(Ptr));
10333         OutChains.push_back(Store);
10334       } else {
10335         // generate CopyFromRegs to associated registers.
10336         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
10337         if (Val.getOpcode() == ISD::MERGE_VALUES) {
10338           for (const SDValue &V : Val->op_values())
10339             handleRegAssign(V);
10340         } else
10341           handleRegAssign(Val);
10342       }
10343     }
10344   }
10345 
10346   // Set results.
10347   if (!ResultValues.empty()) {
10348     assert(CurResultType == ResultTypes.end() &&
10349            "Mismatch in number of ResultTypes");
10350     assert(ResultValues.size() == ResultTypes.size() &&
10351            "Mismatch in number of output operands in asm result");
10352 
10353     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
10354                             DAG.getVTList(ResultVTs), ResultValues);
10355     setValue(&Call, V);
10356   }
10357 
10358   // Collect store chains.
10359   if (!OutChains.empty())
10360     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
10361 
10362   if (EmitEHLabels) {
10363     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
10364   }
10365 
10366   // Only Update Root if inline assembly has a memory effect.
10367   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
10368       EmitEHLabels)
10369     DAG.setRoot(Chain);
10370 }
10371 
10372 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
10373                                              const Twine &Message) {
10374   LLVMContext &Ctx = *DAG.getContext();
10375   Ctx.emitError(&Call, Message);
10376 
10377   // Make sure we leave the DAG in a valid state
10378   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10379   SmallVector<EVT, 1> ValueVTs;
10380   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
10381 
10382   if (ValueVTs.empty())
10383     return;
10384 
10385   SmallVector<SDValue, 1> Ops;
10386   for (const EVT &VT : ValueVTs)
10387     Ops.push_back(DAG.getUNDEF(VT));
10388 
10389   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
10390 }
10391 
10392 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
10393   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
10394                           MVT::Other, getRoot(),
10395                           getValue(I.getArgOperand(0)),
10396                           DAG.getSrcValue(I.getArgOperand(0))));
10397 }
10398 
10399 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
10400   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10401   const DataLayout &DL = DAG.getDataLayout();
10402   SDValue V = DAG.getVAArg(
10403       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
10404       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
10405       DL.getABITypeAlign(I.getType()).value());
10406   DAG.setRoot(V.getValue(1));
10407 
10408   if (I.getType()->isPointerTy())
10409     V = DAG.getPtrExtOrTrunc(
10410         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
10411   setValue(&I, V);
10412 }
10413 
10414 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
10415   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
10416                           MVT::Other, getRoot(),
10417                           getValue(I.getArgOperand(0)),
10418                           DAG.getSrcValue(I.getArgOperand(0))));
10419 }
10420 
10421 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
10422   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
10423                           MVT::Other, getRoot(),
10424                           getValue(I.getArgOperand(0)),
10425                           getValue(I.getArgOperand(1)),
10426                           DAG.getSrcValue(I.getArgOperand(0)),
10427                           DAG.getSrcValue(I.getArgOperand(1))));
10428 }
10429 
10430 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
10431                                                     const Instruction &I,
10432                                                     SDValue Op) {
10433   std::optional<ConstantRange> CR = getRange(I);
10434 
10435   if (!CR || CR->isFullSet() || CR->isEmptySet() || CR->isUpperWrapped())
10436     return Op;
10437 
10438   APInt Lo = CR->getUnsignedMin();
10439   if (!Lo.isMinValue())
10440     return Op;
10441 
10442   APInt Hi = CR->getUnsignedMax();
10443   unsigned Bits = std::max(Hi.getActiveBits(),
10444                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
10445 
10446   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
10447 
10448   SDLoc SL = getCurSDLoc();
10449 
10450   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
10451                              DAG.getValueType(SmallVT));
10452   unsigned NumVals = Op.getNode()->getNumValues();
10453   if (NumVals == 1)
10454     return ZExt;
10455 
10456   SmallVector<SDValue, 4> Ops;
10457 
10458   Ops.push_back(ZExt);
10459   for (unsigned I = 1; I != NumVals; ++I)
10460     Ops.push_back(Op.getValue(I));
10461 
10462   return DAG.getMergeValues(Ops, SL);
10463 }
10464 
10465 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
10466 /// the call being lowered.
10467 ///
10468 /// This is a helper for lowering intrinsics that follow a target calling
10469 /// convention or require stack pointer adjustment. Only a subset of the
10470 /// intrinsic's operands need to participate in the calling convention.
10471 void SelectionDAGBuilder::populateCallLoweringInfo(
10472     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
10473     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
10474     AttributeSet RetAttrs, bool IsPatchPoint) {
10475   TargetLowering::ArgListTy Args;
10476   Args.reserve(NumArgs);
10477 
10478   // Populate the argument list.
10479   // Attributes for args start at offset 1, after the return attribute.
10480   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
10481        ArgI != ArgE; ++ArgI) {
10482     const Value *V = Call->getOperand(ArgI);
10483 
10484     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
10485 
10486     TargetLowering::ArgListEntry Entry;
10487     Entry.Node = getValue(V);
10488     Entry.Ty = V->getType();
10489     Entry.setAttributes(Call, ArgI);
10490     Args.push_back(Entry);
10491   }
10492 
10493   CLI.setDebugLoc(getCurSDLoc())
10494       .setChain(getRoot())
10495       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args),
10496                  RetAttrs)
10497       .setDiscardResult(Call->use_empty())
10498       .setIsPatchPoint(IsPatchPoint)
10499       .setIsPreallocated(
10500           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
10501 }
10502 
10503 /// Add a stack map intrinsic call's live variable operands to a stackmap
10504 /// or patchpoint target node's operand list.
10505 ///
10506 /// Constants are converted to TargetConstants purely as an optimization to
10507 /// avoid constant materialization and register allocation.
10508 ///
10509 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
10510 /// generate addess computation nodes, and so FinalizeISel can convert the
10511 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
10512 /// address materialization and register allocation, but may also be required
10513 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
10514 /// alloca in the entry block, then the runtime may assume that the alloca's
10515 /// StackMap location can be read immediately after compilation and that the
10516 /// location is valid at any point during execution (this is similar to the
10517 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
10518 /// only available in a register, then the runtime would need to trap when
10519 /// execution reaches the StackMap in order to read the alloca's location.
10520 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
10521                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
10522                                 SelectionDAGBuilder &Builder) {
10523   SelectionDAG &DAG = Builder.DAG;
10524   for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
10525     SDValue Op = Builder.getValue(Call.getArgOperand(I));
10526 
10527     // Things on the stack are pointer-typed, meaning that they are already
10528     // legal and can be emitted directly to target nodes.
10529     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
10530       Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
10531     } else {
10532       // Otherwise emit a target independent node to be legalised.
10533       Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
10534     }
10535   }
10536 }
10537 
10538 /// Lower llvm.experimental.stackmap.
10539 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
10540   // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
10541   //                                  [live variables...])
10542 
10543   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
10544 
10545   SDValue Chain, InGlue, Callee;
10546   SmallVector<SDValue, 32> Ops;
10547 
10548   SDLoc DL = getCurSDLoc();
10549   Callee = getValue(CI.getCalledOperand());
10550 
10551   // The stackmap intrinsic only records the live variables (the arguments
10552   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
10553   // intrinsic, this won't be lowered to a function call. This means we don't
10554   // have to worry about calling conventions and target specific lowering code.
10555   // Instead we perform the call lowering right here.
10556   //
10557   // chain, flag = CALLSEQ_START(chain, 0, 0)
10558   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
10559   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
10560   //
10561   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
10562   InGlue = Chain.getValue(1);
10563 
10564   // Add the STACKMAP operands, starting with DAG house-keeping.
10565   Ops.push_back(Chain);
10566   Ops.push_back(InGlue);
10567 
10568   // Add the <id>, <numShadowBytes> operands.
10569   //
10570   // These do not require legalisation, and can be emitted directly to target
10571   // constant nodes.
10572   SDValue ID = getValue(CI.getArgOperand(0));
10573   assert(ID.getValueType() == MVT::i64);
10574   SDValue IDConst =
10575       DAG.getTargetConstant(ID->getAsZExtVal(), DL, ID.getValueType());
10576   Ops.push_back(IDConst);
10577 
10578   SDValue Shad = getValue(CI.getArgOperand(1));
10579   assert(Shad.getValueType() == MVT::i32);
10580   SDValue ShadConst =
10581       DAG.getTargetConstant(Shad->getAsZExtVal(), DL, Shad.getValueType());
10582   Ops.push_back(ShadConst);
10583 
10584   // Add the live variables.
10585   addStackMapLiveVars(CI, 2, DL, Ops, *this);
10586 
10587   // Create the STACKMAP node.
10588   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10589   Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
10590   InGlue = Chain.getValue(1);
10591 
10592   Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL);
10593 
10594   // Stackmaps don't generate values, so nothing goes into the NodeMap.
10595 
10596   // Set the root to the target-lowered call chain.
10597   DAG.setRoot(Chain);
10598 
10599   // Inform the Frame Information that we have a stackmap in this function.
10600   FuncInfo.MF->getFrameInfo().setHasStackMap();
10601 }
10602 
10603 /// Lower llvm.experimental.patchpoint directly to its target opcode.
10604 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
10605                                           const BasicBlock *EHPadBB) {
10606   // <ty> @llvm.experimental.patchpoint.<ty>(i64 <id>,
10607   //                                         i32 <numBytes>,
10608   //                                         i8* <target>,
10609   //                                         i32 <numArgs>,
10610   //                                         [Args...],
10611   //                                         [live variables...])
10612 
10613   CallingConv::ID CC = CB.getCallingConv();
10614   bool IsAnyRegCC = CC == CallingConv::AnyReg;
10615   bool HasDef = !CB.getType()->isVoidTy();
10616   SDLoc dl = getCurSDLoc();
10617   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
10618 
10619   // Handle immediate and symbolic callees.
10620   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
10621     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
10622                                    /*isTarget=*/true);
10623   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
10624     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
10625                                          SDLoc(SymbolicCallee),
10626                                          SymbolicCallee->getValueType(0));
10627 
10628   // Get the real number of arguments participating in the call <numArgs>
10629   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
10630   unsigned NumArgs = NArgVal->getAsZExtVal();
10631 
10632   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
10633   // Intrinsics include all meta-operands up to but not including CC.
10634   unsigned NumMetaOpers = PatchPointOpers::CCPos;
10635   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
10636          "Not enough arguments provided to the patchpoint intrinsic");
10637 
10638   // For AnyRegCC the arguments are lowered later on manually.
10639   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
10640   Type *ReturnTy =
10641       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
10642 
10643   TargetLowering::CallLoweringInfo CLI(DAG);
10644   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
10645                            ReturnTy, CB.getAttributes().getRetAttrs(), true);
10646   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
10647 
10648   SDNode *CallEnd = Result.second.getNode();
10649   if (CallEnd->getOpcode() == ISD::EH_LABEL)
10650     CallEnd = CallEnd->getOperand(0).getNode();
10651   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
10652     CallEnd = CallEnd->getOperand(0).getNode();
10653 
10654   /// Get a call instruction from the call sequence chain.
10655   /// Tail calls are not allowed.
10656   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
10657          "Expected a callseq node.");
10658   SDNode *Call = CallEnd->getOperand(0).getNode();
10659   bool HasGlue = Call->getGluedNode();
10660 
10661   // Replace the target specific call node with the patchable intrinsic.
10662   SmallVector<SDValue, 8> Ops;
10663 
10664   // Push the chain.
10665   Ops.push_back(*(Call->op_begin()));
10666 
10667   // Optionally, push the glue (if any).
10668   if (HasGlue)
10669     Ops.push_back(*(Call->op_end() - 1));
10670 
10671   // Push the register mask info.
10672   if (HasGlue)
10673     Ops.push_back(*(Call->op_end() - 2));
10674   else
10675     Ops.push_back(*(Call->op_end() - 1));
10676 
10677   // Add the <id> and <numBytes> constants.
10678   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
10679   Ops.push_back(DAG.getTargetConstant(IDVal->getAsZExtVal(), dl, MVT::i64));
10680   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
10681   Ops.push_back(DAG.getTargetConstant(NBytesVal->getAsZExtVal(), dl, MVT::i32));
10682 
10683   // Add the callee.
10684   Ops.push_back(Callee);
10685 
10686   // Adjust <numArgs> to account for any arguments that have been passed on the
10687   // stack instead.
10688   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
10689   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
10690   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
10691   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
10692 
10693   // Add the calling convention
10694   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
10695 
10696   // Add the arguments we omitted previously. The register allocator should
10697   // place these in any free register.
10698   if (IsAnyRegCC)
10699     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
10700       Ops.push_back(getValue(CB.getArgOperand(i)));
10701 
10702   // Push the arguments from the call instruction.
10703   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
10704   Ops.append(Call->op_begin() + 2, e);
10705 
10706   // Push live variables for the stack map.
10707   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
10708 
10709   SDVTList NodeTys;
10710   if (IsAnyRegCC && HasDef) {
10711     // Create the return types based on the intrinsic definition
10712     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10713     SmallVector<EVT, 3> ValueVTs;
10714     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
10715     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
10716 
10717     // There is always a chain and a glue type at the end
10718     ValueVTs.push_back(MVT::Other);
10719     ValueVTs.push_back(MVT::Glue);
10720     NodeTys = DAG.getVTList(ValueVTs);
10721   } else
10722     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10723 
10724   // Replace the target specific call node with a PATCHPOINT node.
10725   SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
10726 
10727   // Update the NodeMap.
10728   if (HasDef) {
10729     if (IsAnyRegCC)
10730       setValue(&CB, SDValue(PPV.getNode(), 0));
10731     else
10732       setValue(&CB, Result.first);
10733   }
10734 
10735   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
10736   // call sequence. Furthermore the location of the chain and glue can change
10737   // when the AnyReg calling convention is used and the intrinsic returns a
10738   // value.
10739   if (IsAnyRegCC && HasDef) {
10740     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
10741     SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
10742     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10743   } else
10744     DAG.ReplaceAllUsesWith(Call, PPV.getNode());
10745   DAG.DeleteNode(Call);
10746 
10747   // Inform the Frame Information that we have a patchpoint in this function.
10748   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
10749 }
10750 
10751 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
10752                                             unsigned Intrinsic) {
10753   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10754   SDValue Op1 = getValue(I.getArgOperand(0));
10755   SDValue Op2;
10756   if (I.arg_size() > 1)
10757     Op2 = getValue(I.getArgOperand(1));
10758   SDLoc dl = getCurSDLoc();
10759   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
10760   SDValue Res;
10761   SDNodeFlags SDFlags;
10762   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
10763     SDFlags.copyFMF(*FPMO);
10764 
10765   switch (Intrinsic) {
10766   case Intrinsic::vector_reduce_fadd:
10767     if (SDFlags.hasAllowReassociation())
10768       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
10769                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
10770                         SDFlags);
10771     else
10772       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
10773     break;
10774   case Intrinsic::vector_reduce_fmul:
10775     if (SDFlags.hasAllowReassociation())
10776       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
10777                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
10778                         SDFlags);
10779     else
10780       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
10781     break;
10782   case Intrinsic::vector_reduce_add:
10783     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
10784     break;
10785   case Intrinsic::vector_reduce_mul:
10786     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
10787     break;
10788   case Intrinsic::vector_reduce_and:
10789     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
10790     break;
10791   case Intrinsic::vector_reduce_or:
10792     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
10793     break;
10794   case Intrinsic::vector_reduce_xor:
10795     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
10796     break;
10797   case Intrinsic::vector_reduce_smax:
10798     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
10799     break;
10800   case Intrinsic::vector_reduce_smin:
10801     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
10802     break;
10803   case Intrinsic::vector_reduce_umax:
10804     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
10805     break;
10806   case Intrinsic::vector_reduce_umin:
10807     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
10808     break;
10809   case Intrinsic::vector_reduce_fmax:
10810     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
10811     break;
10812   case Intrinsic::vector_reduce_fmin:
10813     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
10814     break;
10815   case Intrinsic::vector_reduce_fmaximum:
10816     Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags);
10817     break;
10818   case Intrinsic::vector_reduce_fminimum:
10819     Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags);
10820     break;
10821   default:
10822     llvm_unreachable("Unhandled vector reduce intrinsic");
10823   }
10824   setValue(&I, Res);
10825 }
10826 
10827 /// Returns an AttributeList representing the attributes applied to the return
10828 /// value of the given call.
10829 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
10830   SmallVector<Attribute::AttrKind, 2> Attrs;
10831   if (CLI.RetSExt)
10832     Attrs.push_back(Attribute::SExt);
10833   if (CLI.RetZExt)
10834     Attrs.push_back(Attribute::ZExt);
10835   if (CLI.IsInReg)
10836     Attrs.push_back(Attribute::InReg);
10837 
10838   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
10839                             Attrs);
10840 }
10841 
10842 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
10843 /// implementation, which just calls LowerCall.
10844 /// FIXME: When all targets are
10845 /// migrated to using LowerCall, this hook should be integrated into SDISel.
10846 std::pair<SDValue, SDValue>
10847 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
10848   // Handle the incoming return values from the call.
10849   CLI.Ins.clear();
10850   Type *OrigRetTy = CLI.RetTy;
10851   SmallVector<EVT, 4> RetTys;
10852   SmallVector<TypeSize, 4> Offsets;
10853   auto &DL = CLI.DAG.getDataLayout();
10854   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
10855 
10856   if (CLI.IsPostTypeLegalization) {
10857     // If we are lowering a libcall after legalization, split the return type.
10858     SmallVector<EVT, 4> OldRetTys;
10859     SmallVector<TypeSize, 4> OldOffsets;
10860     RetTys.swap(OldRetTys);
10861     Offsets.swap(OldOffsets);
10862 
10863     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
10864       EVT RetVT = OldRetTys[i];
10865       uint64_t Offset = OldOffsets[i];
10866       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
10867       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
10868       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
10869       RetTys.append(NumRegs, RegisterVT);
10870       for (unsigned j = 0; j != NumRegs; ++j)
10871         Offsets.push_back(TypeSize::getFixed(Offset + j * RegisterVTByteSZ));
10872     }
10873   }
10874 
10875   SmallVector<ISD::OutputArg, 4> Outs;
10876   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
10877 
10878   bool CanLowerReturn =
10879       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
10880                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
10881 
10882   SDValue DemoteStackSlot;
10883   int DemoteStackIdx = -100;
10884   if (!CanLowerReturn) {
10885     // FIXME: equivalent assert?
10886     // assert(!CS.hasInAllocaArgument() &&
10887     //        "sret demotion is incompatible with inalloca");
10888     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
10889     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
10890     MachineFunction &MF = CLI.DAG.getMachineFunction();
10891     DemoteStackIdx =
10892         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
10893     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
10894                                               DL.getAllocaAddrSpace());
10895 
10896     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
10897     ArgListEntry Entry;
10898     Entry.Node = DemoteStackSlot;
10899     Entry.Ty = StackSlotPtrType;
10900     Entry.IsSExt = false;
10901     Entry.IsZExt = false;
10902     Entry.IsInReg = false;
10903     Entry.IsSRet = true;
10904     Entry.IsNest = false;
10905     Entry.IsByVal = false;
10906     Entry.IsByRef = false;
10907     Entry.IsReturned = false;
10908     Entry.IsSwiftSelf = false;
10909     Entry.IsSwiftAsync = false;
10910     Entry.IsSwiftError = false;
10911     Entry.IsCFGuardTarget = false;
10912     Entry.Alignment = Alignment;
10913     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
10914     CLI.NumFixedArgs += 1;
10915     CLI.getArgs()[0].IndirectType = CLI.RetTy;
10916     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
10917 
10918     // sret demotion isn't compatible with tail-calls, since the sret argument
10919     // points into the callers stack frame.
10920     CLI.IsTailCall = false;
10921   } else {
10922     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10923         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
10924     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
10925       ISD::ArgFlagsTy Flags;
10926       if (NeedsRegBlock) {
10927         Flags.setInConsecutiveRegs();
10928         if (I == RetTys.size() - 1)
10929           Flags.setInConsecutiveRegsLast();
10930       }
10931       EVT VT = RetTys[I];
10932       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10933                                                      CLI.CallConv, VT);
10934       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10935                                                        CLI.CallConv, VT);
10936       for (unsigned i = 0; i != NumRegs; ++i) {
10937         ISD::InputArg MyFlags;
10938         MyFlags.Flags = Flags;
10939         MyFlags.VT = RegisterVT;
10940         MyFlags.ArgVT = VT;
10941         MyFlags.Used = CLI.IsReturnValueUsed;
10942         if (CLI.RetTy->isPointerTy()) {
10943           MyFlags.Flags.setPointer();
10944           MyFlags.Flags.setPointerAddrSpace(
10945               cast<PointerType>(CLI.RetTy)->getAddressSpace());
10946         }
10947         if (CLI.RetSExt)
10948           MyFlags.Flags.setSExt();
10949         if (CLI.RetZExt)
10950           MyFlags.Flags.setZExt();
10951         if (CLI.IsInReg)
10952           MyFlags.Flags.setInReg();
10953         CLI.Ins.push_back(MyFlags);
10954       }
10955     }
10956   }
10957 
10958   // We push in swifterror return as the last element of CLI.Ins.
10959   ArgListTy &Args = CLI.getArgs();
10960   if (supportSwiftError()) {
10961     for (const ArgListEntry &Arg : Args) {
10962       if (Arg.IsSwiftError) {
10963         ISD::InputArg MyFlags;
10964         MyFlags.VT = getPointerTy(DL);
10965         MyFlags.ArgVT = EVT(getPointerTy(DL));
10966         MyFlags.Flags.setSwiftError();
10967         CLI.Ins.push_back(MyFlags);
10968       }
10969     }
10970   }
10971 
10972   // Handle all of the outgoing arguments.
10973   CLI.Outs.clear();
10974   CLI.OutVals.clear();
10975   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
10976     SmallVector<EVT, 4> ValueVTs;
10977     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
10978     // FIXME: Split arguments if CLI.IsPostTypeLegalization
10979     Type *FinalType = Args[i].Ty;
10980     if (Args[i].IsByVal)
10981       FinalType = Args[i].IndirectType;
10982     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10983         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
10984     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
10985          ++Value) {
10986       EVT VT = ValueVTs[Value];
10987       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
10988       SDValue Op = SDValue(Args[i].Node.getNode(),
10989                            Args[i].Node.getResNo() + Value);
10990       ISD::ArgFlagsTy Flags;
10991 
10992       // Certain targets (such as MIPS), may have a different ABI alignment
10993       // for a type depending on the context. Give the target a chance to
10994       // specify the alignment it wants.
10995       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
10996       Flags.setOrigAlign(OriginalAlignment);
10997 
10998       if (Args[i].Ty->isPointerTy()) {
10999         Flags.setPointer();
11000         Flags.setPointerAddrSpace(
11001             cast<PointerType>(Args[i].Ty)->getAddressSpace());
11002       }
11003       if (Args[i].IsZExt)
11004         Flags.setZExt();
11005       if (Args[i].IsSExt)
11006         Flags.setSExt();
11007       if (Args[i].IsInReg) {
11008         // If we are using vectorcall calling convention, a structure that is
11009         // passed InReg - is surely an HVA
11010         if (CLI.CallConv == CallingConv::X86_VectorCall &&
11011             isa<StructType>(FinalType)) {
11012           // The first value of a structure is marked
11013           if (0 == Value)
11014             Flags.setHvaStart();
11015           Flags.setHva();
11016         }
11017         // Set InReg Flag
11018         Flags.setInReg();
11019       }
11020       if (Args[i].IsSRet)
11021         Flags.setSRet();
11022       if (Args[i].IsSwiftSelf)
11023         Flags.setSwiftSelf();
11024       if (Args[i].IsSwiftAsync)
11025         Flags.setSwiftAsync();
11026       if (Args[i].IsSwiftError)
11027         Flags.setSwiftError();
11028       if (Args[i].IsCFGuardTarget)
11029         Flags.setCFGuardTarget();
11030       if (Args[i].IsByVal)
11031         Flags.setByVal();
11032       if (Args[i].IsByRef)
11033         Flags.setByRef();
11034       if (Args[i].IsPreallocated) {
11035         Flags.setPreallocated();
11036         // Set the byval flag for CCAssignFn callbacks that don't know about
11037         // preallocated.  This way we can know how many bytes we should've
11038         // allocated and how many bytes a callee cleanup function will pop.  If
11039         // we port preallocated to more targets, we'll have to add custom
11040         // preallocated handling in the various CC lowering callbacks.
11041         Flags.setByVal();
11042       }
11043       if (Args[i].IsInAlloca) {
11044         Flags.setInAlloca();
11045         // Set the byval flag for CCAssignFn callbacks that don't know about
11046         // inalloca.  This way we can know how many bytes we should've allocated
11047         // and how many bytes a callee cleanup function will pop.  If we port
11048         // inalloca to more targets, we'll have to add custom inalloca handling
11049         // in the various CC lowering callbacks.
11050         Flags.setByVal();
11051       }
11052       Align MemAlign;
11053       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
11054         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
11055         Flags.setByValSize(FrameSize);
11056 
11057         // info is not there but there are cases it cannot get right.
11058         if (auto MA = Args[i].Alignment)
11059           MemAlign = *MA;
11060         else
11061           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
11062       } else if (auto MA = Args[i].Alignment) {
11063         MemAlign = *MA;
11064       } else {
11065         MemAlign = OriginalAlignment;
11066       }
11067       Flags.setMemAlign(MemAlign);
11068       if (Args[i].IsNest)
11069         Flags.setNest();
11070       if (NeedsRegBlock)
11071         Flags.setInConsecutiveRegs();
11072 
11073       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
11074                                                  CLI.CallConv, VT);
11075       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
11076                                                         CLI.CallConv, VT);
11077       SmallVector<SDValue, 4> Parts(NumParts);
11078       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
11079 
11080       if (Args[i].IsSExt)
11081         ExtendKind = ISD::SIGN_EXTEND;
11082       else if (Args[i].IsZExt)
11083         ExtendKind = ISD::ZERO_EXTEND;
11084 
11085       // Conservatively only handle 'returned' on non-vectors that can be lowered,
11086       // for now.
11087       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
11088           CanLowerReturn) {
11089         assert((CLI.RetTy == Args[i].Ty ||
11090                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
11091                  CLI.RetTy->getPointerAddressSpace() ==
11092                      Args[i].Ty->getPointerAddressSpace())) &&
11093                RetTys.size() == NumValues && "unexpected use of 'returned'");
11094         // Before passing 'returned' to the target lowering code, ensure that
11095         // either the register MVT and the actual EVT are the same size or that
11096         // the return value and argument are extended in the same way; in these
11097         // cases it's safe to pass the argument register value unchanged as the
11098         // return register value (although it's at the target's option whether
11099         // to do so)
11100         // TODO: allow code generation to take advantage of partially preserved
11101         // registers rather than clobbering the entire register when the
11102         // parameter extension method is not compatible with the return
11103         // extension method
11104         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
11105             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
11106              CLI.RetZExt == Args[i].IsZExt))
11107           Flags.setReturned();
11108       }
11109 
11110       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
11111                      CLI.CallConv, ExtendKind);
11112 
11113       for (unsigned j = 0; j != NumParts; ++j) {
11114         // if it isn't first piece, alignment must be 1
11115         // For scalable vectors the scalable part is currently handled
11116         // by individual targets, so we just use the known minimum size here.
11117         ISD::OutputArg MyFlags(
11118             Flags, Parts[j].getValueType().getSimpleVT(), VT,
11119             i < CLI.NumFixedArgs, i,
11120             j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
11121         if (NumParts > 1 && j == 0)
11122           MyFlags.Flags.setSplit();
11123         else if (j != 0) {
11124           MyFlags.Flags.setOrigAlign(Align(1));
11125           if (j == NumParts - 1)
11126             MyFlags.Flags.setSplitEnd();
11127         }
11128 
11129         CLI.Outs.push_back(MyFlags);
11130         CLI.OutVals.push_back(Parts[j]);
11131       }
11132 
11133       if (NeedsRegBlock && Value == NumValues - 1)
11134         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
11135     }
11136   }
11137 
11138   SmallVector<SDValue, 4> InVals;
11139   CLI.Chain = LowerCall(CLI, InVals);
11140 
11141   // Update CLI.InVals to use outside of this function.
11142   CLI.InVals = InVals;
11143 
11144   // Verify that the target's LowerCall behaved as expected.
11145   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
11146          "LowerCall didn't return a valid chain!");
11147   assert((!CLI.IsTailCall || InVals.empty()) &&
11148          "LowerCall emitted a return value for a tail call!");
11149   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
11150          "LowerCall didn't emit the correct number of values!");
11151 
11152   // For a tail call, the return value is merely live-out and there aren't
11153   // any nodes in the DAG representing it. Return a special value to
11154   // indicate that a tail call has been emitted and no more Instructions
11155   // should be processed in the current block.
11156   if (CLI.IsTailCall) {
11157     CLI.DAG.setRoot(CLI.Chain);
11158     return std::make_pair(SDValue(), SDValue());
11159   }
11160 
11161 #ifndef NDEBUG
11162   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
11163     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
11164     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
11165            "LowerCall emitted a value with the wrong type!");
11166   }
11167 #endif
11168 
11169   SmallVector<SDValue, 4> ReturnValues;
11170   if (!CanLowerReturn) {
11171     // The instruction result is the result of loading from the
11172     // hidden sret parameter.
11173     SmallVector<EVT, 1> PVTs;
11174     Type *PtrRetTy =
11175         PointerType::get(OrigRetTy->getContext(), DL.getAllocaAddrSpace());
11176 
11177     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
11178     assert(PVTs.size() == 1 && "Pointers should fit in one register");
11179     EVT PtrVT = PVTs[0];
11180 
11181     unsigned NumValues = RetTys.size();
11182     ReturnValues.resize(NumValues);
11183     SmallVector<SDValue, 4> Chains(NumValues);
11184 
11185     // An aggregate return value cannot wrap around the address space, so
11186     // offsets to its parts don't wrap either.
11187     SDNodeFlags Flags;
11188     Flags.setNoUnsignedWrap(true);
11189 
11190     MachineFunction &MF = CLI.DAG.getMachineFunction();
11191     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
11192     for (unsigned i = 0; i < NumValues; ++i) {
11193       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
11194                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
11195                                                         PtrVT), Flags);
11196       SDValue L = CLI.DAG.getLoad(
11197           RetTys[i], CLI.DL, CLI.Chain, Add,
11198           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
11199                                             DemoteStackIdx, Offsets[i]),
11200           HiddenSRetAlign);
11201       ReturnValues[i] = L;
11202       Chains[i] = L.getValue(1);
11203     }
11204 
11205     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
11206   } else {
11207     // Collect the legal value parts into potentially illegal values
11208     // that correspond to the original function's return values.
11209     std::optional<ISD::NodeType> AssertOp;
11210     if (CLI.RetSExt)
11211       AssertOp = ISD::AssertSext;
11212     else if (CLI.RetZExt)
11213       AssertOp = ISD::AssertZext;
11214     unsigned CurReg = 0;
11215     for (EVT VT : RetTys) {
11216       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
11217                                                      CLI.CallConv, VT);
11218       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
11219                                                        CLI.CallConv, VT);
11220 
11221       ReturnValues.push_back(getCopyFromParts(
11222           CLI.DAG, CLI.DL, &InVals[CurReg], NumRegs, RegisterVT, VT, nullptr,
11223           CLI.Chain, CLI.CallConv, AssertOp));
11224       CurReg += NumRegs;
11225     }
11226 
11227     // For a function returning void, there is no return value. We can't create
11228     // such a node, so we just return a null return value in that case. In
11229     // that case, nothing will actually look at the value.
11230     if (ReturnValues.empty())
11231       return std::make_pair(SDValue(), CLI.Chain);
11232   }
11233 
11234   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
11235                                 CLI.DAG.getVTList(RetTys), ReturnValues);
11236   return std::make_pair(Res, CLI.Chain);
11237 }
11238 
11239 /// Places new result values for the node in Results (their number
11240 /// and types must exactly match those of the original return values of
11241 /// the node), or leaves Results empty, which indicates that the node is not
11242 /// to be custom lowered after all.
11243 void TargetLowering::LowerOperationWrapper(SDNode *N,
11244                                            SmallVectorImpl<SDValue> &Results,
11245                                            SelectionDAG &DAG) const {
11246   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
11247 
11248   if (!Res.getNode())
11249     return;
11250 
11251   // If the original node has one result, take the return value from
11252   // LowerOperation as is. It might not be result number 0.
11253   if (N->getNumValues() == 1) {
11254     Results.push_back(Res);
11255     return;
11256   }
11257 
11258   // If the original node has multiple results, then the return node should
11259   // have the same number of results.
11260   assert((N->getNumValues() == Res->getNumValues()) &&
11261       "Lowering returned the wrong number of results!");
11262 
11263   // Places new result values base on N result number.
11264   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
11265     Results.push_back(Res.getValue(I));
11266 }
11267 
11268 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11269   llvm_unreachable("LowerOperation not implemented for this target!");
11270 }
11271 
11272 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
11273                                                      unsigned Reg,
11274                                                      ISD::NodeType ExtendType) {
11275   SDValue Op = getNonRegisterValue(V);
11276   assert((Op.getOpcode() != ISD::CopyFromReg ||
11277           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
11278          "Copy from a reg to the same reg!");
11279   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
11280 
11281   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11282   // If this is an InlineAsm we have to match the registers required, not the
11283   // notional registers required by the type.
11284 
11285   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
11286                    std::nullopt); // This is not an ABI copy.
11287   SDValue Chain = DAG.getEntryNode();
11288 
11289   if (ExtendType == ISD::ANY_EXTEND) {
11290     auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
11291     if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
11292       ExtendType = PreferredExtendIt->second;
11293   }
11294   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
11295   PendingExports.push_back(Chain);
11296 }
11297 
11298 #include "llvm/CodeGen/SelectionDAGISel.h"
11299 
11300 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
11301 /// entry block, return true.  This includes arguments used by switches, since
11302 /// the switch may expand into multiple basic blocks.
11303 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
11304   // With FastISel active, we may be splitting blocks, so force creation
11305   // of virtual registers for all non-dead arguments.
11306   if (FastISel)
11307     return A->use_empty();
11308 
11309   const BasicBlock &Entry = A->getParent()->front();
11310   for (const User *U : A->users())
11311     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
11312       return false;  // Use not in entry block.
11313 
11314   return true;
11315 }
11316 
11317 using ArgCopyElisionMapTy =
11318     DenseMap<const Argument *,
11319              std::pair<const AllocaInst *, const StoreInst *>>;
11320 
11321 /// Scan the entry block of the function in FuncInfo for arguments that look
11322 /// like copies into a local alloca. Record any copied arguments in
11323 /// ArgCopyElisionCandidates.
11324 static void
11325 findArgumentCopyElisionCandidates(const DataLayout &DL,
11326                                   FunctionLoweringInfo *FuncInfo,
11327                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
11328   // Record the state of every static alloca used in the entry block. Argument
11329   // allocas are all used in the entry block, so we need approximately as many
11330   // entries as we have arguments.
11331   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
11332   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
11333   unsigned NumArgs = FuncInfo->Fn->arg_size();
11334   StaticAllocas.reserve(NumArgs * 2);
11335 
11336   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
11337     if (!V)
11338       return nullptr;
11339     V = V->stripPointerCasts();
11340     const auto *AI = dyn_cast<AllocaInst>(V);
11341     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
11342       return nullptr;
11343     auto Iter = StaticAllocas.insert({AI, Unknown});
11344     return &Iter.first->second;
11345   };
11346 
11347   // Look for stores of arguments to static allocas. Look through bitcasts and
11348   // GEPs to handle type coercions, as long as the alloca is fully initialized
11349   // by the store. Any non-store use of an alloca escapes it and any subsequent
11350   // unanalyzed store might write it.
11351   // FIXME: Handle structs initialized with multiple stores.
11352   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
11353     // Look for stores, and handle non-store uses conservatively.
11354     const auto *SI = dyn_cast<StoreInst>(&I);
11355     if (!SI) {
11356       // We will look through cast uses, so ignore them completely.
11357       if (I.isCast())
11358         continue;
11359       // Ignore debug info and pseudo op intrinsics, they don't escape or store
11360       // to allocas.
11361       if (I.isDebugOrPseudoInst())
11362         continue;
11363       // This is an unknown instruction. Assume it escapes or writes to all
11364       // static alloca operands.
11365       for (const Use &U : I.operands()) {
11366         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
11367           *Info = StaticAllocaInfo::Clobbered;
11368       }
11369       continue;
11370     }
11371 
11372     // If the stored value is a static alloca, mark it as escaped.
11373     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
11374       *Info = StaticAllocaInfo::Clobbered;
11375 
11376     // Check if the destination is a static alloca.
11377     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
11378     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
11379     if (!Info)
11380       continue;
11381     const AllocaInst *AI = cast<AllocaInst>(Dst);
11382 
11383     // Skip allocas that have been initialized or clobbered.
11384     if (*Info != StaticAllocaInfo::Unknown)
11385       continue;
11386 
11387     // Check if the stored value is an argument, and that this store fully
11388     // initializes the alloca.
11389     // If the argument type has padding bits we can't directly forward a pointer
11390     // as the upper bits may contain garbage.
11391     // Don't elide copies from the same argument twice.
11392     const Value *Val = SI->getValueOperand()->stripPointerCasts();
11393     const auto *Arg = dyn_cast<Argument>(Val);
11394     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
11395         Arg->getType()->isEmptyTy() ||
11396         DL.getTypeStoreSize(Arg->getType()) !=
11397             DL.getTypeAllocSize(AI->getAllocatedType()) ||
11398         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
11399         ArgCopyElisionCandidates.count(Arg)) {
11400       *Info = StaticAllocaInfo::Clobbered;
11401       continue;
11402     }
11403 
11404     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
11405                       << '\n');
11406 
11407     // Mark this alloca and store for argument copy elision.
11408     *Info = StaticAllocaInfo::Elidable;
11409     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
11410 
11411     // Stop scanning if we've seen all arguments. This will happen early in -O0
11412     // builds, which is useful, because -O0 builds have large entry blocks and
11413     // many allocas.
11414     if (ArgCopyElisionCandidates.size() == NumArgs)
11415       break;
11416   }
11417 }
11418 
11419 /// Try to elide argument copies from memory into a local alloca. Succeeds if
11420 /// ArgVal is a load from a suitable fixed stack object.
11421 static void tryToElideArgumentCopy(
11422     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
11423     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
11424     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
11425     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
11426     ArrayRef<SDValue> ArgVals, bool &ArgHasUses) {
11427   // Check if this is a load from a fixed stack object.
11428   auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]);
11429   if (!LNode)
11430     return;
11431   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
11432   if (!FINode)
11433     return;
11434 
11435   // Check that the fixed stack object is the right size and alignment.
11436   // Look at the alignment that the user wrote on the alloca instead of looking
11437   // at the stack object.
11438   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
11439   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
11440   const AllocaInst *AI = ArgCopyIter->second.first;
11441   int FixedIndex = FINode->getIndex();
11442   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
11443   int OldIndex = AllocaIndex;
11444   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
11445   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
11446     LLVM_DEBUG(
11447         dbgs() << "  argument copy elision failed due to bad fixed stack "
11448                   "object size\n");
11449     return;
11450   }
11451   Align RequiredAlignment = AI->getAlign();
11452   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
11453     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
11454                          "greater than stack argument alignment ("
11455                       << DebugStr(RequiredAlignment) << " vs "
11456                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
11457     return;
11458   }
11459 
11460   // Perform the elision. Delete the old stack object and replace its only use
11461   // in the variable info map. Mark the stack object as mutable and aliased.
11462   LLVM_DEBUG({
11463     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
11464            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
11465            << '\n';
11466   });
11467   MFI.RemoveStackObject(OldIndex);
11468   MFI.setIsImmutableObjectIndex(FixedIndex, false);
11469   MFI.setIsAliasedObjectIndex(FixedIndex, true);
11470   AllocaIndex = FixedIndex;
11471   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
11472   for (SDValue ArgVal : ArgVals)
11473     Chains.push_back(ArgVal.getValue(1));
11474 
11475   // Avoid emitting code for the store implementing the copy.
11476   const StoreInst *SI = ArgCopyIter->second.second;
11477   ElidedArgCopyInstrs.insert(SI);
11478 
11479   // Check for uses of the argument again so that we can avoid exporting ArgVal
11480   // if it is't used by anything other than the store.
11481   for (const Value *U : Arg.users()) {
11482     if (U != SI) {
11483       ArgHasUses = true;
11484       break;
11485     }
11486   }
11487 }
11488 
11489 void SelectionDAGISel::LowerArguments(const Function &F) {
11490   SelectionDAG &DAG = SDB->DAG;
11491   SDLoc dl = SDB->getCurSDLoc();
11492   const DataLayout &DL = DAG.getDataLayout();
11493   SmallVector<ISD::InputArg, 16> Ins;
11494 
11495   // In Naked functions we aren't going to save any registers.
11496   if (F.hasFnAttribute(Attribute::Naked))
11497     return;
11498 
11499   if (!FuncInfo->CanLowerReturn) {
11500     // Put in an sret pointer parameter before all the other parameters.
11501     SmallVector<EVT, 1> ValueVTs;
11502     ComputeValueVTs(*TLI, DAG.getDataLayout(),
11503                     PointerType::get(F.getContext(),
11504                                      DAG.getDataLayout().getAllocaAddrSpace()),
11505                     ValueVTs);
11506 
11507     // NOTE: Assuming that a pointer will never break down to more than one VT
11508     // or one register.
11509     ISD::ArgFlagsTy Flags;
11510     Flags.setSRet();
11511     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
11512     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
11513                          ISD::InputArg::NoArgIndex, 0);
11514     Ins.push_back(RetArg);
11515   }
11516 
11517   // Look for stores of arguments to static allocas. Mark such arguments with a
11518   // flag to ask the target to give us the memory location of that argument if
11519   // available.
11520   ArgCopyElisionMapTy ArgCopyElisionCandidates;
11521   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
11522                                     ArgCopyElisionCandidates);
11523 
11524   // Set up the incoming argument description vector.
11525   for (const Argument &Arg : F.args()) {
11526     unsigned ArgNo = Arg.getArgNo();
11527     SmallVector<EVT, 4> ValueVTs;
11528     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
11529     bool isArgValueUsed = !Arg.use_empty();
11530     unsigned PartBase = 0;
11531     Type *FinalType = Arg.getType();
11532     if (Arg.hasAttribute(Attribute::ByVal))
11533       FinalType = Arg.getParamByValType();
11534     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
11535         FinalType, F.getCallingConv(), F.isVarArg(), DL);
11536     for (unsigned Value = 0, NumValues = ValueVTs.size();
11537          Value != NumValues; ++Value) {
11538       EVT VT = ValueVTs[Value];
11539       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
11540       ISD::ArgFlagsTy Flags;
11541 
11542 
11543       if (Arg.getType()->isPointerTy()) {
11544         Flags.setPointer();
11545         Flags.setPointerAddrSpace(
11546             cast<PointerType>(Arg.getType())->getAddressSpace());
11547       }
11548       if (Arg.hasAttribute(Attribute::ZExt))
11549         Flags.setZExt();
11550       if (Arg.hasAttribute(Attribute::SExt))
11551         Flags.setSExt();
11552       if (Arg.hasAttribute(Attribute::InReg)) {
11553         // If we are using vectorcall calling convention, a structure that is
11554         // passed InReg - is surely an HVA
11555         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
11556             isa<StructType>(Arg.getType())) {
11557           // The first value of a structure is marked
11558           if (0 == Value)
11559             Flags.setHvaStart();
11560           Flags.setHva();
11561         }
11562         // Set InReg Flag
11563         Flags.setInReg();
11564       }
11565       if (Arg.hasAttribute(Attribute::StructRet))
11566         Flags.setSRet();
11567       if (Arg.hasAttribute(Attribute::SwiftSelf))
11568         Flags.setSwiftSelf();
11569       if (Arg.hasAttribute(Attribute::SwiftAsync))
11570         Flags.setSwiftAsync();
11571       if (Arg.hasAttribute(Attribute::SwiftError))
11572         Flags.setSwiftError();
11573       if (Arg.hasAttribute(Attribute::ByVal))
11574         Flags.setByVal();
11575       if (Arg.hasAttribute(Attribute::ByRef))
11576         Flags.setByRef();
11577       if (Arg.hasAttribute(Attribute::InAlloca)) {
11578         Flags.setInAlloca();
11579         // Set the byval flag for CCAssignFn callbacks that don't know about
11580         // inalloca.  This way we can know how many bytes we should've allocated
11581         // and how many bytes a callee cleanup function will pop.  If we port
11582         // inalloca to more targets, we'll have to add custom inalloca handling
11583         // in the various CC lowering callbacks.
11584         Flags.setByVal();
11585       }
11586       if (Arg.hasAttribute(Attribute::Preallocated)) {
11587         Flags.setPreallocated();
11588         // Set the byval flag for CCAssignFn callbacks that don't know about
11589         // preallocated.  This way we can know how many bytes we should've
11590         // allocated and how many bytes a callee cleanup function will pop.  If
11591         // we port preallocated to more targets, we'll have to add custom
11592         // preallocated handling in the various CC lowering callbacks.
11593         Flags.setByVal();
11594       }
11595 
11596       // Certain targets (such as MIPS), may have a different ABI alignment
11597       // for a type depending on the context. Give the target a chance to
11598       // specify the alignment it wants.
11599       const Align OriginalAlignment(
11600           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
11601       Flags.setOrigAlign(OriginalAlignment);
11602 
11603       Align MemAlign;
11604       Type *ArgMemTy = nullptr;
11605       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
11606           Flags.isByRef()) {
11607         if (!ArgMemTy)
11608           ArgMemTy = Arg.getPointeeInMemoryValueType();
11609 
11610         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
11611 
11612         // For in-memory arguments, size and alignment should be passed from FE.
11613         // BE will guess if this info is not there but there are cases it cannot
11614         // get right.
11615         if (auto ParamAlign = Arg.getParamStackAlign())
11616           MemAlign = *ParamAlign;
11617         else if ((ParamAlign = Arg.getParamAlign()))
11618           MemAlign = *ParamAlign;
11619         else
11620           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
11621         if (Flags.isByRef())
11622           Flags.setByRefSize(MemSize);
11623         else
11624           Flags.setByValSize(MemSize);
11625       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
11626         MemAlign = *ParamAlign;
11627       } else {
11628         MemAlign = OriginalAlignment;
11629       }
11630       Flags.setMemAlign(MemAlign);
11631 
11632       if (Arg.hasAttribute(Attribute::Nest))
11633         Flags.setNest();
11634       if (NeedsRegBlock)
11635         Flags.setInConsecutiveRegs();
11636       if (ArgCopyElisionCandidates.count(&Arg))
11637         Flags.setCopyElisionCandidate();
11638       if (Arg.hasAttribute(Attribute::Returned))
11639         Flags.setReturned();
11640 
11641       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
11642           *CurDAG->getContext(), F.getCallingConv(), VT);
11643       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
11644           *CurDAG->getContext(), F.getCallingConv(), VT);
11645       for (unsigned i = 0; i != NumRegs; ++i) {
11646         // For scalable vectors, use the minimum size; individual targets
11647         // are responsible for handling scalable vector arguments and
11648         // return values.
11649         ISD::InputArg MyFlags(
11650             Flags, RegisterVT, VT, isArgValueUsed, ArgNo,
11651             PartBase + i * RegisterVT.getStoreSize().getKnownMinValue());
11652         if (NumRegs > 1 && i == 0)
11653           MyFlags.Flags.setSplit();
11654         // if it isn't first piece, alignment must be 1
11655         else if (i > 0) {
11656           MyFlags.Flags.setOrigAlign(Align(1));
11657           if (i == NumRegs - 1)
11658             MyFlags.Flags.setSplitEnd();
11659         }
11660         Ins.push_back(MyFlags);
11661       }
11662       if (NeedsRegBlock && Value == NumValues - 1)
11663         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
11664       PartBase += VT.getStoreSize().getKnownMinValue();
11665     }
11666   }
11667 
11668   // Call the target to set up the argument values.
11669   SmallVector<SDValue, 8> InVals;
11670   SDValue NewRoot = TLI->LowerFormalArguments(
11671       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
11672 
11673   // Verify that the target's LowerFormalArguments behaved as expected.
11674   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
11675          "LowerFormalArguments didn't return a valid chain!");
11676   assert(InVals.size() == Ins.size() &&
11677          "LowerFormalArguments didn't emit the correct number of values!");
11678   LLVM_DEBUG({
11679     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
11680       assert(InVals[i].getNode() &&
11681              "LowerFormalArguments emitted a null value!");
11682       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
11683              "LowerFormalArguments emitted a value with the wrong type!");
11684     }
11685   });
11686 
11687   // Update the DAG with the new chain value resulting from argument lowering.
11688   DAG.setRoot(NewRoot);
11689 
11690   // Set up the argument values.
11691   unsigned i = 0;
11692   if (!FuncInfo->CanLowerReturn) {
11693     // Create a virtual register for the sret pointer, and put in a copy
11694     // from the sret argument into it.
11695     SmallVector<EVT, 1> ValueVTs;
11696     ComputeValueVTs(*TLI, DAG.getDataLayout(),
11697                     PointerType::get(F.getContext(),
11698                                      DAG.getDataLayout().getAllocaAddrSpace()),
11699                     ValueVTs);
11700     MVT VT = ValueVTs[0].getSimpleVT();
11701     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
11702     std::optional<ISD::NodeType> AssertOp;
11703     SDValue ArgValue =
11704         getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, nullptr, NewRoot,
11705                          F.getCallingConv(), AssertOp);
11706 
11707     MachineFunction& MF = SDB->DAG.getMachineFunction();
11708     MachineRegisterInfo& RegInfo = MF.getRegInfo();
11709     Register SRetReg =
11710         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
11711     FuncInfo->DemoteRegister = SRetReg;
11712     NewRoot =
11713         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
11714     DAG.setRoot(NewRoot);
11715 
11716     // i indexes lowered arguments.  Bump it past the hidden sret argument.
11717     ++i;
11718   }
11719 
11720   SmallVector<SDValue, 4> Chains;
11721   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
11722   for (const Argument &Arg : F.args()) {
11723     SmallVector<SDValue, 4> ArgValues;
11724     SmallVector<EVT, 4> ValueVTs;
11725     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
11726     unsigned NumValues = ValueVTs.size();
11727     if (NumValues == 0)
11728       continue;
11729 
11730     bool ArgHasUses = !Arg.use_empty();
11731 
11732     // Elide the copying store if the target loaded this argument from a
11733     // suitable fixed stack object.
11734     if (Ins[i].Flags.isCopyElisionCandidate()) {
11735       unsigned NumParts = 0;
11736       for (EVT VT : ValueVTs)
11737         NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(),
11738                                                        F.getCallingConv(), VT);
11739 
11740       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
11741                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
11742                              ArrayRef(&InVals[i], NumParts), ArgHasUses);
11743     }
11744 
11745     // If this argument is unused then remember its value. It is used to generate
11746     // debugging information.
11747     bool isSwiftErrorArg =
11748         TLI->supportSwiftError() &&
11749         Arg.hasAttribute(Attribute::SwiftError);
11750     if (!ArgHasUses && !isSwiftErrorArg) {
11751       SDB->setUnusedArgValue(&Arg, InVals[i]);
11752 
11753       // Also remember any frame index for use in FastISel.
11754       if (FrameIndexSDNode *FI =
11755           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
11756         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11757     }
11758 
11759     for (unsigned Val = 0; Val != NumValues; ++Val) {
11760       EVT VT = ValueVTs[Val];
11761       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
11762                                                       F.getCallingConv(), VT);
11763       unsigned NumParts = TLI->getNumRegistersForCallingConv(
11764           *CurDAG->getContext(), F.getCallingConv(), VT);
11765 
11766       // Even an apparent 'unused' swifterror argument needs to be returned. So
11767       // we do generate a copy for it that can be used on return from the
11768       // function.
11769       if (ArgHasUses || isSwiftErrorArg) {
11770         std::optional<ISD::NodeType> AssertOp;
11771         if (Arg.hasAttribute(Attribute::SExt))
11772           AssertOp = ISD::AssertSext;
11773         else if (Arg.hasAttribute(Attribute::ZExt))
11774           AssertOp = ISD::AssertZext;
11775 
11776         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
11777                                              PartVT, VT, nullptr, NewRoot,
11778                                              F.getCallingConv(), AssertOp));
11779       }
11780 
11781       i += NumParts;
11782     }
11783 
11784     // We don't need to do anything else for unused arguments.
11785     if (ArgValues.empty())
11786       continue;
11787 
11788     // Note down frame index.
11789     if (FrameIndexSDNode *FI =
11790         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
11791       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11792 
11793     SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues),
11794                                      SDB->getCurSDLoc());
11795 
11796     SDB->setValue(&Arg, Res);
11797     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
11798       // We want to associate the argument with the frame index, among
11799       // involved operands, that correspond to the lowest address. The
11800       // getCopyFromParts function, called earlier, is swapping the order of
11801       // the operands to BUILD_PAIR depending on endianness. The result of
11802       // that swapping is that the least significant bits of the argument will
11803       // be in the first operand of the BUILD_PAIR node, and the most
11804       // significant bits will be in the second operand.
11805       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
11806       if (LoadSDNode *LNode =
11807           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
11808         if (FrameIndexSDNode *FI =
11809             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
11810           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11811     }
11812 
11813     // Analyses past this point are naive and don't expect an assertion.
11814     if (Res.getOpcode() == ISD::AssertZext)
11815       Res = Res.getOperand(0);
11816 
11817     // Update the SwiftErrorVRegDefMap.
11818     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
11819       Register Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11820       if (Reg.isVirtual())
11821         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
11822                                    Reg);
11823     }
11824 
11825     // If this argument is live outside of the entry block, insert a copy from
11826     // wherever we got it to the vreg that other BB's will reference it as.
11827     if (Res.getOpcode() == ISD::CopyFromReg) {
11828       // If we can, though, try to skip creating an unnecessary vreg.
11829       // FIXME: This isn't very clean... it would be nice to make this more
11830       // general.
11831       Register Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11832       if (Reg.isVirtual()) {
11833         FuncInfo->ValueMap[&Arg] = Reg;
11834         continue;
11835       }
11836     }
11837     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
11838       FuncInfo->InitializeRegForValue(&Arg);
11839       SDB->CopyToExportRegsIfNeeded(&Arg);
11840     }
11841   }
11842 
11843   if (!Chains.empty()) {
11844     Chains.push_back(NewRoot);
11845     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
11846   }
11847 
11848   DAG.setRoot(NewRoot);
11849 
11850   assert(i == InVals.size() && "Argument register count mismatch!");
11851 
11852   // If any argument copy elisions occurred and we have debug info, update the
11853   // stale frame indices used in the dbg.declare variable info table.
11854   if (!ArgCopyElisionFrameIndexMap.empty()) {
11855     for (MachineFunction::VariableDbgInfo &VI :
11856          MF->getInStackSlotVariableDbgInfo()) {
11857       auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot());
11858       if (I != ArgCopyElisionFrameIndexMap.end())
11859         VI.updateStackSlot(I->second);
11860     }
11861   }
11862 
11863   // Finally, if the target has anything special to do, allow it to do so.
11864   emitFunctionEntryCode();
11865 }
11866 
11867 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
11868 /// ensure constants are generated when needed.  Remember the virtual registers
11869 /// that need to be added to the Machine PHI nodes as input.  We cannot just
11870 /// directly add them, because expansion might result in multiple MBB's for one
11871 /// BB.  As such, the start of the BB might correspond to a different MBB than
11872 /// the end.
11873 void
11874 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
11875   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11876 
11877   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
11878 
11879   // Check PHI nodes in successors that expect a value to be available from this
11880   // block.
11881   for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
11882     if (!isa<PHINode>(SuccBB->begin())) continue;
11883     MachineBasicBlock *SuccMBB = FuncInfo.getMBB(SuccBB);
11884 
11885     // If this terminator has multiple identical successors (common for
11886     // switches), only handle each succ once.
11887     if (!SuccsHandled.insert(SuccMBB).second)
11888       continue;
11889 
11890     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
11891 
11892     // At this point we know that there is a 1-1 correspondence between LLVM PHI
11893     // nodes and Machine PHI nodes, but the incoming operands have not been
11894     // emitted yet.
11895     for (const PHINode &PN : SuccBB->phis()) {
11896       // Ignore dead phi's.
11897       if (PN.use_empty())
11898         continue;
11899 
11900       // Skip empty types
11901       if (PN.getType()->isEmptyTy())
11902         continue;
11903 
11904       unsigned Reg;
11905       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
11906 
11907       if (const auto *C = dyn_cast<Constant>(PHIOp)) {
11908         unsigned &RegOut = ConstantsOut[C];
11909         if (RegOut == 0) {
11910           RegOut = FuncInfo.CreateRegs(C);
11911           // We need to zero/sign extend ConstantInt phi operands to match
11912           // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
11913           ISD::NodeType ExtendType = ISD::ANY_EXTEND;
11914           if (auto *CI = dyn_cast<ConstantInt>(C))
11915             ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
11916                                                     : ISD::ZERO_EXTEND;
11917           CopyValueToVirtualRegister(C, RegOut, ExtendType);
11918         }
11919         Reg = RegOut;
11920       } else {
11921         DenseMap<const Value *, Register>::iterator I =
11922           FuncInfo.ValueMap.find(PHIOp);
11923         if (I != FuncInfo.ValueMap.end())
11924           Reg = I->second;
11925         else {
11926           assert(isa<AllocaInst>(PHIOp) &&
11927                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
11928                  "Didn't codegen value into a register!??");
11929           Reg = FuncInfo.CreateRegs(PHIOp);
11930           CopyValueToVirtualRegister(PHIOp, Reg);
11931         }
11932       }
11933 
11934       // Remember that this register needs to added to the machine PHI node as
11935       // the input for this MBB.
11936       SmallVector<EVT, 4> ValueVTs;
11937       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
11938       for (EVT VT : ValueVTs) {
11939         const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
11940         for (unsigned i = 0; i != NumRegisters; ++i)
11941           FuncInfo.PHINodesToUpdate.push_back(
11942               std::make_pair(&*MBBI++, Reg + i));
11943         Reg += NumRegisters;
11944       }
11945     }
11946   }
11947 
11948   ConstantsOut.clear();
11949 }
11950 
11951 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
11952   MachineFunction::iterator I(MBB);
11953   if (++I == FuncInfo.MF->end())
11954     return nullptr;
11955   return &*I;
11956 }
11957 
11958 /// During lowering new call nodes can be created (such as memset, etc.).
11959 /// Those will become new roots of the current DAG, but complications arise
11960 /// when they are tail calls. In such cases, the call lowering will update
11961 /// the root, but the builder still needs to know that a tail call has been
11962 /// lowered in order to avoid generating an additional return.
11963 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
11964   // If the node is null, we do have a tail call.
11965   if (MaybeTC.getNode() != nullptr)
11966     DAG.setRoot(MaybeTC);
11967   else
11968     HasTailCall = true;
11969 }
11970 
11971 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
11972                                         MachineBasicBlock *SwitchMBB,
11973                                         MachineBasicBlock *DefaultMBB) {
11974   MachineFunction *CurMF = FuncInfo.MF;
11975   MachineBasicBlock *NextMBB = nullptr;
11976   MachineFunction::iterator BBI(W.MBB);
11977   if (++BBI != FuncInfo.MF->end())
11978     NextMBB = &*BBI;
11979 
11980   unsigned Size = W.LastCluster - W.FirstCluster + 1;
11981 
11982   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11983 
11984   if (Size == 2 && W.MBB == SwitchMBB) {
11985     // If any two of the cases has the same destination, and if one value
11986     // is the same as the other, but has one bit unset that the other has set,
11987     // use bit manipulation to do two compares at once.  For example:
11988     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
11989     // TODO: This could be extended to merge any 2 cases in switches with 3
11990     // cases.
11991     // TODO: Handle cases where W.CaseBB != SwitchBB.
11992     CaseCluster &Small = *W.FirstCluster;
11993     CaseCluster &Big = *W.LastCluster;
11994 
11995     if (Small.Low == Small.High && Big.Low == Big.High &&
11996         Small.MBB == Big.MBB) {
11997       const APInt &SmallValue = Small.Low->getValue();
11998       const APInt &BigValue = Big.Low->getValue();
11999 
12000       // Check that there is only one bit different.
12001       APInt CommonBit = BigValue ^ SmallValue;
12002       if (CommonBit.isPowerOf2()) {
12003         SDValue CondLHS = getValue(Cond);
12004         EVT VT = CondLHS.getValueType();
12005         SDLoc DL = getCurSDLoc();
12006 
12007         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
12008                                  DAG.getConstant(CommonBit, DL, VT));
12009         SDValue Cond = DAG.getSetCC(
12010             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
12011             ISD::SETEQ);
12012 
12013         // Update successor info.
12014         // Both Small and Big will jump to Small.BB, so we sum up the
12015         // probabilities.
12016         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
12017         if (BPI)
12018           addSuccessorWithProb(
12019               SwitchMBB, DefaultMBB,
12020               // The default destination is the first successor in IR.
12021               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
12022         else
12023           addSuccessorWithProb(SwitchMBB, DefaultMBB);
12024 
12025         // Insert the true branch.
12026         SDValue BrCond =
12027             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
12028                         DAG.getBasicBlock(Small.MBB));
12029         // Insert the false branch.
12030         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
12031                              DAG.getBasicBlock(DefaultMBB));
12032 
12033         DAG.setRoot(BrCond);
12034         return;
12035       }
12036     }
12037   }
12038 
12039   if (TM.getOptLevel() != CodeGenOptLevel::None) {
12040     // Here, we order cases by probability so the most likely case will be
12041     // checked first. However, two clusters can have the same probability in
12042     // which case their relative ordering is non-deterministic. So we use Low
12043     // as a tie-breaker as clusters are guaranteed to never overlap.
12044     llvm::sort(W.FirstCluster, W.LastCluster + 1,
12045                [](const CaseCluster &a, const CaseCluster &b) {
12046       return a.Prob != b.Prob ?
12047              a.Prob > b.Prob :
12048              a.Low->getValue().slt(b.Low->getValue());
12049     });
12050 
12051     // Rearrange the case blocks so that the last one falls through if possible
12052     // without changing the order of probabilities.
12053     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
12054       --I;
12055       if (I->Prob > W.LastCluster->Prob)
12056         break;
12057       if (I->Kind == CC_Range && I->MBB == NextMBB) {
12058         std::swap(*I, *W.LastCluster);
12059         break;
12060       }
12061     }
12062   }
12063 
12064   // Compute total probability.
12065   BranchProbability DefaultProb = W.DefaultProb;
12066   BranchProbability UnhandledProbs = DefaultProb;
12067   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
12068     UnhandledProbs += I->Prob;
12069 
12070   MachineBasicBlock *CurMBB = W.MBB;
12071   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
12072     bool FallthroughUnreachable = false;
12073     MachineBasicBlock *Fallthrough;
12074     if (I == W.LastCluster) {
12075       // For the last cluster, fall through to the default destination.
12076       Fallthrough = DefaultMBB;
12077       FallthroughUnreachable = isa<UnreachableInst>(
12078           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
12079     } else {
12080       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
12081       CurMF->insert(BBI, Fallthrough);
12082       // Put Cond in a virtual register to make it available from the new blocks.
12083       ExportFromCurrentBlock(Cond);
12084     }
12085     UnhandledProbs -= I->Prob;
12086 
12087     switch (I->Kind) {
12088       case CC_JumpTable: {
12089         // FIXME: Optimize away range check based on pivot comparisons.
12090         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
12091         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
12092 
12093         // The jump block hasn't been inserted yet; insert it here.
12094         MachineBasicBlock *JumpMBB = JT->MBB;
12095         CurMF->insert(BBI, JumpMBB);
12096 
12097         auto JumpProb = I->Prob;
12098         auto FallthroughProb = UnhandledProbs;
12099 
12100         // If the default statement is a target of the jump table, we evenly
12101         // distribute the default probability to successors of CurMBB. Also
12102         // update the probability on the edge from JumpMBB to Fallthrough.
12103         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
12104                                               SE = JumpMBB->succ_end();
12105              SI != SE; ++SI) {
12106           if (*SI == DefaultMBB) {
12107             JumpProb += DefaultProb / 2;
12108             FallthroughProb -= DefaultProb / 2;
12109             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
12110             JumpMBB->normalizeSuccProbs();
12111             break;
12112           }
12113         }
12114 
12115         // If the default clause is unreachable, propagate that knowledge into
12116         // JTH->FallthroughUnreachable which will use it to suppress the range
12117         // check.
12118         //
12119         // However, don't do this if we're doing branch target enforcement,
12120         // because a table branch _without_ a range check can be a tempting JOP
12121         // gadget - out-of-bounds inputs that are impossible in correct
12122         // execution become possible again if an attacker can influence the
12123         // control flow. So if an attacker doesn't already have a BTI bypass
12124         // available, we don't want them to be able to get one out of this
12125         // table branch.
12126         if (FallthroughUnreachable) {
12127           Function &CurFunc = CurMF->getFunction();
12128           if (!CurFunc.hasFnAttribute("branch-target-enforcement"))
12129             JTH->FallthroughUnreachable = true;
12130         }
12131 
12132         if (!JTH->FallthroughUnreachable)
12133           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
12134         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
12135         CurMBB->normalizeSuccProbs();
12136 
12137         // The jump table header will be inserted in our current block, do the
12138         // range check, and fall through to our fallthrough block.
12139         JTH->HeaderBB = CurMBB;
12140         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
12141 
12142         // If we're in the right place, emit the jump table header right now.
12143         if (CurMBB == SwitchMBB) {
12144           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
12145           JTH->Emitted = true;
12146         }
12147         break;
12148       }
12149       case CC_BitTests: {
12150         // FIXME: Optimize away range check based on pivot comparisons.
12151         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
12152 
12153         // The bit test blocks haven't been inserted yet; insert them here.
12154         for (BitTestCase &BTC : BTB->Cases)
12155           CurMF->insert(BBI, BTC.ThisBB);
12156 
12157         // Fill in fields of the BitTestBlock.
12158         BTB->Parent = CurMBB;
12159         BTB->Default = Fallthrough;
12160 
12161         BTB->DefaultProb = UnhandledProbs;
12162         // If the cases in bit test don't form a contiguous range, we evenly
12163         // distribute the probability on the edge to Fallthrough to two
12164         // successors of CurMBB.
12165         if (!BTB->ContiguousRange) {
12166           BTB->Prob += DefaultProb / 2;
12167           BTB->DefaultProb -= DefaultProb / 2;
12168         }
12169 
12170         if (FallthroughUnreachable)
12171           BTB->FallthroughUnreachable = true;
12172 
12173         // If we're in the right place, emit the bit test header right now.
12174         if (CurMBB == SwitchMBB) {
12175           visitBitTestHeader(*BTB, SwitchMBB);
12176           BTB->Emitted = true;
12177         }
12178         break;
12179       }
12180       case CC_Range: {
12181         const Value *RHS, *LHS, *MHS;
12182         ISD::CondCode CC;
12183         if (I->Low == I->High) {
12184           // Check Cond == I->Low.
12185           CC = ISD::SETEQ;
12186           LHS = Cond;
12187           RHS=I->Low;
12188           MHS = nullptr;
12189         } else {
12190           // Check I->Low <= Cond <= I->High.
12191           CC = ISD::SETLE;
12192           LHS = I->Low;
12193           MHS = Cond;
12194           RHS = I->High;
12195         }
12196 
12197         // If Fallthrough is unreachable, fold away the comparison.
12198         if (FallthroughUnreachable)
12199           CC = ISD::SETTRUE;
12200 
12201         // The false probability is the sum of all unhandled cases.
12202         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
12203                      getCurSDLoc(), I->Prob, UnhandledProbs);
12204 
12205         if (CurMBB == SwitchMBB)
12206           visitSwitchCase(CB, SwitchMBB);
12207         else
12208           SL->SwitchCases.push_back(CB);
12209 
12210         break;
12211       }
12212     }
12213     CurMBB = Fallthrough;
12214   }
12215 }
12216 
12217 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
12218                                         const SwitchWorkListItem &W,
12219                                         Value *Cond,
12220                                         MachineBasicBlock *SwitchMBB) {
12221   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
12222          "Clusters not sorted?");
12223   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
12224 
12225   auto [LastLeft, FirstRight, LeftProb, RightProb] =
12226       SL->computeSplitWorkItemInfo(W);
12227 
12228   // Use the first element on the right as pivot since we will make less-than
12229   // comparisons against it.
12230   CaseClusterIt PivotCluster = FirstRight;
12231   assert(PivotCluster > W.FirstCluster);
12232   assert(PivotCluster <= W.LastCluster);
12233 
12234   CaseClusterIt FirstLeft = W.FirstCluster;
12235   CaseClusterIt LastRight = W.LastCluster;
12236 
12237   const ConstantInt *Pivot = PivotCluster->Low;
12238 
12239   // New blocks will be inserted immediately after the current one.
12240   MachineFunction::iterator BBI(W.MBB);
12241   ++BBI;
12242 
12243   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
12244   // we can branch to its destination directly if it's squeezed exactly in
12245   // between the known lower bound and Pivot - 1.
12246   MachineBasicBlock *LeftMBB;
12247   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
12248       FirstLeft->Low == W.GE &&
12249       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
12250     LeftMBB = FirstLeft->MBB;
12251   } else {
12252     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12253     FuncInfo.MF->insert(BBI, LeftMBB);
12254     WorkList.push_back(
12255         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
12256     // Put Cond in a virtual register to make it available from the new blocks.
12257     ExportFromCurrentBlock(Cond);
12258   }
12259 
12260   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
12261   // single cluster, RHS.Low == Pivot, and we can branch to its destination
12262   // directly if RHS.High equals the current upper bound.
12263   MachineBasicBlock *RightMBB;
12264   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
12265       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
12266     RightMBB = FirstRight->MBB;
12267   } else {
12268     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12269     FuncInfo.MF->insert(BBI, RightMBB);
12270     WorkList.push_back(
12271         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
12272     // Put Cond in a virtual register to make it available from the new blocks.
12273     ExportFromCurrentBlock(Cond);
12274   }
12275 
12276   // Create the CaseBlock record that will be used to lower the branch.
12277   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
12278                getCurSDLoc(), LeftProb, RightProb);
12279 
12280   if (W.MBB == SwitchMBB)
12281     visitSwitchCase(CB, SwitchMBB);
12282   else
12283     SL->SwitchCases.push_back(CB);
12284 }
12285 
12286 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
12287 // from the swith statement.
12288 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
12289                                             BranchProbability PeeledCaseProb) {
12290   if (PeeledCaseProb == BranchProbability::getOne())
12291     return BranchProbability::getZero();
12292   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
12293 
12294   uint32_t Numerator = CaseProb.getNumerator();
12295   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
12296   return BranchProbability(Numerator, std::max(Numerator, Denominator));
12297 }
12298 
12299 // Try to peel the top probability case if it exceeds the threshold.
12300 // Return current MachineBasicBlock for the switch statement if the peeling
12301 // does not occur.
12302 // If the peeling is performed, return the newly created MachineBasicBlock
12303 // for the peeled switch statement. Also update Clusters to remove the peeled
12304 // case. PeeledCaseProb is the BranchProbability for the peeled case.
12305 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
12306     const SwitchInst &SI, CaseClusterVector &Clusters,
12307     BranchProbability &PeeledCaseProb) {
12308   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12309   // Don't perform if there is only one cluster or optimizing for size.
12310   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
12311       TM.getOptLevel() == CodeGenOptLevel::None ||
12312       SwitchMBB->getParent()->getFunction().hasMinSize())
12313     return SwitchMBB;
12314 
12315   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
12316   unsigned PeeledCaseIndex = 0;
12317   bool SwitchPeeled = false;
12318   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
12319     CaseCluster &CC = Clusters[Index];
12320     if (CC.Prob < TopCaseProb)
12321       continue;
12322     TopCaseProb = CC.Prob;
12323     PeeledCaseIndex = Index;
12324     SwitchPeeled = true;
12325   }
12326   if (!SwitchPeeled)
12327     return SwitchMBB;
12328 
12329   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
12330                     << TopCaseProb << "\n");
12331 
12332   // Record the MBB for the peeled switch statement.
12333   MachineFunction::iterator BBI(SwitchMBB);
12334   ++BBI;
12335   MachineBasicBlock *PeeledSwitchMBB =
12336       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
12337   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
12338 
12339   ExportFromCurrentBlock(SI.getCondition());
12340   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
12341   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
12342                           nullptr,   nullptr,      TopCaseProb.getCompl()};
12343   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
12344 
12345   Clusters.erase(PeeledCaseIt);
12346   for (CaseCluster &CC : Clusters) {
12347     LLVM_DEBUG(
12348         dbgs() << "Scale the probablity for one cluster, before scaling: "
12349                << CC.Prob << "\n");
12350     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
12351     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
12352   }
12353   PeeledCaseProb = TopCaseProb;
12354   return PeeledSwitchMBB;
12355 }
12356 
12357 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
12358   // Extract cases from the switch.
12359   BranchProbabilityInfo *BPI = FuncInfo.BPI;
12360   CaseClusterVector Clusters;
12361   Clusters.reserve(SI.getNumCases());
12362   for (auto I : SI.cases()) {
12363     MachineBasicBlock *Succ = FuncInfo.getMBB(I.getCaseSuccessor());
12364     const ConstantInt *CaseVal = I.getCaseValue();
12365     BranchProbability Prob =
12366         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
12367             : BranchProbability(1, SI.getNumCases() + 1);
12368     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
12369   }
12370 
12371   MachineBasicBlock *DefaultMBB = FuncInfo.getMBB(SI.getDefaultDest());
12372 
12373   // Cluster adjacent cases with the same destination. We do this at all
12374   // optimization levels because it's cheap to do and will make codegen faster
12375   // if there are many clusters.
12376   sortAndRangeify(Clusters);
12377 
12378   // The branch probablity of the peeled case.
12379   BranchProbability PeeledCaseProb = BranchProbability::getZero();
12380   MachineBasicBlock *PeeledSwitchMBB =
12381       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
12382 
12383   // If there is only the default destination, jump there directly.
12384   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12385   if (Clusters.empty()) {
12386     assert(PeeledSwitchMBB == SwitchMBB);
12387     SwitchMBB->addSuccessor(DefaultMBB);
12388     if (DefaultMBB != NextBlock(SwitchMBB)) {
12389       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
12390                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
12391     }
12392     return;
12393   }
12394 
12395   SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(),
12396                      DAG.getBFI());
12397   SL->findBitTestClusters(Clusters, &SI);
12398 
12399   LLVM_DEBUG({
12400     dbgs() << "Case clusters: ";
12401     for (const CaseCluster &C : Clusters) {
12402       if (C.Kind == CC_JumpTable)
12403         dbgs() << "JT:";
12404       if (C.Kind == CC_BitTests)
12405         dbgs() << "BT:";
12406 
12407       C.Low->getValue().print(dbgs(), true);
12408       if (C.Low != C.High) {
12409         dbgs() << '-';
12410         C.High->getValue().print(dbgs(), true);
12411       }
12412       dbgs() << ' ';
12413     }
12414     dbgs() << '\n';
12415   });
12416 
12417   assert(!Clusters.empty());
12418   SwitchWorkList WorkList;
12419   CaseClusterIt First = Clusters.begin();
12420   CaseClusterIt Last = Clusters.end() - 1;
12421   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
12422   // Scale the branchprobability for DefaultMBB if the peel occurs and
12423   // DefaultMBB is not replaced.
12424   if (PeeledCaseProb != BranchProbability::getZero() &&
12425       DefaultMBB == FuncInfo.getMBB(SI.getDefaultDest()))
12426     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
12427   WorkList.push_back(
12428       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
12429 
12430   while (!WorkList.empty()) {
12431     SwitchWorkListItem W = WorkList.pop_back_val();
12432     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
12433 
12434     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None &&
12435         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
12436       // For optimized builds, lower large range as a balanced binary tree.
12437       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
12438       continue;
12439     }
12440 
12441     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
12442   }
12443 }
12444 
12445 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
12446   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12447   auto DL = getCurSDLoc();
12448   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12449   setValue(&I, DAG.getStepVector(DL, ResultVT));
12450 }
12451 
12452 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
12453   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12454   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12455 
12456   SDLoc DL = getCurSDLoc();
12457   SDValue V = getValue(I.getOperand(0));
12458   assert(VT == V.getValueType() && "Malformed vector.reverse!");
12459 
12460   if (VT.isScalableVector()) {
12461     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
12462     return;
12463   }
12464 
12465   // Use VECTOR_SHUFFLE for the fixed-length vector
12466   // to maintain existing behavior.
12467   SmallVector<int, 8> Mask;
12468   unsigned NumElts = VT.getVectorMinNumElements();
12469   for (unsigned i = 0; i != NumElts; ++i)
12470     Mask.push_back(NumElts - 1 - i);
12471 
12472   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
12473 }
12474 
12475 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) {
12476   auto DL = getCurSDLoc();
12477   SDValue InVec = getValue(I.getOperand(0));
12478   EVT OutVT =
12479       InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
12480 
12481   unsigned OutNumElts = OutVT.getVectorMinNumElements();
12482 
12483   // ISD Node needs the input vectors split into two equal parts
12484   SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
12485                            DAG.getVectorIdxConstant(0, DL));
12486   SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
12487                            DAG.getVectorIdxConstant(OutNumElts, DL));
12488 
12489   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
12490   // legalisation and combines.
12491   if (OutVT.isFixedLengthVector()) {
12492     SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
12493                                         createStrideMask(0, 2, OutNumElts));
12494     SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
12495                                        createStrideMask(1, 2, OutNumElts));
12496     SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc());
12497     setValue(&I, Res);
12498     return;
12499   }
12500 
12501   SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL,
12502                             DAG.getVTList(OutVT, OutVT), Lo, Hi);
12503   setValue(&I, Res);
12504 }
12505 
12506 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) {
12507   auto DL = getCurSDLoc();
12508   EVT InVT = getValue(I.getOperand(0)).getValueType();
12509   SDValue InVec0 = getValue(I.getOperand(0));
12510   SDValue InVec1 = getValue(I.getOperand(1));
12511   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12512   EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12513 
12514   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
12515   // legalisation and combines.
12516   if (OutVT.isFixedLengthVector()) {
12517     unsigned NumElts = InVT.getVectorMinNumElements();
12518     SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1);
12519     setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT),
12520                                       createInterleaveMask(NumElts, 2)));
12521     return;
12522   }
12523 
12524   SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL,
12525                             DAG.getVTList(InVT, InVT), InVec0, InVec1);
12526   Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0),
12527                     Res.getValue(1));
12528   setValue(&I, Res);
12529 }
12530 
12531 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
12532   SmallVector<EVT, 4> ValueVTs;
12533   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
12534                   ValueVTs);
12535   unsigned NumValues = ValueVTs.size();
12536   if (NumValues == 0) return;
12537 
12538   SmallVector<SDValue, 4> Values(NumValues);
12539   SDValue Op = getValue(I.getOperand(0));
12540 
12541   for (unsigned i = 0; i != NumValues; ++i)
12542     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
12543                             SDValue(Op.getNode(), Op.getResNo() + i));
12544 
12545   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12546                            DAG.getVTList(ValueVTs), Values));
12547 }
12548 
12549 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
12550   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12551   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12552 
12553   SDLoc DL = getCurSDLoc();
12554   SDValue V1 = getValue(I.getOperand(0));
12555   SDValue V2 = getValue(I.getOperand(1));
12556   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
12557 
12558   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
12559   if (VT.isScalableVector()) {
12560     setValue(
12561         &I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
12562                         DAG.getSignedConstant(
12563                             Imm, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))));
12564     return;
12565   }
12566 
12567   unsigned NumElts = VT.getVectorNumElements();
12568 
12569   uint64_t Idx = (NumElts + Imm) % NumElts;
12570 
12571   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
12572   SmallVector<int, 8> Mask;
12573   for (unsigned i = 0; i < NumElts; ++i)
12574     Mask.push_back(Idx + i);
12575   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
12576 }
12577 
12578 // Consider the following MIR after SelectionDAG, which produces output in
12579 // phyregs in the first case or virtregs in the second case.
12580 //
12581 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx
12582 // %5:gr32 = COPY $ebx
12583 // %6:gr32 = COPY $edx
12584 // %1:gr32 = COPY %6:gr32
12585 // %0:gr32 = COPY %5:gr32
12586 //
12587 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32
12588 // %1:gr32 = COPY %6:gr32
12589 // %0:gr32 = COPY %5:gr32
12590 //
12591 // Given %0, we'd like to return $ebx in the first case and %5 in the second.
12592 // Given %1, we'd like to return $edx in the first case and %6 in the second.
12593 //
12594 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap
12595 // to a single virtreg (such as %0). The remaining outputs monotonically
12596 // increase in virtreg number from there. If a callbr has no outputs, then it
12597 // should not have a corresponding callbr landingpad; in fact, the callbr
12598 // landingpad would not even be able to refer to such a callbr.
12599 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) {
12600   MachineInstr *MI = MRI.def_begin(Reg)->getParent();
12601   // There is definitely at least one copy.
12602   assert(MI->getOpcode() == TargetOpcode::COPY &&
12603          "start of copy chain MUST be COPY");
12604   Reg = MI->getOperand(1).getReg();
12605   MI = MRI.def_begin(Reg)->getParent();
12606   // There may be an optional second copy.
12607   if (MI->getOpcode() == TargetOpcode::COPY) {
12608     assert(Reg.isVirtual() && "expected COPY of virtual register");
12609     Reg = MI->getOperand(1).getReg();
12610     assert(Reg.isPhysical() && "expected COPY of physical register");
12611     MI = MRI.def_begin(Reg)->getParent();
12612   }
12613   // The start of the chain must be an INLINEASM_BR.
12614   assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR &&
12615          "end of copy chain MUST be INLINEASM_BR");
12616   return Reg;
12617 }
12618 
12619 // We must do this walk rather than the simpler
12620 //   setValue(&I, getCopyFromRegs(CBR, CBR->getType()));
12621 // otherwise we will end up with copies of virtregs only valid along direct
12622 // edges.
12623 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) {
12624   SmallVector<EVT, 8> ResultVTs;
12625   SmallVector<SDValue, 8> ResultValues;
12626   const auto *CBR =
12627       cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator());
12628 
12629   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12630   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
12631   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
12632 
12633   unsigned InitialDef = FuncInfo.ValueMap[CBR];
12634   SDValue Chain = DAG.getRoot();
12635 
12636   // Re-parse the asm constraints string.
12637   TargetLowering::AsmOperandInfoVector TargetConstraints =
12638       TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR);
12639   for (auto &T : TargetConstraints) {
12640     SDISelAsmOperandInfo OpInfo(T);
12641     if (OpInfo.Type != InlineAsm::isOutput)
12642       continue;
12643 
12644     // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the
12645     // individual constraint.
12646     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
12647 
12648     switch (OpInfo.ConstraintType) {
12649     case TargetLowering::C_Register:
12650     case TargetLowering::C_RegisterClass: {
12651       // Fill in OpInfo.AssignedRegs.Regs.
12652       getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo);
12653 
12654       // getRegistersForValue may produce 1 to many registers based on whether
12655       // the OpInfo.ConstraintVT is legal on the target or not.
12656       for (Register &Reg : OpInfo.AssignedRegs.Regs) {
12657         Register OriginalDef = FollowCopyChain(MRI, InitialDef++);
12658         if (Register::isPhysicalRegister(OriginalDef))
12659           FuncInfo.MBB->addLiveIn(OriginalDef);
12660         // Update the assigned registers to use the original defs.
12661         Reg = OriginalDef;
12662       }
12663 
12664       SDValue V = OpInfo.AssignedRegs.getCopyFromRegs(
12665           DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR);
12666       ResultValues.push_back(V);
12667       ResultVTs.push_back(OpInfo.ConstraintVT);
12668       break;
12669     }
12670     case TargetLowering::C_Other: {
12671       SDValue Flag;
12672       SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
12673                                                   OpInfo, DAG);
12674       ++InitialDef;
12675       ResultValues.push_back(V);
12676       ResultVTs.push_back(OpInfo.ConstraintVT);
12677       break;
12678     }
12679     default:
12680       break;
12681     }
12682   }
12683   SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12684                           DAG.getVTList(ResultVTs), ResultValues);
12685   setValue(&I, V);
12686 }
12687