xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 40986feda8b1437ed475b144d5b9a208b008782a)
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/SelectionDAG.h"
48 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
49 #include "llvm/CodeGen/StackMaps.h"
50 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
51 #include "llvm/CodeGen/TargetFrameLowering.h"
52 #include "llvm/CodeGen/TargetInstrInfo.h"
53 #include "llvm/CodeGen/TargetOpcodes.h"
54 #include "llvm/CodeGen/TargetRegisterInfo.h"
55 #include "llvm/CodeGen/TargetSubtargetInfo.h"
56 #include "llvm/CodeGen/WinEHFuncInfo.h"
57 #include "llvm/IR/Argument.h"
58 #include "llvm/IR/Attributes.h"
59 #include "llvm/IR/BasicBlock.h"
60 #include "llvm/IR/CFG.h"
61 #include "llvm/IR/CallingConv.h"
62 #include "llvm/IR/Constant.h"
63 #include "llvm/IR/ConstantRange.h"
64 #include "llvm/IR/Constants.h"
65 #include "llvm/IR/DataLayout.h"
66 #include "llvm/IR/DebugInfo.h"
67 #include "llvm/IR/DebugInfoMetadata.h"
68 #include "llvm/IR/DerivedTypes.h"
69 #include "llvm/IR/DiagnosticInfo.h"
70 #include "llvm/IR/EHPersonalities.h"
71 #include "llvm/IR/Function.h"
72 #include "llvm/IR/GetElementPtrTypeIterator.h"
73 #include "llvm/IR/InlineAsm.h"
74 #include "llvm/IR/InstrTypes.h"
75 #include "llvm/IR/Instructions.h"
76 #include "llvm/IR/IntrinsicInst.h"
77 #include "llvm/IR/Intrinsics.h"
78 #include "llvm/IR/IntrinsicsAArch64.h"
79 #include "llvm/IR/IntrinsicsAMDGPU.h"
80 #include "llvm/IR/IntrinsicsWebAssembly.h"
81 #include "llvm/IR/LLVMContext.h"
82 #include "llvm/IR/MemoryModelRelaxationAnnotations.h"
83 #include "llvm/IR/Metadata.h"
84 #include "llvm/IR/Module.h"
85 #include "llvm/IR/Operator.h"
86 #include "llvm/IR/PatternMatch.h"
87 #include "llvm/IR/Statepoint.h"
88 #include "llvm/IR/Type.h"
89 #include "llvm/IR/User.h"
90 #include "llvm/IR/Value.h"
91 #include "llvm/MC/MCContext.h"
92 #include "llvm/Support/AtomicOrdering.h"
93 #include "llvm/Support/Casting.h"
94 #include "llvm/Support/CommandLine.h"
95 #include "llvm/Support/Compiler.h"
96 #include "llvm/Support/Debug.h"
97 #include "llvm/Support/InstructionCost.h"
98 #include "llvm/Support/MathExtras.h"
99 #include "llvm/Support/raw_ostream.h"
100 #include "llvm/Target/TargetIntrinsicInfo.h"
101 #include "llvm/Target/TargetMachine.h"
102 #include "llvm/Target/TargetOptions.h"
103 #include "llvm/TargetParser/Triple.h"
104 #include "llvm/Transforms/Utils/Local.h"
105 #include <cstddef>
106 #include <limits>
107 #include <optional>
108 #include <tuple>
109 
110 using namespace llvm;
111 using namespace PatternMatch;
112 using namespace SwitchCG;
113 
114 #define DEBUG_TYPE "isel"
115 
116 /// LimitFloatPrecision - Generate low-precision inline sequences for
117 /// some float libcalls (6, 8 or 12 bits).
118 static unsigned LimitFloatPrecision;
119 
120 static cl::opt<bool>
121     InsertAssertAlign("insert-assert-align", cl::init(true),
122                       cl::desc("Insert the experimental `assertalign` node."),
123                       cl::ReallyHidden);
124 
125 static cl::opt<unsigned, true>
126     LimitFPPrecision("limit-float-precision",
127                      cl::desc("Generate low-precision inline sequences "
128                               "for some float libcalls"),
129                      cl::location(LimitFloatPrecision), cl::Hidden,
130                      cl::init(0));
131 
132 static cl::opt<unsigned> SwitchPeelThreshold(
133     "switch-peel-threshold", cl::Hidden, cl::init(66),
134     cl::desc("Set the case probability threshold for peeling the case from a "
135              "switch statement. A value greater than 100 will void this "
136              "optimization"));
137 
138 // Limit the width of DAG chains. This is important in general to prevent
139 // DAG-based analysis from blowing up. For example, alias analysis and
140 // load clustering may not complete in reasonable time. It is difficult to
141 // recognize and avoid this situation within each individual analysis, and
142 // future analyses are likely to have the same behavior. Limiting DAG width is
143 // the safe approach and will be especially important with global DAGs.
144 //
145 // MaxParallelChains default is arbitrarily high to avoid affecting
146 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
147 // sequence over this should have been converted to llvm.memcpy by the
148 // frontend. It is easy to induce this behavior with .ll code such as:
149 // %buffer = alloca [4096 x i8]
150 // %data = load [4096 x i8]* %argPtr
151 // store [4096 x i8] %data, [4096 x i8]* %buffer
152 static const unsigned MaxParallelChains = 64;
153 
154 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
155                                       const SDValue *Parts, unsigned NumParts,
156                                       MVT PartVT, EVT ValueVT, const Value *V,
157                                       SDValue InChain,
158                                       std::optional<CallingConv::ID> CC);
159 
160 /// getCopyFromParts - Create a value that contains the specified legal parts
161 /// combined into the value they represent.  If the parts combine to a type
162 /// larger than ValueVT then AssertOp can be used to specify whether the extra
163 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
164 /// (ISD::AssertSext).
165 static SDValue
166 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts,
167                  unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V,
168                  SDValue InChain,
169                  std::optional<CallingConv::ID> CC = std::nullopt,
170                  std::optional<ISD::NodeType> AssertOp = std::nullopt) {
171   // Let the target assemble the parts if it wants to
172   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
173   if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
174                                                    PartVT, ValueVT, CC))
175     return Val;
176 
177   if (ValueVT.isVector())
178     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
179                                   InChain, CC);
180 
181   assert(NumParts > 0 && "No parts to assemble!");
182   SDValue Val = Parts[0];
183 
184   if (NumParts > 1) {
185     // Assemble the value from multiple parts.
186     if (ValueVT.isInteger()) {
187       unsigned PartBits = PartVT.getSizeInBits();
188       unsigned ValueBits = ValueVT.getSizeInBits();
189 
190       // Assemble the power of 2 part.
191       unsigned RoundParts = llvm::bit_floor(NumParts);
192       unsigned RoundBits = PartBits * RoundParts;
193       EVT RoundVT = RoundBits == ValueBits ?
194         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
195       SDValue Lo, Hi;
196 
197       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
198 
199       if (RoundParts > 2) {
200         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, PartVT, HalfVT, V,
201                               InChain);
202         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, RoundParts / 2,
203                               PartVT, HalfVT, V, InChain);
204       } else {
205         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
206         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
207       }
208 
209       if (DAG.getDataLayout().isBigEndian())
210         std::swap(Lo, Hi);
211 
212       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
213 
214       if (RoundParts < NumParts) {
215         // Assemble the trailing non-power-of-2 part.
216         unsigned OddParts = NumParts - RoundParts;
217         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
218         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
219                               OddVT, V, InChain, CC);
220 
221         // Combine the round and odd parts.
222         Lo = Val;
223         if (DAG.getDataLayout().isBigEndian())
224           std::swap(Lo, Hi);
225         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
226         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
227         Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
228                          DAG.getConstant(Lo.getValueSizeInBits(), DL,
229                                          TLI.getShiftAmountTy(
230                                              TotalVT, DAG.getDataLayout())));
231         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
232         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
233       }
234     } else if (PartVT.isFloatingPoint()) {
235       // FP split into multiple FP parts (for ppcf128)
236       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
237              "Unexpected split");
238       SDValue Lo, Hi;
239       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
240       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
241       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
242         std::swap(Lo, Hi);
243       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
244     } else {
245       // FP split into integer parts (soft fp)
246       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
247              !PartVT.isVector() && "Unexpected split");
248       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
249       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V,
250                              InChain, CC);
251     }
252   }
253 
254   // There is now one part, held in Val.  Correct it to match ValueVT.
255   // PartEVT is the type of the register class that holds the value.
256   // ValueVT is the type of the inline asm operation.
257   EVT PartEVT = Val.getValueType();
258 
259   if (PartEVT == ValueVT)
260     return Val;
261 
262   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
263       ValueVT.bitsLT(PartEVT)) {
264     // For an FP value in an integer part, we need to truncate to the right
265     // width first.
266     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
267     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
268   }
269 
270   // Handle types that have the same size.
271   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
272     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
273 
274   // Handle types with different sizes.
275   if (PartEVT.isInteger() && ValueVT.isInteger()) {
276     if (ValueVT.bitsLT(PartEVT)) {
277       // For a truncate, see if we have any information to
278       // indicate whether the truncated bits will always be
279       // zero or sign-extension.
280       if (AssertOp)
281         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
282                           DAG.getValueType(ValueVT));
283       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
284     }
285     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
286   }
287 
288   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
289     // FP_ROUND's are always exact here.
290     if (ValueVT.bitsLT(Val.getValueType())) {
291 
292       SDValue NoChange =
293           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
294 
295       if (DAG.getMachineFunction().getFunction().getAttributes().hasFnAttr(
296               llvm::Attribute::StrictFP)) {
297         return DAG.getNode(ISD::STRICT_FP_ROUND, DL,
298                            DAG.getVTList(ValueVT, MVT::Other), InChain, Val,
299                            NoChange);
300       }
301 
302       return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val, NoChange);
303     }
304 
305     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
306   }
307 
308   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
309   // then truncating.
310   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
311       ValueVT.bitsLT(PartEVT)) {
312     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
313     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
314   }
315 
316   report_fatal_error("Unknown mismatch in getCopyFromParts!");
317 }
318 
319 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
320                                               const Twine &ErrMsg) {
321   const Instruction *I = dyn_cast_or_null<Instruction>(V);
322   if (!V)
323     return Ctx.emitError(ErrMsg);
324 
325   const char *AsmError = ", possible invalid constraint for vector type";
326   if (const CallInst *CI = dyn_cast<CallInst>(I))
327     if (CI->isInlineAsm())
328       return Ctx.emitError(I, ErrMsg + AsmError);
329 
330   return Ctx.emitError(I, ErrMsg);
331 }
332 
333 /// getCopyFromPartsVector - Create a value that contains the specified legal
334 /// parts combined into the value they represent.  If the parts combine to a
335 /// type larger than ValueVT then AssertOp can be used to specify whether the
336 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
337 /// ValueVT (ISD::AssertSext).
338 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
339                                       const SDValue *Parts, unsigned NumParts,
340                                       MVT PartVT, EVT ValueVT, const Value *V,
341                                       SDValue InChain,
342                                       std::optional<CallingConv::ID> CallConv) {
343   assert(ValueVT.isVector() && "Not a vector value");
344   assert(NumParts > 0 && "No parts to assemble!");
345   const bool IsABIRegCopy = CallConv.has_value();
346 
347   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
348   SDValue Val = Parts[0];
349 
350   // Handle a multi-element vector.
351   if (NumParts > 1) {
352     EVT IntermediateVT;
353     MVT RegisterVT;
354     unsigned NumIntermediates;
355     unsigned NumRegs;
356 
357     if (IsABIRegCopy) {
358       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
359           *DAG.getContext(), *CallConv, ValueVT, IntermediateVT,
360           NumIntermediates, RegisterVT);
361     } else {
362       NumRegs =
363           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
364                                      NumIntermediates, RegisterVT);
365     }
366 
367     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
368     NumParts = NumRegs; // Silence a compiler warning.
369     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
370     assert(RegisterVT.getSizeInBits() ==
371            Parts[0].getSimpleValueType().getSizeInBits() &&
372            "Part type sizes don't match!");
373 
374     // Assemble the parts into intermediate operands.
375     SmallVector<SDValue, 8> Ops(NumIntermediates);
376     if (NumIntermediates == NumParts) {
377       // If the register was not expanded, truncate or copy the value,
378       // as appropriate.
379       for (unsigned i = 0; i != NumParts; ++i)
380         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, PartVT, IntermediateVT,
381                                   V, InChain, CallConv);
382     } else if (NumParts > 0) {
383       // If the intermediate type was expanded, build the intermediate
384       // operands from the parts.
385       assert(NumParts % NumIntermediates == 0 &&
386              "Must expand into a divisible number of parts!");
387       unsigned Factor = NumParts / NumIntermediates;
388       for (unsigned i = 0; i != NumIntermediates; ++i)
389         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, PartVT,
390                                   IntermediateVT, V, InChain, CallConv);
391     }
392 
393     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
394     // intermediate operands.
395     EVT BuiltVectorTy =
396         IntermediateVT.isVector()
397             ? EVT::getVectorVT(
398                   *DAG.getContext(), IntermediateVT.getScalarType(),
399                   IntermediateVT.getVectorElementCount() * NumParts)
400             : EVT::getVectorVT(*DAG.getContext(),
401                                IntermediateVT.getScalarType(),
402                                NumIntermediates);
403     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
404                                                 : ISD::BUILD_VECTOR,
405                       DL, BuiltVectorTy, Ops);
406   }
407 
408   // There is now one part, held in Val.  Correct it to match ValueVT.
409   EVT PartEVT = Val.getValueType();
410 
411   if (PartEVT == ValueVT)
412     return Val;
413 
414   if (PartEVT.isVector()) {
415     // Vector/Vector bitcast.
416     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
417       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
418 
419     // If the parts vector has more elements than the value vector, then we
420     // have a vector widening case (e.g. <2 x float> -> <4 x float>).
421     // Extract the elements we want.
422     if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
423       assert((PartEVT.getVectorElementCount().getKnownMinValue() >
424               ValueVT.getVectorElementCount().getKnownMinValue()) &&
425              (PartEVT.getVectorElementCount().isScalable() ==
426               ValueVT.getVectorElementCount().isScalable()) &&
427              "Cannot narrow, it would be a lossy transformation");
428       PartEVT =
429           EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(),
430                            ValueVT.getVectorElementCount());
431       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val,
432                         DAG.getVectorIdxConstant(0, DL));
433       if (PartEVT == ValueVT)
434         return Val;
435       if (PartEVT.isInteger() && ValueVT.isFloatingPoint())
436         return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
437 
438       // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>).
439       if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
440         return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
441     }
442 
443     // Promoted vector extract
444     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
445   }
446 
447   // Trivial bitcast if the types are the same size and the destination
448   // vector type is legal.
449   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
450       TLI.isTypeLegal(ValueVT))
451     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
452 
453   if (ValueVT.getVectorNumElements() != 1) {
454      // Certain ABIs require that vectors are passed as integers. For vectors
455      // are the same size, this is an obvious bitcast.
456      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
457        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
458      } else if (ValueVT.bitsLT(PartEVT)) {
459        const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
460        EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
461        // Drop the extra bits.
462        Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
463        return DAG.getBitcast(ValueVT, Val);
464      }
465 
466      diagnosePossiblyInvalidConstraint(
467          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
468      return DAG.getUNDEF(ValueVT);
469   }
470 
471   // Handle cases such as i8 -> <1 x i1>
472   EVT ValueSVT = ValueVT.getVectorElementType();
473   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
474     unsigned ValueSize = ValueSVT.getSizeInBits();
475     if (ValueSize == PartEVT.getSizeInBits()) {
476       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
477     } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) {
478       // It's possible a scalar floating point type gets softened to integer and
479       // then promoted to a larger integer. If PartEVT is the larger integer
480       // we need to truncate it and then bitcast to the FP type.
481       assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types");
482       EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
483       Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
484       Val = DAG.getBitcast(ValueSVT, Val);
485     } else {
486       Val = ValueVT.isFloatingPoint()
487                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
488                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
489     }
490   }
491 
492   return DAG.getBuildVector(ValueVT, DL, Val);
493 }
494 
495 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
496                                  SDValue Val, SDValue *Parts, unsigned NumParts,
497                                  MVT PartVT, const Value *V,
498                                  std::optional<CallingConv::ID> CallConv);
499 
500 /// getCopyToParts - Create a series of nodes that contain the specified value
501 /// split into legal parts.  If the parts contain more bits than Val, then, for
502 /// integers, ExtendKind can be used to specify how to generate the extra bits.
503 static void
504 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
505                unsigned NumParts, MVT PartVT, const Value *V,
506                std::optional<CallingConv::ID> CallConv = std::nullopt,
507                ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
508   // Let the target split the parts if it wants to
509   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
510   if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
511                                       CallConv))
512     return;
513   EVT ValueVT = Val.getValueType();
514 
515   // Handle the vector case separately.
516   if (ValueVT.isVector())
517     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
518                                 CallConv);
519 
520   unsigned OrigNumParts = NumParts;
521   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
522          "Copying to an illegal type!");
523 
524   if (NumParts == 0)
525     return;
526 
527   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
528   EVT PartEVT = PartVT;
529   if (PartEVT == ValueVT) {
530     assert(NumParts == 1 && "No-op copy with multiple parts!");
531     Parts[0] = Val;
532     return;
533   }
534 
535   unsigned PartBits = PartVT.getSizeInBits();
536   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
537     // If the parts cover more bits than the value has, promote the value.
538     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
539       assert(NumParts == 1 && "Do not know what to promote to!");
540       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
541     } else {
542       if (ValueVT.isFloatingPoint()) {
543         // FP values need to be bitcast, then extended if they are being put
544         // into a larger container.
545         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
546         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
547       }
548       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
549              ValueVT.isInteger() &&
550              "Unknown mismatch!");
551       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
552       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
553       if (PartVT == MVT::x86mmx)
554         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
555     }
556   } else if (PartBits == ValueVT.getSizeInBits()) {
557     // Different types of the same size.
558     assert(NumParts == 1 && PartEVT != ValueVT);
559     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
560   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
561     // If the parts cover less bits than value has, truncate the value.
562     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
563            ValueVT.isInteger() &&
564            "Unknown mismatch!");
565     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
566     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
567     if (PartVT == MVT::x86mmx)
568       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
569   }
570 
571   // The value may have changed - recompute ValueVT.
572   ValueVT = Val.getValueType();
573   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
574          "Failed to tile the value with PartVT!");
575 
576   if (NumParts == 1) {
577     if (PartEVT != ValueVT) {
578       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
579                                         "scalar-to-vector conversion failed");
580       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
581     }
582 
583     Parts[0] = Val;
584     return;
585   }
586 
587   // Expand the value into multiple parts.
588   if (NumParts & (NumParts - 1)) {
589     // The number of parts is not a power of 2.  Split off and copy the tail.
590     assert(PartVT.isInteger() && ValueVT.isInteger() &&
591            "Do not know what to expand to!");
592     unsigned RoundParts = llvm::bit_floor(NumParts);
593     unsigned RoundBits = RoundParts * PartBits;
594     unsigned OddParts = NumParts - RoundParts;
595     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
596       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL));
597 
598     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
599                    CallConv);
600 
601     if (DAG.getDataLayout().isBigEndian())
602       // The odd parts were reversed by getCopyToParts - unreverse them.
603       std::reverse(Parts + RoundParts, Parts + NumParts);
604 
605     NumParts = RoundParts;
606     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
607     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
608   }
609 
610   // The number of parts is a power of 2.  Repeatedly bisect the value using
611   // EXTRACT_ELEMENT.
612   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
613                          EVT::getIntegerVT(*DAG.getContext(),
614                                            ValueVT.getSizeInBits()),
615                          Val);
616 
617   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
618     for (unsigned i = 0; i < NumParts; i += StepSize) {
619       unsigned ThisBits = StepSize * PartBits / 2;
620       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
621       SDValue &Part0 = Parts[i];
622       SDValue &Part1 = Parts[i+StepSize/2];
623 
624       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
625                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
626       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
627                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
628 
629       if (ThisBits == PartBits && ThisVT != PartVT) {
630         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
631         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
632       }
633     }
634   }
635 
636   if (DAG.getDataLayout().isBigEndian())
637     std::reverse(Parts, Parts + OrigNumParts);
638 }
639 
640 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val,
641                                      const SDLoc &DL, EVT PartVT) {
642   if (!PartVT.isVector())
643     return SDValue();
644 
645   EVT ValueVT = Val.getValueType();
646   EVT PartEVT = PartVT.getVectorElementType();
647   EVT ValueEVT = ValueVT.getVectorElementType();
648   ElementCount PartNumElts = PartVT.getVectorElementCount();
649   ElementCount ValueNumElts = ValueVT.getVectorElementCount();
650 
651   // We only support widening vectors with equivalent element types and
652   // fixed/scalable properties. If a target needs to widen a fixed-length type
653   // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
654   if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
655       PartNumElts.isScalable() != ValueNumElts.isScalable())
656     return SDValue();
657 
658   // Have a try for bf16 because some targets share its ABI with fp16.
659   if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) {
660     assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
661            "Cannot widen to illegal type");
662     Val = DAG.getNode(ISD::BITCAST, DL,
663                       ValueVT.changeVectorElementType(MVT::f16), Val);
664   } else if (PartEVT != ValueEVT) {
665     return SDValue();
666   }
667 
668   // Widening a scalable vector to another scalable vector is done by inserting
669   // the vector into a larger undef one.
670   if (PartNumElts.isScalable())
671     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
672                        Val, DAG.getVectorIdxConstant(0, DL));
673 
674   // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
675   // undef elements.
676   SmallVector<SDValue, 16> Ops;
677   DAG.ExtractVectorElements(Val, Ops);
678   SDValue EltUndef = DAG.getUNDEF(PartEVT);
679   Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
680 
681   // FIXME: Use CONCAT for 2x -> 4x.
682   return DAG.getBuildVector(PartVT, DL, Ops);
683 }
684 
685 /// getCopyToPartsVector - Create a series of nodes that contain the specified
686 /// value split into legal parts.
687 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
688                                  SDValue Val, SDValue *Parts, unsigned NumParts,
689                                  MVT PartVT, const Value *V,
690                                  std::optional<CallingConv::ID> CallConv) {
691   EVT ValueVT = Val.getValueType();
692   assert(ValueVT.isVector() && "Not a vector");
693   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
694   const bool IsABIRegCopy = CallConv.has_value();
695 
696   if (NumParts == 1) {
697     EVT PartEVT = PartVT;
698     if (PartEVT == ValueVT) {
699       // Nothing to do.
700     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
701       // Bitconvert vector->vector case.
702       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
703     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
704       Val = Widened;
705     } else if (PartVT.isVector() &&
706                PartEVT.getVectorElementType().bitsGE(
707                    ValueVT.getVectorElementType()) &&
708                PartEVT.getVectorElementCount() ==
709                    ValueVT.getVectorElementCount()) {
710 
711       // Promoted vector extract
712       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
713     } else if (PartEVT.isVector() &&
714                PartEVT.getVectorElementType() !=
715                    ValueVT.getVectorElementType() &&
716                TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
717                    TargetLowering::TypeWidenVector) {
718       // Combination of widening and promotion.
719       EVT WidenVT =
720           EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(),
721                            PartVT.getVectorElementCount());
722       SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
723       Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
724     } else {
725       // Don't extract an integer from a float vector. This can happen if the
726       // FP type gets softened to integer and then promoted. The promotion
727       // prevents it from being picked up by the earlier bitcast case.
728       if (ValueVT.getVectorElementCount().isScalar() &&
729           (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) {
730         // If we reach this condition and PartVT is FP, this means that
731         // ValueVT is also FP and both have a different size, otherwise we
732         // would have bitcasted them. Producing an EXTRACT_VECTOR_ELT here
733         // would be invalid since that would mean the smaller FP type has to
734         // be extended to the larger one.
735         if (PartVT.isFloatingPoint()) {
736           Val = DAG.getBitcast(ValueVT.getScalarType(), Val);
737           Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
738         } else
739           Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
740                             DAG.getVectorIdxConstant(0, DL));
741       } else {
742         uint64_t ValueSize = ValueVT.getFixedSizeInBits();
743         assert(PartVT.getFixedSizeInBits() > ValueSize &&
744                "lossy conversion of vector to scalar type");
745         EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
746         Val = DAG.getBitcast(IntermediateType, Val);
747         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
748       }
749     }
750 
751     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
752     Parts[0] = Val;
753     return;
754   }
755 
756   // Handle a multi-element vector.
757   EVT IntermediateVT;
758   MVT RegisterVT;
759   unsigned NumIntermediates;
760   unsigned NumRegs;
761   if (IsABIRegCopy) {
762     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
763         *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates,
764         RegisterVT);
765   } else {
766     NumRegs =
767         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
768                                    NumIntermediates, RegisterVT);
769   }
770 
771   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
772   NumParts = NumRegs; // Silence a compiler warning.
773   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
774 
775   assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
776          "Mixing scalable and fixed vectors when copying in parts");
777 
778   std::optional<ElementCount> DestEltCnt;
779 
780   if (IntermediateVT.isVector())
781     DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
782   else
783     DestEltCnt = ElementCount::getFixed(NumIntermediates);
784 
785   EVT BuiltVectorTy = EVT::getVectorVT(
786       *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt);
787 
788   if (ValueVT == BuiltVectorTy) {
789     // Nothing to do.
790   } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
791     // Bitconvert vector->vector case.
792     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
793   } else {
794     if (BuiltVectorTy.getVectorElementType().bitsGT(
795             ValueVT.getVectorElementType())) {
796       // Integer promotion.
797       ValueVT = EVT::getVectorVT(*DAG.getContext(),
798                                  BuiltVectorTy.getVectorElementType(),
799                                  ValueVT.getVectorElementCount());
800       Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
801     }
802 
803     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
804       Val = Widened;
805     }
806   }
807 
808   assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
809 
810   // Split the vector into intermediate operands.
811   SmallVector<SDValue, 8> Ops(NumIntermediates);
812   for (unsigned i = 0; i != NumIntermediates; ++i) {
813     if (IntermediateVT.isVector()) {
814       // This does something sensible for scalable vectors - see the
815       // definition of EXTRACT_SUBVECTOR for further details.
816       unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
817       Ops[i] =
818           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
819                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
820     } else {
821       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
822                            DAG.getVectorIdxConstant(i, DL));
823     }
824   }
825 
826   // Split the intermediate operands into legal parts.
827   if (NumParts == NumIntermediates) {
828     // If the register was not expanded, promote or copy the value,
829     // as appropriate.
830     for (unsigned i = 0; i != NumParts; ++i)
831       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
832   } else if (NumParts > 0) {
833     // If the intermediate type was expanded, split each the value into
834     // legal parts.
835     assert(NumIntermediates != 0 && "division by zero");
836     assert(NumParts % NumIntermediates == 0 &&
837            "Must expand into a divisible number of parts!");
838     unsigned Factor = NumParts / NumIntermediates;
839     for (unsigned i = 0; i != NumIntermediates; ++i)
840       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
841                      CallConv);
842   }
843 }
844 
845 RegsForValue::RegsForValue(const SmallVector<Register, 4> &regs, MVT regvt,
846                            EVT valuevt, std::optional<CallingConv::ID> CC)
847     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
848       RegCount(1, regs.size()), CallConv(CC) {}
849 
850 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
851                            const DataLayout &DL, Register Reg, Type *Ty,
852                            std::optional<CallingConv::ID> CC) {
853   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
854 
855   CallConv = CC;
856 
857   for (EVT ValueVT : ValueVTs) {
858     unsigned NumRegs =
859         isABIMangled()
860             ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT)
861             : TLI.getNumRegisters(Context, ValueVT);
862     MVT RegisterVT =
863         isABIMangled()
864             ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT)
865             : TLI.getRegisterType(Context, ValueVT);
866     for (unsigned i = 0; i != NumRegs; ++i)
867       Regs.push_back(Reg + i);
868     RegVTs.push_back(RegisterVT);
869     RegCount.push_back(NumRegs);
870     Reg = Reg.id() + NumRegs;
871   }
872 }
873 
874 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
875                                       FunctionLoweringInfo &FuncInfo,
876                                       const SDLoc &dl, SDValue &Chain,
877                                       SDValue *Glue, const Value *V) const {
878   // A Value with type {} or [0 x %t] needs no registers.
879   if (ValueVTs.empty())
880     return SDValue();
881 
882   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
883 
884   // Assemble the legal parts into the final values.
885   SmallVector<SDValue, 4> Values(ValueVTs.size());
886   SmallVector<SDValue, 8> Parts;
887   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
888     // Copy the legal parts from the registers.
889     EVT ValueVT = ValueVTs[Value];
890     unsigned NumRegs = RegCount[Value];
891     MVT RegisterVT = isABIMangled()
892                          ? TLI.getRegisterTypeForCallingConv(
893                                *DAG.getContext(), *CallConv, RegVTs[Value])
894                          : RegVTs[Value];
895 
896     Parts.resize(NumRegs);
897     for (unsigned i = 0; i != NumRegs; ++i) {
898       SDValue P;
899       if (!Glue) {
900         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
901       } else {
902         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue);
903         *Glue = P.getValue(2);
904       }
905 
906       Chain = P.getValue(1);
907       Parts[i] = P;
908 
909       // If the source register was virtual and if we know something about it,
910       // add an assert node.
911       if (!Register::isVirtualRegister(Regs[Part + i]) ||
912           !RegisterVT.isInteger())
913         continue;
914 
915       const FunctionLoweringInfo::LiveOutInfo *LOI =
916         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
917       if (!LOI)
918         continue;
919 
920       unsigned RegSize = RegisterVT.getScalarSizeInBits();
921       unsigned NumSignBits = LOI->NumSignBits;
922       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
923 
924       if (NumZeroBits == RegSize) {
925         // The current value is a zero.
926         // Explicitly express that as it would be easier for
927         // optimizations to kick in.
928         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
929         continue;
930       }
931 
932       // FIXME: We capture more information than the dag can represent.  For
933       // now, just use the tightest assertzext/assertsext possible.
934       bool isSExt;
935       EVT FromVT(MVT::Other);
936       if (NumZeroBits) {
937         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
938         isSExt = false;
939       } else if (NumSignBits > 1) {
940         FromVT =
941             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
942         isSExt = true;
943       } else {
944         continue;
945       }
946       // Add an assertion node.
947       assert(FromVT != MVT::Other);
948       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
949                              RegisterVT, P, DAG.getValueType(FromVT));
950     }
951 
952     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
953                                      RegisterVT, ValueVT, V, Chain, CallConv);
954     Part += NumRegs;
955     Parts.clear();
956   }
957 
958   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
959 }
960 
961 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
962                                  const SDLoc &dl, SDValue &Chain, SDValue *Glue,
963                                  const Value *V,
964                                  ISD::NodeType PreferredExtendType) const {
965   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
966   ISD::NodeType ExtendKind = PreferredExtendType;
967 
968   // Get the list of the values's legal parts.
969   unsigned NumRegs = Regs.size();
970   SmallVector<SDValue, 8> Parts(NumRegs);
971   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
972     unsigned NumParts = RegCount[Value];
973 
974     MVT RegisterVT = isABIMangled()
975                          ? TLI.getRegisterTypeForCallingConv(
976                                *DAG.getContext(), *CallConv, RegVTs[Value])
977                          : RegVTs[Value];
978 
979     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
980       ExtendKind = ISD::ZERO_EXTEND;
981 
982     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
983                    NumParts, RegisterVT, V, CallConv, ExtendKind);
984     Part += NumParts;
985   }
986 
987   // Copy the parts into the registers.
988   SmallVector<SDValue, 8> Chains(NumRegs);
989   for (unsigned i = 0; i != NumRegs; ++i) {
990     SDValue Part;
991     if (!Glue) {
992       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
993     } else {
994       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue);
995       *Glue = Part.getValue(1);
996     }
997 
998     Chains[i] = Part.getValue(0);
999   }
1000 
1001   if (NumRegs == 1 || Glue)
1002     // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is
1003     // flagged to it. That is the CopyToReg nodes and the user are considered
1004     // a single scheduling unit. If we create a TokenFactor and return it as
1005     // chain, then the TokenFactor is both a predecessor (operand) of the
1006     // user as well as a successor (the TF operands are flagged to the user).
1007     // c1, f1 = CopyToReg
1008     // c2, f2 = CopyToReg
1009     // c3     = TokenFactor c1, c2
1010     // ...
1011     //        = op c3, ..., f2
1012     Chain = Chains[NumRegs-1];
1013   else
1014     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
1015 }
1016 
1017 void RegsForValue::AddInlineAsmOperands(InlineAsm::Kind Code, bool HasMatching,
1018                                         unsigned MatchingIdx, const SDLoc &dl,
1019                                         SelectionDAG &DAG,
1020                                         std::vector<SDValue> &Ops) const {
1021   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1022 
1023   InlineAsm::Flag Flag(Code, Regs.size());
1024   if (HasMatching)
1025     Flag.setMatchingOp(MatchingIdx);
1026   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
1027     // Put the register class of the virtual registers in the flag word.  That
1028     // way, later passes can recompute register class constraints for inline
1029     // assembly as well as normal instructions.
1030     // Don't do this for tied operands that can use the regclass information
1031     // from the def.
1032     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1033     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
1034     Flag.setRegClass(RC->getID());
1035   }
1036 
1037   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
1038   Ops.push_back(Res);
1039 
1040   if (Code == InlineAsm::Kind::Clobber) {
1041     // Clobbers should always have a 1:1 mapping with registers, and may
1042     // reference registers that have illegal (e.g. vector) types. Hence, we
1043     // shouldn't try to apply any sort of splitting logic to them.
1044     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
1045            "No 1:1 mapping from clobbers to regs?");
1046     Register SP = TLI.getStackPointerRegisterToSaveRestore();
1047     (void)SP;
1048     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
1049       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
1050       assert(
1051           (Regs[I] != SP ||
1052            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
1053           "If we clobbered the stack pointer, MFI should know about it.");
1054     }
1055     return;
1056   }
1057 
1058   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1059     MVT RegisterVT = RegVTs[Value];
1060     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
1061                                            RegisterVT);
1062     for (unsigned i = 0; i != NumRegs; ++i) {
1063       assert(Reg < Regs.size() && "Mismatch in # registers expected");
1064       unsigned TheReg = Regs[Reg++];
1065       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1066     }
1067   }
1068 }
1069 
1070 SmallVector<std::pair<Register, TypeSize>, 4>
1071 RegsForValue::getRegsAndSizes() const {
1072   SmallVector<std::pair<Register, TypeSize>, 4> OutVec;
1073   unsigned I = 0;
1074   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1075     unsigned RegCount = std::get<0>(CountAndVT);
1076     MVT RegisterVT = std::get<1>(CountAndVT);
1077     TypeSize RegisterSize = RegisterVT.getSizeInBits();
1078     for (unsigned E = I + RegCount; I != E; ++I)
1079       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1080   }
1081   return OutVec;
1082 }
1083 
1084 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1085                                AssumptionCache *ac,
1086                                const TargetLibraryInfo *li) {
1087   AA = aa;
1088   AC = ac;
1089   GFI = gfi;
1090   LibInfo = li;
1091   Context = DAG.getContext();
1092   LPadToCallSiteMap.clear();
1093   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1094   AssignmentTrackingEnabled = isAssignmentTrackingEnabled(
1095       *DAG.getMachineFunction().getFunction().getParent());
1096 }
1097 
1098 void SelectionDAGBuilder::clear() {
1099   NodeMap.clear();
1100   UnusedArgNodeMap.clear();
1101   PendingLoads.clear();
1102   PendingExports.clear();
1103   PendingConstrainedFP.clear();
1104   PendingConstrainedFPStrict.clear();
1105   CurInst = nullptr;
1106   HasTailCall = false;
1107   SDNodeOrder = LowestSDNodeOrder;
1108   StatepointLowering.clear();
1109 }
1110 
1111 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1112   DanglingDebugInfoMap.clear();
1113 }
1114 
1115 // Update DAG root to include dependencies on Pending chains.
1116 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1117   SDValue Root = DAG.getRoot();
1118 
1119   if (Pending.empty())
1120     return Root;
1121 
1122   // Add current root to PendingChains, unless we already indirectly
1123   // depend on it.
1124   if (Root.getOpcode() != ISD::EntryToken) {
1125     unsigned i = 0, e = Pending.size();
1126     for (; i != e; ++i) {
1127       assert(Pending[i].getNode()->getNumOperands() > 1);
1128       if (Pending[i].getNode()->getOperand(0) == Root)
1129         break;  // Don't add the root if we already indirectly depend on it.
1130     }
1131 
1132     if (i == e)
1133       Pending.push_back(Root);
1134   }
1135 
1136   if (Pending.size() == 1)
1137     Root = Pending[0];
1138   else
1139     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1140 
1141   DAG.setRoot(Root);
1142   Pending.clear();
1143   return Root;
1144 }
1145 
1146 SDValue SelectionDAGBuilder::getMemoryRoot() {
1147   return updateRoot(PendingLoads);
1148 }
1149 
1150 SDValue SelectionDAGBuilder::getRoot() {
1151   // Chain up all pending constrained intrinsics together with all
1152   // pending loads, by simply appending them to PendingLoads and
1153   // then calling getMemoryRoot().
1154   PendingLoads.reserve(PendingLoads.size() +
1155                        PendingConstrainedFP.size() +
1156                        PendingConstrainedFPStrict.size());
1157   PendingLoads.append(PendingConstrainedFP.begin(),
1158                       PendingConstrainedFP.end());
1159   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1160                       PendingConstrainedFPStrict.end());
1161   PendingConstrainedFP.clear();
1162   PendingConstrainedFPStrict.clear();
1163   return getMemoryRoot();
1164 }
1165 
1166 SDValue SelectionDAGBuilder::getControlRoot() {
1167   // We need to emit pending fpexcept.strict constrained intrinsics,
1168   // so append them to the PendingExports list.
1169   PendingExports.append(PendingConstrainedFPStrict.begin(),
1170                         PendingConstrainedFPStrict.end());
1171   PendingConstrainedFPStrict.clear();
1172   return updateRoot(PendingExports);
1173 }
1174 
1175 void SelectionDAGBuilder::handleDebugDeclare(Value *Address,
1176                                              DILocalVariable *Variable,
1177                                              DIExpression *Expression,
1178                                              DebugLoc DL) {
1179   assert(Variable && "Missing variable");
1180 
1181   // Check if address has undef value.
1182   if (!Address || isa<UndefValue>(Address) ||
1183       (Address->use_empty() && !isa<Argument>(Address))) {
1184     LLVM_DEBUG(
1185         dbgs()
1186         << "dbg_declare: Dropping debug info (bad/undef/unused-arg address)\n");
1187     return;
1188   }
1189 
1190   bool IsParameter = Variable->isParameter() || isa<Argument>(Address);
1191 
1192   SDValue &N = NodeMap[Address];
1193   if (!N.getNode() && isa<Argument>(Address))
1194     // Check unused arguments map.
1195     N = UnusedArgNodeMap[Address];
1196   SDDbgValue *SDV;
1197   if (N.getNode()) {
1198     if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
1199       Address = BCI->getOperand(0);
1200     // Parameters are handled specially.
1201     auto *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
1202     if (IsParameter && FINode) {
1203       // Byval parameter. We have a frame index at this point.
1204       SDV = DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
1205                                       /*IsIndirect*/ true, DL, SDNodeOrder);
1206     } else if (isa<Argument>(Address)) {
1207       // Address is an argument, so try to emit its dbg value using
1208       // virtual register info from the FuncInfo.ValueMap.
1209       EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1210                                FuncArgumentDbgValueKind::Declare, N);
1211       return;
1212     } else {
1213       SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
1214                             true, DL, SDNodeOrder);
1215     }
1216     DAG.AddDbgValue(SDV, IsParameter);
1217   } else {
1218     // If Address is an argument then try to emit its dbg value using
1219     // virtual register info from the FuncInfo.ValueMap.
1220     if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1221                                   FuncArgumentDbgValueKind::Declare, N)) {
1222       LLVM_DEBUG(dbgs() << "dbg_declare: Dropping debug info"
1223                         << " (could not emit func-arg dbg_value)\n");
1224     }
1225   }
1226 }
1227 
1228 void SelectionDAGBuilder::visitDbgInfo(const Instruction &I) {
1229   // Add SDDbgValue nodes for any var locs here. Do so before updating
1230   // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1231   if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) {
1232     // Add SDDbgValue nodes for any var locs here. Do so before updating
1233     // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1234     for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I);
1235          It != End; ++It) {
1236       auto *Var = FnVarLocs->getDILocalVariable(It->VariableID);
1237       dropDanglingDebugInfo(Var, It->Expr);
1238       if (It->Values.isKillLocation(It->Expr)) {
1239         handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder);
1240         continue;
1241       }
1242       SmallVector<Value *> Values(It->Values.location_ops());
1243       if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder,
1244                             It->Values.hasArgList())) {
1245         SmallVector<Value *, 4> Vals(It->Values.location_ops());
1246         addDanglingDebugInfo(Vals,
1247                              FnVarLocs->getDILocalVariable(It->VariableID),
1248                              It->Expr, Vals.size() > 1, It->DL, SDNodeOrder);
1249       }
1250     }
1251   }
1252 
1253   // We must skip DbgVariableRecords if they've already been processed above as
1254   // we have just emitted the debug values resulting from assignment tracking
1255   // analysis, making any existing DbgVariableRecords redundant (and probably
1256   // less correct). We still need to process DbgLabelRecords. This does sink
1257   // DbgLabelRecords to the bottom of the group of debug records. That sholdn't
1258   // be important as it does so deterministcally and ordering between
1259   // DbgLabelRecords and DbgVariableRecords is immaterial (other than for MIR/IR
1260   // printing).
1261   bool SkipDbgVariableRecords = DAG.getFunctionVarLocs();
1262   // Is there is any debug-info attached to this instruction, in the form of
1263   // DbgRecord non-instruction debug-info records.
1264   for (DbgRecord &DR : I.getDbgRecordRange()) {
1265     if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
1266       assert(DLR->getLabel() && "Missing label");
1267       SDDbgLabel *SDV =
1268           DAG.getDbgLabel(DLR->getLabel(), DLR->getDebugLoc(), SDNodeOrder);
1269       DAG.AddDbgLabel(SDV);
1270       continue;
1271     }
1272 
1273     if (SkipDbgVariableRecords)
1274       continue;
1275     DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR);
1276     DILocalVariable *Variable = DVR.getVariable();
1277     DIExpression *Expression = DVR.getExpression();
1278     dropDanglingDebugInfo(Variable, Expression);
1279 
1280     if (DVR.getType() == DbgVariableRecord::LocationType::Declare) {
1281       if (FuncInfo.PreprocessedDVRDeclares.contains(&DVR))
1282         continue;
1283       LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DVR
1284                         << "\n");
1285       handleDebugDeclare(DVR.getVariableLocationOp(0), Variable, Expression,
1286                          DVR.getDebugLoc());
1287       continue;
1288     }
1289 
1290     // A DbgVariableRecord with no locations is a kill location.
1291     SmallVector<Value *, 4> Values(DVR.location_ops());
1292     if (Values.empty()) {
1293       handleKillDebugValue(Variable, Expression, DVR.getDebugLoc(),
1294                            SDNodeOrder);
1295       continue;
1296     }
1297 
1298     // A DbgVariableRecord with an undef or absent location is also a kill
1299     // location.
1300     if (llvm::any_of(Values,
1301                      [](Value *V) { return !V || isa<UndefValue>(V); })) {
1302       handleKillDebugValue(Variable, Expression, DVR.getDebugLoc(),
1303                            SDNodeOrder);
1304       continue;
1305     }
1306 
1307     bool IsVariadic = DVR.hasArgList();
1308     if (!handleDebugValue(Values, Variable, Expression, DVR.getDebugLoc(),
1309                           SDNodeOrder, IsVariadic)) {
1310       addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
1311                            DVR.getDebugLoc(), SDNodeOrder);
1312     }
1313   }
1314 }
1315 
1316 void SelectionDAGBuilder::visit(const Instruction &I) {
1317   visitDbgInfo(I);
1318 
1319   // Set up outgoing PHI node register values before emitting the terminator.
1320   if (I.isTerminator()) {
1321     HandlePHINodesInSuccessorBlocks(I.getParent());
1322   }
1323 
1324   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1325   if (!isa<DbgInfoIntrinsic>(I))
1326     ++SDNodeOrder;
1327 
1328   CurInst = &I;
1329 
1330   // Set inserted listener only if required.
1331   bool NodeInserted = false;
1332   std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener;
1333   MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections);
1334   MDNode *MMRA = I.getMetadata(LLVMContext::MD_mmra);
1335   if (PCSectionsMD || MMRA) {
1336     InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>(
1337         DAG, [&](SDNode *) { NodeInserted = true; });
1338   }
1339 
1340   visit(I.getOpcode(), I);
1341 
1342   if (!I.isTerminator() && !HasTailCall &&
1343       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1344     CopyToExportRegsIfNeeded(&I);
1345 
1346   // Handle metadata.
1347   if (PCSectionsMD || MMRA) {
1348     auto It = NodeMap.find(&I);
1349     if (It != NodeMap.end()) {
1350       if (PCSectionsMD)
1351         DAG.addPCSections(It->second.getNode(), PCSectionsMD);
1352       if (MMRA)
1353         DAG.addMMRAMetadata(It->second.getNode(), MMRA);
1354     } else if (NodeInserted) {
1355       // This should not happen; if it does, don't let it go unnoticed so we can
1356       // fix it. Relevant visit*() function is probably missing a setValue().
1357       errs() << "warning: loosing !pcsections and/or !mmra metadata ["
1358              << I.getModule()->getName() << "]\n";
1359       LLVM_DEBUG(I.dump());
1360       assert(false);
1361     }
1362   }
1363 
1364   CurInst = nullptr;
1365 }
1366 
1367 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1368   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1369 }
1370 
1371 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1372   // Note: this doesn't use InstVisitor, because it has to work with
1373   // ConstantExpr's in addition to instructions.
1374   switch (Opcode) {
1375   default: llvm_unreachable("Unknown instruction type encountered!");
1376     // Build the switch statement using the Instruction.def file.
1377 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1378     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1379 #include "llvm/IR/Instruction.def"
1380   }
1381 }
1382 
1383 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG,
1384                                             DILocalVariable *Variable,
1385                                             DebugLoc DL, unsigned Order,
1386                                             SmallVectorImpl<Value *> &Values,
1387                                             DIExpression *Expression) {
1388   // For variadic dbg_values we will now insert an undef.
1389   // FIXME: We can potentially recover these!
1390   SmallVector<SDDbgOperand, 2> Locs;
1391   for (const Value *V : Values) {
1392     auto *Undef = UndefValue::get(V->getType());
1393     Locs.push_back(SDDbgOperand::fromConst(Undef));
1394   }
1395   SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {},
1396                                         /*IsIndirect=*/false, DL, Order,
1397                                         /*IsVariadic=*/true);
1398   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1399   return true;
1400 }
1401 
1402 void SelectionDAGBuilder::addDanglingDebugInfo(SmallVectorImpl<Value *> &Values,
1403                                                DILocalVariable *Var,
1404                                                DIExpression *Expr,
1405                                                bool IsVariadic, DebugLoc DL,
1406                                                unsigned Order) {
1407   if (IsVariadic) {
1408     handleDanglingVariadicDebugInfo(DAG, Var, DL, Order, Values, Expr);
1409     return;
1410   }
1411   // TODO: Dangling debug info will eventually either be resolved or produce
1412   // an Undef DBG_VALUE. However in the resolution case, a gap may appear
1413   // between the original dbg.value location and its resolved DBG_VALUE,
1414   // which we should ideally fill with an extra Undef DBG_VALUE.
1415   assert(Values.size() == 1);
1416   DanglingDebugInfoMap[Values[0]].emplace_back(Var, Expr, DL, Order);
1417 }
1418 
1419 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1420                                                 const DIExpression *Expr) {
1421   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1422     DIVariable *DanglingVariable = DDI.getVariable();
1423     DIExpression *DanglingExpr = DDI.getExpression();
1424     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1425       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for "
1426                         << printDDI(nullptr, DDI) << "\n");
1427       return true;
1428     }
1429     return false;
1430   };
1431 
1432   for (auto &DDIMI : DanglingDebugInfoMap) {
1433     DanglingDebugInfoVector &DDIV = DDIMI.second;
1434 
1435     // If debug info is to be dropped, run it through final checks to see
1436     // whether it can be salvaged.
1437     for (auto &DDI : DDIV)
1438       if (isMatchingDbgValue(DDI))
1439         salvageUnresolvedDbgValue(DDIMI.first, DDI);
1440 
1441     erase_if(DDIV, isMatchingDbgValue);
1442   }
1443 }
1444 
1445 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1446 // generate the debug data structures now that we've seen its definition.
1447 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1448                                                    SDValue Val) {
1449   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1450   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1451     return;
1452 
1453   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1454   for (auto &DDI : DDIV) {
1455     DebugLoc DL = DDI.getDebugLoc();
1456     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1457     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1458     DILocalVariable *Variable = DDI.getVariable();
1459     DIExpression *Expr = DDI.getExpression();
1460     assert(Variable->isValidLocationForIntrinsic(DL) &&
1461            "Expected inlined-at fields to agree");
1462     SDDbgValue *SDV;
1463     if (Val.getNode()) {
1464       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1465       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1466       // we couldn't resolve it directly when examining the DbgValue intrinsic
1467       // in the first place we should not be more successful here). Unless we
1468       // have some test case that prove this to be correct we should avoid
1469       // calling EmitFuncArgumentDbgValue here.
1470       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL,
1471                                     FuncArgumentDbgValueKind::Value, Val)) {
1472         LLVM_DEBUG(dbgs() << "Resolve dangling debug info for "
1473                           << printDDI(V, DDI) << "\n");
1474         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1475         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1476         // inserted after the definition of Val when emitting the instructions
1477         // after ISel. An alternative could be to teach
1478         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1479         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1480                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1481                    << ValSDNodeOrder << "\n");
1482         SDV = getDbgValue(Val, Variable, Expr, DL,
1483                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1484         DAG.AddDbgValue(SDV, false);
1485       } else
1486         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for "
1487                           << printDDI(V, DDI)
1488                           << " in EmitFuncArgumentDbgValue\n");
1489     } else {
1490       LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(V, DDI)
1491                         << "\n");
1492       auto Undef = UndefValue::get(V->getType());
1493       auto SDV =
1494           DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder);
1495       DAG.AddDbgValue(SDV, false);
1496     }
1497   }
1498   DDIV.clear();
1499 }
1500 
1501 void SelectionDAGBuilder::salvageUnresolvedDbgValue(const Value *V,
1502                                                     DanglingDebugInfo &DDI) {
1503   // TODO: For the variadic implementation, instead of only checking the fail
1504   // state of `handleDebugValue`, we need know specifically which values were
1505   // invalid, so that we attempt to salvage only those values when processing
1506   // a DIArgList.
1507   const Value *OrigV = V;
1508   DILocalVariable *Var = DDI.getVariable();
1509   DIExpression *Expr = DDI.getExpression();
1510   DebugLoc DL = DDI.getDebugLoc();
1511   unsigned SDOrder = DDI.getSDNodeOrder();
1512 
1513   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1514   // that DW_OP_stack_value is desired.
1515   bool StackValue = true;
1516 
1517   // Can this Value can be encoded without any further work?
1518   if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false))
1519     return;
1520 
1521   // Attempt to salvage back through as many instructions as possible. Bail if
1522   // a non-instruction is seen, such as a constant expression or global
1523   // variable. FIXME: Further work could recover those too.
1524   while (isa<Instruction>(V)) {
1525     const Instruction &VAsInst = *cast<const Instruction>(V);
1526     // Temporary "0", awaiting real implementation.
1527     SmallVector<uint64_t, 16> Ops;
1528     SmallVector<Value *, 4> AdditionalValues;
1529     V = salvageDebugInfoImpl(const_cast<Instruction &>(VAsInst),
1530                              Expr->getNumLocationOperands(), Ops,
1531                              AdditionalValues);
1532     // If we cannot salvage any further, and haven't yet found a suitable debug
1533     // expression, bail out.
1534     if (!V)
1535       break;
1536 
1537     // TODO: If AdditionalValues isn't empty, then the salvage can only be
1538     // represented with a DBG_VALUE_LIST, so we give up. When we have support
1539     // here for variadic dbg_values, remove that condition.
1540     if (!AdditionalValues.empty())
1541       break;
1542 
1543     // New value and expr now represent this debuginfo.
1544     Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue);
1545 
1546     // Some kind of simplification occurred: check whether the operand of the
1547     // salvaged debug expression can be encoded in this DAG.
1548     if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) {
1549       LLVM_DEBUG(
1550           dbgs() << "Salvaged debug location info for:\n  " << *Var << "\n"
1551                  << *OrigV << "\nBy stripping back to:\n  " << *V << "\n");
1552       return;
1553     }
1554   }
1555 
1556   // This was the final opportunity to salvage this debug information, and it
1557   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1558   // any earlier variable location.
1559   assert(OrigV && "V shouldn't be null");
1560   auto *Undef = UndefValue::get(OrigV->getType());
1561   auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1562   DAG.AddDbgValue(SDV, false);
1563   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  "
1564                     << printDDI(OrigV, DDI) << "\n");
1565 }
1566 
1567 void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var,
1568                                                DIExpression *Expr,
1569                                                DebugLoc DbgLoc,
1570                                                unsigned Order) {
1571   Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context));
1572   DIExpression *NewExpr =
1573       const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr));
1574   handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order,
1575                    /*IsVariadic*/ false);
1576 }
1577 
1578 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1579                                            DILocalVariable *Var,
1580                                            DIExpression *Expr, DebugLoc DbgLoc,
1581                                            unsigned Order, bool IsVariadic) {
1582   if (Values.empty())
1583     return true;
1584 
1585   // Filter EntryValue locations out early.
1586   if (visitEntryValueDbgValue(Values, Var, Expr, DbgLoc))
1587     return true;
1588 
1589   SmallVector<SDDbgOperand> LocationOps;
1590   SmallVector<SDNode *> Dependencies;
1591   for (const Value *V : Values) {
1592     // Constant value.
1593     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1594         isa<ConstantPointerNull>(V)) {
1595       LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1596       continue;
1597     }
1598 
1599     // Look through IntToPtr constants.
1600     if (auto *CE = dyn_cast<ConstantExpr>(V))
1601       if (CE->getOpcode() == Instruction::IntToPtr) {
1602         LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0)));
1603         continue;
1604       }
1605 
1606     // If the Value is a frame index, we can create a FrameIndex debug value
1607     // without relying on the DAG at all.
1608     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1609       auto SI = FuncInfo.StaticAllocaMap.find(AI);
1610       if (SI != FuncInfo.StaticAllocaMap.end()) {
1611         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1612         continue;
1613       }
1614     }
1615 
1616     // Do not use getValue() in here; we don't want to generate code at
1617     // this point if it hasn't been done yet.
1618     SDValue N = NodeMap[V];
1619     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1620       N = UnusedArgNodeMap[V];
1621 
1622     if (N.getNode()) {
1623       // Only emit func arg dbg value for non-variadic dbg.values for now.
1624       if (!IsVariadic &&
1625           EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc,
1626                                    FuncArgumentDbgValueKind::Value, N))
1627         return true;
1628       if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1629         // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1630         // describe stack slot locations.
1631         //
1632         // Consider "int x = 0; int *px = &x;". There are two kinds of
1633         // interesting debug values here after optimization:
1634         //
1635         //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
1636         //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1637         //
1638         // Both describe the direct values of their associated variables.
1639         Dependencies.push_back(N.getNode());
1640         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1641         continue;
1642       }
1643       LocationOps.emplace_back(
1644           SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1645       continue;
1646     }
1647 
1648     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1649     // Special rules apply for the first dbg.values of parameter variables in a
1650     // function. Identify them by the fact they reference Argument Values, that
1651     // they're parameters, and they are parameters of the current function. We
1652     // need to let them dangle until they get an SDNode.
1653     bool IsParamOfFunc =
1654         isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt();
1655     if (IsParamOfFunc)
1656       return false;
1657 
1658     // The value is not used in this block yet (or it would have an SDNode).
1659     // We still want the value to appear for the user if possible -- if it has
1660     // an associated VReg, we can refer to that instead.
1661     auto VMI = FuncInfo.ValueMap.find(V);
1662     if (VMI != FuncInfo.ValueMap.end()) {
1663       unsigned Reg = VMI->second;
1664       // If this is a PHI node, it may be split up into several MI PHI nodes
1665       // (in FunctionLoweringInfo::set).
1666       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1667                        V->getType(), std::nullopt);
1668       if (RFV.occupiesMultipleRegs()) {
1669         // FIXME: We could potentially support variadic dbg_values here.
1670         if (IsVariadic)
1671           return false;
1672         unsigned Offset = 0;
1673         unsigned BitsToDescribe = 0;
1674         if (auto VarSize = Var->getSizeInBits())
1675           BitsToDescribe = *VarSize;
1676         if (auto Fragment = Expr->getFragmentInfo())
1677           BitsToDescribe = Fragment->SizeInBits;
1678         for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1679           // Bail out if all bits are described already.
1680           if (Offset >= BitsToDescribe)
1681             break;
1682           // TODO: handle scalable vectors.
1683           unsigned RegisterSize = RegAndSize.second;
1684           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1685                                       ? BitsToDescribe - Offset
1686                                       : RegisterSize;
1687           auto FragmentExpr = DIExpression::createFragmentExpression(
1688               Expr, Offset, FragmentSize);
1689           if (!FragmentExpr)
1690             continue;
1691           SDDbgValue *SDV = DAG.getVRegDbgValue(
1692               Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, Order);
1693           DAG.AddDbgValue(SDV, false);
1694           Offset += RegisterSize;
1695         }
1696         return true;
1697       }
1698       // We can use simple vreg locations for variadic dbg_values as well.
1699       LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1700       continue;
1701     }
1702     // We failed to create a SDDbgOperand for V.
1703     return false;
1704   }
1705 
1706   // We have created a SDDbgOperand for each Value in Values.
1707   assert(!LocationOps.empty());
1708   SDDbgValue *SDV =
1709       DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1710                           /*IsIndirect=*/false, DbgLoc, Order, IsVariadic);
1711   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1712   return true;
1713 }
1714 
1715 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1716   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1717   for (auto &Pair : DanglingDebugInfoMap)
1718     for (auto &DDI : Pair.second)
1719       salvageUnresolvedDbgValue(const_cast<Value *>(Pair.first), DDI);
1720   clearDanglingDebugInfo();
1721 }
1722 
1723 /// getCopyFromRegs - If there was virtual register allocated for the value V
1724 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1725 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1726   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1727   SDValue Result;
1728 
1729   if (It != FuncInfo.ValueMap.end()) {
1730     Register InReg = It->second;
1731 
1732     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1733                      DAG.getDataLayout(), InReg, Ty,
1734                      std::nullopt); // This is not an ABI copy.
1735     SDValue Chain = DAG.getEntryNode();
1736     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1737                                  V);
1738     resolveDanglingDebugInfo(V, Result);
1739   }
1740 
1741   return Result;
1742 }
1743 
1744 /// getValue - Return an SDValue for the given Value.
1745 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1746   // If we already have an SDValue for this value, use it. It's important
1747   // to do this first, so that we don't create a CopyFromReg if we already
1748   // have a regular SDValue.
1749   SDValue &N = NodeMap[V];
1750   if (N.getNode()) return N;
1751 
1752   // If there's a virtual register allocated and initialized for this
1753   // value, use it.
1754   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1755     return copyFromReg;
1756 
1757   // Otherwise create a new SDValue and remember it.
1758   SDValue Val = getValueImpl(V);
1759   NodeMap[V] = Val;
1760   resolveDanglingDebugInfo(V, Val);
1761   return Val;
1762 }
1763 
1764 /// getNonRegisterValue - Return an SDValue for the given Value, but
1765 /// don't look in FuncInfo.ValueMap for a virtual register.
1766 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1767   // If we already have an SDValue for this value, use it.
1768   SDValue &N = NodeMap[V];
1769   if (N.getNode()) {
1770     if (isIntOrFPConstant(N)) {
1771       // Remove the debug location from the node as the node is about to be used
1772       // in a location which may differ from the original debug location.  This
1773       // is relevant to Constant and ConstantFP nodes because they can appear
1774       // as constant expressions inside PHI nodes.
1775       N->setDebugLoc(DebugLoc());
1776     }
1777     return N;
1778   }
1779 
1780   // Otherwise create a new SDValue and remember it.
1781   SDValue Val = getValueImpl(V);
1782   NodeMap[V] = Val;
1783   resolveDanglingDebugInfo(V, Val);
1784   return Val;
1785 }
1786 
1787 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1788 /// Create an SDValue for the given value.
1789 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1790   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1791 
1792   if (const Constant *C = dyn_cast<Constant>(V)) {
1793     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1794 
1795     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1796       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1797 
1798     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1799       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1800 
1801     if (const ConstantPtrAuth *CPA = dyn_cast<ConstantPtrAuth>(C)) {
1802       return DAG.getNode(ISD::PtrAuthGlobalAddress, getCurSDLoc(), VT,
1803                          getValue(CPA->getPointer()), getValue(CPA->getKey()),
1804                          getValue(CPA->getAddrDiscriminator()),
1805                          getValue(CPA->getDiscriminator()));
1806     }
1807 
1808     if (isa<ConstantPointerNull>(C)) {
1809       unsigned AS = V->getType()->getPointerAddressSpace();
1810       return DAG.getConstant(0, getCurSDLoc(),
1811                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1812     }
1813 
1814     if (match(C, m_VScale()))
1815       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1816 
1817     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1818       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1819 
1820     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1821       return DAG.getUNDEF(VT);
1822 
1823     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1824       visit(CE->getOpcode(), *CE);
1825       SDValue N1 = NodeMap[V];
1826       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1827       return N1;
1828     }
1829 
1830     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1831       SmallVector<SDValue, 4> Constants;
1832       for (const Use &U : C->operands()) {
1833         SDNode *Val = getValue(U).getNode();
1834         // If the operand is an empty aggregate, there are no values.
1835         if (!Val) continue;
1836         // Add each leaf value from the operand to the Constants list
1837         // to form a flattened list of all the values.
1838         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1839           Constants.push_back(SDValue(Val, i));
1840       }
1841 
1842       return DAG.getMergeValues(Constants, getCurSDLoc());
1843     }
1844 
1845     if (const ConstantDataSequential *CDS =
1846           dyn_cast<ConstantDataSequential>(C)) {
1847       SmallVector<SDValue, 4> Ops;
1848       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1849         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1850         // Add each leaf value from the operand to the Constants list
1851         // to form a flattened list of all the values.
1852         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1853           Ops.push_back(SDValue(Val, i));
1854       }
1855 
1856       if (isa<ArrayType>(CDS->getType()))
1857         return DAG.getMergeValues(Ops, getCurSDLoc());
1858       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1859     }
1860 
1861     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1862       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1863              "Unknown struct or array constant!");
1864 
1865       SmallVector<EVT, 4> ValueVTs;
1866       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1867       unsigned NumElts = ValueVTs.size();
1868       if (NumElts == 0)
1869         return SDValue(); // empty struct
1870       SmallVector<SDValue, 4> Constants(NumElts);
1871       for (unsigned i = 0; i != NumElts; ++i) {
1872         EVT EltVT = ValueVTs[i];
1873         if (isa<UndefValue>(C))
1874           Constants[i] = DAG.getUNDEF(EltVT);
1875         else if (EltVT.isFloatingPoint())
1876           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1877         else
1878           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1879       }
1880 
1881       return DAG.getMergeValues(Constants, getCurSDLoc());
1882     }
1883 
1884     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1885       return DAG.getBlockAddress(BA, VT);
1886 
1887     if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1888       return getValue(Equiv->getGlobalValue());
1889 
1890     if (const auto *NC = dyn_cast<NoCFIValue>(C))
1891       return getValue(NC->getGlobalValue());
1892 
1893     if (VT == MVT::aarch64svcount) {
1894       assert(C->isNullValue() && "Can only zero this target type!");
1895       return DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT,
1896                          DAG.getConstant(0, getCurSDLoc(), MVT::nxv16i1));
1897     }
1898 
1899     if (VT.isRISCVVectorTuple()) {
1900       assert(C->isNullValue() && "Can only zero this target type!");
1901       return NodeMap[V] = DAG.getNode(
1902                  ISD::BITCAST, getCurSDLoc(), VT,
1903                  DAG.getNode(
1904                      ISD::SPLAT_VECTOR, getCurSDLoc(),
1905                      EVT::getVectorVT(*DAG.getContext(), MVT::i8,
1906                                       VT.getSizeInBits().getKnownMinValue() / 8,
1907                                       true),
1908                      DAG.getConstant(0, getCurSDLoc(), MVT::getIntegerVT(8))));
1909     }
1910 
1911     VectorType *VecTy = cast<VectorType>(V->getType());
1912 
1913     // Now that we know the number and type of the elements, get that number of
1914     // elements into the Ops array based on what kind of constant it is.
1915     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1916       SmallVector<SDValue, 16> Ops;
1917       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1918       for (unsigned i = 0; i != NumElements; ++i)
1919         Ops.push_back(getValue(CV->getOperand(i)));
1920 
1921       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1922     }
1923 
1924     if (isa<ConstantAggregateZero>(C)) {
1925       EVT EltVT =
1926           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1927 
1928       SDValue Op;
1929       if (EltVT.isFloatingPoint())
1930         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1931       else
1932         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1933 
1934       return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op);
1935     }
1936 
1937     llvm_unreachable("Unknown vector constant");
1938   }
1939 
1940   // If this is a static alloca, generate it as the frameindex instead of
1941   // computation.
1942   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1943     DenseMap<const AllocaInst*, int>::iterator SI =
1944       FuncInfo.StaticAllocaMap.find(AI);
1945     if (SI != FuncInfo.StaticAllocaMap.end())
1946       return DAG.getFrameIndex(
1947           SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType()));
1948   }
1949 
1950   // If this is an instruction which fast-isel has deferred, select it now.
1951   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1952     Register InReg = FuncInfo.InitializeRegForValue(Inst);
1953 
1954     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1955                      Inst->getType(), std::nullopt);
1956     SDValue Chain = DAG.getEntryNode();
1957     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1958   }
1959 
1960   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V))
1961     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1962 
1963   if (const auto *BB = dyn_cast<BasicBlock>(V))
1964     return DAG.getBasicBlock(FuncInfo.getMBB(BB));
1965 
1966   llvm_unreachable("Can't get register for value!");
1967 }
1968 
1969 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1970   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1971   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1972   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1973   bool IsSEH = isAsynchronousEHPersonality(Pers);
1974   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1975   if (!IsSEH)
1976     CatchPadMBB->setIsEHScopeEntry();
1977   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1978   if (IsMSVCCXX || IsCoreCLR)
1979     CatchPadMBB->setIsEHFuncletEntry();
1980 }
1981 
1982 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1983   // Update machine-CFG edge.
1984   MachineBasicBlock *TargetMBB = FuncInfo.getMBB(I.getSuccessor());
1985   FuncInfo.MBB->addSuccessor(TargetMBB);
1986   TargetMBB->setIsEHCatchretTarget(true);
1987   DAG.getMachineFunction().setHasEHCatchret(true);
1988 
1989   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1990   bool IsSEH = isAsynchronousEHPersonality(Pers);
1991   if (IsSEH) {
1992     // If this is not a fall-through branch or optimizations are switched off,
1993     // emit the branch.
1994     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1995         TM.getOptLevel() == CodeGenOptLevel::None)
1996       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1997                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1998     return;
1999   }
2000 
2001   // Figure out the funclet membership for the catchret's successor.
2002   // This will be used by the FuncletLayout pass to determine how to order the
2003   // BB's.
2004   // A 'catchret' returns to the outer scope's color.
2005   Value *ParentPad = I.getCatchSwitchParentPad();
2006   const BasicBlock *SuccessorColor;
2007   if (isa<ConstantTokenNone>(ParentPad))
2008     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
2009   else
2010     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
2011   assert(SuccessorColor && "No parent funclet for catchret!");
2012   MachineBasicBlock *SuccessorColorMBB = FuncInfo.getMBB(SuccessorColor);
2013   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
2014 
2015   // Create the terminator node.
2016   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
2017                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
2018                             DAG.getBasicBlock(SuccessorColorMBB));
2019   DAG.setRoot(Ret);
2020 }
2021 
2022 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
2023   // Don't emit any special code for the cleanuppad instruction. It just marks
2024   // the start of an EH scope/funclet.
2025   FuncInfo.MBB->setIsEHScopeEntry();
2026   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
2027   if (Pers != EHPersonality::Wasm_CXX) {
2028     FuncInfo.MBB->setIsEHFuncletEntry();
2029     FuncInfo.MBB->setIsCleanupFuncletEntry();
2030   }
2031 }
2032 
2033 // In wasm EH, even though a catchpad may not catch an exception if a tag does
2034 // not match, it is OK to add only the first unwind destination catchpad to the
2035 // successors, because there will be at least one invoke instruction within the
2036 // catch scope that points to the next unwind destination, if one exists, so
2037 // CFGSort cannot mess up with BB sorting order.
2038 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
2039 // call within them, and catchpads only consisting of 'catch (...)' have a
2040 // '__cxa_end_catch' call within them, both of which generate invokes in case
2041 // the next unwind destination exists, i.e., the next unwind destination is not
2042 // the caller.)
2043 //
2044 // Having at most one EH pad successor is also simpler and helps later
2045 // transformations.
2046 //
2047 // For example,
2048 // current:
2049 //   invoke void @foo to ... unwind label %catch.dispatch
2050 // catch.dispatch:
2051 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
2052 // catch.start:
2053 //   ...
2054 //   ... in this BB or some other child BB dominated by this BB there will be an
2055 //   invoke that points to 'next' BB as an unwind destination
2056 //
2057 // next: ; We don't need to add this to 'current' BB's successor
2058 //   ...
2059 static void findWasmUnwindDestinations(
2060     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2061     BranchProbability Prob,
2062     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2063         &UnwindDests) {
2064   while (EHPadBB) {
2065     const Instruction *Pad = EHPadBB->getFirstNonPHI();
2066     if (isa<CleanupPadInst>(Pad)) {
2067       // Stop on cleanup pads.
2068       UnwindDests.emplace_back(FuncInfo.getMBB(EHPadBB), Prob);
2069       UnwindDests.back().first->setIsEHScopeEntry();
2070       break;
2071     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
2072       // Add the catchpad handlers to the possible destinations. We don't
2073       // continue to the unwind destination of the catchswitch for wasm.
2074       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2075         UnwindDests.emplace_back(FuncInfo.getMBB(CatchPadBB), Prob);
2076         UnwindDests.back().first->setIsEHScopeEntry();
2077       }
2078       break;
2079     } else {
2080       continue;
2081     }
2082   }
2083 }
2084 
2085 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
2086 /// many places it could ultimately go. In the IR, we have a single unwind
2087 /// destination, but in the machine CFG, we enumerate all the possible blocks.
2088 /// This function skips over imaginary basic blocks that hold catchswitch
2089 /// instructions, and finds all the "real" machine
2090 /// basic block destinations. As those destinations may not be successors of
2091 /// EHPadBB, here we also calculate the edge probability to those destinations.
2092 /// The passed-in Prob is the edge probability to EHPadBB.
2093 static void findUnwindDestinations(
2094     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2095     BranchProbability Prob,
2096     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2097         &UnwindDests) {
2098   EHPersonality Personality =
2099     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
2100   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
2101   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
2102   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
2103   bool IsSEH = isAsynchronousEHPersonality(Personality);
2104 
2105   if (IsWasmCXX) {
2106     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
2107     assert(UnwindDests.size() <= 1 &&
2108            "There should be at most one unwind destination for wasm");
2109     return;
2110   }
2111 
2112   while (EHPadBB) {
2113     const Instruction *Pad = EHPadBB->getFirstNonPHI();
2114     BasicBlock *NewEHPadBB = nullptr;
2115     if (isa<LandingPadInst>(Pad)) {
2116       // Stop on landingpads. They are not funclets.
2117       UnwindDests.emplace_back(FuncInfo.getMBB(EHPadBB), Prob);
2118       break;
2119     } else if (isa<CleanupPadInst>(Pad)) {
2120       // Stop on cleanup pads. Cleanups are always funclet entries for all known
2121       // personalities.
2122       UnwindDests.emplace_back(FuncInfo.getMBB(EHPadBB), Prob);
2123       UnwindDests.back().first->setIsEHScopeEntry();
2124       UnwindDests.back().first->setIsEHFuncletEntry();
2125       break;
2126     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
2127       // Add the catchpad handlers to the possible destinations.
2128       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2129         UnwindDests.emplace_back(FuncInfo.getMBB(CatchPadBB), Prob);
2130         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
2131         if (IsMSVCCXX || IsCoreCLR)
2132           UnwindDests.back().first->setIsEHFuncletEntry();
2133         if (!IsSEH)
2134           UnwindDests.back().first->setIsEHScopeEntry();
2135       }
2136       NewEHPadBB = CatchSwitch->getUnwindDest();
2137     } else {
2138       continue;
2139     }
2140 
2141     BranchProbabilityInfo *BPI = FuncInfo.BPI;
2142     if (BPI && NewEHPadBB)
2143       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
2144     EHPadBB = NewEHPadBB;
2145   }
2146 }
2147 
2148 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
2149   // Update successor info.
2150   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2151   auto UnwindDest = I.getUnwindDest();
2152   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2153   BranchProbability UnwindDestProb =
2154       (BPI && UnwindDest)
2155           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
2156           : BranchProbability::getZero();
2157   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
2158   for (auto &UnwindDest : UnwindDests) {
2159     UnwindDest.first->setIsEHPad();
2160     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
2161   }
2162   FuncInfo.MBB->normalizeSuccProbs();
2163 
2164   // Create the terminator node.
2165   MachineBasicBlock *CleanupPadMBB =
2166       FuncInfo.getMBB(I.getCleanupPad()->getParent());
2167   SDValue Ret = DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other,
2168                             getControlRoot(), DAG.getBasicBlock(CleanupPadMBB));
2169   DAG.setRoot(Ret);
2170 }
2171 
2172 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
2173   report_fatal_error("visitCatchSwitch not yet implemented!");
2174 }
2175 
2176 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
2177   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2178   auto &DL = DAG.getDataLayout();
2179   SDValue Chain = getControlRoot();
2180   SmallVector<ISD::OutputArg, 8> Outs;
2181   SmallVector<SDValue, 8> OutVals;
2182 
2183   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
2184   // lower
2185   //
2186   //   %val = call <ty> @llvm.experimental.deoptimize()
2187   //   ret <ty> %val
2188   //
2189   // differently.
2190   if (I.getParent()->getTerminatingDeoptimizeCall()) {
2191     LowerDeoptimizingReturn();
2192     return;
2193   }
2194 
2195   if (!FuncInfo.CanLowerReturn) {
2196     Register DemoteReg = FuncInfo.DemoteRegister;
2197 
2198     // Emit a store of the return value through the virtual register.
2199     // Leave Outs empty so that LowerReturn won't try to load return
2200     // registers the usual way.
2201     MVT PtrValueVT = TLI.getPointerTy(DL, DL.getAllocaAddrSpace());
2202     SDValue RetPtr =
2203         DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVT);
2204     SDValue RetOp = getValue(I.getOperand(0));
2205 
2206     SmallVector<EVT, 4> ValueVTs, MemVTs;
2207     SmallVector<uint64_t, 4> Offsets;
2208     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
2209                     &Offsets, 0);
2210     unsigned NumValues = ValueVTs.size();
2211 
2212     SmallVector<SDValue, 4> Chains(NumValues);
2213     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
2214     for (unsigned i = 0; i != NumValues; ++i) {
2215       // An aggregate return value cannot wrap around the address space, so
2216       // offsets to its parts don't wrap either.
2217       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
2218                                            TypeSize::getFixed(Offsets[i]));
2219 
2220       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
2221       if (MemVTs[i] != ValueVTs[i])
2222         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
2223       Chains[i] = DAG.getStore(
2224           Chain, getCurSDLoc(), Val,
2225           // FIXME: better loc info would be nice.
2226           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
2227           commonAlignment(BaseAlign, Offsets[i]));
2228     }
2229 
2230     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
2231                         MVT::Other, Chains);
2232   } else if (I.getNumOperands() != 0) {
2233     SmallVector<EVT, 4> ValueVTs;
2234     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
2235     unsigned NumValues = ValueVTs.size();
2236     if (NumValues) {
2237       SDValue RetOp = getValue(I.getOperand(0));
2238 
2239       const Function *F = I.getParent()->getParent();
2240 
2241       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
2242           I.getOperand(0)->getType(), F->getCallingConv(),
2243           /*IsVarArg*/ false, DL);
2244 
2245       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
2246       if (F->getAttributes().hasRetAttr(Attribute::SExt))
2247         ExtendKind = ISD::SIGN_EXTEND;
2248       else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
2249         ExtendKind = ISD::ZERO_EXTEND;
2250 
2251       LLVMContext &Context = F->getContext();
2252       bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
2253 
2254       for (unsigned j = 0; j != NumValues; ++j) {
2255         EVT VT = ValueVTs[j];
2256 
2257         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2258           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
2259 
2260         CallingConv::ID CC = F->getCallingConv();
2261 
2262         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
2263         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2264         SmallVector<SDValue, 4> Parts(NumParts);
2265         getCopyToParts(DAG, getCurSDLoc(),
2266                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2267                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
2268 
2269         // 'inreg' on function refers to return value
2270         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2271         if (RetInReg)
2272           Flags.setInReg();
2273 
2274         if (I.getOperand(0)->getType()->isPointerTy()) {
2275           Flags.setPointer();
2276           Flags.setPointerAddrSpace(
2277               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2278         }
2279 
2280         if (NeedsRegBlock) {
2281           Flags.setInConsecutiveRegs();
2282           if (j == NumValues - 1)
2283             Flags.setInConsecutiveRegsLast();
2284         }
2285 
2286         // Propagate extension type if any
2287         if (ExtendKind == ISD::SIGN_EXTEND)
2288           Flags.setSExt();
2289         else if (ExtendKind == ISD::ZERO_EXTEND)
2290           Flags.setZExt();
2291         else if (F->getAttributes().hasRetAttr(Attribute::NoExt))
2292           Flags.setNoExt();
2293 
2294         for (unsigned i = 0; i < NumParts; ++i) {
2295           Outs.push_back(ISD::OutputArg(Flags,
2296                                         Parts[i].getValueType().getSimpleVT(),
2297                                         VT, /*isfixed=*/true, 0, 0));
2298           OutVals.push_back(Parts[i]);
2299         }
2300       }
2301     }
2302   }
2303 
2304   // Push in swifterror virtual register as the last element of Outs. This makes
2305   // sure swifterror virtual register will be returned in the swifterror
2306   // physical register.
2307   const Function *F = I.getParent()->getParent();
2308   if (TLI.supportSwiftError() &&
2309       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2310     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2311     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2312     Flags.setSwiftError();
2313     Outs.push_back(ISD::OutputArg(
2314         Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
2315         /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
2316     // Create SDNode for the swifterror virtual register.
2317     OutVals.push_back(
2318         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2319                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2320                         EVT(TLI.getPointerTy(DL))));
2321   }
2322 
2323   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2324   CallingConv::ID CallConv =
2325     DAG.getMachineFunction().getFunction().getCallingConv();
2326   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2327       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2328 
2329   // Verify that the target's LowerReturn behaved as expected.
2330   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2331          "LowerReturn didn't return a valid chain!");
2332 
2333   // Update the DAG with the new chain value resulting from return lowering.
2334   DAG.setRoot(Chain);
2335 }
2336 
2337 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2338 /// created for it, emit nodes to copy the value into the virtual
2339 /// registers.
2340 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2341   // Skip empty types
2342   if (V->getType()->isEmptyTy())
2343     return;
2344 
2345   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2346   if (VMI != FuncInfo.ValueMap.end()) {
2347     assert((!V->use_empty() || isa<CallBrInst>(V)) &&
2348            "Unused value assigned virtual registers!");
2349     CopyValueToVirtualRegister(V, VMI->second);
2350   }
2351 }
2352 
2353 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2354 /// the current basic block, add it to ValueMap now so that we'll get a
2355 /// CopyTo/FromReg.
2356 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2357   // No need to export constants.
2358   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2359 
2360   // Already exported?
2361   if (FuncInfo.isExportedInst(V)) return;
2362 
2363   Register Reg = FuncInfo.InitializeRegForValue(V);
2364   CopyValueToVirtualRegister(V, Reg);
2365 }
2366 
2367 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2368                                                      const BasicBlock *FromBB) {
2369   // The operands of the setcc have to be in this block.  We don't know
2370   // how to export them from some other block.
2371   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2372     // Can export from current BB.
2373     if (VI->getParent() == FromBB)
2374       return true;
2375 
2376     // Is already exported, noop.
2377     return FuncInfo.isExportedInst(V);
2378   }
2379 
2380   // If this is an argument, we can export it if the BB is the entry block or
2381   // if it is already exported.
2382   if (isa<Argument>(V)) {
2383     if (FromBB->isEntryBlock())
2384       return true;
2385 
2386     // Otherwise, can only export this if it is already exported.
2387     return FuncInfo.isExportedInst(V);
2388   }
2389 
2390   // Otherwise, constants can always be exported.
2391   return true;
2392 }
2393 
2394 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2395 BranchProbability
2396 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2397                                         const MachineBasicBlock *Dst) const {
2398   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2399   const BasicBlock *SrcBB = Src->getBasicBlock();
2400   const BasicBlock *DstBB = Dst->getBasicBlock();
2401   if (!BPI) {
2402     // If BPI is not available, set the default probability as 1 / N, where N is
2403     // the number of successors.
2404     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2405     return BranchProbability(1, SuccSize);
2406   }
2407   return BPI->getEdgeProbability(SrcBB, DstBB);
2408 }
2409 
2410 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2411                                                MachineBasicBlock *Dst,
2412                                                BranchProbability Prob) {
2413   if (!FuncInfo.BPI)
2414     Src->addSuccessorWithoutProb(Dst);
2415   else {
2416     if (Prob.isUnknown())
2417       Prob = getEdgeProbability(Src, Dst);
2418     Src->addSuccessor(Dst, Prob);
2419   }
2420 }
2421 
2422 static bool InBlock(const Value *V, const BasicBlock *BB) {
2423   if (const Instruction *I = dyn_cast<Instruction>(V))
2424     return I->getParent() == BB;
2425   return true;
2426 }
2427 
2428 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2429 /// This function emits a branch and is used at the leaves of an OR or an
2430 /// AND operator tree.
2431 void
2432 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2433                                                   MachineBasicBlock *TBB,
2434                                                   MachineBasicBlock *FBB,
2435                                                   MachineBasicBlock *CurBB,
2436                                                   MachineBasicBlock *SwitchBB,
2437                                                   BranchProbability TProb,
2438                                                   BranchProbability FProb,
2439                                                   bool InvertCond) {
2440   const BasicBlock *BB = CurBB->getBasicBlock();
2441 
2442   // If the leaf of the tree is a comparison, merge the condition into
2443   // the caseblock.
2444   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2445     // The operands of the cmp have to be in this block.  We don't know
2446     // how to export them from some other block.  If this is the first block
2447     // of the sequence, no exporting is needed.
2448     if (CurBB == SwitchBB ||
2449         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2450          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2451       ISD::CondCode Condition;
2452       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2453         ICmpInst::Predicate Pred =
2454             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2455         Condition = getICmpCondCode(Pred);
2456       } else {
2457         const FCmpInst *FC = cast<FCmpInst>(Cond);
2458         FCmpInst::Predicate Pred =
2459             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2460         Condition = getFCmpCondCode(Pred);
2461         if (TM.Options.NoNaNsFPMath)
2462           Condition = getFCmpCodeWithoutNaN(Condition);
2463       }
2464 
2465       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2466                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2467       SL->SwitchCases.push_back(CB);
2468       return;
2469     }
2470   }
2471 
2472   // Create a CaseBlock record representing this branch.
2473   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2474   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2475                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2476   SL->SwitchCases.push_back(CB);
2477 }
2478 
2479 // Collect dependencies on V recursively. This is used for the cost analysis in
2480 // `shouldKeepJumpConditionsTogether`.
2481 static bool collectInstructionDeps(
2482     SmallMapVector<const Instruction *, bool, 8> *Deps, const Value *V,
2483     SmallMapVector<const Instruction *, bool, 8> *Necessary = nullptr,
2484     unsigned Depth = 0) {
2485   // Return false if we have an incomplete count.
2486   if (Depth >= SelectionDAG::MaxRecursionDepth)
2487     return false;
2488 
2489   auto *I = dyn_cast<Instruction>(V);
2490   if (I == nullptr)
2491     return true;
2492 
2493   if (Necessary != nullptr) {
2494     // This instruction is necessary for the other side of the condition so
2495     // don't count it.
2496     if (Necessary->contains(I))
2497       return true;
2498   }
2499 
2500   // Already added this dep.
2501   if (!Deps->try_emplace(I, false).second)
2502     return true;
2503 
2504   for (unsigned OpIdx = 0, E = I->getNumOperands(); OpIdx < E; ++OpIdx)
2505     if (!collectInstructionDeps(Deps, I->getOperand(OpIdx), Necessary,
2506                                 Depth + 1))
2507       return false;
2508   return true;
2509 }
2510 
2511 bool SelectionDAGBuilder::shouldKeepJumpConditionsTogether(
2512     const FunctionLoweringInfo &FuncInfo, const BranchInst &I,
2513     Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs,
2514     TargetLoweringBase::CondMergingParams Params) const {
2515   if (I.getNumSuccessors() != 2)
2516     return false;
2517 
2518   if (!I.isConditional())
2519     return false;
2520 
2521   if (Params.BaseCost < 0)
2522     return false;
2523 
2524   // Baseline cost.
2525   InstructionCost CostThresh = Params.BaseCost;
2526 
2527   BranchProbabilityInfo *BPI = nullptr;
2528   if (Params.LikelyBias || Params.UnlikelyBias)
2529     BPI = FuncInfo.BPI;
2530   if (BPI != nullptr) {
2531     // See if we are either likely to get an early out or compute both lhs/rhs
2532     // of the condition.
2533     BasicBlock *IfFalse = I.getSuccessor(0);
2534     BasicBlock *IfTrue = I.getSuccessor(1);
2535 
2536     std::optional<bool> Likely;
2537     if (BPI->isEdgeHot(I.getParent(), IfTrue))
2538       Likely = true;
2539     else if (BPI->isEdgeHot(I.getParent(), IfFalse))
2540       Likely = false;
2541 
2542     if (Likely) {
2543       if (Opc == (*Likely ? Instruction::And : Instruction::Or))
2544         // Its likely we will have to compute both lhs and rhs of condition
2545         CostThresh += Params.LikelyBias;
2546       else {
2547         if (Params.UnlikelyBias < 0)
2548           return false;
2549         // Its likely we will get an early out.
2550         CostThresh -= Params.UnlikelyBias;
2551       }
2552     }
2553   }
2554 
2555   if (CostThresh <= 0)
2556     return false;
2557 
2558   // Collect "all" instructions that lhs condition is dependent on.
2559   // Use map for stable iteration (to avoid non-determanism of iteration of
2560   // SmallPtrSet). The `bool` value is just a dummy.
2561   SmallMapVector<const Instruction *, bool, 8> LhsDeps, RhsDeps;
2562   collectInstructionDeps(&LhsDeps, Lhs);
2563   // Collect "all" instructions that rhs condition is dependent on AND are
2564   // dependencies of lhs. This gives us an estimate on which instructions we
2565   // stand to save by splitting the condition.
2566   if (!collectInstructionDeps(&RhsDeps, Rhs, &LhsDeps))
2567     return false;
2568   // Add the compare instruction itself unless its a dependency on the LHS.
2569   if (const auto *RhsI = dyn_cast<Instruction>(Rhs))
2570     if (!LhsDeps.contains(RhsI))
2571       RhsDeps.try_emplace(RhsI, false);
2572 
2573   const auto &TLI = DAG.getTargetLoweringInfo();
2574   const auto &TTI =
2575       TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction());
2576 
2577   InstructionCost CostOfIncluding = 0;
2578   // See if this instruction will need to computed independently of whether RHS
2579   // is.
2580   Value *BrCond = I.getCondition();
2581   auto ShouldCountInsn = [&RhsDeps, &BrCond](const Instruction *Ins) {
2582     for (const auto *U : Ins->users()) {
2583       // If user is independent of RHS calculation we don't need to count it.
2584       if (auto *UIns = dyn_cast<Instruction>(U))
2585         if (UIns != BrCond && !RhsDeps.contains(UIns))
2586           return false;
2587     }
2588     return true;
2589   };
2590 
2591   // Prune instructions from RHS Deps that are dependencies of unrelated
2592   // instructions. The value (SelectionDAG::MaxRecursionDepth) is fairly
2593   // arbitrary and just meant to cap the how much time we spend in the pruning
2594   // loop. Its highly unlikely to come into affect.
2595   const unsigned MaxPruneIters = SelectionDAG::MaxRecursionDepth;
2596   // Stop after a certain point. No incorrectness from including too many
2597   // instructions.
2598   for (unsigned PruneIters = 0; PruneIters < MaxPruneIters; ++PruneIters) {
2599     const Instruction *ToDrop = nullptr;
2600     for (const auto &InsPair : RhsDeps) {
2601       if (!ShouldCountInsn(InsPair.first)) {
2602         ToDrop = InsPair.first;
2603         break;
2604       }
2605     }
2606     if (ToDrop == nullptr)
2607       break;
2608     RhsDeps.erase(ToDrop);
2609   }
2610 
2611   for (const auto &InsPair : RhsDeps) {
2612     // Finally accumulate latency that we can only attribute to computing the
2613     // RHS condition. Use latency because we are essentially trying to calculate
2614     // the cost of the dependency chain.
2615     // Possible TODO: We could try to estimate ILP and make this more precise.
2616     CostOfIncluding +=
2617         TTI.getInstructionCost(InsPair.first, TargetTransformInfo::TCK_Latency);
2618 
2619     if (CostOfIncluding > CostThresh)
2620       return false;
2621   }
2622   return true;
2623 }
2624 
2625 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2626                                                MachineBasicBlock *TBB,
2627                                                MachineBasicBlock *FBB,
2628                                                MachineBasicBlock *CurBB,
2629                                                MachineBasicBlock *SwitchBB,
2630                                                Instruction::BinaryOps Opc,
2631                                                BranchProbability TProb,
2632                                                BranchProbability FProb,
2633                                                bool InvertCond) {
2634   // Skip over not part of the tree and remember to invert op and operands at
2635   // next level.
2636   Value *NotCond;
2637   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2638       InBlock(NotCond, CurBB->getBasicBlock())) {
2639     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2640                          !InvertCond);
2641     return;
2642   }
2643 
2644   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2645   const Value *BOpOp0, *BOpOp1;
2646   // Compute the effective opcode for Cond, taking into account whether it needs
2647   // to be inverted, e.g.
2648   //   and (not (or A, B)), C
2649   // gets lowered as
2650   //   and (and (not A, not B), C)
2651   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2652   if (BOp) {
2653     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2654                ? Instruction::And
2655                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2656                       ? Instruction::Or
2657                       : (Instruction::BinaryOps)0);
2658     if (InvertCond) {
2659       if (BOpc == Instruction::And)
2660         BOpc = Instruction::Or;
2661       else if (BOpc == Instruction::Or)
2662         BOpc = Instruction::And;
2663     }
2664   }
2665 
2666   // If this node is not part of the or/and tree, emit it as a branch.
2667   // Note that all nodes in the tree should have same opcode.
2668   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2669   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2670       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2671       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2672     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2673                                  TProb, FProb, InvertCond);
2674     return;
2675   }
2676 
2677   //  Create TmpBB after CurBB.
2678   MachineFunction::iterator BBI(CurBB);
2679   MachineFunction &MF = DAG.getMachineFunction();
2680   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2681   CurBB->getParent()->insert(++BBI, TmpBB);
2682 
2683   if (Opc == Instruction::Or) {
2684     // Codegen X | Y as:
2685     // BB1:
2686     //   jmp_if_X TBB
2687     //   jmp TmpBB
2688     // TmpBB:
2689     //   jmp_if_Y TBB
2690     //   jmp FBB
2691     //
2692 
2693     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2694     // The requirement is that
2695     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2696     //     = TrueProb for original BB.
2697     // Assuming the original probabilities are A and B, one choice is to set
2698     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2699     // A/(1+B) and 2B/(1+B). This choice assumes that
2700     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2701     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2702     // TmpBB, but the math is more complicated.
2703 
2704     auto NewTrueProb = TProb / 2;
2705     auto NewFalseProb = TProb / 2 + FProb;
2706     // Emit the LHS condition.
2707     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2708                          NewFalseProb, InvertCond);
2709 
2710     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2711     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2712     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2713     // Emit the RHS condition into TmpBB.
2714     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2715                          Probs[1], InvertCond);
2716   } else {
2717     assert(Opc == Instruction::And && "Unknown merge op!");
2718     // Codegen X & Y as:
2719     // BB1:
2720     //   jmp_if_X TmpBB
2721     //   jmp FBB
2722     // TmpBB:
2723     //   jmp_if_Y TBB
2724     //   jmp FBB
2725     //
2726     //  This requires creation of TmpBB after CurBB.
2727 
2728     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2729     // The requirement is that
2730     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2731     //     = FalseProb for original BB.
2732     // Assuming the original probabilities are A and B, one choice is to set
2733     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2734     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2735     // TrueProb for BB1 * FalseProb for TmpBB.
2736 
2737     auto NewTrueProb = TProb + FProb / 2;
2738     auto NewFalseProb = FProb / 2;
2739     // Emit the LHS condition.
2740     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2741                          NewFalseProb, InvertCond);
2742 
2743     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2744     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2745     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2746     // Emit the RHS condition into TmpBB.
2747     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2748                          Probs[1], InvertCond);
2749   }
2750 }
2751 
2752 /// If the set of cases should be emitted as a series of branches, return true.
2753 /// If we should emit this as a bunch of and/or'd together conditions, return
2754 /// false.
2755 bool
2756 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2757   if (Cases.size() != 2) return true;
2758 
2759   // If this is two comparisons of the same values or'd or and'd together, they
2760   // will get folded into a single comparison, so don't emit two blocks.
2761   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2762        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2763       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2764        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2765     return false;
2766   }
2767 
2768   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2769   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2770   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2771       Cases[0].CC == Cases[1].CC &&
2772       isa<Constant>(Cases[0].CmpRHS) &&
2773       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2774     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2775       return false;
2776     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2777       return false;
2778   }
2779 
2780   return true;
2781 }
2782 
2783 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2784   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2785 
2786   // Update machine-CFG edges.
2787   MachineBasicBlock *Succ0MBB = FuncInfo.getMBB(I.getSuccessor(0));
2788 
2789   if (I.isUnconditional()) {
2790     // Update machine-CFG edges.
2791     BrMBB->addSuccessor(Succ0MBB);
2792 
2793     // If this is not a fall-through branch or optimizations are switched off,
2794     // emit the branch.
2795     if (Succ0MBB != NextBlock(BrMBB) ||
2796         TM.getOptLevel() == CodeGenOptLevel::None) {
2797       auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
2798                             getControlRoot(), DAG.getBasicBlock(Succ0MBB));
2799       setValue(&I, Br);
2800       DAG.setRoot(Br);
2801     }
2802 
2803     return;
2804   }
2805 
2806   // If this condition is one of the special cases we handle, do special stuff
2807   // now.
2808   const Value *CondVal = I.getCondition();
2809   MachineBasicBlock *Succ1MBB = FuncInfo.getMBB(I.getSuccessor(1));
2810 
2811   // If this is a series of conditions that are or'd or and'd together, emit
2812   // this as a sequence of branches instead of setcc's with and/or operations.
2813   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2814   // unpredictable branches, and vector extracts because those jumps are likely
2815   // expensive for any target), this should improve performance.
2816   // For example, instead of something like:
2817   //     cmp A, B
2818   //     C = seteq
2819   //     cmp D, E
2820   //     F = setle
2821   //     or C, F
2822   //     jnz foo
2823   // Emit:
2824   //     cmp A, B
2825   //     je foo
2826   //     cmp D, E
2827   //     jle foo
2828   bool IsUnpredictable = I.hasMetadata(LLVMContext::MD_unpredictable);
2829   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2830   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2831       BOp->hasOneUse() && !IsUnpredictable) {
2832     Value *Vec;
2833     const Value *BOp0, *BOp1;
2834     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2835     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2836       Opcode = Instruction::And;
2837     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2838       Opcode = Instruction::Or;
2839 
2840     if (Opcode &&
2841         !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2842           match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value()))) &&
2843         !shouldKeepJumpConditionsTogether(
2844             FuncInfo, I, Opcode, BOp0, BOp1,
2845             DAG.getTargetLoweringInfo().getJumpConditionMergingParams(
2846                 Opcode, BOp0, BOp1))) {
2847       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2848                            getEdgeProbability(BrMBB, Succ0MBB),
2849                            getEdgeProbability(BrMBB, Succ1MBB),
2850                            /*InvertCond=*/false);
2851       // If the compares in later blocks need to use values not currently
2852       // exported from this block, export them now.  This block should always
2853       // be the first entry.
2854       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2855 
2856       // Allow some cases to be rejected.
2857       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2858         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2859           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2860           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2861         }
2862 
2863         // Emit the branch for this block.
2864         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2865         SL->SwitchCases.erase(SL->SwitchCases.begin());
2866         return;
2867       }
2868 
2869       // Okay, we decided not to do this, remove any inserted MBB's and clear
2870       // SwitchCases.
2871       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2872         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2873 
2874       SL->SwitchCases.clear();
2875     }
2876   }
2877 
2878   // Create a CaseBlock record representing this branch.
2879   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2880                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc(),
2881                BranchProbability::getUnknown(), BranchProbability::getUnknown(),
2882                IsUnpredictable);
2883 
2884   // Use visitSwitchCase to actually insert the fast branch sequence for this
2885   // cond branch.
2886   visitSwitchCase(CB, BrMBB);
2887 }
2888 
2889 /// visitSwitchCase - Emits the necessary code to represent a single node in
2890 /// the binary search tree resulting from lowering a switch instruction.
2891 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2892                                           MachineBasicBlock *SwitchBB) {
2893   SDValue Cond;
2894   SDValue CondLHS = getValue(CB.CmpLHS);
2895   SDLoc dl = CB.DL;
2896 
2897   if (CB.CC == ISD::SETTRUE) {
2898     // Branch or fall through to TrueBB.
2899     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2900     SwitchBB->normalizeSuccProbs();
2901     if (CB.TrueBB != NextBlock(SwitchBB)) {
2902       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2903                               DAG.getBasicBlock(CB.TrueBB)));
2904     }
2905     return;
2906   }
2907 
2908   auto &TLI = DAG.getTargetLoweringInfo();
2909   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2910 
2911   // Build the setcc now.
2912   if (!CB.CmpMHS) {
2913     // Fold "(X == true)" to X and "(X == false)" to !X to
2914     // handle common cases produced by branch lowering.
2915     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2916         CB.CC == ISD::SETEQ)
2917       Cond = CondLHS;
2918     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2919              CB.CC == ISD::SETEQ) {
2920       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2921       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2922     } else {
2923       SDValue CondRHS = getValue(CB.CmpRHS);
2924 
2925       // If a pointer's DAG type is larger than its memory type then the DAG
2926       // values are zero-extended. This breaks signed comparisons so truncate
2927       // back to the underlying type before doing the compare.
2928       if (CondLHS.getValueType() != MemVT) {
2929         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2930         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2931       }
2932       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2933     }
2934   } else {
2935     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2936 
2937     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2938     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2939 
2940     SDValue CmpOp = getValue(CB.CmpMHS);
2941     EVT VT = CmpOp.getValueType();
2942 
2943     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2944       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2945                           ISD::SETLE);
2946     } else {
2947       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2948                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2949       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2950                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2951     }
2952   }
2953 
2954   // Update successor info
2955   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2956   // TrueBB and FalseBB are always different unless the incoming IR is
2957   // degenerate. This only happens when running llc on weird IR.
2958   if (CB.TrueBB != CB.FalseBB)
2959     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2960   SwitchBB->normalizeSuccProbs();
2961 
2962   // If the lhs block is the next block, invert the condition so that we can
2963   // fall through to the lhs instead of the rhs block.
2964   if (CB.TrueBB == NextBlock(SwitchBB)) {
2965     std::swap(CB.TrueBB, CB.FalseBB);
2966     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2967     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2968   }
2969 
2970   SDNodeFlags Flags;
2971   Flags.setUnpredictable(CB.IsUnpredictable);
2972   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, MVT::Other, getControlRoot(),
2973                                Cond, DAG.getBasicBlock(CB.TrueBB), Flags);
2974 
2975   setValue(CurInst, BrCond);
2976 
2977   // Insert the false branch. Do this even if it's a fall through branch,
2978   // this makes it easier to do DAG optimizations which require inverting
2979   // the branch condition.
2980   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2981                        DAG.getBasicBlock(CB.FalseBB));
2982 
2983   DAG.setRoot(BrCond);
2984 }
2985 
2986 /// visitJumpTable - Emit JumpTable node in the current MBB
2987 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2988   // Emit the code for the jump table
2989   assert(JT.SL && "Should set SDLoc for SelectionDAG!");
2990   assert(JT.Reg && "Should lower JT Header first!");
2991   EVT PTy = DAG.getTargetLoweringInfo().getJumpTableRegTy(DAG.getDataLayout());
2992   SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy);
2993   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2994   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other,
2995                                     Index.getValue(1), Table, Index);
2996   DAG.setRoot(BrJumpTable);
2997 }
2998 
2999 /// visitJumpTableHeader - This function emits necessary code to produce index
3000 /// in the JumpTable from switch case.
3001 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
3002                                                JumpTableHeader &JTH,
3003                                                MachineBasicBlock *SwitchBB) {
3004   assert(JT.SL && "Should set SDLoc for SelectionDAG!");
3005   const SDLoc &dl = *JT.SL;
3006 
3007   // Subtract the lowest switch case value from the value being switched on.
3008   SDValue SwitchOp = getValue(JTH.SValue);
3009   EVT VT = SwitchOp.getValueType();
3010   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
3011                             DAG.getConstant(JTH.First, dl, VT));
3012 
3013   // The SDNode we just created, which holds the value being switched on minus
3014   // the smallest case value, needs to be copied to a virtual register so it
3015   // can be used as an index into the jump table in a subsequent basic block.
3016   // This value may be smaller or larger than the target's pointer type, and
3017   // therefore require extension or truncating.
3018   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3019   SwitchOp =
3020       DAG.getZExtOrTrunc(Sub, dl, TLI.getJumpTableRegTy(DAG.getDataLayout()));
3021 
3022   Register JumpTableReg =
3023       FuncInfo.CreateReg(TLI.getJumpTableRegTy(DAG.getDataLayout()));
3024   SDValue CopyTo =
3025       DAG.getCopyToReg(getControlRoot(), dl, JumpTableReg, SwitchOp);
3026   JT.Reg = JumpTableReg;
3027 
3028   if (!JTH.FallthroughUnreachable) {
3029     // Emit the range check for the jump table, and branch to the default block
3030     // for the switch statement if the value being switched on exceeds the
3031     // largest case in the switch.
3032     SDValue CMP = DAG.getSetCC(
3033         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3034                                    Sub.getValueType()),
3035         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
3036 
3037     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
3038                                  MVT::Other, CopyTo, CMP,
3039                                  DAG.getBasicBlock(JT.Default));
3040 
3041     // Avoid emitting unnecessary branches to the next block.
3042     if (JT.MBB != NextBlock(SwitchBB))
3043       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
3044                            DAG.getBasicBlock(JT.MBB));
3045 
3046     DAG.setRoot(BrCond);
3047   } else {
3048     // Avoid emitting unnecessary branches to the next block.
3049     if (JT.MBB != NextBlock(SwitchBB))
3050       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
3051                               DAG.getBasicBlock(JT.MBB)));
3052     else
3053       DAG.setRoot(CopyTo);
3054   }
3055 }
3056 
3057 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
3058 /// variable if there exists one.
3059 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
3060                                  SDValue &Chain) {
3061   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3062   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
3063   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
3064   MachineFunction &MF = DAG.getMachineFunction();
3065   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
3066   MachineSDNode *Node =
3067       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
3068   if (Global) {
3069     MachinePointerInfo MPInfo(Global);
3070     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
3071                  MachineMemOperand::MODereferenceable;
3072     MachineMemOperand *MemRef = MF.getMachineMemOperand(
3073         MPInfo, Flags, LocationSize::precise(PtrTy.getSizeInBits() / 8),
3074         DAG.getEVTAlign(PtrTy));
3075     DAG.setNodeMemRefs(Node, {MemRef});
3076   }
3077   if (PtrTy != PtrMemTy)
3078     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
3079   return SDValue(Node, 0);
3080 }
3081 
3082 /// Codegen a new tail for a stack protector check ParentMBB which has had its
3083 /// tail spliced into a stack protector check success bb.
3084 ///
3085 /// For a high level explanation of how this fits into the stack protector
3086 /// generation see the comment on the declaration of class
3087 /// StackProtectorDescriptor.
3088 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
3089                                                   MachineBasicBlock *ParentBB) {
3090 
3091   // First create the loads to the guard/stack slot for the comparison.
3092   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3093   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
3094   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
3095 
3096   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3097   int FI = MFI.getStackProtectorIndex();
3098 
3099   SDValue Guard;
3100   SDLoc dl = getCurSDLoc();
3101   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
3102   const Module &M = *ParentBB->getParent()->getFunction().getParent();
3103   Align Align =
3104       DAG.getDataLayout().getPrefTypeAlign(PointerType::get(M.getContext(), 0));
3105 
3106   // Generate code to load the content of the guard slot.
3107   SDValue GuardVal = DAG.getLoad(
3108       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
3109       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
3110       MachineMemOperand::MOVolatile);
3111 
3112   if (TLI.useStackGuardXorFP())
3113     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
3114 
3115   // Retrieve guard check function, nullptr if instrumentation is inlined.
3116   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
3117     // The target provides a guard check function to validate the guard value.
3118     // Generate a call to that function with the content of the guard slot as
3119     // argument.
3120     FunctionType *FnTy = GuardCheckFn->getFunctionType();
3121     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3122 
3123     TargetLowering::ArgListTy Args;
3124     TargetLowering::ArgListEntry Entry;
3125     Entry.Node = GuardVal;
3126     Entry.Ty = FnTy->getParamType(0);
3127     if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
3128       Entry.IsInReg = true;
3129     Args.push_back(Entry);
3130 
3131     TargetLowering::CallLoweringInfo CLI(DAG);
3132     CLI.setDebugLoc(getCurSDLoc())
3133         .setChain(DAG.getEntryNode())
3134         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
3135                    getValue(GuardCheckFn), std::move(Args));
3136 
3137     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
3138     DAG.setRoot(Result.second);
3139     return;
3140   }
3141 
3142   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
3143   // Otherwise, emit a volatile load to retrieve the stack guard value.
3144   SDValue Chain = DAG.getEntryNode();
3145   if (TLI.useLoadStackGuardNode(M)) {
3146     Guard = getLoadStackGuard(DAG, dl, Chain);
3147   } else {
3148     const Value *IRGuard = TLI.getSDagStackGuard(M);
3149     SDValue GuardPtr = getValue(IRGuard);
3150 
3151     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
3152                         MachinePointerInfo(IRGuard, 0), Align,
3153                         MachineMemOperand::MOVolatile);
3154   }
3155 
3156   // Perform the comparison via a getsetcc.
3157   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
3158                                                         *DAG.getContext(),
3159                                                         Guard.getValueType()),
3160                              Guard, GuardVal, ISD::SETNE);
3161 
3162   // If the guard/stackslot do not equal, branch to failure MBB.
3163   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
3164                                MVT::Other, GuardVal.getOperand(0),
3165                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
3166   // Otherwise branch to success MBB.
3167   SDValue Br = DAG.getNode(ISD::BR, dl,
3168                            MVT::Other, BrCond,
3169                            DAG.getBasicBlock(SPD.getSuccessMBB()));
3170 
3171   DAG.setRoot(Br);
3172 }
3173 
3174 /// Codegen the failure basic block for a stack protector check.
3175 ///
3176 /// A failure stack protector machine basic block consists simply of a call to
3177 /// __stack_chk_fail().
3178 ///
3179 /// For a high level explanation of how this fits into the stack protector
3180 /// generation see the comment on the declaration of class
3181 /// StackProtectorDescriptor.
3182 void
3183 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
3184   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3185   TargetLowering::MakeLibCallOptions CallOptions;
3186   CallOptions.setDiscardResult(true);
3187   SDValue Chain = TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL,
3188                                   MVT::isVoid, {}, CallOptions, getCurSDLoc())
3189                       .second;
3190 
3191   // Emit a trap instruction if we are required to do so.
3192   const TargetOptions &TargetOpts = DAG.getTarget().Options;
3193   if (TargetOpts.TrapUnreachable && !TargetOpts.NoTrapAfterNoreturn)
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   SDNodeFlags Flags;
3660   Flags.setSameSign(I.hasSameSign());
3661   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3662 
3663   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3664                                                         I.getType());
3665   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3666 }
3667 
3668 void SelectionDAGBuilder::visitFCmp(const FCmpInst &I) {
3669   FCmpInst::Predicate predicate = I.getPredicate();
3670   SDValue Op1 = getValue(I.getOperand(0));
3671   SDValue Op2 = getValue(I.getOperand(1));
3672 
3673   ISD::CondCode Condition = getFCmpCondCode(predicate);
3674   auto *FPMO = cast<FPMathOperator>(&I);
3675   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3676     Condition = getFCmpCodeWithoutNaN(Condition);
3677 
3678   SDNodeFlags Flags;
3679   Flags.copyFMF(*FPMO);
3680   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3681 
3682   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3683                                                         I.getType());
3684   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3685 }
3686 
3687 // Check if the condition of the select has one use or two users that are both
3688 // selects with the same condition.
3689 static bool hasOnlySelectUsers(const Value *Cond) {
3690   return llvm::all_of(Cond->users(), [](const Value *V) {
3691     return isa<SelectInst>(V);
3692   });
3693 }
3694 
3695 void SelectionDAGBuilder::visitSelect(const User &I) {
3696   SmallVector<EVT, 4> ValueVTs;
3697   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3698                   ValueVTs);
3699   unsigned NumValues = ValueVTs.size();
3700   if (NumValues == 0) return;
3701 
3702   SmallVector<SDValue, 4> Values(NumValues);
3703   SDValue Cond     = getValue(I.getOperand(0));
3704   SDValue LHSVal   = getValue(I.getOperand(1));
3705   SDValue RHSVal   = getValue(I.getOperand(2));
3706   SmallVector<SDValue, 1> BaseOps(1, Cond);
3707   ISD::NodeType OpCode =
3708       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3709 
3710   bool IsUnaryAbs = false;
3711   bool Negate = false;
3712 
3713   SDNodeFlags Flags;
3714   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3715     Flags.copyFMF(*FPOp);
3716 
3717   Flags.setUnpredictable(
3718       cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable));
3719 
3720   // Min/max matching is only viable if all output VTs are the same.
3721   if (all_equal(ValueVTs)) {
3722     EVT VT = ValueVTs[0];
3723     LLVMContext &Ctx = *DAG.getContext();
3724     auto &TLI = DAG.getTargetLoweringInfo();
3725 
3726     // We care about the legality of the operation after it has been type
3727     // legalized.
3728     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3729       VT = TLI.getTypeToTransformTo(Ctx, VT);
3730 
3731     // If the vselect is legal, assume we want to leave this as a vector setcc +
3732     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3733     // min/max is legal on the scalar type.
3734     bool UseScalarMinMax = VT.isVector() &&
3735       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3736 
3737     // ValueTracking's select pattern matching does not account for -0.0,
3738     // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that
3739     // -0.0 is less than +0.0.
3740     const Value *LHS, *RHS;
3741     auto SPR = matchSelectPattern(&I, LHS, RHS);
3742     ISD::NodeType Opc = ISD::DELETED_NODE;
3743     switch (SPR.Flavor) {
3744     case SPF_UMAX:    Opc = ISD::UMAX; break;
3745     case SPF_UMIN:    Opc = ISD::UMIN; break;
3746     case SPF_SMAX:    Opc = ISD::SMAX; break;
3747     case SPF_SMIN:    Opc = ISD::SMIN; break;
3748     case SPF_FMINNUM:
3749       switch (SPR.NaNBehavior) {
3750       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3751       case SPNB_RETURNS_NAN: break;
3752       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3753       case SPNB_RETURNS_ANY:
3754         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) ||
3755             (UseScalarMinMax &&
3756              TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType())))
3757           Opc = ISD::FMINNUM;
3758         break;
3759       }
3760       break;
3761     case SPF_FMAXNUM:
3762       switch (SPR.NaNBehavior) {
3763       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3764       case SPNB_RETURNS_NAN: break;
3765       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3766       case SPNB_RETURNS_ANY:
3767         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) ||
3768             (UseScalarMinMax &&
3769              TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType())))
3770           Opc = ISD::FMAXNUM;
3771         break;
3772       }
3773       break;
3774     case SPF_NABS:
3775       Negate = true;
3776       [[fallthrough]];
3777     case SPF_ABS:
3778       IsUnaryAbs = true;
3779       Opc = ISD::ABS;
3780       break;
3781     default: break;
3782     }
3783 
3784     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3785         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3786          (UseScalarMinMax &&
3787           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3788         // If the underlying comparison instruction is used by any other
3789         // instruction, the consumed instructions won't be destroyed, so it is
3790         // not profitable to convert to a min/max.
3791         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3792       OpCode = Opc;
3793       LHSVal = getValue(LHS);
3794       RHSVal = getValue(RHS);
3795       BaseOps.clear();
3796     }
3797 
3798     if (IsUnaryAbs) {
3799       OpCode = Opc;
3800       LHSVal = getValue(LHS);
3801       BaseOps.clear();
3802     }
3803   }
3804 
3805   if (IsUnaryAbs) {
3806     for (unsigned i = 0; i != NumValues; ++i) {
3807       SDLoc dl = getCurSDLoc();
3808       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3809       Values[i] =
3810           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3811       if (Negate)
3812         Values[i] = DAG.getNegative(Values[i], dl, VT);
3813     }
3814   } else {
3815     for (unsigned i = 0; i != NumValues; ++i) {
3816       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3817       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3818       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3819       Values[i] = DAG.getNode(
3820           OpCode, getCurSDLoc(),
3821           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3822     }
3823   }
3824 
3825   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3826                            DAG.getVTList(ValueVTs), Values));
3827 }
3828 
3829 void SelectionDAGBuilder::visitTrunc(const User &I) {
3830   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3831   SDValue N = getValue(I.getOperand(0));
3832   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3833                                                         I.getType());
3834   SDNodeFlags Flags;
3835   if (auto *Trunc = dyn_cast<TruncInst>(&I)) {
3836     Flags.setNoSignedWrap(Trunc->hasNoSignedWrap());
3837     Flags.setNoUnsignedWrap(Trunc->hasNoUnsignedWrap());
3838   }
3839 
3840   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N, Flags));
3841 }
3842 
3843 void SelectionDAGBuilder::visitZExt(const User &I) {
3844   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3845   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3846   SDValue N = getValue(I.getOperand(0));
3847   auto &TLI = DAG.getTargetLoweringInfo();
3848   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3849 
3850   SDNodeFlags Flags;
3851   if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
3852     Flags.setNonNeg(PNI->hasNonNeg());
3853 
3854   // Eagerly use nonneg information to canonicalize towards sign_extend if
3855   // that is the target's preference.
3856   // TODO: Let the target do this later.
3857   if (Flags.hasNonNeg() &&
3858       TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) {
3859     setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3860     return;
3861   }
3862 
3863   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags));
3864 }
3865 
3866 void SelectionDAGBuilder::visitSExt(const User &I) {
3867   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3868   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3869   SDValue N = getValue(I.getOperand(0));
3870   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3871                                                         I.getType());
3872   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3873 }
3874 
3875 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3876   // FPTrunc is never a no-op cast, no need to check
3877   SDValue N = getValue(I.getOperand(0));
3878   SDLoc dl = getCurSDLoc();
3879   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3880   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3881   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3882                            DAG.getTargetConstant(
3883                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3884 }
3885 
3886 void SelectionDAGBuilder::visitFPExt(const User &I) {
3887   // FPExt is never a no-op cast, no need to check
3888   SDValue N = getValue(I.getOperand(0));
3889   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3890                                                         I.getType());
3891   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3892 }
3893 
3894 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3895   // FPToUI is never a no-op cast, no need to check
3896   SDValue N = getValue(I.getOperand(0));
3897   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3898                                                         I.getType());
3899   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3900 }
3901 
3902 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3903   // FPToSI is never a no-op cast, no need to check
3904   SDValue N = getValue(I.getOperand(0));
3905   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3906                                                         I.getType());
3907   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3908 }
3909 
3910 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3911   // UIToFP is never a no-op cast, no need to check
3912   SDValue N = getValue(I.getOperand(0));
3913   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3914                                                         I.getType());
3915   SDNodeFlags Flags;
3916   if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
3917     Flags.setNonNeg(PNI->hasNonNeg());
3918 
3919   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N, Flags));
3920 }
3921 
3922 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3923   // SIToFP is never a no-op cast, no need to check
3924   SDValue N = getValue(I.getOperand(0));
3925   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3926                                                         I.getType());
3927   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3928 }
3929 
3930 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3931   // What to do depends on the size of the integer and the size of the pointer.
3932   // We can either truncate, zero extend, or no-op, accordingly.
3933   SDValue N = getValue(I.getOperand(0));
3934   auto &TLI = DAG.getTargetLoweringInfo();
3935   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3936                                                         I.getType());
3937   EVT PtrMemVT =
3938       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3939   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3940   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3941   setValue(&I, N);
3942 }
3943 
3944 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3945   // What to do depends on the size of the integer and the size of the pointer.
3946   // We can either truncate, zero extend, or no-op, accordingly.
3947   SDValue N = getValue(I.getOperand(0));
3948   auto &TLI = DAG.getTargetLoweringInfo();
3949   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3950   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3951   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3952   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3953   setValue(&I, N);
3954 }
3955 
3956 void SelectionDAGBuilder::visitBitCast(const User &I) {
3957   SDValue N = getValue(I.getOperand(0));
3958   SDLoc dl = getCurSDLoc();
3959   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3960                                                         I.getType());
3961 
3962   // BitCast assures us that source and destination are the same size so this is
3963   // either a BITCAST or a no-op.
3964   if (DestVT != N.getValueType())
3965     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3966                              DestVT, N)); // convert types.
3967   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3968   // might fold any kind of constant expression to an integer constant and that
3969   // is not what we are looking for. Only recognize a bitcast of a genuine
3970   // constant integer as an opaque constant.
3971   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3972     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3973                                  /*isOpaque*/true));
3974   else
3975     setValue(&I, N);            // noop cast.
3976 }
3977 
3978 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3979   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3980   const Value *SV = I.getOperand(0);
3981   SDValue N = getValue(SV);
3982   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3983 
3984   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3985   unsigned DestAS = I.getType()->getPointerAddressSpace();
3986 
3987   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3988     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3989 
3990   setValue(&I, N);
3991 }
3992 
3993 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3994   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3995   SDValue InVec = getValue(I.getOperand(0));
3996   SDValue InVal = getValue(I.getOperand(1));
3997   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3998                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3999   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
4000                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
4001                            InVec, InVal, InIdx));
4002 }
4003 
4004 void SelectionDAGBuilder::visitExtractElement(const User &I) {
4005   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4006   SDValue InVec = getValue(I.getOperand(0));
4007   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
4008                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
4009   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
4010                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
4011                            InVec, InIdx));
4012 }
4013 
4014 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
4015   SDValue Src1 = getValue(I.getOperand(0));
4016   SDValue Src2 = getValue(I.getOperand(1));
4017   ArrayRef<int> Mask;
4018   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
4019     Mask = SVI->getShuffleMask();
4020   else
4021     Mask = cast<ConstantExpr>(I).getShuffleMask();
4022   SDLoc DL = getCurSDLoc();
4023   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4024   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4025   EVT SrcVT = Src1.getValueType();
4026 
4027   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
4028       VT.isScalableVector()) {
4029     // Canonical splat form of first element of first input vector.
4030     SDValue FirstElt =
4031         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
4032                     DAG.getVectorIdxConstant(0, DL));
4033     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
4034     return;
4035   }
4036 
4037   // For now, we only handle splats for scalable vectors.
4038   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
4039   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
4040   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
4041 
4042   unsigned SrcNumElts = SrcVT.getVectorNumElements();
4043   unsigned MaskNumElts = Mask.size();
4044 
4045   if (SrcNumElts == MaskNumElts) {
4046     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
4047     return;
4048   }
4049 
4050   // Normalize the shuffle vector since mask and vector length don't match.
4051   if (SrcNumElts < MaskNumElts) {
4052     // Mask is longer than the source vectors. We can use concatenate vector to
4053     // make the mask and vectors lengths match.
4054 
4055     if (MaskNumElts % SrcNumElts == 0) {
4056       // Mask length is a multiple of the source vector length.
4057       // Check if the shuffle is some kind of concatenation of the input
4058       // vectors.
4059       unsigned NumConcat = MaskNumElts / SrcNumElts;
4060       bool IsConcat = true;
4061       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
4062       for (unsigned i = 0; i != MaskNumElts; ++i) {
4063         int Idx = Mask[i];
4064         if (Idx < 0)
4065           continue;
4066         // Ensure the indices in each SrcVT sized piece are sequential and that
4067         // the same source is used for the whole piece.
4068         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
4069             (ConcatSrcs[i / SrcNumElts] >= 0 &&
4070              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
4071           IsConcat = false;
4072           break;
4073         }
4074         // Remember which source this index came from.
4075         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
4076       }
4077 
4078       // The shuffle is concatenating multiple vectors together. Just emit
4079       // a CONCAT_VECTORS operation.
4080       if (IsConcat) {
4081         SmallVector<SDValue, 8> ConcatOps;
4082         for (auto Src : ConcatSrcs) {
4083           if (Src < 0)
4084             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
4085           else if (Src == 0)
4086             ConcatOps.push_back(Src1);
4087           else
4088             ConcatOps.push_back(Src2);
4089         }
4090         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
4091         return;
4092       }
4093     }
4094 
4095     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
4096     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
4097     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
4098                                     PaddedMaskNumElts);
4099 
4100     // Pad both vectors with undefs to make them the same length as the mask.
4101     SDValue UndefVal = DAG.getUNDEF(SrcVT);
4102 
4103     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
4104     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
4105     MOps1[0] = Src1;
4106     MOps2[0] = Src2;
4107 
4108     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
4109     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
4110 
4111     // Readjust mask for new input vector length.
4112     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
4113     for (unsigned i = 0; i != MaskNumElts; ++i) {
4114       int Idx = Mask[i];
4115       if (Idx >= (int)SrcNumElts)
4116         Idx -= SrcNumElts - PaddedMaskNumElts;
4117       MappedOps[i] = Idx;
4118     }
4119 
4120     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
4121 
4122     // If the concatenated vector was padded, extract a subvector with the
4123     // correct number of elements.
4124     if (MaskNumElts != PaddedMaskNumElts)
4125       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
4126                            DAG.getVectorIdxConstant(0, DL));
4127 
4128     setValue(&I, Result);
4129     return;
4130   }
4131 
4132   assert(SrcNumElts > MaskNumElts);
4133 
4134   // Analyze the access pattern of the vector to see if we can extract
4135   // two subvectors and do the shuffle.
4136   int StartIdx[2] = {-1, -1}; // StartIdx to extract from
4137   bool CanExtract = true;
4138   for (int Idx : Mask) {
4139     unsigned Input = 0;
4140     if (Idx < 0)
4141       continue;
4142 
4143     if (Idx >= (int)SrcNumElts) {
4144       Input = 1;
4145       Idx -= SrcNumElts;
4146     }
4147 
4148     // If all the indices come from the same MaskNumElts sized portion of
4149     // the sources we can use extract. Also make sure the extract wouldn't
4150     // extract past the end of the source.
4151     int NewStartIdx = alignDown(Idx, MaskNumElts);
4152     if (NewStartIdx + MaskNumElts > SrcNumElts ||
4153         (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
4154       CanExtract = false;
4155     // Make sure we always update StartIdx as we use it to track if all
4156     // elements are undef.
4157     StartIdx[Input] = NewStartIdx;
4158   }
4159 
4160   if (StartIdx[0] < 0 && StartIdx[1] < 0) {
4161     setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
4162     return;
4163   }
4164   if (CanExtract) {
4165     // Extract appropriate subvector and generate a vector shuffle
4166     for (unsigned Input = 0; Input < 2; ++Input) {
4167       SDValue &Src = Input == 0 ? Src1 : Src2;
4168       if (StartIdx[Input] < 0)
4169         Src = DAG.getUNDEF(VT);
4170       else {
4171         Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
4172                           DAG.getVectorIdxConstant(StartIdx[Input], DL));
4173       }
4174     }
4175 
4176     // Calculate new mask.
4177     SmallVector<int, 8> MappedOps(Mask);
4178     for (int &Idx : MappedOps) {
4179       if (Idx >= (int)SrcNumElts)
4180         Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
4181       else if (Idx >= 0)
4182         Idx -= StartIdx[0];
4183     }
4184 
4185     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
4186     return;
4187   }
4188 
4189   // We can't use either concat vectors or extract subvectors so fall back to
4190   // replacing the shuffle with extract and build vector.
4191   // to insert and build vector.
4192   EVT EltVT = VT.getVectorElementType();
4193   SmallVector<SDValue,8> Ops;
4194   for (int Idx : Mask) {
4195     SDValue Res;
4196 
4197     if (Idx < 0) {
4198       Res = DAG.getUNDEF(EltVT);
4199     } else {
4200       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
4201       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
4202 
4203       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
4204                         DAG.getVectorIdxConstant(Idx, DL));
4205     }
4206 
4207     Ops.push_back(Res);
4208   }
4209 
4210   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
4211 }
4212 
4213 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
4214   ArrayRef<unsigned> Indices = I.getIndices();
4215   const Value *Op0 = I.getOperand(0);
4216   const Value *Op1 = I.getOperand(1);
4217   Type *AggTy = I.getType();
4218   Type *ValTy = Op1->getType();
4219   bool IntoUndef = isa<UndefValue>(Op0);
4220   bool FromUndef = isa<UndefValue>(Op1);
4221 
4222   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4223 
4224   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4225   SmallVector<EVT, 4> AggValueVTs;
4226   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
4227   SmallVector<EVT, 4> ValValueVTs;
4228   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4229 
4230   unsigned NumAggValues = AggValueVTs.size();
4231   unsigned NumValValues = ValValueVTs.size();
4232   SmallVector<SDValue, 4> Values(NumAggValues);
4233 
4234   // Ignore an insertvalue that produces an empty object
4235   if (!NumAggValues) {
4236     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4237     return;
4238   }
4239 
4240   SDValue Agg = getValue(Op0);
4241   unsigned i = 0;
4242   // Copy the beginning value(s) from the original aggregate.
4243   for (; i != LinearIndex; ++i)
4244     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4245                 SDValue(Agg.getNode(), Agg.getResNo() + i);
4246   // Copy values from the inserted value(s).
4247   if (NumValValues) {
4248     SDValue Val = getValue(Op1);
4249     for (; i != LinearIndex + NumValValues; ++i)
4250       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4251                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
4252   }
4253   // Copy remaining value(s) from the original aggregate.
4254   for (; i != NumAggValues; ++i)
4255     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4256                 SDValue(Agg.getNode(), Agg.getResNo() + i);
4257 
4258   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
4259                            DAG.getVTList(AggValueVTs), Values));
4260 }
4261 
4262 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
4263   ArrayRef<unsigned> Indices = I.getIndices();
4264   const Value *Op0 = I.getOperand(0);
4265   Type *AggTy = Op0->getType();
4266   Type *ValTy = I.getType();
4267   bool OutOfUndef = isa<UndefValue>(Op0);
4268 
4269   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4270 
4271   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4272   SmallVector<EVT, 4> ValValueVTs;
4273   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4274 
4275   unsigned NumValValues = ValValueVTs.size();
4276 
4277   // Ignore a extractvalue that produces an empty object
4278   if (!NumValValues) {
4279     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4280     return;
4281   }
4282 
4283   SmallVector<SDValue, 4> Values(NumValValues);
4284 
4285   SDValue Agg = getValue(Op0);
4286   // Copy out the selected value(s).
4287   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
4288     Values[i - LinearIndex] =
4289       OutOfUndef ?
4290         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
4291         SDValue(Agg.getNode(), Agg.getResNo() + i);
4292 
4293   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
4294                            DAG.getVTList(ValValueVTs), Values));
4295 }
4296 
4297 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
4298   Value *Op0 = I.getOperand(0);
4299   // Note that the pointer operand may be a vector of pointers. Take the scalar
4300   // element which holds a pointer.
4301   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
4302   SDValue N = getValue(Op0);
4303   SDLoc dl = getCurSDLoc();
4304   auto &TLI = DAG.getTargetLoweringInfo();
4305   GEPNoWrapFlags NW = cast<GEPOperator>(I).getNoWrapFlags();
4306 
4307   // Normalize Vector GEP - all scalar operands should be converted to the
4308   // splat vector.
4309   bool IsVectorGEP = I.getType()->isVectorTy();
4310   ElementCount VectorElementCount =
4311       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
4312                   : ElementCount::getFixed(0);
4313 
4314   if (IsVectorGEP && !N.getValueType().isVector()) {
4315     LLVMContext &Context = *DAG.getContext();
4316     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
4317     N = DAG.getSplat(VT, dl, N);
4318   }
4319 
4320   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
4321        GTI != E; ++GTI) {
4322     const Value *Idx = GTI.getOperand();
4323     if (StructType *StTy = GTI.getStructTypeOrNull()) {
4324       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
4325       if (Field) {
4326         // N = N + Offset
4327         uint64_t Offset =
4328             DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
4329 
4330         // In an inbounds GEP with an offset that is nonnegative even when
4331         // interpreted as signed, assume there is no unsigned overflow.
4332         SDNodeFlags Flags;
4333         if (NW.hasNoUnsignedWrap() ||
4334             (int64_t(Offset) >= 0 && NW.hasNoUnsignedSignedWrap()))
4335           Flags |= SDNodeFlags::NoUnsignedWrap;
4336 
4337         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
4338                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
4339       }
4340     } else {
4341       // IdxSize is the width of the arithmetic according to IR semantics.
4342       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
4343       // (and fix up the result later).
4344       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
4345       MVT IdxTy = MVT::getIntegerVT(IdxSize);
4346       TypeSize ElementSize =
4347           GTI.getSequentialElementStride(DAG.getDataLayout());
4348       // We intentionally mask away the high bits here; ElementSize may not
4349       // fit in IdxTy.
4350       APInt ElementMul(IdxSize, ElementSize.getKnownMinValue(),
4351                        /*isSigned=*/false, /*implicitTrunc=*/true);
4352       bool ElementScalable = ElementSize.isScalable();
4353 
4354       // If this is a scalar constant or a splat vector of constants,
4355       // handle it quickly.
4356       const auto *C = dyn_cast<Constant>(Idx);
4357       if (C && isa<VectorType>(C->getType()))
4358         C = C->getSplatValue();
4359 
4360       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
4361       if (CI && CI->isZero())
4362         continue;
4363       if (CI && !ElementScalable) {
4364         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
4365         LLVMContext &Context = *DAG.getContext();
4366         SDValue OffsVal;
4367         if (IsVectorGEP)
4368           OffsVal = DAG.getConstant(
4369               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
4370         else
4371           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
4372 
4373         // In an inbounds GEP with an offset that is nonnegative even when
4374         // interpreted as signed, assume there is no unsigned overflow.
4375         SDNodeFlags Flags;
4376         if (NW.hasNoUnsignedWrap() ||
4377             (Offs.isNonNegative() && NW.hasNoUnsignedSignedWrap()))
4378           Flags.setNoUnsignedWrap(true);
4379 
4380         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
4381 
4382         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
4383         continue;
4384       }
4385 
4386       // N = N + Idx * ElementMul;
4387       SDValue IdxN = getValue(Idx);
4388 
4389       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
4390         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
4391                                   VectorElementCount);
4392         IdxN = DAG.getSplat(VT, dl, IdxN);
4393       }
4394 
4395       // If the index is smaller or larger than intptr_t, truncate or extend
4396       // it.
4397       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
4398 
4399       SDNodeFlags ScaleFlags;
4400       // The multiplication of an index by the type size does not wrap the
4401       // pointer index type in a signed sense (mul nsw).
4402       ScaleFlags.setNoSignedWrap(NW.hasNoUnsignedSignedWrap());
4403 
4404       // The multiplication of an index by the type size does not wrap the
4405       // pointer index type in an unsigned sense (mul nuw).
4406       ScaleFlags.setNoUnsignedWrap(NW.hasNoUnsignedWrap());
4407 
4408       if (ElementScalable) {
4409         EVT VScaleTy = N.getValueType().getScalarType();
4410         SDValue VScale = DAG.getNode(
4411             ISD::VSCALE, dl, VScaleTy,
4412             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
4413         if (IsVectorGEP)
4414           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
4415         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale,
4416                            ScaleFlags);
4417       } else {
4418         // If this is a multiply by a power of two, turn it into a shl
4419         // immediately.  This is a very common case.
4420         if (ElementMul != 1) {
4421           if (ElementMul.isPowerOf2()) {
4422             unsigned Amt = ElementMul.logBase2();
4423             IdxN = DAG.getNode(ISD::SHL, dl, N.getValueType(), IdxN,
4424                                DAG.getConstant(Amt, dl, IdxN.getValueType()),
4425                                ScaleFlags);
4426           } else {
4427             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
4428                                             IdxN.getValueType());
4429             IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, Scale,
4430                                ScaleFlags);
4431           }
4432         }
4433       }
4434 
4435       // The successive addition of the current address, truncated to the
4436       // pointer index type and interpreted as an unsigned number, and each
4437       // offset, also interpreted as an unsigned number, does not wrap the
4438       // pointer index type (add nuw).
4439       SDNodeFlags AddFlags;
4440       AddFlags.setNoUnsignedWrap(NW.hasNoUnsignedWrap());
4441 
4442       N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, IdxN, AddFlags);
4443     }
4444   }
4445 
4446   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4447   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4448   if (IsVectorGEP) {
4449     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4450     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4451   }
4452 
4453   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4454     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4455 
4456   setValue(&I, N);
4457 }
4458 
4459 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4460   // If this is a fixed sized alloca in the entry block of the function,
4461   // allocate it statically on the stack.
4462   if (FuncInfo.StaticAllocaMap.count(&I))
4463     return;   // getValue will auto-populate this.
4464 
4465   SDLoc dl = getCurSDLoc();
4466   Type *Ty = I.getAllocatedType();
4467   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4468   auto &DL = DAG.getDataLayout();
4469   TypeSize TySize = DL.getTypeAllocSize(Ty);
4470   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4471 
4472   SDValue AllocSize = getValue(I.getArraySize());
4473 
4474   EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace());
4475   if (AllocSize.getValueType() != IntPtr)
4476     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4477 
4478   if (TySize.isScalable())
4479     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4480                             DAG.getVScale(dl, IntPtr,
4481                                           APInt(IntPtr.getScalarSizeInBits(),
4482                                                 TySize.getKnownMinValue())));
4483   else {
4484     SDValue TySizeValue =
4485         DAG.getConstant(TySize.getFixedValue(), dl, MVT::getIntegerVT(64));
4486     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4487                             DAG.getZExtOrTrunc(TySizeValue, dl, IntPtr));
4488   }
4489 
4490   // Handle alignment.  If the requested alignment is less than or equal to
4491   // the stack alignment, ignore it.  If the size is greater than or equal to
4492   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4493   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4494   if (*Alignment <= StackAlign)
4495     Alignment = std::nullopt;
4496 
4497   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4498   // Round the size of the allocation up to the stack alignment size
4499   // by add SA-1 to the size. This doesn't overflow because we're computing
4500   // an address inside an alloca.
4501   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4502                           DAG.getConstant(StackAlignMask, dl, IntPtr),
4503                           SDNodeFlags::NoUnsignedWrap);
4504 
4505   // Mask out the low bits for alignment purposes.
4506   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4507                           DAG.getSignedConstant(~StackAlignMask, dl, IntPtr));
4508 
4509   SDValue Ops[] = {
4510       getRoot(), AllocSize,
4511       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4512   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4513   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4514   setValue(&I, DSA);
4515   DAG.setRoot(DSA.getValue(1));
4516 
4517   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4518 }
4519 
4520 static const MDNode *getRangeMetadata(const Instruction &I) {
4521   // If !noundef is not present, then !range violation results in a poison
4522   // value rather than immediate undefined behavior. In theory, transferring
4523   // these annotations to SDAG is fine, but in practice there are key SDAG
4524   // transforms that are known not to be poison-safe, such as folding logical
4525   // and/or to bitwise and/or. For now, only transfer !range if !noundef is
4526   // also present.
4527   if (!I.hasMetadata(LLVMContext::MD_noundef))
4528     return nullptr;
4529   return I.getMetadata(LLVMContext::MD_range);
4530 }
4531 
4532 static std::optional<ConstantRange> getRange(const Instruction &I) {
4533   if (const auto *CB = dyn_cast<CallBase>(&I)) {
4534     // see comment in getRangeMetadata about this check
4535     if (CB->hasRetAttr(Attribute::NoUndef))
4536       return CB->getRange();
4537   }
4538   if (const MDNode *Range = getRangeMetadata(I))
4539     return getConstantRangeFromMetadata(*Range);
4540   return std::nullopt;
4541 }
4542 
4543 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4544   if (I.isAtomic())
4545     return visitAtomicLoad(I);
4546 
4547   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4548   const Value *SV = I.getOperand(0);
4549   if (TLI.supportSwiftError()) {
4550     // Swifterror values can come from either a function parameter with
4551     // swifterror attribute or an alloca with swifterror attribute.
4552     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4553       if (Arg->hasSwiftErrorAttr())
4554         return visitLoadFromSwiftError(I);
4555     }
4556 
4557     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4558       if (Alloca->isSwiftError())
4559         return visitLoadFromSwiftError(I);
4560     }
4561   }
4562 
4563   SDValue Ptr = getValue(SV);
4564 
4565   Type *Ty = I.getType();
4566   SmallVector<EVT, 4> ValueVTs, MemVTs;
4567   SmallVector<TypeSize, 4> Offsets;
4568   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4569   unsigned NumValues = ValueVTs.size();
4570   if (NumValues == 0)
4571     return;
4572 
4573   Align Alignment = I.getAlign();
4574   AAMDNodes AAInfo = I.getAAMetadata();
4575   const MDNode *Ranges = getRangeMetadata(I);
4576   bool isVolatile = I.isVolatile();
4577   MachineMemOperand::Flags MMOFlags =
4578       TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4579 
4580   SDValue Root;
4581   bool ConstantMemory = false;
4582   if (isVolatile)
4583     // Serialize volatile loads with other side effects.
4584     Root = getRoot();
4585   else if (NumValues > MaxParallelChains)
4586     Root = getMemoryRoot();
4587   else if (AA &&
4588            AA->pointsToConstantMemory(MemoryLocation(
4589                SV,
4590                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4591                AAInfo))) {
4592     // Do not serialize (non-volatile) loads of constant memory with anything.
4593     Root = DAG.getEntryNode();
4594     ConstantMemory = true;
4595     MMOFlags |= MachineMemOperand::MOInvariant;
4596   } else {
4597     // Do not serialize non-volatile loads against each other.
4598     Root = DAG.getRoot();
4599   }
4600 
4601   SDLoc dl = getCurSDLoc();
4602 
4603   if (isVolatile)
4604     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4605 
4606   SmallVector<SDValue, 4> Values(NumValues);
4607   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4608 
4609   unsigned ChainI = 0;
4610   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4611     // Serializing loads here may result in excessive register pressure, and
4612     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4613     // could recover a bit by hoisting nodes upward in the chain by recognizing
4614     // they are side-effect free or do not alias. The optimizer should really
4615     // avoid this case by converting large object/array copies to llvm.memcpy
4616     // (MaxParallelChains should always remain as failsafe).
4617     if (ChainI == MaxParallelChains) {
4618       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4619       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4620                                   ArrayRef(Chains.data(), ChainI));
4621       Root = Chain;
4622       ChainI = 0;
4623     }
4624 
4625     // TODO: MachinePointerInfo only supports a fixed length offset.
4626     MachinePointerInfo PtrInfo =
4627         !Offsets[i].isScalable() || Offsets[i].isZero()
4628             ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue())
4629             : MachinePointerInfo();
4630 
4631     SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4632     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment,
4633                             MMOFlags, AAInfo, Ranges);
4634     Chains[ChainI] = L.getValue(1);
4635 
4636     if (MemVTs[i] != ValueVTs[i])
4637       L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]);
4638 
4639     Values[i] = L;
4640   }
4641 
4642   if (!ConstantMemory) {
4643     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4644                                 ArrayRef(Chains.data(), ChainI));
4645     if (isVolatile)
4646       DAG.setRoot(Chain);
4647     else
4648       PendingLoads.push_back(Chain);
4649   }
4650 
4651   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4652                            DAG.getVTList(ValueVTs), Values));
4653 }
4654 
4655 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4656   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4657          "call visitStoreToSwiftError when backend supports swifterror");
4658 
4659   SmallVector<EVT, 4> ValueVTs;
4660   SmallVector<uint64_t, 4> Offsets;
4661   const Value *SrcV = I.getOperand(0);
4662   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4663                   SrcV->getType(), ValueVTs, &Offsets, 0);
4664   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4665          "expect a single EVT for swifterror");
4666 
4667   SDValue Src = getValue(SrcV);
4668   // Create a virtual register, then update the virtual register.
4669   Register VReg =
4670       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4671   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4672   // Chain can be getRoot or getControlRoot.
4673   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4674                                       SDValue(Src.getNode(), Src.getResNo()));
4675   DAG.setRoot(CopyNode);
4676 }
4677 
4678 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4679   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4680          "call visitLoadFromSwiftError when backend supports swifterror");
4681 
4682   assert(!I.isVolatile() &&
4683          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4684          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4685          "Support volatile, non temporal, invariant for load_from_swift_error");
4686 
4687   const Value *SV = I.getOperand(0);
4688   Type *Ty = I.getType();
4689   assert(
4690       (!AA ||
4691        !AA->pointsToConstantMemory(MemoryLocation(
4692            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4693            I.getAAMetadata()))) &&
4694       "load_from_swift_error should not be constant memory");
4695 
4696   SmallVector<EVT, 4> ValueVTs;
4697   SmallVector<uint64_t, 4> Offsets;
4698   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4699                   ValueVTs, &Offsets, 0);
4700   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4701          "expect a single EVT for swifterror");
4702 
4703   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4704   SDValue L = DAG.getCopyFromReg(
4705       getRoot(), getCurSDLoc(),
4706       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4707 
4708   setValue(&I, L);
4709 }
4710 
4711 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4712   if (I.isAtomic())
4713     return visitAtomicStore(I);
4714 
4715   const Value *SrcV = I.getOperand(0);
4716   const Value *PtrV = I.getOperand(1);
4717 
4718   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4719   if (TLI.supportSwiftError()) {
4720     // Swifterror values can come from either a function parameter with
4721     // swifterror attribute or an alloca with swifterror attribute.
4722     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4723       if (Arg->hasSwiftErrorAttr())
4724         return visitStoreToSwiftError(I);
4725     }
4726 
4727     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4728       if (Alloca->isSwiftError())
4729         return visitStoreToSwiftError(I);
4730     }
4731   }
4732 
4733   SmallVector<EVT, 4> ValueVTs, MemVTs;
4734   SmallVector<TypeSize, 4> Offsets;
4735   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4736                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4737   unsigned NumValues = ValueVTs.size();
4738   if (NumValues == 0)
4739     return;
4740 
4741   // Get the lowered operands. Note that we do this after
4742   // checking if NumResults is zero, because with zero results
4743   // the operands won't have values in the map.
4744   SDValue Src = getValue(SrcV);
4745   SDValue Ptr = getValue(PtrV);
4746 
4747   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4748   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4749   SDLoc dl = getCurSDLoc();
4750   Align Alignment = I.getAlign();
4751   AAMDNodes AAInfo = I.getAAMetadata();
4752 
4753   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4754 
4755   unsigned ChainI = 0;
4756   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4757     // See visitLoad comments.
4758     if (ChainI == MaxParallelChains) {
4759       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4760                                   ArrayRef(Chains.data(), ChainI));
4761       Root = Chain;
4762       ChainI = 0;
4763     }
4764 
4765     // TODO: MachinePointerInfo only supports a fixed length offset.
4766     MachinePointerInfo PtrInfo =
4767         !Offsets[i].isScalable() || Offsets[i].isZero()
4768             ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue())
4769             : MachinePointerInfo();
4770 
4771     SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4772     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4773     if (MemVTs[i] != ValueVTs[i])
4774       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4775     SDValue St =
4776         DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags, AAInfo);
4777     Chains[ChainI] = St;
4778   }
4779 
4780   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4781                                   ArrayRef(Chains.data(), ChainI));
4782   setValue(&I, StoreNode);
4783   DAG.setRoot(StoreNode);
4784 }
4785 
4786 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4787                                            bool IsCompressing) {
4788   SDLoc sdl = getCurSDLoc();
4789 
4790   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4791                                Align &Alignment) {
4792     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4793     Src0 = I.getArgOperand(0);
4794     Ptr = I.getArgOperand(1);
4795     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getAlignValue();
4796     Mask = I.getArgOperand(3);
4797   };
4798   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4799                                     Align &Alignment) {
4800     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4801     Src0 = I.getArgOperand(0);
4802     Ptr = I.getArgOperand(1);
4803     Mask = I.getArgOperand(2);
4804     Alignment = I.getParamAlign(1).valueOrOne();
4805   };
4806 
4807   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4808   Align Alignment;
4809   if (IsCompressing)
4810     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4811   else
4812     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4813 
4814   SDValue Ptr = getValue(PtrOperand);
4815   SDValue Src0 = getValue(Src0Operand);
4816   SDValue Mask = getValue(MaskOperand);
4817   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4818 
4819   EVT VT = Src0.getValueType();
4820 
4821   auto MMOFlags = MachineMemOperand::MOStore;
4822   if (I.hasMetadata(LLVMContext::MD_nontemporal))
4823     MMOFlags |= MachineMemOperand::MONonTemporal;
4824 
4825   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4826       MachinePointerInfo(PtrOperand), MMOFlags,
4827       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata());
4828 
4829   const auto &TLI = DAG.getTargetLoweringInfo();
4830   const auto &TTI =
4831       TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction());
4832   SDValue StoreNode =
4833       !IsCompressing &&
4834               TTI.hasConditionalLoadStoreForType(I.getArgOperand(0)->getType())
4835           ? TLI.visitMaskedStore(DAG, sdl, getMemoryRoot(), MMO, Ptr, Src0,
4836                                  Mask)
4837           : DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask,
4838                                VT, MMO, ISD::UNINDEXED, /*Truncating=*/false,
4839                                IsCompressing);
4840   DAG.setRoot(StoreNode);
4841   setValue(&I, StoreNode);
4842 }
4843 
4844 // Get a uniform base for the Gather/Scatter intrinsic.
4845 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4846 // We try to represent it as a base pointer + vector of indices.
4847 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4848 // The first operand of the GEP may be a single pointer or a vector of pointers
4849 // Example:
4850 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4851 //  or
4852 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4853 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4854 //
4855 // When the first GEP operand is a single pointer - it is the uniform base we
4856 // are looking for. If first operand of the GEP is a splat vector - we
4857 // extract the splat value and use it as a uniform base.
4858 // In all other cases the function returns 'false'.
4859 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4860                            ISD::MemIndexType &IndexType, SDValue &Scale,
4861                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB,
4862                            uint64_t ElemSize) {
4863   SelectionDAG& DAG = SDB->DAG;
4864   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4865   const DataLayout &DL = DAG.getDataLayout();
4866 
4867   assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4868 
4869   // Handle splat constant pointer.
4870   if (auto *C = dyn_cast<Constant>(Ptr)) {
4871     C = C->getSplatValue();
4872     if (!C)
4873       return false;
4874 
4875     Base = SDB->getValue(C);
4876 
4877     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4878     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4879     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4880     IndexType = ISD::SIGNED_SCALED;
4881     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4882     return true;
4883   }
4884 
4885   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4886   if (!GEP || GEP->getParent() != CurBB)
4887     return false;
4888 
4889   if (GEP->getNumOperands() != 2)
4890     return false;
4891 
4892   const Value *BasePtr = GEP->getPointerOperand();
4893   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4894 
4895   // Make sure the base is scalar and the index is a vector.
4896   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4897     return false;
4898 
4899   TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
4900   if (ScaleVal.isScalable())
4901     return false;
4902 
4903   // Target may not support the required addressing mode.
4904   if (ScaleVal != 1 &&
4905       !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize))
4906     return false;
4907 
4908   Base = SDB->getValue(BasePtr);
4909   Index = SDB->getValue(IndexVal);
4910   IndexType = ISD::SIGNED_SCALED;
4911 
4912   Scale =
4913       DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4914   return true;
4915 }
4916 
4917 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4918   SDLoc sdl = getCurSDLoc();
4919 
4920   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4921   const Value *Ptr = I.getArgOperand(1);
4922   SDValue Src0 = getValue(I.getArgOperand(0));
4923   SDValue Mask = getValue(I.getArgOperand(3));
4924   EVT VT = Src0.getValueType();
4925   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4926                         ->getMaybeAlignValue()
4927                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4928   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4929 
4930   SDValue Base;
4931   SDValue Index;
4932   ISD::MemIndexType IndexType;
4933   SDValue Scale;
4934   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4935                                     I.getParent(), VT.getScalarStoreSize());
4936 
4937   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4938   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4939       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4940       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata());
4941   if (!UniformBase) {
4942     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4943     Index = getValue(Ptr);
4944     IndexType = ISD::SIGNED_SCALED;
4945     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4946   }
4947 
4948   EVT IdxVT = Index.getValueType();
4949   EVT EltTy = IdxVT.getVectorElementType();
4950   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4951     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4952     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4953   }
4954 
4955   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4956   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4957                                          Ops, MMO, IndexType, false);
4958   DAG.setRoot(Scatter);
4959   setValue(&I, Scatter);
4960 }
4961 
4962 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4963   SDLoc sdl = getCurSDLoc();
4964 
4965   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4966                               Align &Alignment) {
4967     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4968     Ptr = I.getArgOperand(0);
4969     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getAlignValue();
4970     Mask = I.getArgOperand(2);
4971     Src0 = I.getArgOperand(3);
4972   };
4973   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4974                                  Align &Alignment) {
4975     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4976     Ptr = I.getArgOperand(0);
4977     Alignment = I.getParamAlign(0).valueOrOne();
4978     Mask = I.getArgOperand(1);
4979     Src0 = I.getArgOperand(2);
4980   };
4981 
4982   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4983   Align Alignment;
4984   if (IsExpanding)
4985     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4986   else
4987     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4988 
4989   SDValue Ptr = getValue(PtrOperand);
4990   SDValue Src0 = getValue(Src0Operand);
4991   SDValue Mask = getValue(MaskOperand);
4992   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4993 
4994   EVT VT = Src0.getValueType();
4995   AAMDNodes AAInfo = I.getAAMetadata();
4996   const MDNode *Ranges = getRangeMetadata(I);
4997 
4998   // Do not serialize masked loads of constant memory with anything.
4999   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
5000   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
5001 
5002   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
5003 
5004   auto MMOFlags = MachineMemOperand::MOLoad;
5005   if (I.hasMetadata(LLVMContext::MD_nontemporal))
5006     MMOFlags |= MachineMemOperand::MONonTemporal;
5007 
5008   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5009       MachinePointerInfo(PtrOperand), MMOFlags,
5010       LocationSize::beforeOrAfterPointer(), Alignment, AAInfo, Ranges);
5011 
5012   const auto &TLI = DAG.getTargetLoweringInfo();
5013   const auto &TTI =
5014       TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction());
5015   // The Load/Res may point to different values and both of them are output
5016   // variables.
5017   SDValue Load;
5018   SDValue Res;
5019   if (!IsExpanding &&
5020       TTI.hasConditionalLoadStoreForType(Src0Operand->getType()))
5021     Res = TLI.visitMaskedLoad(DAG, sdl, InChain, MMO, Load, Ptr, Src0, Mask);
5022   else
5023     Res = Load =
5024         DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
5025                           ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
5026   if (AddToChain)
5027     PendingLoads.push_back(Load.getValue(1));
5028   setValue(&I, Res);
5029 }
5030 
5031 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
5032   SDLoc sdl = getCurSDLoc();
5033 
5034   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
5035   const Value *Ptr = I.getArgOperand(0);
5036   SDValue Src0 = getValue(I.getArgOperand(3));
5037   SDValue Mask = getValue(I.getArgOperand(2));
5038 
5039   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5040   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5041   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
5042                         ->getMaybeAlignValue()
5043                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
5044 
5045   const MDNode *Ranges = getRangeMetadata(I);
5046 
5047   SDValue Root = DAG.getRoot();
5048   SDValue Base;
5049   SDValue Index;
5050   ISD::MemIndexType IndexType;
5051   SDValue Scale;
5052   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
5053                                     I.getParent(), VT.getScalarStoreSize());
5054   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
5055   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5056       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
5057       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata(),
5058       Ranges);
5059 
5060   if (!UniformBase) {
5061     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5062     Index = getValue(Ptr);
5063     IndexType = ISD::SIGNED_SCALED;
5064     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5065   }
5066 
5067   EVT IdxVT = Index.getValueType();
5068   EVT EltTy = IdxVT.getVectorElementType();
5069   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
5070     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
5071     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
5072   }
5073 
5074   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
5075   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
5076                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
5077 
5078   PendingLoads.push_back(Gather.getValue(1));
5079   setValue(&I, Gather);
5080 }
5081 
5082 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
5083   SDLoc dl = getCurSDLoc();
5084   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
5085   AtomicOrdering FailureOrdering = I.getFailureOrdering();
5086   SyncScope::ID SSID = I.getSyncScopeID();
5087 
5088   SDValue InChain = getRoot();
5089 
5090   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
5091   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
5092 
5093   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5094   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5095 
5096   MachineFunction &MF = DAG.getMachineFunction();
5097   MachineMemOperand *MMO = MF.getMachineMemOperand(
5098       MachinePointerInfo(I.getPointerOperand()), Flags,
5099       LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT),
5100       AAMDNodes(), nullptr, SSID, SuccessOrdering, FailureOrdering);
5101 
5102   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
5103                                    dl, MemVT, VTs, InChain,
5104                                    getValue(I.getPointerOperand()),
5105                                    getValue(I.getCompareOperand()),
5106                                    getValue(I.getNewValOperand()), MMO);
5107 
5108   SDValue OutChain = L.getValue(2);
5109 
5110   setValue(&I, L);
5111   DAG.setRoot(OutChain);
5112 }
5113 
5114 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
5115   SDLoc dl = getCurSDLoc();
5116   ISD::NodeType NT;
5117   switch (I.getOperation()) {
5118   default: llvm_unreachable("Unknown atomicrmw operation");
5119   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
5120   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
5121   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
5122   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
5123   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
5124   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
5125   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
5126   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
5127   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
5128   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
5129   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
5130   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
5131   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
5132   case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break;
5133   case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break;
5134   case AtomicRMWInst::UIncWrap:
5135     NT = ISD::ATOMIC_LOAD_UINC_WRAP;
5136     break;
5137   case AtomicRMWInst::UDecWrap:
5138     NT = ISD::ATOMIC_LOAD_UDEC_WRAP;
5139     break;
5140   case AtomicRMWInst::USubCond:
5141     NT = ISD::ATOMIC_LOAD_USUB_COND;
5142     break;
5143   case AtomicRMWInst::USubSat:
5144     NT = ISD::ATOMIC_LOAD_USUB_SAT;
5145     break;
5146   }
5147   AtomicOrdering Ordering = I.getOrdering();
5148   SyncScope::ID SSID = I.getSyncScopeID();
5149 
5150   SDValue InChain = getRoot();
5151 
5152   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
5153   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5154   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5155 
5156   MachineFunction &MF = DAG.getMachineFunction();
5157   MachineMemOperand *MMO = MF.getMachineMemOperand(
5158       MachinePointerInfo(I.getPointerOperand()), Flags,
5159       LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT),
5160       AAMDNodes(), nullptr, SSID, Ordering);
5161 
5162   SDValue L =
5163     DAG.getAtomic(NT, dl, MemVT, InChain,
5164                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
5165                   MMO);
5166 
5167   SDValue OutChain = L.getValue(1);
5168 
5169   setValue(&I, L);
5170   DAG.setRoot(OutChain);
5171 }
5172 
5173 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
5174   SDLoc dl = getCurSDLoc();
5175   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5176   SDValue Ops[3];
5177   Ops[0] = getRoot();
5178   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
5179                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
5180   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
5181                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
5182   SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
5183   setValue(&I, N);
5184   DAG.setRoot(N);
5185 }
5186 
5187 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
5188   SDLoc dl = getCurSDLoc();
5189   AtomicOrdering Order = I.getOrdering();
5190   SyncScope::ID SSID = I.getSyncScopeID();
5191 
5192   SDValue InChain = getRoot();
5193 
5194   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5195   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5196   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
5197 
5198   if (!TLI.supportsUnalignedAtomics() &&
5199       I.getAlign().value() < MemVT.getSizeInBits() / 8)
5200     report_fatal_error("Cannot generate unaligned atomic load");
5201 
5202   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
5203 
5204   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5205       MachinePointerInfo(I.getPointerOperand()), Flags,
5206       LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(),
5207       nullptr, SSID, Order);
5208 
5209   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
5210 
5211   SDValue Ptr = getValue(I.getPointerOperand());
5212   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
5213                             Ptr, MMO);
5214 
5215   SDValue OutChain = L.getValue(1);
5216   if (MemVT != VT)
5217     L = DAG.getPtrExtOrTrunc(L, dl, VT);
5218 
5219   setValue(&I, L);
5220   DAG.setRoot(OutChain);
5221 }
5222 
5223 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
5224   SDLoc dl = getCurSDLoc();
5225 
5226   AtomicOrdering Ordering = I.getOrdering();
5227   SyncScope::ID SSID = I.getSyncScopeID();
5228 
5229   SDValue InChain = getRoot();
5230 
5231   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5232   EVT MemVT =
5233       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
5234 
5235   if (!TLI.supportsUnalignedAtomics() &&
5236       I.getAlign().value() < MemVT.getSizeInBits() / 8)
5237     report_fatal_error("Cannot generate unaligned atomic store");
5238 
5239   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
5240 
5241   MachineFunction &MF = DAG.getMachineFunction();
5242   MachineMemOperand *MMO = MF.getMachineMemOperand(
5243       MachinePointerInfo(I.getPointerOperand()), Flags,
5244       LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(),
5245       nullptr, SSID, Ordering);
5246 
5247   SDValue Val = getValue(I.getValueOperand());
5248   if (Val.getValueType() != MemVT)
5249     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
5250   SDValue Ptr = getValue(I.getPointerOperand());
5251 
5252   SDValue OutChain =
5253       DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO);
5254 
5255   setValue(&I, OutChain);
5256   DAG.setRoot(OutChain);
5257 }
5258 
5259 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
5260 /// node.
5261 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
5262                                                unsigned Intrinsic) {
5263   // Ignore the callsite's attributes. A specific call site may be marked with
5264   // readnone, but the lowering code will expect the chain based on the
5265   // definition.
5266   const Function *F = I.getCalledFunction();
5267   bool HasChain = !F->doesNotAccessMemory();
5268   bool OnlyLoad =
5269       HasChain && F->onlyReadsMemory() && F->willReturn() && F->doesNotThrow();
5270 
5271   // Build the operand list.
5272   SmallVector<SDValue, 8> Ops;
5273   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
5274     if (OnlyLoad) {
5275       // We don't need to serialize loads against other loads.
5276       Ops.push_back(DAG.getRoot());
5277     } else {
5278       Ops.push_back(getRoot());
5279     }
5280   }
5281 
5282   // Info is set by getTgtMemIntrinsic
5283   TargetLowering::IntrinsicInfo Info;
5284   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5285   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
5286                                                DAG.getMachineFunction(),
5287                                                Intrinsic);
5288 
5289   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
5290   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
5291       Info.opc == ISD::INTRINSIC_W_CHAIN)
5292     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
5293                                         TLI.getPointerTy(DAG.getDataLayout())));
5294 
5295   // Add all operands of the call to the operand list.
5296   for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
5297     const Value *Arg = I.getArgOperand(i);
5298     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
5299       Ops.push_back(getValue(Arg));
5300       continue;
5301     }
5302 
5303     // Use TargetConstant instead of a regular constant for immarg.
5304     EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
5305     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
5306       assert(CI->getBitWidth() <= 64 &&
5307              "large intrinsic immediates not handled");
5308       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
5309     } else {
5310       Ops.push_back(
5311           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
5312     }
5313   }
5314 
5315   SmallVector<EVT, 4> ValueVTs;
5316   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
5317 
5318   if (HasChain)
5319     ValueVTs.push_back(MVT::Other);
5320 
5321   SDVTList VTs = DAG.getVTList(ValueVTs);
5322 
5323   // Propagate fast-math-flags from IR to node(s).
5324   SDNodeFlags Flags;
5325   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
5326     Flags.copyFMF(*FPMO);
5327   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
5328 
5329   // Create the node.
5330   SDValue Result;
5331 
5332   if (auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl)) {
5333     auto *Token = Bundle->Inputs[0].get();
5334     SDValue ConvControlToken = getValue(Token);
5335     assert(Ops.back().getValueType() != MVT::Glue &&
5336            "Did not expected another glue node here.");
5337     ConvControlToken =
5338         DAG.getNode(ISD::CONVERGENCECTRL_GLUE, {}, MVT::Glue, ConvControlToken);
5339     Ops.push_back(ConvControlToken);
5340   }
5341 
5342   // In some cases, custom collection of operands from CallInst I may be needed.
5343   TLI.CollectTargetIntrinsicOperands(I, Ops, DAG);
5344   if (IsTgtIntrinsic) {
5345     // This is target intrinsic that touches memory
5346     //
5347     // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic
5348     //       didn't yield anything useful.
5349     MachinePointerInfo MPI;
5350     if (Info.ptrVal)
5351       MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
5352     else if (Info.fallbackAddressSpace)
5353       MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
5354     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops,
5355                                      Info.memVT, MPI, Info.align, Info.flags,
5356                                      Info.size, I.getAAMetadata());
5357   } else if (!HasChain) {
5358     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
5359   } else if (!I.getType()->isVoidTy()) {
5360     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
5361   } else {
5362     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
5363   }
5364 
5365   if (HasChain) {
5366     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
5367     if (OnlyLoad)
5368       PendingLoads.push_back(Chain);
5369     else
5370       DAG.setRoot(Chain);
5371   }
5372 
5373   if (!I.getType()->isVoidTy()) {
5374     if (!isa<VectorType>(I.getType()))
5375       Result = lowerRangeToAssertZExt(DAG, I, Result);
5376 
5377     MaybeAlign Alignment = I.getRetAlign();
5378 
5379     // Insert `assertalign` node if there's an alignment.
5380     if (InsertAssertAlign && Alignment) {
5381       Result =
5382           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
5383     }
5384   }
5385 
5386   setValue(&I, Result);
5387 }
5388 
5389 /// GetSignificand - Get the significand and build it into a floating-point
5390 /// number with exponent of 1:
5391 ///
5392 ///   Op = (Op & 0x007fffff) | 0x3f800000;
5393 ///
5394 /// where Op is the hexadecimal representation of floating point value.
5395 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
5396   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5397                            DAG.getConstant(0x007fffff, dl, MVT::i32));
5398   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
5399                            DAG.getConstant(0x3f800000, dl, MVT::i32));
5400   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
5401 }
5402 
5403 /// GetExponent - Get the exponent:
5404 ///
5405 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
5406 ///
5407 /// where Op is the hexadecimal representation of floating point value.
5408 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
5409                            const TargetLowering &TLI, const SDLoc &dl) {
5410   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5411                            DAG.getConstant(0x7f800000, dl, MVT::i32));
5412   SDValue t1 = DAG.getNode(
5413       ISD::SRL, dl, MVT::i32, t0,
5414       DAG.getConstant(23, dl,
5415                       TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout())));
5416   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
5417                            DAG.getConstant(127, dl, MVT::i32));
5418   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
5419 }
5420 
5421 /// getF32Constant - Get 32-bit floating point constant.
5422 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
5423                               const SDLoc &dl) {
5424   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
5425                            MVT::f32);
5426 }
5427 
5428 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
5429                                        SelectionDAG &DAG) {
5430   // TODO: What fast-math-flags should be set on the floating-point nodes?
5431 
5432   //   IntegerPartOfX = ((int32_t)(t0);
5433   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
5434 
5435   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
5436   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
5437   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
5438 
5439   //   IntegerPartOfX <<= 23;
5440   IntegerPartOfX =
5441       DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
5442                   DAG.getConstant(23, dl,
5443                                   DAG.getTargetLoweringInfo().getShiftAmountTy(
5444                                       MVT::i32, DAG.getDataLayout())));
5445 
5446   SDValue TwoToFractionalPartOfX;
5447   if (LimitFloatPrecision <= 6) {
5448     // For floating-point precision of 6:
5449     //
5450     //   TwoToFractionalPartOfX =
5451     //     0.997535578f +
5452     //       (0.735607626f + 0.252464424f * x) * x;
5453     //
5454     // error 0.0144103317, which is 6 bits
5455     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5456                              getF32Constant(DAG, 0x3e814304, dl));
5457     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5458                              getF32Constant(DAG, 0x3f3c50c8, dl));
5459     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5460     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5461                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
5462   } else if (LimitFloatPrecision <= 12) {
5463     // For floating-point precision of 12:
5464     //
5465     //   TwoToFractionalPartOfX =
5466     //     0.999892986f +
5467     //       (0.696457318f +
5468     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
5469     //
5470     // error 0.000107046256, which is 13 to 14 bits
5471     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5472                              getF32Constant(DAG, 0x3da235e3, dl));
5473     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5474                              getF32Constant(DAG, 0x3e65b8f3, dl));
5475     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5476     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5477                              getF32Constant(DAG, 0x3f324b07, dl));
5478     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5479     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5480                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
5481   } else { // LimitFloatPrecision <= 18
5482     // For floating-point precision of 18:
5483     //
5484     //   TwoToFractionalPartOfX =
5485     //     0.999999982f +
5486     //       (0.693148872f +
5487     //         (0.240227044f +
5488     //           (0.554906021e-1f +
5489     //             (0.961591928e-2f +
5490     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5491     // error 2.47208000*10^(-7), which is better than 18 bits
5492     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5493                              getF32Constant(DAG, 0x3924b03e, dl));
5494     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5495                              getF32Constant(DAG, 0x3ab24b87, dl));
5496     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5497     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5498                              getF32Constant(DAG, 0x3c1d8c17, dl));
5499     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5500     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5501                              getF32Constant(DAG, 0x3d634a1d, dl));
5502     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5503     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5504                              getF32Constant(DAG, 0x3e75fe14, dl));
5505     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5506     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5507                               getF32Constant(DAG, 0x3f317234, dl));
5508     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5509     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5510                                          getF32Constant(DAG, 0x3f800000, dl));
5511   }
5512 
5513   // Add the exponent into the result in integer domain.
5514   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5515   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5516                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5517 }
5518 
5519 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5520 /// limited-precision mode.
5521 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5522                          const TargetLowering &TLI, SDNodeFlags Flags) {
5523   if (Op.getValueType() == MVT::f32 &&
5524       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5525 
5526     // Put the exponent in the right bit position for later addition to the
5527     // final result:
5528     //
5529     // t0 = Op * log2(e)
5530 
5531     // TODO: What fast-math-flags should be set here?
5532     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5533                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5534     return getLimitedPrecisionExp2(t0, dl, DAG);
5535   }
5536 
5537   // No special expansion.
5538   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5539 }
5540 
5541 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5542 /// limited-precision mode.
5543 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5544                          const TargetLowering &TLI, SDNodeFlags Flags) {
5545   // TODO: What fast-math-flags should be set on the floating-point nodes?
5546 
5547   if (Op.getValueType() == MVT::f32 &&
5548       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5549     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5550 
5551     // Scale the exponent by log(2).
5552     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5553     SDValue LogOfExponent =
5554         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5555                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5556 
5557     // Get the significand and build it into a floating-point number with
5558     // exponent of 1.
5559     SDValue X = GetSignificand(DAG, Op1, dl);
5560 
5561     SDValue LogOfMantissa;
5562     if (LimitFloatPrecision <= 6) {
5563       // For floating-point precision of 6:
5564       //
5565       //   LogofMantissa =
5566       //     -1.1609546f +
5567       //       (1.4034025f - 0.23903021f * x) * x;
5568       //
5569       // error 0.0034276066, which is better than 8 bits
5570       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5571                                getF32Constant(DAG, 0xbe74c456, dl));
5572       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5573                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5574       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5575       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5576                                   getF32Constant(DAG, 0x3f949a29, dl));
5577     } else if (LimitFloatPrecision <= 12) {
5578       // For floating-point precision of 12:
5579       //
5580       //   LogOfMantissa =
5581       //     -1.7417939f +
5582       //       (2.8212026f +
5583       //         (-1.4699568f +
5584       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5585       //
5586       // error 0.000061011436, which is 14 bits
5587       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5588                                getF32Constant(DAG, 0xbd67b6d6, dl));
5589       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5590                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5591       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5592       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5593                                getF32Constant(DAG, 0x3fbc278b, dl));
5594       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5595       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5596                                getF32Constant(DAG, 0x40348e95, dl));
5597       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5598       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5599                                   getF32Constant(DAG, 0x3fdef31a, dl));
5600     } else { // LimitFloatPrecision <= 18
5601       // For floating-point precision of 18:
5602       //
5603       //   LogOfMantissa =
5604       //     -2.1072184f +
5605       //       (4.2372794f +
5606       //         (-3.7029485f +
5607       //           (2.2781945f +
5608       //             (-0.87823314f +
5609       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5610       //
5611       // error 0.0000023660568, which is better than 18 bits
5612       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5613                                getF32Constant(DAG, 0xbc91e5ac, dl));
5614       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5615                                getF32Constant(DAG, 0x3e4350aa, dl));
5616       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5617       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5618                                getF32Constant(DAG, 0x3f60d3e3, dl));
5619       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5620       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5621                                getF32Constant(DAG, 0x4011cdf0, dl));
5622       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5623       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5624                                getF32Constant(DAG, 0x406cfd1c, dl));
5625       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5626       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5627                                getF32Constant(DAG, 0x408797cb, dl));
5628       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5629       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5630                                   getF32Constant(DAG, 0x4006dcab, dl));
5631     }
5632 
5633     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5634   }
5635 
5636   // No special expansion.
5637   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5638 }
5639 
5640 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5641 /// limited-precision mode.
5642 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5643                           const TargetLowering &TLI, SDNodeFlags Flags) {
5644   // TODO: What fast-math-flags should be set on the floating-point nodes?
5645 
5646   if (Op.getValueType() == MVT::f32 &&
5647       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5648     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5649 
5650     // Get the exponent.
5651     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5652 
5653     // Get the significand and build it into a floating-point number with
5654     // exponent of 1.
5655     SDValue X = GetSignificand(DAG, Op1, dl);
5656 
5657     // Different possible minimax approximations of significand in
5658     // floating-point for various degrees of accuracy over [1,2].
5659     SDValue Log2ofMantissa;
5660     if (LimitFloatPrecision <= 6) {
5661       // For floating-point precision of 6:
5662       //
5663       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5664       //
5665       // error 0.0049451742, which is more than 7 bits
5666       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5667                                getF32Constant(DAG, 0xbeb08fe0, dl));
5668       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5669                                getF32Constant(DAG, 0x40019463, dl));
5670       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5671       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5672                                    getF32Constant(DAG, 0x3fd6633d, dl));
5673     } else if (LimitFloatPrecision <= 12) {
5674       // For floating-point precision of 12:
5675       //
5676       //   Log2ofMantissa =
5677       //     -2.51285454f +
5678       //       (4.07009056f +
5679       //         (-2.12067489f +
5680       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5681       //
5682       // error 0.0000876136000, which is better than 13 bits
5683       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5684                                getF32Constant(DAG, 0xbda7262e, dl));
5685       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5686                                getF32Constant(DAG, 0x3f25280b, 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, 0x4007b923, 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, 0x40823e2f, dl));
5693       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5694       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5695                                    getF32Constant(DAG, 0x4020d29c, dl));
5696     } else { // LimitFloatPrecision <= 18
5697       // For floating-point precision of 18:
5698       //
5699       //   Log2ofMantissa =
5700       //     -3.0400495f +
5701       //       (6.1129976f +
5702       //         (-5.3420409f +
5703       //           (3.2865683f +
5704       //             (-1.2669343f +
5705       //               (0.27515199f -
5706       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5707       //
5708       // error 0.0000018516, which is better than 18 bits
5709       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5710                                getF32Constant(DAG, 0xbcd2769e, dl));
5711       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5712                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5713       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5714       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5715                                getF32Constant(DAG, 0x3fa22ae7, dl));
5716       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5717       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5718                                getF32Constant(DAG, 0x40525723, dl));
5719       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5720       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5721                                getF32Constant(DAG, 0x40aaf200, dl));
5722       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5723       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5724                                getF32Constant(DAG, 0x40c39dad, dl));
5725       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5726       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5727                                    getF32Constant(DAG, 0x4042902c, dl));
5728     }
5729 
5730     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5731   }
5732 
5733   // No special expansion.
5734   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5735 }
5736 
5737 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5738 /// limited-precision mode.
5739 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5740                            const TargetLowering &TLI, SDNodeFlags Flags) {
5741   // TODO: What fast-math-flags should be set on the floating-point nodes?
5742 
5743   if (Op.getValueType() == MVT::f32 &&
5744       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5745     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5746 
5747     // Scale the exponent by log10(2) [0.30102999f].
5748     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5749     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5750                                         getF32Constant(DAG, 0x3e9a209a, dl));
5751 
5752     // Get the significand and build it into a floating-point number with
5753     // exponent of 1.
5754     SDValue X = GetSignificand(DAG, Op1, dl);
5755 
5756     SDValue Log10ofMantissa;
5757     if (LimitFloatPrecision <= 6) {
5758       // For floating-point precision of 6:
5759       //
5760       //   Log10ofMantissa =
5761       //     -0.50419619f +
5762       //       (0.60948995f - 0.10380950f * x) * x;
5763       //
5764       // error 0.0014886165, which is 6 bits
5765       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5766                                getF32Constant(DAG, 0xbdd49a13, dl));
5767       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5768                                getF32Constant(DAG, 0x3f1c0789, dl));
5769       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5770       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5771                                     getF32Constant(DAG, 0x3f011300, dl));
5772     } else if (LimitFloatPrecision <= 12) {
5773       // For floating-point precision of 12:
5774       //
5775       //   Log10ofMantissa =
5776       //     -0.64831180f +
5777       //       (0.91751397f +
5778       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5779       //
5780       // error 0.00019228036, which is better than 12 bits
5781       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5782                                getF32Constant(DAG, 0x3d431f31, dl));
5783       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5784                                getF32Constant(DAG, 0x3ea21fb2, dl));
5785       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5786       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5787                                getF32Constant(DAG, 0x3f6ae232, dl));
5788       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5789       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5790                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5791     } else { // LimitFloatPrecision <= 18
5792       // For floating-point precision of 18:
5793       //
5794       //   Log10ofMantissa =
5795       //     -0.84299375f +
5796       //       (1.5327582f +
5797       //         (-1.0688956f +
5798       //           (0.49102474f +
5799       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5800       //
5801       // error 0.0000037995730, which is better than 18 bits
5802       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5803                                getF32Constant(DAG, 0x3c5d51ce, dl));
5804       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5805                                getF32Constant(DAG, 0x3e00685a, dl));
5806       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5807       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5808                                getF32Constant(DAG, 0x3efb6798, dl));
5809       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5810       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5811                                getF32Constant(DAG, 0x3f88d192, dl));
5812       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5813       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5814                                getF32Constant(DAG, 0x3fc4316c, dl));
5815       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5816       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5817                                     getF32Constant(DAG, 0x3f57ce70, dl));
5818     }
5819 
5820     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5821   }
5822 
5823   // No special expansion.
5824   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5825 }
5826 
5827 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5828 /// limited-precision mode.
5829 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5830                           const TargetLowering &TLI, SDNodeFlags Flags) {
5831   if (Op.getValueType() == MVT::f32 &&
5832       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5833     return getLimitedPrecisionExp2(Op, dl, DAG);
5834 
5835   // No special expansion.
5836   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5837 }
5838 
5839 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5840 /// limited-precision mode with x == 10.0f.
5841 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5842                          SelectionDAG &DAG, const TargetLowering &TLI,
5843                          SDNodeFlags Flags) {
5844   bool IsExp10 = false;
5845   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5846       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5847     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5848       APFloat Ten(10.0f);
5849       IsExp10 = LHSC->isExactlyValue(Ten);
5850     }
5851   }
5852 
5853   // TODO: What fast-math-flags should be set on the FMUL node?
5854   if (IsExp10) {
5855     // Put the exponent in the right bit position for later addition to the
5856     // final result:
5857     //
5858     //   #define LOG2OF10 3.3219281f
5859     //   t0 = Op * LOG2OF10;
5860     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5861                              getF32Constant(DAG, 0x40549a78, dl));
5862     return getLimitedPrecisionExp2(t0, dl, DAG);
5863   }
5864 
5865   // No special expansion.
5866   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5867 }
5868 
5869 /// ExpandPowI - Expand a llvm.powi intrinsic.
5870 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5871                           SelectionDAG &DAG) {
5872   // If RHS is a constant, we can expand this out to a multiplication tree if
5873   // it's beneficial on the target, otherwise we end up lowering to a call to
5874   // __powidf2 (for example).
5875   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5876     unsigned Val = RHSC->getSExtValue();
5877 
5878     // powi(x, 0) -> 1.0
5879     if (Val == 0)
5880       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5881 
5882     if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI(
5883             Val, DAG.shouldOptForSize())) {
5884       // Get the exponent as a positive value.
5885       if ((int)Val < 0)
5886         Val = -Val;
5887       // We use the simple binary decomposition method to generate the multiply
5888       // sequence.  There are more optimal ways to do this (for example,
5889       // powi(x,15) generates one more multiply than it should), but this has
5890       // the benefit of being both really simple and much better than a libcall.
5891       SDValue Res; // Logically starts equal to 1.0
5892       SDValue CurSquare = LHS;
5893       // TODO: Intrinsics should have fast-math-flags that propagate to these
5894       // nodes.
5895       while (Val) {
5896         if (Val & 1) {
5897           if (Res.getNode())
5898             Res =
5899                 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
5900           else
5901             Res = CurSquare; // 1.0*CurSquare.
5902         }
5903 
5904         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5905                                 CurSquare, CurSquare);
5906         Val >>= 1;
5907       }
5908 
5909       // If the original was negative, invert the result, producing 1/(x*x*x).
5910       if (RHSC->getSExtValue() < 0)
5911         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5912                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5913       return Res;
5914     }
5915   }
5916 
5917   // Otherwise, expand to a libcall.
5918   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5919 }
5920 
5921 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5922                             SDValue LHS, SDValue RHS, SDValue Scale,
5923                             SelectionDAG &DAG, const TargetLowering &TLI) {
5924   EVT VT = LHS.getValueType();
5925   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5926   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5927   LLVMContext &Ctx = *DAG.getContext();
5928 
5929   // If the type is legal but the operation isn't, this node might survive all
5930   // the way to operation legalization. If we end up there and we do not have
5931   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5932   // node.
5933 
5934   // Coax the legalizer into expanding the node during type legalization instead
5935   // by bumping the size by one bit. This will force it to Promote, enabling the
5936   // early expansion and avoiding the need to expand later.
5937 
5938   // We don't have to do this if Scale is 0; that can always be expanded, unless
5939   // it's a saturating signed operation. Those can experience true integer
5940   // division overflow, a case which we must avoid.
5941 
5942   // FIXME: We wouldn't have to do this (or any of the early
5943   // expansion/promotion) if it was possible to expand a libcall of an
5944   // illegal type during operation legalization. But it's not, so things
5945   // get a bit hacky.
5946   unsigned ScaleInt = Scale->getAsZExtVal();
5947   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5948       (TLI.isTypeLegal(VT) ||
5949        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5950     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5951         Opcode, VT, ScaleInt);
5952     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5953       EVT PromVT;
5954       if (VT.isScalarInteger())
5955         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5956       else if (VT.isVector()) {
5957         PromVT = VT.getVectorElementType();
5958         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5959         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5960       } else
5961         llvm_unreachable("Wrong VT for DIVFIX?");
5962       LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT);
5963       RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT);
5964       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5965       // For saturating operations, we need to shift up the LHS to get the
5966       // proper saturation width, and then shift down again afterwards.
5967       if (Saturating)
5968         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5969                           DAG.getConstant(1, DL, ShiftTy));
5970       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5971       if (Saturating)
5972         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5973                           DAG.getConstant(1, DL, ShiftTy));
5974       return DAG.getZExtOrTrunc(Res, DL, VT);
5975     }
5976   }
5977 
5978   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5979 }
5980 
5981 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5982 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5983 static void
5984 getUnderlyingArgRegs(SmallVectorImpl<std::pair<Register, TypeSize>> &Regs,
5985                      const SDValue &N) {
5986   switch (N.getOpcode()) {
5987   case ISD::CopyFromReg: {
5988     SDValue Op = N.getOperand(1);
5989     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5990                       Op.getValueType().getSizeInBits());
5991     return;
5992   }
5993   case ISD::BITCAST:
5994   case ISD::AssertZext:
5995   case ISD::AssertSext:
5996   case ISD::TRUNCATE:
5997     getUnderlyingArgRegs(Regs, N.getOperand(0));
5998     return;
5999   case ISD::BUILD_PAIR:
6000   case ISD::BUILD_VECTOR:
6001   case ISD::CONCAT_VECTORS:
6002     for (SDValue Op : N->op_values())
6003       getUnderlyingArgRegs(Regs, Op);
6004     return;
6005   default:
6006     return;
6007   }
6008 }
6009 
6010 /// If the DbgValueInst is a dbg_value of a function argument, create the
6011 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
6012 /// instruction selection, they will be inserted to the entry BB.
6013 /// We don't currently support this for variadic dbg_values, as they shouldn't
6014 /// appear for function arguments or in the prologue.
6015 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
6016     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
6017     DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
6018   const Argument *Arg = dyn_cast<Argument>(V);
6019   if (!Arg)
6020     return false;
6021 
6022   MachineFunction &MF = DAG.getMachineFunction();
6023   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6024 
6025   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
6026   // we've been asked to pursue.
6027   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
6028                               bool Indirect) {
6029     if (Reg.isVirtual() && MF.useDebugInstrRef()) {
6030       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
6031       // pointing at the VReg, which will be patched up later.
6032       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
6033       SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg(
6034           /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
6035           /* isKill */ false, /* isDead */ false,
6036           /* isUndef */ false, /* isEarlyClobber */ false,
6037           /* SubReg */ 0, /* isDebug */ true)});
6038 
6039       auto *NewDIExpr = FragExpr;
6040       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
6041       // the DIExpression.
6042       if (Indirect)
6043         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
6044       SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0});
6045       NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops);
6046       return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr);
6047     } else {
6048       // Create a completely standard DBG_VALUE.
6049       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
6050       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
6051     }
6052   };
6053 
6054   if (Kind == FuncArgumentDbgValueKind::Value) {
6055     // ArgDbgValues are hoisted to the beginning of the entry block. So we
6056     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
6057     // the entry block.
6058     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
6059     if (!IsInEntryBlock)
6060       return false;
6061 
6062     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
6063     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
6064     // variable that also is a param.
6065     //
6066     // Although, if we are at the top of the entry block already, we can still
6067     // emit using ArgDbgValue. This might catch some situations when the
6068     // dbg.value refers to an argument that isn't used in the entry block, so
6069     // any CopyToReg node would be optimized out and the only way to express
6070     // this DBG_VALUE is by using the physical reg (or FI) as done in this
6071     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
6072     // we should only emit as ArgDbgValue if the Variable is an argument to the
6073     // current function, and the dbg.value intrinsic is found in the entry
6074     // block.
6075     bool VariableIsFunctionInputArg = Variable->isParameter() &&
6076         !DL->getInlinedAt();
6077     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
6078     if (!IsInPrologue && !VariableIsFunctionInputArg)
6079       return false;
6080 
6081     // Here we assume that a function argument on IR level only can be used to
6082     // describe one input parameter on source level. If we for example have
6083     // source code like this
6084     //
6085     //    struct A { long x, y; };
6086     //    void foo(struct A a, long b) {
6087     //      ...
6088     //      b = a.x;
6089     //      ...
6090     //    }
6091     //
6092     // and IR like this
6093     //
6094     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
6095     //  entry:
6096     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
6097     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
6098     //    call void @llvm.dbg.value(metadata i32 %b, "b",
6099     //    ...
6100     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
6101     //    ...
6102     //
6103     // then the last dbg.value is describing a parameter "b" using a value that
6104     // is an argument. But since we already has used %a1 to describe a parameter
6105     // we should not handle that last dbg.value here (that would result in an
6106     // incorrect hoisting of the DBG_VALUE to the function entry).
6107     // Notice that we allow one dbg.value per IR level argument, to accommodate
6108     // for the situation with fragments above.
6109     // If there is no node for the value being handled, we return true to skip
6110     // the normal generation of debug info, as it would kill existing debug
6111     // info for the parameter in case of duplicates.
6112     if (VariableIsFunctionInputArg) {
6113       unsigned ArgNo = Arg->getArgNo();
6114       if (ArgNo >= FuncInfo.DescribedArgs.size())
6115         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
6116       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
6117         return !NodeMap[V].getNode();
6118       FuncInfo.DescribedArgs.set(ArgNo);
6119     }
6120   }
6121 
6122   bool IsIndirect = false;
6123   std::optional<MachineOperand> Op;
6124   // Some arguments' frame index is recorded during argument lowering.
6125   int FI = FuncInfo.getArgumentFrameIndex(Arg);
6126   if (FI != std::numeric_limits<int>::max())
6127     Op = MachineOperand::CreateFI(FI);
6128 
6129   SmallVector<std::pair<Register, TypeSize>, 8> ArgRegsAndSizes;
6130   if (!Op && N.getNode()) {
6131     getUnderlyingArgRegs(ArgRegsAndSizes, N);
6132     Register Reg;
6133     if (ArgRegsAndSizes.size() == 1)
6134       Reg = ArgRegsAndSizes.front().first;
6135 
6136     if (Reg && Reg.isVirtual()) {
6137       MachineRegisterInfo &RegInfo = MF.getRegInfo();
6138       Register PR = RegInfo.getLiveInPhysReg(Reg);
6139       if (PR)
6140         Reg = PR;
6141     }
6142     if (Reg) {
6143       Op = MachineOperand::CreateReg(Reg, false);
6144       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6145     }
6146   }
6147 
6148   if (!Op && N.getNode()) {
6149     // Check if frame index is available.
6150     SDValue LCandidate = peekThroughBitcasts(N);
6151     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
6152       if (FrameIndexSDNode *FINode =
6153           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
6154         Op = MachineOperand::CreateFI(FINode->getIndex());
6155   }
6156 
6157   if (!Op) {
6158     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
6159     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<Register, TypeSize>>
6160                                          SplitRegs) {
6161       unsigned Offset = 0;
6162       for (const auto &RegAndSize : SplitRegs) {
6163         // If the expression is already a fragment, the current register
6164         // offset+size might extend beyond the fragment. In this case, only
6165         // the register bits that are inside the fragment are relevant.
6166         int RegFragmentSizeInBits = RegAndSize.second;
6167         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
6168           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
6169           // The register is entirely outside the expression fragment,
6170           // so is irrelevant for debug info.
6171           if (Offset >= ExprFragmentSizeInBits)
6172             break;
6173           // The register is partially outside the expression fragment, only
6174           // the low bits within the fragment are relevant for debug info.
6175           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
6176             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
6177           }
6178         }
6179 
6180         auto FragmentExpr = DIExpression::createFragmentExpression(
6181             Expr, Offset, RegFragmentSizeInBits);
6182         Offset += RegAndSize.second;
6183         // If a valid fragment expression cannot be created, the variable's
6184         // correct value cannot be determined and so it is set as Undef.
6185         if (!FragmentExpr) {
6186           SDDbgValue *SDV = DAG.getConstantDbgValue(
6187               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
6188           DAG.AddDbgValue(SDV, false);
6189           continue;
6190         }
6191         MachineInstr *NewMI =
6192             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr,
6193                              Kind != FuncArgumentDbgValueKind::Value);
6194         FuncInfo.ArgDbgValues.push_back(NewMI);
6195       }
6196     };
6197 
6198     // Check if ValueMap has reg number.
6199     DenseMap<const Value *, Register>::const_iterator
6200       VMI = FuncInfo.ValueMap.find(V);
6201     if (VMI != FuncInfo.ValueMap.end()) {
6202       const auto &TLI = DAG.getTargetLoweringInfo();
6203       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
6204                        V->getType(), std::nullopt);
6205       if (RFV.occupiesMultipleRegs()) {
6206         splitMultiRegDbgValue(RFV.getRegsAndSizes());
6207         return true;
6208       }
6209 
6210       Op = MachineOperand::CreateReg(VMI->second, false);
6211       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6212     } else if (ArgRegsAndSizes.size() > 1) {
6213       // This was split due to the calling convention, and no virtual register
6214       // mapping exists for the value.
6215       splitMultiRegDbgValue(ArgRegsAndSizes);
6216       return true;
6217     }
6218   }
6219 
6220   if (!Op)
6221     return false;
6222 
6223   assert(Variable->isValidLocationForIntrinsic(DL) &&
6224          "Expected inlined-at fields to agree");
6225   MachineInstr *NewMI = nullptr;
6226 
6227   if (Op->isReg())
6228     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
6229   else
6230     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
6231                     Variable, Expr);
6232 
6233   // Otherwise, use ArgDbgValues.
6234   FuncInfo.ArgDbgValues.push_back(NewMI);
6235   return true;
6236 }
6237 
6238 /// Return the appropriate SDDbgValue based on N.
6239 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
6240                                              DILocalVariable *Variable,
6241                                              DIExpression *Expr,
6242                                              const DebugLoc &dl,
6243                                              unsigned DbgSDNodeOrder) {
6244   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
6245     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
6246     // stack slot locations.
6247     //
6248     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
6249     // debug values here after optimization:
6250     //
6251     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
6252     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
6253     //
6254     // Both describe the direct values of their associated variables.
6255     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
6256                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6257   }
6258   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
6259                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6260 }
6261 
6262 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
6263   switch (Intrinsic) {
6264   case Intrinsic::smul_fix:
6265     return ISD::SMULFIX;
6266   case Intrinsic::umul_fix:
6267     return ISD::UMULFIX;
6268   case Intrinsic::smul_fix_sat:
6269     return ISD::SMULFIXSAT;
6270   case Intrinsic::umul_fix_sat:
6271     return ISD::UMULFIXSAT;
6272   case Intrinsic::sdiv_fix:
6273     return ISD::SDIVFIX;
6274   case Intrinsic::udiv_fix:
6275     return ISD::UDIVFIX;
6276   case Intrinsic::sdiv_fix_sat:
6277     return ISD::SDIVFIXSAT;
6278   case Intrinsic::udiv_fix_sat:
6279     return ISD::UDIVFIXSAT;
6280   default:
6281     llvm_unreachable("Unhandled fixed point intrinsic");
6282   }
6283 }
6284 
6285 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
6286                                            const char *FunctionName) {
6287   assert(FunctionName && "FunctionName must not be nullptr");
6288   SDValue Callee = DAG.getExternalSymbol(
6289       FunctionName,
6290       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6291   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
6292 }
6293 
6294 /// Given a @llvm.call.preallocated.setup, return the corresponding
6295 /// preallocated call.
6296 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
6297   assert(cast<CallBase>(PreallocatedSetup)
6298                  ->getCalledFunction()
6299                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
6300          "expected call_preallocated_setup Value");
6301   for (const auto *U : PreallocatedSetup->users()) {
6302     auto *UseCall = cast<CallBase>(U);
6303     const Function *Fn = UseCall->getCalledFunction();
6304     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
6305       return UseCall;
6306     }
6307   }
6308   llvm_unreachable("expected corresponding call to preallocated setup/arg");
6309 }
6310 
6311 /// If DI is a debug value with an EntryValue expression, lower it using the
6312 /// corresponding physical register of the associated Argument value
6313 /// (guaranteed to exist by the verifier).
6314 bool SelectionDAGBuilder::visitEntryValueDbgValue(
6315     ArrayRef<const Value *> Values, DILocalVariable *Variable,
6316     DIExpression *Expr, DebugLoc DbgLoc) {
6317   if (!Expr->isEntryValue() || !hasSingleElement(Values))
6318     return false;
6319 
6320   // These properties are guaranteed by the verifier.
6321   const Argument *Arg = cast<Argument>(Values[0]);
6322   assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync));
6323 
6324   auto ArgIt = FuncInfo.ValueMap.find(Arg);
6325   if (ArgIt == FuncInfo.ValueMap.end()) {
6326     LLVM_DEBUG(
6327         dbgs() << "Dropping dbg.value: expression is entry_value but "
6328                   "couldn't find an associated register for the Argument\n");
6329     return true;
6330   }
6331   Register ArgVReg = ArgIt->getSecond();
6332 
6333   for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
6334     if (ArgVReg == VirtReg || ArgVReg == PhysReg) {
6335       SDDbgValue *SDV = DAG.getVRegDbgValue(
6336           Variable, Expr, PhysReg, false /*IsIndidrect*/, DbgLoc, SDNodeOrder);
6337       DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/);
6338       return true;
6339     }
6340   LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but "
6341                        "couldn't find a physical register\n");
6342   return true;
6343 }
6344 
6345 /// Lower the call to the specified intrinsic function.
6346 void SelectionDAGBuilder::visitConvergenceControl(const CallInst &I,
6347                                                   unsigned Intrinsic) {
6348   SDLoc sdl = getCurSDLoc();
6349   switch (Intrinsic) {
6350   case Intrinsic::experimental_convergence_anchor:
6351     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ANCHOR, sdl, MVT::Untyped));
6352     break;
6353   case Intrinsic::experimental_convergence_entry:
6354     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ENTRY, sdl, MVT::Untyped));
6355     break;
6356   case Intrinsic::experimental_convergence_loop: {
6357     auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl);
6358     auto *Token = Bundle->Inputs[0].get();
6359     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_LOOP, sdl, MVT::Untyped,
6360                              getValue(Token)));
6361     break;
6362   }
6363   }
6364 }
6365 
6366 void SelectionDAGBuilder::visitVectorHistogram(const CallInst &I,
6367                                                unsigned IntrinsicID) {
6368   // For now, we're only lowering an 'add' histogram.
6369   // We can add others later, e.g. saturating adds, min/max.
6370   assert(IntrinsicID == Intrinsic::experimental_vector_histogram_add &&
6371          "Tried to lower unsupported histogram type");
6372   SDLoc sdl = getCurSDLoc();
6373   Value *Ptr = I.getOperand(0);
6374   SDValue Inc = getValue(I.getOperand(1));
6375   SDValue Mask = getValue(I.getOperand(2));
6376 
6377   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6378   DataLayout TargetDL = DAG.getDataLayout();
6379   EVT VT = Inc.getValueType();
6380   Align Alignment = DAG.getEVTAlign(VT);
6381 
6382   const MDNode *Ranges = getRangeMetadata(I);
6383 
6384   SDValue Root = DAG.getRoot();
6385   SDValue Base;
6386   SDValue Index;
6387   ISD::MemIndexType IndexType;
6388   SDValue Scale;
6389   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
6390                                     I.getParent(), VT.getScalarStoreSize());
6391 
6392   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
6393 
6394   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6395       MachinePointerInfo(AS),
6396       MachineMemOperand::MOLoad | MachineMemOperand::MOStore,
6397       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
6398 
6399   if (!UniformBase) {
6400     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6401     Index = getValue(Ptr);
6402     IndexType = ISD::SIGNED_SCALED;
6403     Scale =
6404         DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6405   }
6406 
6407   EVT IdxVT = Index.getValueType();
6408   EVT EltTy = IdxVT.getVectorElementType();
6409   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
6410     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
6411     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
6412   }
6413 
6414   SDValue ID = DAG.getTargetConstant(IntrinsicID, sdl, MVT::i32);
6415 
6416   SDValue Ops[] = {Root, Inc, Mask, Base, Index, Scale, ID};
6417   SDValue Histogram = DAG.getMaskedHistogram(DAG.getVTList(MVT::Other), VT, sdl,
6418                                              Ops, MMO, IndexType);
6419 
6420   setValue(&I, Histogram);
6421   DAG.setRoot(Histogram);
6422 }
6423 
6424 void SelectionDAGBuilder::visitVectorExtractLastActive(const CallInst &I,
6425                                                        unsigned Intrinsic) {
6426   assert(Intrinsic == Intrinsic::experimental_vector_extract_last_active &&
6427          "Tried lowering invalid vector extract last");
6428   SDLoc sdl = getCurSDLoc();
6429   SDValue Data = getValue(I.getOperand(0));
6430   SDValue Mask = getValue(I.getOperand(1));
6431   SDValue PassThru = getValue(I.getOperand(2));
6432 
6433   EVT DataVT = Data.getValueType();
6434   EVT ScalarVT = PassThru.getValueType();
6435   EVT BoolVT = Mask.getValueType().getScalarType();
6436 
6437   // Find a suitable type for a stepvector.
6438   ConstantRange VScaleRange(1, /*isFullSet=*/true); // Dummy value.
6439   if (DataVT.isScalableVector())
6440     VScaleRange = getVScaleRange(I.getCaller(), 64);
6441   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6442   unsigned EltWidth = TLI.getBitWidthForCttzElements(
6443       I.getType(), DataVT.getVectorElementCount(), /*ZeroIsPoison=*/true,
6444       &VScaleRange);
6445   MVT StepVT = MVT::getIntegerVT(EltWidth);
6446   EVT StepVecVT = DataVT.changeVectorElementType(StepVT);
6447 
6448   // Zero out lanes with inactive elements, then find the highest remaining
6449   // value from the stepvector.
6450   SDValue Zeroes = DAG.getConstant(0, sdl, StepVecVT);
6451   SDValue StepVec = DAG.getStepVector(sdl, StepVecVT);
6452   SDValue ActiveElts = DAG.getSelect(sdl, StepVecVT, Mask, StepVec, Zeroes);
6453   SDValue HighestIdx =
6454       DAG.getNode(ISD::VECREDUCE_UMAX, sdl, StepVT, ActiveElts);
6455 
6456   // Extract the corresponding lane from the data vector
6457   EVT ExtVT = TLI.getVectorIdxTy(DAG.getDataLayout());
6458   SDValue Idx = DAG.getZExtOrTrunc(HighestIdx, sdl, ExtVT);
6459   SDValue Extract =
6460       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, sdl, ScalarVT, Data, Idx);
6461 
6462   // If all mask lanes were inactive, choose the passthru value instead.
6463   SDValue AnyActive = DAG.getNode(ISD::VECREDUCE_OR, sdl, BoolVT, Mask);
6464   SDValue Result = DAG.getSelect(sdl, ScalarVT, AnyActive, Extract, PassThru);
6465   setValue(&I, Result);
6466 }
6467 
6468 /// Lower the call to the specified intrinsic function.
6469 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
6470                                              unsigned Intrinsic) {
6471   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6472   SDLoc sdl = getCurSDLoc();
6473   DebugLoc dl = getCurDebugLoc();
6474   SDValue Res;
6475 
6476   SDNodeFlags Flags;
6477   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
6478     Flags.copyFMF(*FPOp);
6479 
6480   switch (Intrinsic) {
6481   default:
6482     // By default, turn this into a target intrinsic node.
6483     visitTargetIntrinsic(I, Intrinsic);
6484     return;
6485   case Intrinsic::vscale: {
6486     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6487     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
6488     return;
6489   }
6490   case Intrinsic::vastart:  visitVAStart(I); return;
6491   case Intrinsic::vaend:    visitVAEnd(I); return;
6492   case Intrinsic::vacopy:   visitVACopy(I); return;
6493   case Intrinsic::returnaddress:
6494     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
6495                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6496                              getValue(I.getArgOperand(0))));
6497     return;
6498   case Intrinsic::addressofreturnaddress:
6499     setValue(&I,
6500              DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
6501                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6502     return;
6503   case Intrinsic::sponentry:
6504     setValue(&I,
6505              DAG.getNode(ISD::SPONENTRY, sdl,
6506                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6507     return;
6508   case Intrinsic::frameaddress:
6509     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
6510                              TLI.getFrameIndexTy(DAG.getDataLayout()),
6511                              getValue(I.getArgOperand(0))));
6512     return;
6513   case Intrinsic::read_volatile_register:
6514   case Intrinsic::read_register: {
6515     Value *Reg = I.getArgOperand(0);
6516     SDValue Chain = getRoot();
6517     SDValue RegName =
6518         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6519     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6520     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
6521       DAG.getVTList(VT, MVT::Other), Chain, RegName);
6522     setValue(&I, Res);
6523     DAG.setRoot(Res.getValue(1));
6524     return;
6525   }
6526   case Intrinsic::write_register: {
6527     Value *Reg = I.getArgOperand(0);
6528     Value *RegValue = I.getArgOperand(1);
6529     SDValue Chain = getRoot();
6530     SDValue RegName =
6531         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6532     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
6533                             RegName, getValue(RegValue)));
6534     return;
6535   }
6536   case Intrinsic::memcpy: {
6537     const auto &MCI = cast<MemCpyInst>(I);
6538     SDValue Op1 = getValue(I.getArgOperand(0));
6539     SDValue Op2 = getValue(I.getArgOperand(1));
6540     SDValue Op3 = getValue(I.getArgOperand(2));
6541     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
6542     Align DstAlign = MCI.getDestAlign().valueOrOne();
6543     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6544     Align Alignment = std::min(DstAlign, SrcAlign);
6545     bool isVol = MCI.isVolatile();
6546     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6547     // node.
6548     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6549     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6550                                /* AlwaysInline */ false, &I, std::nullopt,
6551                                MachinePointerInfo(I.getArgOperand(0)),
6552                                MachinePointerInfo(I.getArgOperand(1)),
6553                                I.getAAMetadata(), AA);
6554     updateDAGForMaybeTailCall(MC);
6555     return;
6556   }
6557   case Intrinsic::memcpy_inline: {
6558     const auto &MCI = cast<MemCpyInlineInst>(I);
6559     SDValue Dst = getValue(I.getArgOperand(0));
6560     SDValue Src = getValue(I.getArgOperand(1));
6561     SDValue Size = getValue(I.getArgOperand(2));
6562     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
6563     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
6564     Align DstAlign = MCI.getDestAlign().valueOrOne();
6565     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6566     Align Alignment = std::min(DstAlign, SrcAlign);
6567     bool isVol = MCI.isVolatile();
6568     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6569     // node.
6570     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
6571                                /* AlwaysInline */ true, &I, std::nullopt,
6572                                MachinePointerInfo(I.getArgOperand(0)),
6573                                MachinePointerInfo(I.getArgOperand(1)),
6574                                I.getAAMetadata(), AA);
6575     updateDAGForMaybeTailCall(MC);
6576     return;
6577   }
6578   case Intrinsic::memset: {
6579     const auto &MSI = cast<MemSetInst>(I);
6580     SDValue Op1 = getValue(I.getArgOperand(0));
6581     SDValue Op2 = getValue(I.getArgOperand(1));
6582     SDValue Op3 = getValue(I.getArgOperand(2));
6583     // @llvm.memset defines 0 and 1 to both mean no alignment.
6584     Align Alignment = MSI.getDestAlign().valueOrOne();
6585     bool isVol = MSI.isVolatile();
6586     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6587     SDValue MS = DAG.getMemset(
6588         Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false,
6589         &I, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
6590     updateDAGForMaybeTailCall(MS);
6591     return;
6592   }
6593   case Intrinsic::memset_inline: {
6594     const auto &MSII = cast<MemSetInlineInst>(I);
6595     SDValue Dst = getValue(I.getArgOperand(0));
6596     SDValue Value = getValue(I.getArgOperand(1));
6597     SDValue Size = getValue(I.getArgOperand(2));
6598     assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size");
6599     // @llvm.memset defines 0 and 1 to both mean no alignment.
6600     Align DstAlign = MSII.getDestAlign().valueOrOne();
6601     bool isVol = MSII.isVolatile();
6602     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6603     SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol,
6604                                /* AlwaysInline */ true, &I,
6605                                MachinePointerInfo(I.getArgOperand(0)),
6606                                I.getAAMetadata());
6607     updateDAGForMaybeTailCall(MC);
6608     return;
6609   }
6610   case Intrinsic::memmove: {
6611     const auto &MMI = cast<MemMoveInst>(I);
6612     SDValue Op1 = getValue(I.getArgOperand(0));
6613     SDValue Op2 = getValue(I.getArgOperand(1));
6614     SDValue Op3 = getValue(I.getArgOperand(2));
6615     // @llvm.memmove defines 0 and 1 to both mean no alignment.
6616     Align DstAlign = MMI.getDestAlign().valueOrOne();
6617     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
6618     Align Alignment = std::min(DstAlign, SrcAlign);
6619     bool isVol = MMI.isVolatile();
6620     // FIXME: Support passing different dest/src alignments to the memmove DAG
6621     // node.
6622     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6623     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, &I,
6624                                 /* OverrideTailCall */ std::nullopt,
6625                                 MachinePointerInfo(I.getArgOperand(0)),
6626                                 MachinePointerInfo(I.getArgOperand(1)),
6627                                 I.getAAMetadata(), AA);
6628     updateDAGForMaybeTailCall(MM);
6629     return;
6630   }
6631   case Intrinsic::memcpy_element_unordered_atomic: {
6632     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
6633     SDValue Dst = getValue(MI.getRawDest());
6634     SDValue Src = getValue(MI.getRawSource());
6635     SDValue Length = getValue(MI.getLength());
6636 
6637     Type *LengthTy = MI.getLength()->getType();
6638     unsigned ElemSz = MI.getElementSizeInBytes();
6639     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6640     SDValue MC =
6641         DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6642                             isTC, MachinePointerInfo(MI.getRawDest()),
6643                             MachinePointerInfo(MI.getRawSource()));
6644     updateDAGForMaybeTailCall(MC);
6645     return;
6646   }
6647   case Intrinsic::memmove_element_unordered_atomic: {
6648     auto &MI = cast<AtomicMemMoveInst>(I);
6649     SDValue Dst = getValue(MI.getRawDest());
6650     SDValue Src = getValue(MI.getRawSource());
6651     SDValue Length = getValue(MI.getLength());
6652 
6653     Type *LengthTy = MI.getLength()->getType();
6654     unsigned ElemSz = MI.getElementSizeInBytes();
6655     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6656     SDValue MC =
6657         DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6658                              isTC, MachinePointerInfo(MI.getRawDest()),
6659                              MachinePointerInfo(MI.getRawSource()));
6660     updateDAGForMaybeTailCall(MC);
6661     return;
6662   }
6663   case Intrinsic::memset_element_unordered_atomic: {
6664     auto &MI = cast<AtomicMemSetInst>(I);
6665     SDValue Dst = getValue(MI.getRawDest());
6666     SDValue Val = getValue(MI.getValue());
6667     SDValue Length = getValue(MI.getLength());
6668 
6669     Type *LengthTy = MI.getLength()->getType();
6670     unsigned ElemSz = MI.getElementSizeInBytes();
6671     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6672     SDValue MC =
6673         DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
6674                             isTC, MachinePointerInfo(MI.getRawDest()));
6675     updateDAGForMaybeTailCall(MC);
6676     return;
6677   }
6678   case Intrinsic::call_preallocated_setup: {
6679     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
6680     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6681     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
6682                               getRoot(), SrcValue);
6683     setValue(&I, Res);
6684     DAG.setRoot(Res);
6685     return;
6686   }
6687   case Intrinsic::call_preallocated_arg: {
6688     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6689     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6690     SDValue Ops[3];
6691     Ops[0] = getRoot();
6692     Ops[1] = SrcValue;
6693     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6694                                    MVT::i32); // arg index
6695     SDValue Res = DAG.getNode(
6696         ISD::PREALLOCATED_ARG, sdl,
6697         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6698     setValue(&I, Res);
6699     DAG.setRoot(Res.getValue(1));
6700     return;
6701   }
6702   case Intrinsic::dbg_declare: {
6703     const auto &DI = cast<DbgDeclareInst>(I);
6704     // Debug intrinsics are handled separately in assignment tracking mode.
6705     // Some intrinsics are handled right after Argument lowering.
6706     if (AssignmentTrackingEnabled ||
6707         FuncInfo.PreprocessedDbgDeclares.count(&DI))
6708       return;
6709     LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DI << "\n");
6710     DILocalVariable *Variable = DI.getVariable();
6711     DIExpression *Expression = DI.getExpression();
6712     dropDanglingDebugInfo(Variable, Expression);
6713     // Assume dbg.declare can not currently use DIArgList, i.e.
6714     // it is non-variadic.
6715     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6716     handleDebugDeclare(DI.getVariableLocationOp(0), Variable, Expression,
6717                        DI.getDebugLoc());
6718     return;
6719   }
6720   case Intrinsic::dbg_label: {
6721     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6722     DILabel *Label = DI.getLabel();
6723     assert(Label && "Missing label");
6724 
6725     SDDbgLabel *SDV;
6726     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6727     DAG.AddDbgLabel(SDV);
6728     return;
6729   }
6730   case Intrinsic::dbg_assign: {
6731     // Debug intrinsics are handled separately in assignment tracking mode.
6732     if (AssignmentTrackingEnabled)
6733       return;
6734     // If assignment tracking hasn't been enabled then fall through and treat
6735     // the dbg.assign as a dbg.value.
6736     [[fallthrough]];
6737   }
6738   case Intrinsic::dbg_value: {
6739     // Debug intrinsics are handled separately in assignment tracking mode.
6740     if (AssignmentTrackingEnabled)
6741       return;
6742     const DbgValueInst &DI = cast<DbgValueInst>(I);
6743     assert(DI.getVariable() && "Missing variable");
6744 
6745     DILocalVariable *Variable = DI.getVariable();
6746     DIExpression *Expression = DI.getExpression();
6747     dropDanglingDebugInfo(Variable, Expression);
6748 
6749     if (DI.isKillLocation()) {
6750       handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder);
6751       return;
6752     }
6753 
6754     SmallVector<Value *, 4> Values(DI.getValues());
6755     if (Values.empty())
6756       return;
6757 
6758     bool IsVariadic = DI.hasArgList();
6759     if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(),
6760                           SDNodeOrder, IsVariadic))
6761       addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
6762                            DI.getDebugLoc(), SDNodeOrder);
6763     return;
6764   }
6765 
6766   case Intrinsic::eh_typeid_for: {
6767     // Find the type id for the given typeinfo.
6768     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6769     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6770     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6771     setValue(&I, Res);
6772     return;
6773   }
6774 
6775   case Intrinsic::eh_return_i32:
6776   case Intrinsic::eh_return_i64:
6777     DAG.getMachineFunction().setCallsEHReturn(true);
6778     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6779                             MVT::Other,
6780                             getControlRoot(),
6781                             getValue(I.getArgOperand(0)),
6782                             getValue(I.getArgOperand(1))));
6783     return;
6784   case Intrinsic::eh_unwind_init:
6785     DAG.getMachineFunction().setCallsUnwindInit(true);
6786     return;
6787   case Intrinsic::eh_dwarf_cfa:
6788     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6789                              TLI.getPointerTy(DAG.getDataLayout()),
6790                              getValue(I.getArgOperand(0))));
6791     return;
6792   case Intrinsic::eh_sjlj_callsite: {
6793     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
6794     assert(FuncInfo.getCurrentCallSite() == 0 && "Overlapping call sites!");
6795 
6796     FuncInfo.setCurrentCallSite(CI->getZExtValue());
6797     return;
6798   }
6799   case Intrinsic::eh_sjlj_functioncontext: {
6800     // Get and store the index of the function context.
6801     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6802     AllocaInst *FnCtx =
6803       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6804     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6805     MFI.setFunctionContextIndex(FI);
6806     return;
6807   }
6808   case Intrinsic::eh_sjlj_setjmp: {
6809     SDValue Ops[2];
6810     Ops[0] = getRoot();
6811     Ops[1] = getValue(I.getArgOperand(0));
6812     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6813                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6814     setValue(&I, Op.getValue(0));
6815     DAG.setRoot(Op.getValue(1));
6816     return;
6817   }
6818   case Intrinsic::eh_sjlj_longjmp:
6819     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6820                             getRoot(), getValue(I.getArgOperand(0))));
6821     return;
6822   case Intrinsic::eh_sjlj_setup_dispatch:
6823     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6824                             getRoot()));
6825     return;
6826   case Intrinsic::masked_gather:
6827     visitMaskedGather(I);
6828     return;
6829   case Intrinsic::masked_load:
6830     visitMaskedLoad(I);
6831     return;
6832   case Intrinsic::masked_scatter:
6833     visitMaskedScatter(I);
6834     return;
6835   case Intrinsic::masked_store:
6836     visitMaskedStore(I);
6837     return;
6838   case Intrinsic::masked_expandload:
6839     visitMaskedLoad(I, true /* IsExpanding */);
6840     return;
6841   case Intrinsic::masked_compressstore:
6842     visitMaskedStore(I, true /* IsCompressing */);
6843     return;
6844   case Intrinsic::powi:
6845     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6846                             getValue(I.getArgOperand(1)), DAG));
6847     return;
6848   case Intrinsic::log:
6849     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6850     return;
6851   case Intrinsic::log2:
6852     setValue(&I,
6853              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6854     return;
6855   case Intrinsic::log10:
6856     setValue(&I,
6857              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6858     return;
6859   case Intrinsic::exp:
6860     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6861     return;
6862   case Intrinsic::exp2:
6863     setValue(&I,
6864              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6865     return;
6866   case Intrinsic::pow:
6867     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6868                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6869     return;
6870   case Intrinsic::sqrt:
6871   case Intrinsic::fabs:
6872   case Intrinsic::sin:
6873   case Intrinsic::cos:
6874   case Intrinsic::tan:
6875   case Intrinsic::asin:
6876   case Intrinsic::acos:
6877   case Intrinsic::atan:
6878   case Intrinsic::sinh:
6879   case Intrinsic::cosh:
6880   case Intrinsic::tanh:
6881   case Intrinsic::exp10:
6882   case Intrinsic::floor:
6883   case Intrinsic::ceil:
6884   case Intrinsic::trunc:
6885   case Intrinsic::rint:
6886   case Intrinsic::nearbyint:
6887   case Intrinsic::round:
6888   case Intrinsic::roundeven:
6889   case Intrinsic::canonicalize: {
6890     unsigned Opcode;
6891     // clang-format off
6892     switch (Intrinsic) {
6893     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6894     case Intrinsic::sqrt:         Opcode = ISD::FSQRT;         break;
6895     case Intrinsic::fabs:         Opcode = ISD::FABS;          break;
6896     case Intrinsic::sin:          Opcode = ISD::FSIN;          break;
6897     case Intrinsic::cos:          Opcode = ISD::FCOS;          break;
6898     case Intrinsic::tan:          Opcode = ISD::FTAN;          break;
6899     case Intrinsic::asin:         Opcode = ISD::FASIN;         break;
6900     case Intrinsic::acos:         Opcode = ISD::FACOS;         break;
6901     case Intrinsic::atan:         Opcode = ISD::FATAN;         break;
6902     case Intrinsic::sinh:         Opcode = ISD::FSINH;         break;
6903     case Intrinsic::cosh:         Opcode = ISD::FCOSH;         break;
6904     case Intrinsic::tanh:         Opcode = ISD::FTANH;         break;
6905     case Intrinsic::exp10:        Opcode = ISD::FEXP10;        break;
6906     case Intrinsic::floor:        Opcode = ISD::FFLOOR;        break;
6907     case Intrinsic::ceil:         Opcode = ISD::FCEIL;         break;
6908     case Intrinsic::trunc:        Opcode = ISD::FTRUNC;        break;
6909     case Intrinsic::rint:         Opcode = ISD::FRINT;         break;
6910     case Intrinsic::nearbyint:    Opcode = ISD::FNEARBYINT;    break;
6911     case Intrinsic::round:        Opcode = ISD::FROUND;        break;
6912     case Intrinsic::roundeven:    Opcode = ISD::FROUNDEVEN;    break;
6913     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6914     }
6915     // clang-format on
6916 
6917     setValue(&I, DAG.getNode(Opcode, sdl,
6918                              getValue(I.getArgOperand(0)).getValueType(),
6919                              getValue(I.getArgOperand(0)), Flags));
6920     return;
6921   }
6922   case Intrinsic::atan2:
6923     setValue(&I, DAG.getNode(ISD::FATAN2, sdl,
6924                              getValue(I.getArgOperand(0)).getValueType(),
6925                              getValue(I.getArgOperand(0)),
6926                              getValue(I.getArgOperand(1)), Flags));
6927     return;
6928   case Intrinsic::lround:
6929   case Intrinsic::llround:
6930   case Intrinsic::lrint:
6931   case Intrinsic::llrint: {
6932     unsigned Opcode;
6933     // clang-format off
6934     switch (Intrinsic) {
6935     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6936     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6937     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6938     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6939     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6940     }
6941     // clang-format on
6942 
6943     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6944     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6945                              getValue(I.getArgOperand(0))));
6946     return;
6947   }
6948   case Intrinsic::minnum:
6949     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6950                              getValue(I.getArgOperand(0)).getValueType(),
6951                              getValue(I.getArgOperand(0)),
6952                              getValue(I.getArgOperand(1)), Flags));
6953     return;
6954   case Intrinsic::maxnum:
6955     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6956                              getValue(I.getArgOperand(0)).getValueType(),
6957                              getValue(I.getArgOperand(0)),
6958                              getValue(I.getArgOperand(1)), Flags));
6959     return;
6960   case Intrinsic::minimum:
6961     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6962                              getValue(I.getArgOperand(0)).getValueType(),
6963                              getValue(I.getArgOperand(0)),
6964                              getValue(I.getArgOperand(1)), Flags));
6965     return;
6966   case Intrinsic::maximum:
6967     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6968                              getValue(I.getArgOperand(0)).getValueType(),
6969                              getValue(I.getArgOperand(0)),
6970                              getValue(I.getArgOperand(1)), Flags));
6971     return;
6972   case Intrinsic::minimumnum:
6973     setValue(&I, DAG.getNode(ISD::FMINIMUMNUM, sdl,
6974                              getValue(I.getArgOperand(0)).getValueType(),
6975                              getValue(I.getArgOperand(0)),
6976                              getValue(I.getArgOperand(1)), Flags));
6977     return;
6978   case Intrinsic::maximumnum:
6979     setValue(&I, DAG.getNode(ISD::FMAXIMUMNUM, sdl,
6980                              getValue(I.getArgOperand(0)).getValueType(),
6981                              getValue(I.getArgOperand(0)),
6982                              getValue(I.getArgOperand(1)), Flags));
6983     return;
6984   case Intrinsic::copysign:
6985     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6986                              getValue(I.getArgOperand(0)).getValueType(),
6987                              getValue(I.getArgOperand(0)),
6988                              getValue(I.getArgOperand(1)), Flags));
6989     return;
6990   case Intrinsic::ldexp:
6991     setValue(&I, DAG.getNode(ISD::FLDEXP, sdl,
6992                              getValue(I.getArgOperand(0)).getValueType(),
6993                              getValue(I.getArgOperand(0)),
6994                              getValue(I.getArgOperand(1)), Flags));
6995     return;
6996   case Intrinsic::sincos:
6997   case Intrinsic::frexp: {
6998     unsigned Opcode;
6999     switch (Intrinsic) {
7000     default:
7001       llvm_unreachable("unexpected intrinsic");
7002     case Intrinsic::sincos:
7003       Opcode = ISD::FSINCOS;
7004       break;
7005     case Intrinsic::frexp:
7006       Opcode = ISD::FFREXP;
7007       break;
7008     }
7009     SmallVector<EVT, 2> ValueVTs;
7010     ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
7011     SDVTList VTs = DAG.getVTList(ValueVTs);
7012     setValue(
7013         &I, DAG.getNode(Opcode, sdl, VTs, getValue(I.getArgOperand(0)), Flags));
7014     return;
7015   }
7016   case Intrinsic::arithmetic_fence: {
7017     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
7018                              getValue(I.getArgOperand(0)).getValueType(),
7019                              getValue(I.getArgOperand(0)), Flags));
7020     return;
7021   }
7022   case Intrinsic::fma:
7023     setValue(&I, DAG.getNode(
7024                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
7025                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
7026                      getValue(I.getArgOperand(2)), Flags));
7027     return;
7028 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
7029   case Intrinsic::INTRINSIC:
7030 #include "llvm/IR/ConstrainedOps.def"
7031     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
7032     return;
7033 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
7034 #include "llvm/IR/VPIntrinsics.def"
7035     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
7036     return;
7037   case Intrinsic::fptrunc_round: {
7038     // Get the last argument, the metadata and convert it to an integer in the
7039     // call
7040     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
7041     std::optional<RoundingMode> RoundMode =
7042         convertStrToRoundingMode(cast<MDString>(MD)->getString());
7043 
7044     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7045 
7046     // Propagate fast-math-flags from IR to node(s).
7047     SDNodeFlags Flags;
7048     Flags.copyFMF(*cast<FPMathOperator>(&I));
7049     SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
7050 
7051     SDValue Result;
7052     Result = DAG.getNode(
7053         ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
7054         DAG.getTargetConstant((int)*RoundMode, sdl, MVT::i32));
7055     setValue(&I, Result);
7056 
7057     return;
7058   }
7059   case Intrinsic::fmuladd: {
7060     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7061     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
7062         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
7063       setValue(&I, DAG.getNode(ISD::FMA, sdl,
7064                                getValue(I.getArgOperand(0)).getValueType(),
7065                                getValue(I.getArgOperand(0)),
7066                                getValue(I.getArgOperand(1)),
7067                                getValue(I.getArgOperand(2)), Flags));
7068     } else {
7069       // TODO: Intrinsic calls should have fast-math-flags.
7070       SDValue Mul = DAG.getNode(
7071           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
7072           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
7073       SDValue Add = DAG.getNode(ISD::FADD, sdl,
7074                                 getValue(I.getArgOperand(0)).getValueType(),
7075                                 Mul, getValue(I.getArgOperand(2)), Flags);
7076       setValue(&I, Add);
7077     }
7078     return;
7079   }
7080   case Intrinsic::convert_to_fp16:
7081     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
7082                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
7083                                          getValue(I.getArgOperand(0)),
7084                                          DAG.getTargetConstant(0, sdl,
7085                                                                MVT::i32))));
7086     return;
7087   case Intrinsic::convert_from_fp16:
7088     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
7089                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
7090                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
7091                                          getValue(I.getArgOperand(0)))));
7092     return;
7093   case Intrinsic::fptosi_sat: {
7094     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7095     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
7096                              getValue(I.getArgOperand(0)),
7097                              DAG.getValueType(VT.getScalarType())));
7098     return;
7099   }
7100   case Intrinsic::fptoui_sat: {
7101     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7102     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
7103                              getValue(I.getArgOperand(0)),
7104                              DAG.getValueType(VT.getScalarType())));
7105     return;
7106   }
7107   case Intrinsic::set_rounding:
7108     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
7109                       {getRoot(), getValue(I.getArgOperand(0))});
7110     setValue(&I, Res);
7111     DAG.setRoot(Res.getValue(0));
7112     return;
7113   case Intrinsic::is_fpclass: {
7114     const DataLayout DLayout = DAG.getDataLayout();
7115     EVT DestVT = TLI.getValueType(DLayout, I.getType());
7116     EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
7117     FPClassTest Test = static_cast<FPClassTest>(
7118         cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
7119     MachineFunction &MF = DAG.getMachineFunction();
7120     const Function &F = MF.getFunction();
7121     SDValue Op = getValue(I.getArgOperand(0));
7122     SDNodeFlags Flags;
7123     Flags.setNoFPExcept(
7124         !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
7125     // If ISD::IS_FPCLASS should be expanded, do it right now, because the
7126     // expansion can use illegal types. Making expansion early allows
7127     // legalizing these types prior to selection.
7128     if (!TLI.isOperationLegal(ISD::IS_FPCLASS, ArgVT) &&
7129         !TLI.isOperationCustom(ISD::IS_FPCLASS, ArgVT)) {
7130       SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
7131       setValue(&I, Result);
7132       return;
7133     }
7134 
7135     SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
7136     SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
7137     setValue(&I, V);
7138     return;
7139   }
7140   case Intrinsic::get_fpenv: {
7141     const DataLayout DLayout = DAG.getDataLayout();
7142     EVT EnvVT = TLI.getValueType(DLayout, I.getType());
7143     Align TempAlign = DAG.getEVTAlign(EnvVT);
7144     SDValue Chain = getRoot();
7145     // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node
7146     // and temporary storage in stack.
7147     if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) {
7148       Res = DAG.getNode(
7149           ISD::GET_FPENV, sdl,
7150           DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7151                         MVT::Other),
7152           Chain);
7153     } else {
7154       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7155       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7156       auto MPI =
7157           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7158       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7159           MPI, MachineMemOperand::MOStore, LocationSize::beforeOrAfterPointer(),
7160           TempAlign);
7161       Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7162       Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI);
7163     }
7164     setValue(&I, Res);
7165     DAG.setRoot(Res.getValue(1));
7166     return;
7167   }
7168   case Intrinsic::set_fpenv: {
7169     const DataLayout DLayout = DAG.getDataLayout();
7170     SDValue Env = getValue(I.getArgOperand(0));
7171     EVT EnvVT = Env.getValueType();
7172     Align TempAlign = DAG.getEVTAlign(EnvVT);
7173     SDValue Chain = getRoot();
7174     // If SET_FPENV is custom or legal, use it. Otherwise use loading
7175     // environment from memory.
7176     if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) {
7177       Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env);
7178     } else {
7179       // Allocate space in stack, copy environment bits into it and use this
7180       // memory in SET_FPENV_MEM.
7181       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7182       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7183       auto MPI =
7184           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7185       Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign,
7186                            MachineMemOperand::MOStore);
7187       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7188           MPI, MachineMemOperand::MOLoad, LocationSize::beforeOrAfterPointer(),
7189           TempAlign);
7190       Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7191     }
7192     DAG.setRoot(Chain);
7193     return;
7194   }
7195   case Intrinsic::reset_fpenv:
7196     DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot()));
7197     return;
7198   case Intrinsic::get_fpmode:
7199     Res = DAG.getNode(
7200         ISD::GET_FPMODE, sdl,
7201         DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7202                       MVT::Other),
7203         DAG.getRoot());
7204     setValue(&I, Res);
7205     DAG.setRoot(Res.getValue(1));
7206     return;
7207   case Intrinsic::set_fpmode:
7208     Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()},
7209                       getValue(I.getArgOperand(0)));
7210     DAG.setRoot(Res);
7211     return;
7212   case Intrinsic::reset_fpmode: {
7213     Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot());
7214     DAG.setRoot(Res);
7215     return;
7216   }
7217   case Intrinsic::pcmarker: {
7218     SDValue Tmp = getValue(I.getArgOperand(0));
7219     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
7220     return;
7221   }
7222   case Intrinsic::readcyclecounter: {
7223     SDValue Op = getRoot();
7224     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
7225                       DAG.getVTList(MVT::i64, MVT::Other), Op);
7226     setValue(&I, Res);
7227     DAG.setRoot(Res.getValue(1));
7228     return;
7229   }
7230   case Intrinsic::readsteadycounter: {
7231     SDValue Op = getRoot();
7232     Res = DAG.getNode(ISD::READSTEADYCOUNTER, sdl,
7233                       DAG.getVTList(MVT::i64, MVT::Other), Op);
7234     setValue(&I, Res);
7235     DAG.setRoot(Res.getValue(1));
7236     return;
7237   }
7238   case Intrinsic::bitreverse:
7239     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
7240                              getValue(I.getArgOperand(0)).getValueType(),
7241                              getValue(I.getArgOperand(0))));
7242     return;
7243   case Intrinsic::bswap:
7244     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
7245                              getValue(I.getArgOperand(0)).getValueType(),
7246                              getValue(I.getArgOperand(0))));
7247     return;
7248   case Intrinsic::cttz: {
7249     SDValue Arg = getValue(I.getArgOperand(0));
7250     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7251     EVT Ty = Arg.getValueType();
7252     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
7253                              sdl, Ty, Arg));
7254     return;
7255   }
7256   case Intrinsic::ctlz: {
7257     SDValue Arg = getValue(I.getArgOperand(0));
7258     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7259     EVT Ty = Arg.getValueType();
7260     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
7261                              sdl, Ty, Arg));
7262     return;
7263   }
7264   case Intrinsic::ctpop: {
7265     SDValue Arg = getValue(I.getArgOperand(0));
7266     EVT Ty = Arg.getValueType();
7267     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
7268     return;
7269   }
7270   case Intrinsic::fshl:
7271   case Intrinsic::fshr: {
7272     bool IsFSHL = Intrinsic == Intrinsic::fshl;
7273     SDValue X = getValue(I.getArgOperand(0));
7274     SDValue Y = getValue(I.getArgOperand(1));
7275     SDValue Z = getValue(I.getArgOperand(2));
7276     EVT VT = X.getValueType();
7277 
7278     if (X == Y) {
7279       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
7280       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
7281     } else {
7282       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
7283       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
7284     }
7285     return;
7286   }
7287   case Intrinsic::sadd_sat: {
7288     SDValue Op1 = getValue(I.getArgOperand(0));
7289     SDValue Op2 = getValue(I.getArgOperand(1));
7290     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7291     return;
7292   }
7293   case Intrinsic::uadd_sat: {
7294     SDValue Op1 = getValue(I.getArgOperand(0));
7295     SDValue Op2 = getValue(I.getArgOperand(1));
7296     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7297     return;
7298   }
7299   case Intrinsic::ssub_sat: {
7300     SDValue Op1 = getValue(I.getArgOperand(0));
7301     SDValue Op2 = getValue(I.getArgOperand(1));
7302     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7303     return;
7304   }
7305   case Intrinsic::usub_sat: {
7306     SDValue Op1 = getValue(I.getArgOperand(0));
7307     SDValue Op2 = getValue(I.getArgOperand(1));
7308     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7309     return;
7310   }
7311   case Intrinsic::sshl_sat: {
7312     SDValue Op1 = getValue(I.getArgOperand(0));
7313     SDValue Op2 = getValue(I.getArgOperand(1));
7314     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
7315     return;
7316   }
7317   case Intrinsic::ushl_sat: {
7318     SDValue Op1 = getValue(I.getArgOperand(0));
7319     SDValue Op2 = getValue(I.getArgOperand(1));
7320     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
7321     return;
7322   }
7323   case Intrinsic::smul_fix:
7324   case Intrinsic::umul_fix:
7325   case Intrinsic::smul_fix_sat:
7326   case Intrinsic::umul_fix_sat: {
7327     SDValue Op1 = getValue(I.getArgOperand(0));
7328     SDValue Op2 = getValue(I.getArgOperand(1));
7329     SDValue Op3 = getValue(I.getArgOperand(2));
7330     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7331                              Op1.getValueType(), Op1, Op2, Op3));
7332     return;
7333   }
7334   case Intrinsic::sdiv_fix:
7335   case Intrinsic::udiv_fix:
7336   case Intrinsic::sdiv_fix_sat:
7337   case Intrinsic::udiv_fix_sat: {
7338     SDValue Op1 = getValue(I.getArgOperand(0));
7339     SDValue Op2 = getValue(I.getArgOperand(1));
7340     SDValue Op3 = getValue(I.getArgOperand(2));
7341     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7342                               Op1, Op2, Op3, DAG, TLI));
7343     return;
7344   }
7345   case Intrinsic::smax: {
7346     SDValue Op1 = getValue(I.getArgOperand(0));
7347     SDValue Op2 = getValue(I.getArgOperand(1));
7348     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
7349     return;
7350   }
7351   case Intrinsic::smin: {
7352     SDValue Op1 = getValue(I.getArgOperand(0));
7353     SDValue Op2 = getValue(I.getArgOperand(1));
7354     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
7355     return;
7356   }
7357   case Intrinsic::umax: {
7358     SDValue Op1 = getValue(I.getArgOperand(0));
7359     SDValue Op2 = getValue(I.getArgOperand(1));
7360     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
7361     return;
7362   }
7363   case Intrinsic::umin: {
7364     SDValue Op1 = getValue(I.getArgOperand(0));
7365     SDValue Op2 = getValue(I.getArgOperand(1));
7366     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
7367     return;
7368   }
7369   case Intrinsic::abs: {
7370     // TODO: Preserve "int min is poison" arg in SDAG?
7371     SDValue Op1 = getValue(I.getArgOperand(0));
7372     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
7373     return;
7374   }
7375   case Intrinsic::scmp: {
7376     SDValue Op1 = getValue(I.getArgOperand(0));
7377     SDValue Op2 = getValue(I.getArgOperand(1));
7378     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7379     setValue(&I, DAG.getNode(ISD::SCMP, sdl, DestVT, Op1, Op2));
7380     break;
7381   }
7382   case Intrinsic::ucmp: {
7383     SDValue Op1 = getValue(I.getArgOperand(0));
7384     SDValue Op2 = getValue(I.getArgOperand(1));
7385     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7386     setValue(&I, DAG.getNode(ISD::UCMP, sdl, DestVT, Op1, Op2));
7387     break;
7388   }
7389   case Intrinsic::stacksave: {
7390     SDValue Op = getRoot();
7391     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7392     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
7393     setValue(&I, Res);
7394     DAG.setRoot(Res.getValue(1));
7395     return;
7396   }
7397   case Intrinsic::stackrestore:
7398     Res = getValue(I.getArgOperand(0));
7399     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
7400     return;
7401   case Intrinsic::get_dynamic_area_offset: {
7402     SDValue Op = getRoot();
7403     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7404     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7405     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
7406     // target.
7407     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
7408       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
7409                          " intrinsic!");
7410     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
7411                       Op);
7412     DAG.setRoot(Op);
7413     setValue(&I, Res);
7414     return;
7415   }
7416   case Intrinsic::stackguard: {
7417     MachineFunction &MF = DAG.getMachineFunction();
7418     const Module &M = *MF.getFunction().getParent();
7419     EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7420     SDValue Chain = getRoot();
7421     if (TLI.useLoadStackGuardNode(M)) {
7422       Res = getLoadStackGuard(DAG, sdl, Chain);
7423       Res = DAG.getPtrExtOrTrunc(Res, sdl, PtrTy);
7424     } else {
7425       const Value *Global = TLI.getSDagStackGuard(M);
7426       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
7427       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
7428                         MachinePointerInfo(Global, 0), Align,
7429                         MachineMemOperand::MOVolatile);
7430     }
7431     if (TLI.useStackGuardXorFP())
7432       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
7433     DAG.setRoot(Chain);
7434     setValue(&I, Res);
7435     return;
7436   }
7437   case Intrinsic::stackprotector: {
7438     // Emit code into the DAG to store the stack guard onto the stack.
7439     MachineFunction &MF = DAG.getMachineFunction();
7440     MachineFrameInfo &MFI = MF.getFrameInfo();
7441     const Module &M = *MF.getFunction().getParent();
7442     SDValue Src, Chain = getRoot();
7443 
7444     if (TLI.useLoadStackGuardNode(M))
7445       Src = getLoadStackGuard(DAG, sdl, Chain);
7446     else
7447       Src = getValue(I.getArgOperand(0));   // The guard's value.
7448 
7449     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
7450 
7451     int FI = FuncInfo.StaticAllocaMap[Slot];
7452     MFI.setStackProtectorIndex(FI);
7453     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7454 
7455     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
7456 
7457     // Store the stack protector onto the stack.
7458     Res = DAG.getStore(
7459         Chain, sdl, Src, FIN,
7460         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
7461         MaybeAlign(), MachineMemOperand::MOVolatile);
7462     setValue(&I, Res);
7463     DAG.setRoot(Res);
7464     return;
7465   }
7466   case Intrinsic::objectsize:
7467     llvm_unreachable("llvm.objectsize.* should have been lowered already");
7468 
7469   case Intrinsic::is_constant:
7470     llvm_unreachable("llvm.is.constant.* should have been lowered already");
7471 
7472   case Intrinsic::annotation:
7473   case Intrinsic::ptr_annotation:
7474   case Intrinsic::launder_invariant_group:
7475   case Intrinsic::strip_invariant_group:
7476     // Drop the intrinsic, but forward the value
7477     setValue(&I, getValue(I.getOperand(0)));
7478     return;
7479 
7480   case Intrinsic::assume:
7481   case Intrinsic::experimental_noalias_scope_decl:
7482   case Intrinsic::var_annotation:
7483   case Intrinsic::sideeffect:
7484     // Discard annotate attributes, noalias scope declarations, assumptions, and
7485     // artificial side-effects.
7486     return;
7487 
7488   case Intrinsic::codeview_annotation: {
7489     // Emit a label associated with this metadata.
7490     MachineFunction &MF = DAG.getMachineFunction();
7491     MCSymbol *Label = MF.getContext().createTempSymbol("annotation", true);
7492     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
7493     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
7494     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
7495     DAG.setRoot(Res);
7496     return;
7497   }
7498 
7499   case Intrinsic::init_trampoline: {
7500     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
7501 
7502     SDValue Ops[6];
7503     Ops[0] = getRoot();
7504     Ops[1] = getValue(I.getArgOperand(0));
7505     Ops[2] = getValue(I.getArgOperand(1));
7506     Ops[3] = getValue(I.getArgOperand(2));
7507     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
7508     Ops[5] = DAG.getSrcValue(F);
7509 
7510     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
7511 
7512     DAG.setRoot(Res);
7513     return;
7514   }
7515   case Intrinsic::adjust_trampoline:
7516     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
7517                              TLI.getPointerTy(DAG.getDataLayout()),
7518                              getValue(I.getArgOperand(0))));
7519     return;
7520   case Intrinsic::gcroot: {
7521     assert(DAG.getMachineFunction().getFunction().hasGC() &&
7522            "only valid in functions with gc specified, enforced by Verifier");
7523     assert(GFI && "implied by previous");
7524     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
7525     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
7526 
7527     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
7528     GFI->addStackRoot(FI->getIndex(), TypeMap);
7529     return;
7530   }
7531   case Intrinsic::gcread:
7532   case Intrinsic::gcwrite:
7533     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
7534   case Intrinsic::get_rounding:
7535     Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot());
7536     setValue(&I, Res);
7537     DAG.setRoot(Res.getValue(1));
7538     return;
7539 
7540   case Intrinsic::expect:
7541   case Intrinsic::expect_with_probability:
7542     // Just replace __builtin_expect(exp, c) and
7543     // __builtin_expect_with_probability(exp, c, p) with EXP.
7544     setValue(&I, getValue(I.getArgOperand(0)));
7545     return;
7546 
7547   case Intrinsic::ubsantrap:
7548   case Intrinsic::debugtrap:
7549   case Intrinsic::trap: {
7550     StringRef TrapFuncName =
7551         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
7552     if (TrapFuncName.empty()) {
7553       switch (Intrinsic) {
7554       case Intrinsic::trap:
7555         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
7556         break;
7557       case Intrinsic::debugtrap:
7558         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
7559         break;
7560       case Intrinsic::ubsantrap:
7561         DAG.setRoot(DAG.getNode(
7562             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
7563             DAG.getTargetConstant(
7564                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
7565                 MVT::i32)));
7566         break;
7567       default: llvm_unreachable("unknown trap intrinsic");
7568       }
7569       DAG.addNoMergeSiteInfo(DAG.getRoot().getNode(),
7570                              I.hasFnAttr(Attribute::NoMerge));
7571       return;
7572     }
7573     TargetLowering::ArgListTy Args;
7574     if (Intrinsic == Intrinsic::ubsantrap) {
7575       Args.push_back(TargetLoweringBase::ArgListEntry());
7576       Args[0].Val = I.getArgOperand(0);
7577       Args[0].Node = getValue(Args[0].Val);
7578       Args[0].Ty = Args[0].Val->getType();
7579     }
7580 
7581     TargetLowering::CallLoweringInfo CLI(DAG);
7582     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
7583         CallingConv::C, I.getType(),
7584         DAG.getExternalSymbol(TrapFuncName.data(),
7585                               TLI.getPointerTy(DAG.getDataLayout())),
7586         std::move(Args));
7587     CLI.NoMerge = I.hasFnAttr(Attribute::NoMerge);
7588     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7589     DAG.setRoot(Result.second);
7590     return;
7591   }
7592 
7593   case Intrinsic::allow_runtime_check:
7594   case Intrinsic::allow_ubsan_check:
7595     setValue(&I, getValue(ConstantInt::getTrue(I.getType())));
7596     return;
7597 
7598   case Intrinsic::uadd_with_overflow:
7599   case Intrinsic::sadd_with_overflow:
7600   case Intrinsic::usub_with_overflow:
7601   case Intrinsic::ssub_with_overflow:
7602   case Intrinsic::umul_with_overflow:
7603   case Intrinsic::smul_with_overflow: {
7604     ISD::NodeType Op;
7605     switch (Intrinsic) {
7606     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7607     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
7608     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
7609     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
7610     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
7611     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
7612     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
7613     }
7614     SDValue Op1 = getValue(I.getArgOperand(0));
7615     SDValue Op2 = getValue(I.getArgOperand(1));
7616 
7617     EVT ResultVT = Op1.getValueType();
7618     EVT OverflowVT = MVT::i1;
7619     if (ResultVT.isVector())
7620       OverflowVT = EVT::getVectorVT(
7621           *Context, OverflowVT, ResultVT.getVectorElementCount());
7622 
7623     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
7624     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
7625     return;
7626   }
7627   case Intrinsic::prefetch: {
7628     SDValue Ops[5];
7629     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7630     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
7631     Ops[0] = DAG.getRoot();
7632     Ops[1] = getValue(I.getArgOperand(0));
7633     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
7634                                    MVT::i32);
7635     Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl,
7636                                    MVT::i32);
7637     Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl,
7638                                    MVT::i32);
7639     SDValue Result = DAG.getMemIntrinsicNode(
7640         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
7641         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
7642         /* align */ std::nullopt, Flags);
7643 
7644     // Chain the prefetch in parallel with any pending loads, to stay out of
7645     // the way of later optimizations.
7646     PendingLoads.push_back(Result);
7647     Result = getRoot();
7648     DAG.setRoot(Result);
7649     return;
7650   }
7651   case Intrinsic::lifetime_start:
7652   case Intrinsic::lifetime_end: {
7653     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
7654     // Stack coloring is not enabled in O0, discard region information.
7655     if (TM.getOptLevel() == CodeGenOptLevel::None)
7656       return;
7657 
7658     const int64_t ObjectSize =
7659         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
7660     Value *const ObjectPtr = I.getArgOperand(1);
7661     SmallVector<const Value *, 4> Allocas;
7662     getUnderlyingObjects(ObjectPtr, Allocas);
7663 
7664     for (const Value *Alloca : Allocas) {
7665       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
7666 
7667       // Could not find an Alloca.
7668       if (!LifetimeObject)
7669         continue;
7670 
7671       // First check that the Alloca is static, otherwise it won't have a
7672       // valid frame index.
7673       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
7674       if (SI == FuncInfo.StaticAllocaMap.end())
7675         return;
7676 
7677       const int FrameIndex = SI->second;
7678       int64_t Offset;
7679       if (GetPointerBaseWithConstantOffset(
7680               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
7681         Offset = -1; // Cannot determine offset from alloca to lifetime object.
7682       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
7683                                 Offset);
7684       DAG.setRoot(Res);
7685     }
7686     return;
7687   }
7688   case Intrinsic::pseudoprobe: {
7689     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
7690     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7691     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
7692     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
7693     DAG.setRoot(Res);
7694     return;
7695   }
7696   case Intrinsic::invariant_start:
7697     // Discard region information.
7698     setValue(&I,
7699              DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
7700     return;
7701   case Intrinsic::invariant_end:
7702     // Discard region information.
7703     return;
7704   case Intrinsic::clear_cache: {
7705     SDValue InputChain = DAG.getRoot();
7706     SDValue StartVal = getValue(I.getArgOperand(0));
7707     SDValue EndVal = getValue(I.getArgOperand(1));
7708     Res = DAG.getNode(ISD::CLEAR_CACHE, sdl, DAG.getVTList(MVT::Other),
7709                       {InputChain, StartVal, EndVal});
7710     setValue(&I, Res);
7711     DAG.setRoot(Res);
7712     return;
7713   }
7714   case Intrinsic::donothing:
7715   case Intrinsic::seh_try_begin:
7716   case Intrinsic::seh_scope_begin:
7717   case Intrinsic::seh_try_end:
7718   case Intrinsic::seh_scope_end:
7719     // ignore
7720     return;
7721   case Intrinsic::experimental_stackmap:
7722     visitStackmap(I);
7723     return;
7724   case Intrinsic::experimental_patchpoint_void:
7725   case Intrinsic::experimental_patchpoint:
7726     visitPatchpoint(I);
7727     return;
7728   case Intrinsic::experimental_gc_statepoint:
7729     LowerStatepoint(cast<GCStatepointInst>(I));
7730     return;
7731   case Intrinsic::experimental_gc_result:
7732     visitGCResult(cast<GCResultInst>(I));
7733     return;
7734   case Intrinsic::experimental_gc_relocate:
7735     visitGCRelocate(cast<GCRelocateInst>(I));
7736     return;
7737   case Intrinsic::instrprof_cover:
7738     llvm_unreachable("instrprof failed to lower a cover");
7739   case Intrinsic::instrprof_increment:
7740     llvm_unreachable("instrprof failed to lower an increment");
7741   case Intrinsic::instrprof_timestamp:
7742     llvm_unreachable("instrprof failed to lower a timestamp");
7743   case Intrinsic::instrprof_value_profile:
7744     llvm_unreachable("instrprof failed to lower a value profiling call");
7745   case Intrinsic::instrprof_mcdc_parameters:
7746     llvm_unreachable("instrprof failed to lower mcdc parameters");
7747   case Intrinsic::instrprof_mcdc_tvbitmap_update:
7748     llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update");
7749   case Intrinsic::localescape: {
7750     MachineFunction &MF = DAG.getMachineFunction();
7751     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
7752 
7753     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
7754     // is the same on all targets.
7755     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
7756       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
7757       if (isa<ConstantPointerNull>(Arg))
7758         continue; // Skip null pointers. They represent a hole in index space.
7759       AllocaInst *Slot = cast<AllocaInst>(Arg);
7760       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
7761              "can only escape static allocas");
7762       int FI = FuncInfo.StaticAllocaMap[Slot];
7763       MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
7764           GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
7765       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
7766               TII->get(TargetOpcode::LOCAL_ESCAPE))
7767           .addSym(FrameAllocSym)
7768           .addFrameIndex(FI);
7769     }
7770 
7771     return;
7772   }
7773 
7774   case Intrinsic::localrecover: {
7775     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
7776     MachineFunction &MF = DAG.getMachineFunction();
7777 
7778     // Get the symbol that defines the frame offset.
7779     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
7780     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
7781     unsigned IdxVal =
7782         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
7783     MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
7784         GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
7785 
7786     Value *FP = I.getArgOperand(1);
7787     SDValue FPVal = getValue(FP);
7788     EVT PtrVT = FPVal.getValueType();
7789 
7790     // Create a MCSymbol for the label to avoid any target lowering
7791     // that would make this PC relative.
7792     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
7793     SDValue OffsetVal =
7794         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
7795 
7796     // Add the offset to the FP.
7797     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
7798     setValue(&I, Add);
7799 
7800     return;
7801   }
7802 
7803   case Intrinsic::fake_use: {
7804     Value *V = I.getArgOperand(0);
7805     SDValue Ops[2];
7806     // For Values not declared or previously used in this basic block, the
7807     // NodeMap will not have an entry, and `getValue` will assert if V has no
7808     // valid register value.
7809     auto FakeUseValue = [&]() -> SDValue {
7810       SDValue &N = NodeMap[V];
7811       if (N.getNode())
7812         return N;
7813 
7814       // If there's a virtual register allocated and initialized for this
7815       // value, use it.
7816       if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
7817         return copyFromReg;
7818       // FIXME: Do we want to preserve constants? It seems pointless.
7819       if (isa<Constant>(V))
7820         return getValue(V);
7821       return SDValue();
7822     }();
7823     if (!FakeUseValue || FakeUseValue.isUndef())
7824       return;
7825     Ops[0] = getRoot();
7826     Ops[1] = FakeUseValue;
7827     // Also, do not translate a fake use with an undef operand, or any other
7828     // empty SDValues.
7829     if (!Ops[1] || Ops[1].isUndef())
7830       return;
7831     DAG.setRoot(DAG.getNode(ISD::FAKE_USE, sdl, MVT::Other, Ops));
7832     return;
7833   }
7834 
7835   case Intrinsic::eh_exceptionpointer:
7836   case Intrinsic::eh_exceptioncode: {
7837     // Get the exception pointer vreg, copy from it, and resize it to fit.
7838     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
7839     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
7840     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
7841     Register VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
7842     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
7843     if (Intrinsic == Intrinsic::eh_exceptioncode)
7844       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
7845     setValue(&I, N);
7846     return;
7847   }
7848   case Intrinsic::xray_customevent: {
7849     // Here we want to make sure that the intrinsic behaves as if it has a
7850     // specific calling convention.
7851     const auto &Triple = DAG.getTarget().getTargetTriple();
7852     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7853       return;
7854 
7855     SmallVector<SDValue, 8> Ops;
7856 
7857     // We want to say that we always want the arguments in registers.
7858     SDValue LogEntryVal = getValue(I.getArgOperand(0));
7859     SDValue StrSizeVal = getValue(I.getArgOperand(1));
7860     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7861     SDValue Chain = getRoot();
7862     Ops.push_back(LogEntryVal);
7863     Ops.push_back(StrSizeVal);
7864     Ops.push_back(Chain);
7865 
7866     // We need to enforce the calling convention for the callsite, so that
7867     // argument ordering is enforced correctly, and that register allocation can
7868     // see that some registers may be assumed clobbered and have to preserve
7869     // them across calls to the intrinsic.
7870     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
7871                                            sdl, NodeTys, Ops);
7872     SDValue patchableNode = SDValue(MN, 0);
7873     DAG.setRoot(patchableNode);
7874     setValue(&I, patchableNode);
7875     return;
7876   }
7877   case Intrinsic::xray_typedevent: {
7878     // Here we want to make sure that the intrinsic behaves as if it has a
7879     // specific calling convention.
7880     const auto &Triple = DAG.getTarget().getTargetTriple();
7881     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7882       return;
7883 
7884     SmallVector<SDValue, 8> Ops;
7885 
7886     // We want to say that we always want the arguments in registers.
7887     // It's unclear to me how manipulating the selection DAG here forces callers
7888     // to provide arguments in registers instead of on the stack.
7889     SDValue LogTypeId = getValue(I.getArgOperand(0));
7890     SDValue LogEntryVal = getValue(I.getArgOperand(1));
7891     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7892     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7893     SDValue Chain = getRoot();
7894     Ops.push_back(LogTypeId);
7895     Ops.push_back(LogEntryVal);
7896     Ops.push_back(StrSizeVal);
7897     Ops.push_back(Chain);
7898 
7899     // We need to enforce the calling convention for the callsite, so that
7900     // argument ordering is enforced correctly, and that register allocation can
7901     // see that some registers may be assumed clobbered and have to preserve
7902     // them across calls to the intrinsic.
7903     MachineSDNode *MN = DAG.getMachineNode(
7904         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7905     SDValue patchableNode = SDValue(MN, 0);
7906     DAG.setRoot(patchableNode);
7907     setValue(&I, patchableNode);
7908     return;
7909   }
7910   case Intrinsic::experimental_deoptimize:
7911     LowerDeoptimizeCall(&I);
7912     return;
7913   case Intrinsic::stepvector:
7914     visitStepVector(I);
7915     return;
7916   case Intrinsic::vector_reduce_fadd:
7917   case Intrinsic::vector_reduce_fmul:
7918   case Intrinsic::vector_reduce_add:
7919   case Intrinsic::vector_reduce_mul:
7920   case Intrinsic::vector_reduce_and:
7921   case Intrinsic::vector_reduce_or:
7922   case Intrinsic::vector_reduce_xor:
7923   case Intrinsic::vector_reduce_smax:
7924   case Intrinsic::vector_reduce_smin:
7925   case Intrinsic::vector_reduce_umax:
7926   case Intrinsic::vector_reduce_umin:
7927   case Intrinsic::vector_reduce_fmax:
7928   case Intrinsic::vector_reduce_fmin:
7929   case Intrinsic::vector_reduce_fmaximum:
7930   case Intrinsic::vector_reduce_fminimum:
7931     visitVectorReduce(I, Intrinsic);
7932     return;
7933 
7934   case Intrinsic::icall_branch_funnel: {
7935     SmallVector<SDValue, 16> Ops;
7936     Ops.push_back(getValue(I.getArgOperand(0)));
7937 
7938     int64_t Offset;
7939     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7940         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7941     if (!Base)
7942       report_fatal_error(
7943           "llvm.icall.branch.funnel operand must be a GlobalValue");
7944     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7945 
7946     struct BranchFunnelTarget {
7947       int64_t Offset;
7948       SDValue Target;
7949     };
7950     SmallVector<BranchFunnelTarget, 8> Targets;
7951 
7952     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7953       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7954           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7955       if (ElemBase != Base)
7956         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7957                            "to the same GlobalValue");
7958 
7959       SDValue Val = getValue(I.getArgOperand(Op + 1));
7960       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7961       if (!GA)
7962         report_fatal_error(
7963             "llvm.icall.branch.funnel operand must be a GlobalValue");
7964       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7965                                      GA->getGlobal(), sdl, Val.getValueType(),
7966                                      GA->getOffset())});
7967     }
7968     llvm::sort(Targets,
7969                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7970                  return T1.Offset < T2.Offset;
7971                });
7972 
7973     for (auto &T : Targets) {
7974       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7975       Ops.push_back(T.Target);
7976     }
7977 
7978     Ops.push_back(DAG.getRoot()); // Chain
7979     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7980                                  MVT::Other, Ops),
7981               0);
7982     DAG.setRoot(N);
7983     setValue(&I, N);
7984     HasTailCall = true;
7985     return;
7986   }
7987 
7988   case Intrinsic::wasm_landingpad_index:
7989     // Information this intrinsic contained has been transferred to
7990     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7991     // delete it now.
7992     return;
7993 
7994   case Intrinsic::aarch64_settag:
7995   case Intrinsic::aarch64_settag_zero: {
7996     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7997     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7998     SDValue Val = TSI.EmitTargetCodeForSetTag(
7999         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
8000         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
8001         ZeroMemory);
8002     DAG.setRoot(Val);
8003     setValue(&I, Val);
8004     return;
8005   }
8006   case Intrinsic::amdgcn_cs_chain: {
8007     assert(I.arg_size() == 5 && "Additional args not supported yet");
8008     assert(cast<ConstantInt>(I.getOperand(4))->isZero() &&
8009            "Non-zero flags not supported yet");
8010 
8011     // At this point we don't care if it's amdgpu_cs_chain or
8012     // amdgpu_cs_chain_preserve.
8013     CallingConv::ID CC = CallingConv::AMDGPU_CS_Chain;
8014 
8015     Type *RetTy = I.getType();
8016     assert(RetTy->isVoidTy() && "Should not return");
8017 
8018     SDValue Callee = getValue(I.getOperand(0));
8019 
8020     // We only have 2 actual args: one for the SGPRs and one for the VGPRs.
8021     // We'll also tack the value of the EXEC mask at the end.
8022     TargetLowering::ArgListTy Args;
8023     Args.reserve(3);
8024 
8025     for (unsigned Idx : {2, 3, 1}) {
8026       TargetLowering::ArgListEntry Arg;
8027       Arg.Node = getValue(I.getOperand(Idx));
8028       Arg.Ty = I.getOperand(Idx)->getType();
8029       Arg.setAttributes(&I, Idx);
8030       Args.push_back(Arg);
8031     }
8032 
8033     assert(Args[0].IsInReg && "SGPR args should be marked inreg");
8034     assert(!Args[1].IsInReg && "VGPR args should not be marked inreg");
8035     Args[2].IsInReg = true; // EXEC should be inreg
8036 
8037     TargetLowering::CallLoweringInfo CLI(DAG);
8038     CLI.setDebugLoc(getCurSDLoc())
8039         .setChain(getRoot())
8040         .setCallee(CC, RetTy, Callee, std::move(Args))
8041         .setNoReturn(true)
8042         .setTailCall(true)
8043         .setConvergent(I.isConvergent());
8044     CLI.CB = &I;
8045     std::pair<SDValue, SDValue> Result =
8046         lowerInvokable(CLI, /*EHPadBB*/ nullptr);
8047     (void)Result;
8048     assert(!Result.first.getNode() && !Result.second.getNode() &&
8049            "Should've lowered as tail call");
8050 
8051     HasTailCall = true;
8052     return;
8053   }
8054   case Intrinsic::ptrmask: {
8055     SDValue Ptr = getValue(I.getOperand(0));
8056     SDValue Mask = getValue(I.getOperand(1));
8057 
8058     // On arm64_32, pointers are 32 bits when stored in memory, but
8059     // zero-extended to 64 bits when in registers.  Thus the mask is 32 bits to
8060     // match the index type, but the pointer is 64 bits, so the the mask must be
8061     // zero-extended up to 64 bits to match the pointer.
8062     EVT PtrVT =
8063         TLI.getValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
8064     EVT MemVT =
8065         TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
8066     assert(PtrVT == Ptr.getValueType());
8067     assert(MemVT == Mask.getValueType());
8068     if (MemVT != PtrVT)
8069       Mask = DAG.getPtrExtOrTrunc(Mask, sdl, PtrVT);
8070 
8071     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask));
8072     return;
8073   }
8074   case Intrinsic::threadlocal_address: {
8075     setValue(&I, getValue(I.getOperand(0)));
8076     return;
8077   }
8078   case Intrinsic::get_active_lane_mask: {
8079     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8080     SDValue Index = getValue(I.getOperand(0));
8081     EVT ElementVT = Index.getValueType();
8082 
8083     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
8084       visitTargetIntrinsic(I, Intrinsic);
8085       return;
8086     }
8087 
8088     SDValue TripCount = getValue(I.getOperand(1));
8089     EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT,
8090                                  CCVT.getVectorElementCount());
8091 
8092     SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
8093     SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
8094     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
8095     SDValue VectorInduction = DAG.getNode(
8096         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
8097     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
8098                                  VectorTripCount, ISD::CondCode::SETULT);
8099     setValue(&I, SetCC);
8100     return;
8101   }
8102   case Intrinsic::experimental_get_vector_length: {
8103     assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 &&
8104            "Expected positive VF");
8105     unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue();
8106     bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne();
8107 
8108     SDValue Count = getValue(I.getOperand(0));
8109     EVT CountVT = Count.getValueType();
8110 
8111     if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) {
8112       visitTargetIntrinsic(I, Intrinsic);
8113       return;
8114     }
8115 
8116     // Expand to a umin between the trip count and the maximum elements the type
8117     // can hold.
8118     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8119 
8120     // Extend the trip count to at least the result VT.
8121     if (CountVT.bitsLT(VT)) {
8122       Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count);
8123       CountVT = VT;
8124     }
8125 
8126     SDValue MaxEVL = DAG.getElementCount(sdl, CountVT,
8127                                          ElementCount::get(VF, IsScalable));
8128 
8129     SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL);
8130     // Clip to the result type if needed.
8131     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin);
8132 
8133     setValue(&I, Trunc);
8134     return;
8135   }
8136   case Intrinsic::experimental_vector_partial_reduce_add: {
8137 
8138     if (!TLI.shouldExpandPartialReductionIntrinsic(cast<IntrinsicInst>(&I))) {
8139       visitTargetIntrinsic(I, Intrinsic);
8140       return;
8141     }
8142 
8143     setValue(&I, DAG.getPartialReduceAdd(sdl, EVT::getEVT(I.getType()),
8144                                          getValue(I.getOperand(0)),
8145                                          getValue(I.getOperand(1))));
8146     return;
8147   }
8148   case Intrinsic::experimental_cttz_elts: {
8149     auto DL = getCurSDLoc();
8150     SDValue Op = getValue(I.getOperand(0));
8151     EVT OpVT = Op.getValueType();
8152 
8153     if (!TLI.shouldExpandCttzElements(OpVT)) {
8154       visitTargetIntrinsic(I, Intrinsic);
8155       return;
8156     }
8157 
8158     if (OpVT.getScalarType() != MVT::i1) {
8159       // Compare the input vector elements to zero & use to count trailing zeros
8160       SDValue AllZero = DAG.getConstant(0, DL, OpVT);
8161       OpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
8162                               OpVT.getVectorElementCount());
8163       Op = DAG.getSetCC(DL, OpVT, Op, AllZero, ISD::SETNE);
8164     }
8165 
8166     // If the zero-is-poison flag is set, we can assume the upper limit
8167     // of the result is VF-1.
8168     bool ZeroIsPoison =
8169         !cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero();
8170     ConstantRange VScaleRange(1, true); // Dummy value.
8171     if (isa<ScalableVectorType>(I.getOperand(0)->getType()))
8172       VScaleRange = getVScaleRange(I.getCaller(), 64);
8173     unsigned EltWidth = TLI.getBitWidthForCttzElements(
8174         I.getType(), OpVT.getVectorElementCount(), ZeroIsPoison, &VScaleRange);
8175 
8176     MVT NewEltTy = MVT::getIntegerVT(EltWidth);
8177 
8178     // Create the new vector type & get the vector length
8179     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), NewEltTy,
8180                                  OpVT.getVectorElementCount());
8181 
8182     SDValue VL =
8183         DAG.getElementCount(DL, NewEltTy, OpVT.getVectorElementCount());
8184 
8185     SDValue StepVec = DAG.getStepVector(DL, NewVT);
8186     SDValue SplatVL = DAG.getSplat(NewVT, DL, VL);
8187     SDValue StepVL = DAG.getNode(ISD::SUB, DL, NewVT, SplatVL, StepVec);
8188     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, Op);
8189     SDValue And = DAG.getNode(ISD::AND, DL, NewVT, StepVL, Ext);
8190     SDValue Max = DAG.getNode(ISD::VECREDUCE_UMAX, DL, NewEltTy, And);
8191     SDValue Sub = DAG.getNode(ISD::SUB, DL, NewEltTy, VL, Max);
8192 
8193     EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
8194     SDValue Ret = DAG.getZExtOrTrunc(Sub, DL, RetTy);
8195 
8196     setValue(&I, Ret);
8197     return;
8198   }
8199   case Intrinsic::vector_insert: {
8200     SDValue Vec = getValue(I.getOperand(0));
8201     SDValue SubVec = getValue(I.getOperand(1));
8202     SDValue Index = getValue(I.getOperand(2));
8203 
8204     // The intrinsic's index type is i64, but the SDNode requires an index type
8205     // suitable for the target. Convert the index as required.
8206     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8207     if (Index.getValueType() != VectorIdxTy)
8208       Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8209 
8210     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8211     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
8212                              Index));
8213     return;
8214   }
8215   case Intrinsic::vector_extract: {
8216     SDValue Vec = getValue(I.getOperand(0));
8217     SDValue Index = getValue(I.getOperand(1));
8218     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8219 
8220     // The intrinsic's index type is i64, but the SDNode requires an index type
8221     // suitable for the target. Convert the index as required.
8222     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8223     if (Index.getValueType() != VectorIdxTy)
8224       Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8225 
8226     setValue(&I,
8227              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
8228     return;
8229   }
8230   case Intrinsic::experimental_vector_match: {
8231     SDValue Op1 = getValue(I.getOperand(0));
8232     SDValue Op2 = getValue(I.getOperand(1));
8233     SDValue Mask = getValue(I.getOperand(2));
8234     EVT Op1VT = Op1.getValueType();
8235     EVT Op2VT = Op2.getValueType();
8236     EVT ResVT = Mask.getValueType();
8237     unsigned SearchSize = Op2VT.getVectorNumElements();
8238 
8239     // If the target has native support for this vector match operation, lower
8240     // the intrinsic untouched; otherwise, expand it below.
8241     if (!TLI.shouldExpandVectorMatch(Op1VT, SearchSize)) {
8242       visitTargetIntrinsic(I, Intrinsic);
8243       return;
8244     }
8245 
8246     SDValue Ret = DAG.getConstant(0, sdl, ResVT);
8247 
8248     for (unsigned i = 0; i < SearchSize; ++i) {
8249       SDValue Op2Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, sdl,
8250                                     Op2VT.getVectorElementType(), Op2,
8251                                     DAG.getVectorIdxConstant(i, sdl));
8252       SDValue Splat = DAG.getNode(ISD::SPLAT_VECTOR, sdl, Op1VT, Op2Elem);
8253       SDValue Cmp = DAG.getSetCC(sdl, ResVT, Op1, Splat, ISD::SETEQ);
8254       Ret = DAG.getNode(ISD::OR, sdl, ResVT, Ret, Cmp);
8255     }
8256 
8257     setValue(&I, DAG.getNode(ISD::AND, sdl, ResVT, Ret, Mask));
8258     return;
8259   }
8260   case Intrinsic::vector_reverse:
8261     visitVectorReverse(I);
8262     return;
8263   case Intrinsic::vector_splice:
8264     visitVectorSplice(I);
8265     return;
8266   case Intrinsic::callbr_landingpad:
8267     visitCallBrLandingPad(I);
8268     return;
8269   case Intrinsic::vector_interleave2:
8270     visitVectorInterleave(I);
8271     return;
8272   case Intrinsic::vector_deinterleave2:
8273     visitVectorDeinterleave(I);
8274     return;
8275   case Intrinsic::experimental_vector_compress:
8276     setValue(&I, DAG.getNode(ISD::VECTOR_COMPRESS, sdl,
8277                              getValue(I.getArgOperand(0)).getValueType(),
8278                              getValue(I.getArgOperand(0)),
8279                              getValue(I.getArgOperand(1)),
8280                              getValue(I.getArgOperand(2)), Flags));
8281     return;
8282   case Intrinsic::experimental_convergence_anchor:
8283   case Intrinsic::experimental_convergence_entry:
8284   case Intrinsic::experimental_convergence_loop:
8285     visitConvergenceControl(I, Intrinsic);
8286     return;
8287   case Intrinsic::experimental_vector_histogram_add: {
8288     visitVectorHistogram(I, Intrinsic);
8289     return;
8290   }
8291   case Intrinsic::experimental_vector_extract_last_active: {
8292     visitVectorExtractLastActive(I, Intrinsic);
8293     return;
8294   }
8295   }
8296 }
8297 
8298 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
8299     const ConstrainedFPIntrinsic &FPI) {
8300   SDLoc sdl = getCurSDLoc();
8301 
8302   // We do not need to serialize constrained FP intrinsics against
8303   // each other or against (nonvolatile) loads, so they can be
8304   // chained like loads.
8305   SDValue Chain = DAG.getRoot();
8306   SmallVector<SDValue, 4> Opers;
8307   Opers.push_back(Chain);
8308   for (unsigned I = 0, E = FPI.getNonMetadataArgCount(); I != E; ++I)
8309     Opers.push_back(getValue(FPI.getArgOperand(I)));
8310 
8311   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
8312     assert(Result.getNode()->getNumValues() == 2);
8313 
8314     // Push node to the appropriate list so that future instructions can be
8315     // chained up correctly.
8316     SDValue OutChain = Result.getValue(1);
8317     switch (EB) {
8318     case fp::ExceptionBehavior::ebIgnore:
8319       // The only reason why ebIgnore nodes still need to be chained is that
8320       // they might depend on the current rounding mode, and therefore must
8321       // not be moved across instruction that may change that mode.
8322       [[fallthrough]];
8323     case fp::ExceptionBehavior::ebMayTrap:
8324       // These must not be moved across calls or instructions that may change
8325       // floating-point exception masks.
8326       PendingConstrainedFP.push_back(OutChain);
8327       break;
8328     case fp::ExceptionBehavior::ebStrict:
8329       // These must not be moved across calls or instructions that may change
8330       // floating-point exception masks or read floating-point exception flags.
8331       // In addition, they cannot be optimized out even if unused.
8332       PendingConstrainedFPStrict.push_back(OutChain);
8333       break;
8334     }
8335   };
8336 
8337   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8338   EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
8339   SDVTList VTs = DAG.getVTList(VT, MVT::Other);
8340   fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
8341 
8342   SDNodeFlags Flags;
8343   if (EB == fp::ExceptionBehavior::ebIgnore)
8344     Flags.setNoFPExcept(true);
8345 
8346   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
8347     Flags.copyFMF(*FPOp);
8348 
8349   unsigned Opcode;
8350   switch (FPI.getIntrinsicID()) {
8351   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
8352 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8353   case Intrinsic::INTRINSIC:                                                   \
8354     Opcode = ISD::STRICT_##DAGN;                                               \
8355     break;
8356 #include "llvm/IR/ConstrainedOps.def"
8357   case Intrinsic::experimental_constrained_fmuladd: {
8358     Opcode = ISD::STRICT_FMA;
8359     // Break fmuladd into fmul and fadd.
8360     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
8361         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
8362       Opers.pop_back();
8363       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
8364       pushOutChain(Mul, EB);
8365       Opcode = ISD::STRICT_FADD;
8366       Opers.clear();
8367       Opers.push_back(Mul.getValue(1));
8368       Opers.push_back(Mul.getValue(0));
8369       Opers.push_back(getValue(FPI.getArgOperand(2)));
8370     }
8371     break;
8372   }
8373   }
8374 
8375   // A few strict DAG nodes carry additional operands that are not
8376   // set up by the default code above.
8377   switch (Opcode) {
8378   default: break;
8379   case ISD::STRICT_FP_ROUND:
8380     Opers.push_back(
8381         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
8382     break;
8383   case ISD::STRICT_FSETCC:
8384   case ISD::STRICT_FSETCCS: {
8385     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
8386     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
8387     if (TM.Options.NoNaNsFPMath)
8388       Condition = getFCmpCodeWithoutNaN(Condition);
8389     Opers.push_back(DAG.getCondCode(Condition));
8390     break;
8391   }
8392   }
8393 
8394   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
8395   pushOutChain(Result, EB);
8396 
8397   SDValue FPResult = Result.getValue(0);
8398   setValue(&FPI, FPResult);
8399 }
8400 
8401 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
8402   std::optional<unsigned> ResOPC;
8403   switch (VPIntrin.getIntrinsicID()) {
8404   case Intrinsic::vp_ctlz: {
8405     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8406     ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ;
8407     break;
8408   }
8409   case Intrinsic::vp_cttz: {
8410     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8411     ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ;
8412     break;
8413   }
8414   case Intrinsic::vp_cttz_elts: {
8415     bool IsZeroPoison = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8416     ResOPC = IsZeroPoison ? ISD::VP_CTTZ_ELTS_ZERO_UNDEF : ISD::VP_CTTZ_ELTS;
8417     break;
8418   }
8419 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD)                                    \
8420   case Intrinsic::VPID:                                                        \
8421     ResOPC = ISD::VPSD;                                                        \
8422     break;
8423 #include "llvm/IR/VPIntrinsics.def"
8424   }
8425 
8426   if (!ResOPC)
8427     llvm_unreachable(
8428         "Inconsistency: no SDNode available for this VPIntrinsic!");
8429 
8430   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
8431       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
8432     if (VPIntrin.getFastMathFlags().allowReassoc())
8433       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
8434                                                 : ISD::VP_REDUCE_FMUL;
8435   }
8436 
8437   return *ResOPC;
8438 }
8439 
8440 void SelectionDAGBuilder::visitVPLoad(
8441     const VPIntrinsic &VPIntrin, EVT VT,
8442     const SmallVectorImpl<SDValue> &OpValues) {
8443   SDLoc DL = getCurSDLoc();
8444   Value *PtrOperand = VPIntrin.getArgOperand(0);
8445   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8446   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8447   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8448   SDValue LD;
8449   // Do not serialize variable-length loads of constant memory with
8450   // anything.
8451   if (!Alignment)
8452     Alignment = DAG.getEVTAlign(VT);
8453   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
8454   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
8455   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8456   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8457       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
8458       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8459   LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
8460                      MMO, false /*IsExpanding */);
8461   if (AddToChain)
8462     PendingLoads.push_back(LD.getValue(1));
8463   setValue(&VPIntrin, LD);
8464 }
8465 
8466 void SelectionDAGBuilder::visitVPGather(
8467     const VPIntrinsic &VPIntrin, EVT VT,
8468     const SmallVectorImpl<SDValue> &OpValues) {
8469   SDLoc DL = getCurSDLoc();
8470   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8471   Value *PtrOperand = VPIntrin.getArgOperand(0);
8472   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8473   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8474   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8475   SDValue LD;
8476   if (!Alignment)
8477     Alignment = DAG.getEVTAlign(VT.getScalarType());
8478   unsigned AS =
8479     PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8480   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8481       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
8482       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8483   SDValue Base, Index, Scale;
8484   ISD::MemIndexType IndexType;
8485   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
8486                                     this, VPIntrin.getParent(),
8487                                     VT.getScalarStoreSize());
8488   if (!UniformBase) {
8489     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
8490     Index = getValue(PtrOperand);
8491     IndexType = ISD::SIGNED_SCALED;
8492     Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
8493   }
8494   EVT IdxVT = Index.getValueType();
8495   EVT EltTy = IdxVT.getVectorElementType();
8496   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
8497     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
8498     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
8499   }
8500   LD = DAG.getGatherVP(
8501       DAG.getVTList(VT, MVT::Other), VT, DL,
8502       {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
8503       IndexType);
8504   PendingLoads.push_back(LD.getValue(1));
8505   setValue(&VPIntrin, LD);
8506 }
8507 
8508 void SelectionDAGBuilder::visitVPStore(
8509     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8510   SDLoc DL = getCurSDLoc();
8511   Value *PtrOperand = VPIntrin.getArgOperand(1);
8512   EVT VT = OpValues[0].getValueType();
8513   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8514   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8515   SDValue ST;
8516   if (!Alignment)
8517     Alignment = DAG.getEVTAlign(VT);
8518   SDValue Ptr = OpValues[1];
8519   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
8520   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8521       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
8522       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8523   ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
8524                       OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
8525                       /* IsTruncating */ false, /*IsCompressing*/ false);
8526   DAG.setRoot(ST);
8527   setValue(&VPIntrin, ST);
8528 }
8529 
8530 void SelectionDAGBuilder::visitVPScatter(
8531     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8532   SDLoc DL = getCurSDLoc();
8533   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8534   Value *PtrOperand = VPIntrin.getArgOperand(1);
8535   EVT VT = OpValues[0].getValueType();
8536   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8537   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8538   SDValue ST;
8539   if (!Alignment)
8540     Alignment = DAG.getEVTAlign(VT.getScalarType());
8541   unsigned AS =
8542       PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8543   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8544       MachinePointerInfo(AS), MachineMemOperand::MOStore,
8545       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8546   SDValue Base, Index, Scale;
8547   ISD::MemIndexType IndexType;
8548   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
8549                                     this, VPIntrin.getParent(),
8550                                     VT.getScalarStoreSize());
8551   if (!UniformBase) {
8552     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
8553     Index = getValue(PtrOperand);
8554     IndexType = ISD::SIGNED_SCALED;
8555     Scale =
8556       DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
8557   }
8558   EVT IdxVT = Index.getValueType();
8559   EVT EltTy = IdxVT.getVectorElementType();
8560   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
8561     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
8562     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
8563   }
8564   ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
8565                         {getMemoryRoot(), OpValues[0], Base, Index, Scale,
8566                          OpValues[2], OpValues[3]},
8567                         MMO, IndexType);
8568   DAG.setRoot(ST);
8569   setValue(&VPIntrin, ST);
8570 }
8571 
8572 void SelectionDAGBuilder::visitVPStridedLoad(
8573     const VPIntrinsic &VPIntrin, EVT VT,
8574     const SmallVectorImpl<SDValue> &OpValues) {
8575   SDLoc DL = getCurSDLoc();
8576   Value *PtrOperand = VPIntrin.getArgOperand(0);
8577   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8578   if (!Alignment)
8579     Alignment = DAG.getEVTAlign(VT.getScalarType());
8580   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8581   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8582   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
8583   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
8584   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8585   unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8586   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8587       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
8588       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8589 
8590   SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
8591                                     OpValues[2], OpValues[3], MMO,
8592                                     false /*IsExpanding*/);
8593 
8594   if (AddToChain)
8595     PendingLoads.push_back(LD.getValue(1));
8596   setValue(&VPIntrin, LD);
8597 }
8598 
8599 void SelectionDAGBuilder::visitVPStridedStore(
8600     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8601   SDLoc DL = getCurSDLoc();
8602   Value *PtrOperand = VPIntrin.getArgOperand(1);
8603   EVT VT = OpValues[0].getValueType();
8604   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8605   if (!Alignment)
8606     Alignment = DAG.getEVTAlign(VT.getScalarType());
8607   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8608   unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8609   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8610       MachinePointerInfo(AS), MachineMemOperand::MOStore,
8611       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8612 
8613   SDValue ST = DAG.getStridedStoreVP(
8614       getMemoryRoot(), DL, OpValues[0], OpValues[1],
8615       DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3],
8616       OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
8617       /*IsCompressing*/ false);
8618 
8619   DAG.setRoot(ST);
8620   setValue(&VPIntrin, ST);
8621 }
8622 
8623 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) {
8624   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8625   SDLoc DL = getCurSDLoc();
8626 
8627   ISD::CondCode Condition;
8628   CmpInst::Predicate CondCode = VPIntrin.getPredicate();
8629   bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy();
8630   if (IsFP) {
8631     // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan)
8632     // flags, but calls that don't return floating-point types can't be
8633     // FPMathOperators, like vp.fcmp. This affects constrained fcmp too.
8634     Condition = getFCmpCondCode(CondCode);
8635     if (TM.Options.NoNaNsFPMath)
8636       Condition = getFCmpCodeWithoutNaN(Condition);
8637   } else {
8638     Condition = getICmpCondCode(CondCode);
8639   }
8640 
8641   SDValue Op1 = getValue(VPIntrin.getOperand(0));
8642   SDValue Op2 = getValue(VPIntrin.getOperand(1));
8643   // #2 is the condition code
8644   SDValue MaskOp = getValue(VPIntrin.getOperand(3));
8645   SDValue EVL = getValue(VPIntrin.getOperand(4));
8646   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8647   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8648          "Unexpected target EVL type");
8649   EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL);
8650 
8651   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8652                                                         VPIntrin.getType());
8653   setValue(&VPIntrin,
8654            DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL));
8655 }
8656 
8657 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
8658     const VPIntrinsic &VPIntrin) {
8659   SDLoc DL = getCurSDLoc();
8660   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
8661 
8662   auto IID = VPIntrin.getIntrinsicID();
8663 
8664   if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin))
8665     return visitVPCmp(*CmpI);
8666 
8667   SmallVector<EVT, 4> ValueVTs;
8668   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8669   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
8670   SDVTList VTs = DAG.getVTList(ValueVTs);
8671 
8672   auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
8673 
8674   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8675   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8676          "Unexpected target EVL type");
8677 
8678   // Request operands.
8679   SmallVector<SDValue, 7> OpValues;
8680   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
8681     auto Op = getValue(VPIntrin.getArgOperand(I));
8682     if (I == EVLParamPos)
8683       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
8684     OpValues.push_back(Op);
8685   }
8686 
8687   switch (Opcode) {
8688   default: {
8689     SDNodeFlags SDFlags;
8690     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8691       SDFlags.copyFMF(*FPMO);
8692     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
8693     setValue(&VPIntrin, Result);
8694     break;
8695   }
8696   case ISD::VP_LOAD:
8697     visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
8698     break;
8699   case ISD::VP_GATHER:
8700     visitVPGather(VPIntrin, ValueVTs[0], OpValues);
8701     break;
8702   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
8703     visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
8704     break;
8705   case ISD::VP_STORE:
8706     visitVPStore(VPIntrin, OpValues);
8707     break;
8708   case ISD::VP_SCATTER:
8709     visitVPScatter(VPIntrin, OpValues);
8710     break;
8711   case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
8712     visitVPStridedStore(VPIntrin, OpValues);
8713     break;
8714   case ISD::VP_FMULADD: {
8715     assert(OpValues.size() == 5 && "Unexpected number of operands");
8716     SDNodeFlags SDFlags;
8717     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8718       SDFlags.copyFMF(*FPMO);
8719     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
8720         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) {
8721       setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags));
8722     } else {
8723       SDValue Mul = DAG.getNode(
8724           ISD::VP_FMUL, DL, VTs,
8725           {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags);
8726       SDValue Add =
8727           DAG.getNode(ISD::VP_FADD, DL, VTs,
8728                       {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags);
8729       setValue(&VPIntrin, Add);
8730     }
8731     break;
8732   }
8733   case ISD::VP_IS_FPCLASS: {
8734     const DataLayout DLayout = DAG.getDataLayout();
8735     EVT DestVT = TLI.getValueType(DLayout, VPIntrin.getType());
8736     auto Constant = OpValues[1]->getAsZExtVal();
8737     SDValue Check = DAG.getTargetConstant(Constant, DL, MVT::i32);
8738     SDValue V = DAG.getNode(ISD::VP_IS_FPCLASS, DL, DestVT,
8739                             {OpValues[0], Check, OpValues[2], OpValues[3]});
8740     setValue(&VPIntrin, V);
8741     return;
8742   }
8743   case ISD::VP_INTTOPTR: {
8744     SDValue N = OpValues[0];
8745     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType());
8746     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType());
8747     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8748                                OpValues[2]);
8749     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8750                              OpValues[2]);
8751     setValue(&VPIntrin, N);
8752     break;
8753   }
8754   case ISD::VP_PTRTOINT: {
8755     SDValue N = OpValues[0];
8756     EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8757                                                           VPIntrin.getType());
8758     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(),
8759                                        VPIntrin.getOperand(0)->getType());
8760     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8761                                OpValues[2]);
8762     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8763                              OpValues[2]);
8764     setValue(&VPIntrin, N);
8765     break;
8766   }
8767   case ISD::VP_ABS:
8768   case ISD::VP_CTLZ:
8769   case ISD::VP_CTLZ_ZERO_UNDEF:
8770   case ISD::VP_CTTZ:
8771   case ISD::VP_CTTZ_ZERO_UNDEF:
8772   case ISD::VP_CTTZ_ELTS_ZERO_UNDEF:
8773   case ISD::VP_CTTZ_ELTS: {
8774     SDValue Result =
8775         DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]});
8776     setValue(&VPIntrin, Result);
8777     break;
8778   }
8779   }
8780 }
8781 
8782 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
8783                                           const BasicBlock *EHPadBB,
8784                                           MCSymbol *&BeginLabel) {
8785   MachineFunction &MF = DAG.getMachineFunction();
8786 
8787   // Insert a label before the invoke call to mark the try range.  This can be
8788   // used to detect deletion of the invoke via the MachineModuleInfo.
8789   BeginLabel = MF.getContext().createTempSymbol();
8790 
8791   // For SjLj, keep track of which landing pads go with which invokes
8792   // so as to maintain the ordering of pads in the LSDA.
8793   unsigned CallSiteIndex = FuncInfo.getCurrentCallSite();
8794   if (CallSiteIndex) {
8795     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
8796     LPadToCallSiteMap[FuncInfo.getMBB(EHPadBB)].push_back(CallSiteIndex);
8797 
8798     // Now that the call site is handled, stop tracking it.
8799     FuncInfo.setCurrentCallSite(0);
8800   }
8801 
8802   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
8803 }
8804 
8805 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
8806                                         const BasicBlock *EHPadBB,
8807                                         MCSymbol *BeginLabel) {
8808   assert(BeginLabel && "BeginLabel should've been set");
8809 
8810   MachineFunction &MF = DAG.getMachineFunction();
8811 
8812   // Insert a label at the end of the invoke call to mark the try range.  This
8813   // can be used to detect deletion of the invoke via the MachineModuleInfo.
8814   MCSymbol *EndLabel = MF.getContext().createTempSymbol();
8815   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
8816 
8817   // Inform MachineModuleInfo of range.
8818   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
8819   // There is a platform (e.g. wasm) that uses funclet style IR but does not
8820   // actually use outlined funclets and their LSDA info style.
8821   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
8822     assert(II && "II should've been set");
8823     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
8824     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
8825   } else if (!isScopedEHPersonality(Pers)) {
8826     assert(EHPadBB);
8827     MF.addInvoke(FuncInfo.getMBB(EHPadBB), BeginLabel, EndLabel);
8828   }
8829 
8830   return Chain;
8831 }
8832 
8833 std::pair<SDValue, SDValue>
8834 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
8835                                     const BasicBlock *EHPadBB) {
8836   MCSymbol *BeginLabel = nullptr;
8837 
8838   if (EHPadBB) {
8839     // Both PendingLoads and PendingExports must be flushed here;
8840     // this call might not return.
8841     (void)getRoot();
8842     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
8843     CLI.setChain(getRoot());
8844   }
8845 
8846   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8847   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
8848 
8849   assert((CLI.IsTailCall || Result.second.getNode()) &&
8850          "Non-null chain expected with non-tail call!");
8851   assert((Result.second.getNode() || !Result.first.getNode()) &&
8852          "Null value expected with tail call!");
8853 
8854   if (!Result.second.getNode()) {
8855     // As a special case, a null chain means that a tail call has been emitted
8856     // and the DAG root is already updated.
8857     HasTailCall = true;
8858 
8859     // Since there's no actual continuation from this block, nothing can be
8860     // relying on us setting vregs for them.
8861     PendingExports.clear();
8862   } else {
8863     DAG.setRoot(Result.second);
8864   }
8865 
8866   if (EHPadBB) {
8867     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
8868                            BeginLabel));
8869     Result.second = getRoot();
8870   }
8871 
8872   return Result;
8873 }
8874 
8875 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
8876                                       bool isTailCall, bool isMustTailCall,
8877                                       const BasicBlock *EHPadBB,
8878                                       const TargetLowering::PtrAuthInfo *PAI) {
8879   auto &DL = DAG.getDataLayout();
8880   FunctionType *FTy = CB.getFunctionType();
8881   Type *RetTy = CB.getType();
8882 
8883   TargetLowering::ArgListTy Args;
8884   Args.reserve(CB.arg_size());
8885 
8886   const Value *SwiftErrorVal = nullptr;
8887   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8888 
8889   if (isTailCall) {
8890     // Avoid emitting tail calls in functions with the disable-tail-calls
8891     // attribute.
8892     auto *Caller = CB.getParent()->getParent();
8893     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
8894         "true" && !isMustTailCall)
8895       isTailCall = false;
8896 
8897     // We can't tail call inside a function with a swifterror argument. Lowering
8898     // does not support this yet. It would have to move into the swifterror
8899     // register before the call.
8900     if (TLI.supportSwiftError() &&
8901         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
8902       isTailCall = false;
8903   }
8904 
8905   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
8906     TargetLowering::ArgListEntry Entry;
8907     const Value *V = *I;
8908 
8909     // Skip empty types
8910     if (V->getType()->isEmptyTy())
8911       continue;
8912 
8913     SDValue ArgNode = getValue(V);
8914     Entry.Node = ArgNode; Entry.Ty = V->getType();
8915 
8916     Entry.setAttributes(&CB, I - CB.arg_begin());
8917 
8918     // Use swifterror virtual register as input to the call.
8919     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
8920       SwiftErrorVal = V;
8921       // We find the virtual register for the actual swifterror argument.
8922       // Instead of using the Value, we use the virtual register instead.
8923       Entry.Node =
8924           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
8925                           EVT(TLI.getPointerTy(DL)));
8926     }
8927 
8928     Args.push_back(Entry);
8929 
8930     // If we have an explicit sret argument that is an Instruction, (i.e., it
8931     // might point to function-local memory), we can't meaningfully tail-call.
8932     if (Entry.IsSRet && isa<Instruction>(V))
8933       isTailCall = false;
8934   }
8935 
8936   // If call site has a cfguardtarget operand bundle, create and add an
8937   // additional ArgListEntry.
8938   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
8939     TargetLowering::ArgListEntry Entry;
8940     Value *V = Bundle->Inputs[0];
8941     SDValue ArgNode = getValue(V);
8942     Entry.Node = ArgNode;
8943     Entry.Ty = V->getType();
8944     Entry.IsCFGuardTarget = true;
8945     Args.push_back(Entry);
8946   }
8947 
8948   // Check if target-independent constraints permit a tail call here.
8949   // Target-dependent constraints are checked within TLI->LowerCallTo.
8950   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
8951     isTailCall = false;
8952 
8953   // Disable tail calls if there is an swifterror argument. Targets have not
8954   // been updated to support tail calls.
8955   if (TLI.supportSwiftError() && SwiftErrorVal)
8956     isTailCall = false;
8957 
8958   ConstantInt *CFIType = nullptr;
8959   if (CB.isIndirectCall()) {
8960     if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
8961       if (!TLI.supportKCFIBundles())
8962         report_fatal_error(
8963             "Target doesn't support calls with kcfi operand bundles.");
8964       CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
8965       assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
8966     }
8967   }
8968 
8969   SDValue ConvControlToken;
8970   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_convergencectrl)) {
8971     auto *Token = Bundle->Inputs[0].get();
8972     ConvControlToken = getValue(Token);
8973   }
8974 
8975   TargetLowering::CallLoweringInfo CLI(DAG);
8976   CLI.setDebugLoc(getCurSDLoc())
8977       .setChain(getRoot())
8978       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
8979       .setTailCall(isTailCall)
8980       .setConvergent(CB.isConvergent())
8981       .setIsPreallocated(
8982           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
8983       .setCFIType(CFIType)
8984       .setConvergenceControlToken(ConvControlToken);
8985 
8986   // Set the pointer authentication info if we have it.
8987   if (PAI) {
8988     if (!TLI.supportPtrAuthBundles())
8989       report_fatal_error(
8990           "This target doesn't support calls with ptrauth operand bundles.");
8991     CLI.setPtrAuth(*PAI);
8992   }
8993 
8994   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8995 
8996   if (Result.first.getNode()) {
8997     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
8998     setValue(&CB, Result.first);
8999   }
9000 
9001   // The last element of CLI.InVals has the SDValue for swifterror return.
9002   // Here we copy it to a virtual register and update SwiftErrorMap for
9003   // book-keeping.
9004   if (SwiftErrorVal && TLI.supportSwiftError()) {
9005     // Get the last element of InVals.
9006     SDValue Src = CLI.InVals.back();
9007     Register VReg =
9008         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
9009     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
9010     DAG.setRoot(CopyNode);
9011   }
9012 }
9013 
9014 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
9015                              SelectionDAGBuilder &Builder) {
9016   // Check to see if this load can be trivially constant folded, e.g. if the
9017   // input is from a string literal.
9018   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
9019     // Cast pointer to the type we really want to load.
9020     Type *LoadTy =
9021         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
9022     if (LoadVT.isVector())
9023       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
9024 
9025     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
9026                                          PointerType::getUnqual(LoadTy));
9027 
9028     if (const Constant *LoadCst =
9029             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
9030                                          LoadTy, Builder.DAG.getDataLayout()))
9031       return Builder.getValue(LoadCst);
9032   }
9033 
9034   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
9035   // still constant memory, the input chain can be the entry node.
9036   SDValue Root;
9037   bool ConstantMemory = false;
9038 
9039   // Do not serialize (non-volatile) loads of constant memory with anything.
9040   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
9041     Root = Builder.DAG.getEntryNode();
9042     ConstantMemory = true;
9043   } else {
9044     // Do not serialize non-volatile loads against each other.
9045     Root = Builder.DAG.getRoot();
9046   }
9047 
9048   SDValue Ptr = Builder.getValue(PtrVal);
9049   SDValue LoadVal =
9050       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
9051                           MachinePointerInfo(PtrVal), Align(1));
9052 
9053   if (!ConstantMemory)
9054     Builder.PendingLoads.push_back(LoadVal.getValue(1));
9055   return LoadVal;
9056 }
9057 
9058 /// Record the value for an instruction that produces an integer result,
9059 /// converting the type where necessary.
9060 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
9061                                                   SDValue Value,
9062                                                   bool IsSigned) {
9063   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
9064                                                     I.getType(), true);
9065   Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT);
9066   setValue(&I, Value);
9067 }
9068 
9069 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
9070 /// true and lower it. Otherwise return false, and it will be lowered like a
9071 /// normal call.
9072 /// The caller already checked that \p I calls the appropriate LibFunc with a
9073 /// correct prototype.
9074 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
9075   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
9076   const Value *Size = I.getArgOperand(2);
9077   const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
9078   if (CSize && CSize->getZExtValue() == 0) {
9079     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
9080                                                           I.getType(), true);
9081     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
9082     return true;
9083   }
9084 
9085   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9086   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
9087       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
9088       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
9089   if (Res.first.getNode()) {
9090     processIntegerCallValue(I, Res.first, true);
9091     PendingLoads.push_back(Res.second);
9092     return true;
9093   }
9094 
9095   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
9096   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
9097   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
9098     return false;
9099 
9100   // If the target has a fast compare for the given size, it will return a
9101   // preferred load type for that size. Require that the load VT is legal and
9102   // that the target supports unaligned loads of that type. Otherwise, return
9103   // INVALID.
9104   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
9105     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9106     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
9107     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
9108       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
9109       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
9110       // TODO: Check alignment of src and dest ptrs.
9111       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
9112       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
9113       if (!TLI.isTypeLegal(LVT) ||
9114           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
9115           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
9116         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
9117     }
9118 
9119     return LVT;
9120   };
9121 
9122   // This turns into unaligned loads. We only do this if the target natively
9123   // supports the MVT we'll be loading or if it is small enough (<= 4) that
9124   // we'll only produce a small number of byte loads.
9125   MVT LoadVT;
9126   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
9127   switch (NumBitsToCompare) {
9128   default:
9129     return false;
9130   case 16:
9131     LoadVT = MVT::i16;
9132     break;
9133   case 32:
9134     LoadVT = MVT::i32;
9135     break;
9136   case 64:
9137   case 128:
9138   case 256:
9139     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
9140     break;
9141   }
9142 
9143   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
9144     return false;
9145 
9146   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
9147   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
9148 
9149   // Bitcast to a wide integer type if the loads are vectors.
9150   if (LoadVT.isVector()) {
9151     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
9152     LoadL = DAG.getBitcast(CmpVT, LoadL);
9153     LoadR = DAG.getBitcast(CmpVT, LoadR);
9154   }
9155 
9156   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
9157   processIntegerCallValue(I, Cmp, false);
9158   return true;
9159 }
9160 
9161 /// See if we can lower a memchr call into an optimized form. If so, return
9162 /// true and lower it. Otherwise return false, and it will be lowered like a
9163 /// normal call.
9164 /// The caller already checked that \p I calls the appropriate LibFunc with a
9165 /// correct prototype.
9166 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
9167   const Value *Src = I.getArgOperand(0);
9168   const Value *Char = I.getArgOperand(1);
9169   const Value *Length = I.getArgOperand(2);
9170 
9171   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9172   std::pair<SDValue, SDValue> Res =
9173     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
9174                                 getValue(Src), getValue(Char), getValue(Length),
9175                                 MachinePointerInfo(Src));
9176   if (Res.first.getNode()) {
9177     setValue(&I, Res.first);
9178     PendingLoads.push_back(Res.second);
9179     return true;
9180   }
9181 
9182   return false;
9183 }
9184 
9185 /// See if we can lower a mempcpy call into an optimized form. If so, return
9186 /// true and lower it. Otherwise return false, and it will be lowered like a
9187 /// normal call.
9188 /// The caller already checked that \p I calls the appropriate LibFunc with a
9189 /// correct prototype.
9190 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
9191   SDValue Dst = getValue(I.getArgOperand(0));
9192   SDValue Src = getValue(I.getArgOperand(1));
9193   SDValue Size = getValue(I.getArgOperand(2));
9194 
9195   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
9196   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
9197   // DAG::getMemcpy needs Alignment to be defined.
9198   Align Alignment = std::min(DstAlign, SrcAlign);
9199 
9200   SDLoc sdl = getCurSDLoc();
9201 
9202   // In the mempcpy context we need to pass in a false value for isTailCall
9203   // because the return pointer needs to be adjusted by the size of
9204   // the copied memory.
9205   SDValue Root = getMemoryRoot();
9206   SDValue MC = DAG.getMemcpy(
9207       Root, sdl, Dst, Src, Size, Alignment, false, false, /*CI=*/nullptr,
9208       std::nullopt, MachinePointerInfo(I.getArgOperand(0)),
9209       MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata());
9210   assert(MC.getNode() != nullptr &&
9211          "** memcpy should not be lowered as TailCall in mempcpy context **");
9212   DAG.setRoot(MC);
9213 
9214   // Check if Size needs to be truncated or extended.
9215   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
9216 
9217   // Adjust return pointer to point just past the last dst byte.
9218   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
9219                                     Dst, Size);
9220   setValue(&I, DstPlusSize);
9221   return true;
9222 }
9223 
9224 /// See if we can lower a strcpy call into an optimized form.  If so, return
9225 /// true and lower it, otherwise return false and it will be lowered like a
9226 /// normal call.
9227 /// The caller already checked that \p I calls the appropriate LibFunc with a
9228 /// correct prototype.
9229 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
9230   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9231 
9232   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9233   std::pair<SDValue, SDValue> Res =
9234     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
9235                                 getValue(Arg0), getValue(Arg1),
9236                                 MachinePointerInfo(Arg0),
9237                                 MachinePointerInfo(Arg1), isStpcpy);
9238   if (Res.first.getNode()) {
9239     setValue(&I, Res.first);
9240     DAG.setRoot(Res.second);
9241     return true;
9242   }
9243 
9244   return false;
9245 }
9246 
9247 /// See if we can lower a strcmp call into an optimized form.  If so, return
9248 /// true and lower it, otherwise return false and it will be lowered like a
9249 /// normal call.
9250 /// The caller already checked that \p I calls the appropriate LibFunc with a
9251 /// correct prototype.
9252 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
9253   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9254 
9255   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9256   std::pair<SDValue, SDValue> Res =
9257     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
9258                                 getValue(Arg0), getValue(Arg1),
9259                                 MachinePointerInfo(Arg0),
9260                                 MachinePointerInfo(Arg1));
9261   if (Res.first.getNode()) {
9262     processIntegerCallValue(I, Res.first, true);
9263     PendingLoads.push_back(Res.second);
9264     return true;
9265   }
9266 
9267   return false;
9268 }
9269 
9270 /// See if we can lower a strlen call into an optimized form.  If so, return
9271 /// true and lower it, otherwise return false and it will be lowered like a
9272 /// normal call.
9273 /// The caller already checked that \p I calls the appropriate LibFunc with a
9274 /// correct prototype.
9275 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
9276   const Value *Arg0 = I.getArgOperand(0);
9277 
9278   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9279   std::pair<SDValue, SDValue> Res =
9280     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
9281                                 getValue(Arg0), MachinePointerInfo(Arg0));
9282   if (Res.first.getNode()) {
9283     processIntegerCallValue(I, Res.first, false);
9284     PendingLoads.push_back(Res.second);
9285     return true;
9286   }
9287 
9288   return false;
9289 }
9290 
9291 /// See if we can lower a strnlen call into an optimized form.  If so, return
9292 /// true and lower it, otherwise return false and it will be lowered like a
9293 /// normal call.
9294 /// The caller already checked that \p I calls the appropriate LibFunc with a
9295 /// correct prototype.
9296 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
9297   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9298 
9299   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9300   std::pair<SDValue, SDValue> Res =
9301     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
9302                                  getValue(Arg0), getValue(Arg1),
9303                                  MachinePointerInfo(Arg0));
9304   if (Res.first.getNode()) {
9305     processIntegerCallValue(I, Res.first, false);
9306     PendingLoads.push_back(Res.second);
9307     return true;
9308   }
9309 
9310   return false;
9311 }
9312 
9313 /// See if we can lower a unary floating-point operation into an SDNode with
9314 /// the specified Opcode.  If so, return true and lower it, otherwise return
9315 /// false and it will be lowered like a normal call.
9316 /// The caller already checked that \p I calls the appropriate LibFunc with a
9317 /// correct prototype.
9318 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
9319                                               unsigned Opcode) {
9320   // We already checked this call's prototype; verify it doesn't modify errno.
9321   if (!I.onlyReadsMemory())
9322     return false;
9323 
9324   SDNodeFlags Flags;
9325   Flags.copyFMF(cast<FPMathOperator>(I));
9326 
9327   SDValue Tmp = getValue(I.getArgOperand(0));
9328   setValue(&I,
9329            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
9330   return true;
9331 }
9332 
9333 /// See if we can lower a binary floating-point operation into an SDNode with
9334 /// the specified Opcode. If so, return true and lower it. Otherwise return
9335 /// false, and it will be lowered like a normal call.
9336 /// The caller already checked that \p I calls the appropriate LibFunc with a
9337 /// correct prototype.
9338 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
9339                                                unsigned Opcode) {
9340   // We already checked this call's prototype; verify it doesn't modify errno.
9341   if (!I.onlyReadsMemory())
9342     return false;
9343 
9344   SDNodeFlags Flags;
9345   Flags.copyFMF(cast<FPMathOperator>(I));
9346 
9347   SDValue Tmp0 = getValue(I.getArgOperand(0));
9348   SDValue Tmp1 = getValue(I.getArgOperand(1));
9349   EVT VT = Tmp0.getValueType();
9350   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
9351   return true;
9352 }
9353 
9354 void SelectionDAGBuilder::visitCall(const CallInst &I) {
9355   // Handle inline assembly differently.
9356   if (I.isInlineAsm()) {
9357     visitInlineAsm(I);
9358     return;
9359   }
9360 
9361   diagnoseDontCall(I);
9362 
9363   if (Function *F = I.getCalledFunction()) {
9364     if (F->isDeclaration()) {
9365       // Is this an LLVM intrinsic or a target-specific intrinsic?
9366       unsigned IID = F->getIntrinsicID();
9367       if (!IID)
9368         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
9369           IID = II->getIntrinsicID(F);
9370 
9371       if (IID) {
9372         visitIntrinsicCall(I, IID);
9373         return;
9374       }
9375     }
9376 
9377     // Check for well-known libc/libm calls.  If the function is internal, it
9378     // can't be a library call.  Don't do the check if marked as nobuiltin for
9379     // some reason or the call site requires strict floating point semantics.
9380     LibFunc Func;
9381     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
9382         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
9383         LibInfo->hasOptimizedCodeGen(Func)) {
9384       switch (Func) {
9385       default: break;
9386       case LibFunc_bcmp:
9387         if (visitMemCmpBCmpCall(I))
9388           return;
9389         break;
9390       case LibFunc_copysign:
9391       case LibFunc_copysignf:
9392       case LibFunc_copysignl:
9393         // We already checked this call's prototype; verify it doesn't modify
9394         // errno.
9395         if (I.onlyReadsMemory()) {
9396           SDValue LHS = getValue(I.getArgOperand(0));
9397           SDValue RHS = getValue(I.getArgOperand(1));
9398           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
9399                                    LHS.getValueType(), LHS, RHS));
9400           return;
9401         }
9402         break;
9403       case LibFunc_fabs:
9404       case LibFunc_fabsf:
9405       case LibFunc_fabsl:
9406         if (visitUnaryFloatCall(I, ISD::FABS))
9407           return;
9408         break;
9409       case LibFunc_fmin:
9410       case LibFunc_fminf:
9411       case LibFunc_fminl:
9412         if (visitBinaryFloatCall(I, ISD::FMINNUM))
9413           return;
9414         break;
9415       case LibFunc_fmax:
9416       case LibFunc_fmaxf:
9417       case LibFunc_fmaxl:
9418         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
9419           return;
9420         break;
9421       case LibFunc_fminimum_num:
9422       case LibFunc_fminimum_numf:
9423       case LibFunc_fminimum_numl:
9424         if (visitBinaryFloatCall(I, ISD::FMINIMUMNUM))
9425           return;
9426         break;
9427       case LibFunc_fmaximum_num:
9428       case LibFunc_fmaximum_numf:
9429       case LibFunc_fmaximum_numl:
9430         if (visitBinaryFloatCall(I, ISD::FMAXIMUMNUM))
9431           return;
9432         break;
9433       case LibFunc_sin:
9434       case LibFunc_sinf:
9435       case LibFunc_sinl:
9436         if (visitUnaryFloatCall(I, ISD::FSIN))
9437           return;
9438         break;
9439       case LibFunc_cos:
9440       case LibFunc_cosf:
9441       case LibFunc_cosl:
9442         if (visitUnaryFloatCall(I, ISD::FCOS))
9443           return;
9444         break;
9445       case LibFunc_tan:
9446       case LibFunc_tanf:
9447       case LibFunc_tanl:
9448         if (visitUnaryFloatCall(I, ISD::FTAN))
9449           return;
9450         break;
9451       case LibFunc_asin:
9452       case LibFunc_asinf:
9453       case LibFunc_asinl:
9454         if (visitUnaryFloatCall(I, ISD::FASIN))
9455           return;
9456         break;
9457       case LibFunc_acos:
9458       case LibFunc_acosf:
9459       case LibFunc_acosl:
9460         if (visitUnaryFloatCall(I, ISD::FACOS))
9461           return;
9462         break;
9463       case LibFunc_atan:
9464       case LibFunc_atanf:
9465       case LibFunc_atanl:
9466         if (visitUnaryFloatCall(I, ISD::FATAN))
9467           return;
9468         break;
9469       case LibFunc_atan2:
9470       case LibFunc_atan2f:
9471       case LibFunc_atan2l:
9472         if (visitBinaryFloatCall(I, ISD::FATAN2))
9473           return;
9474         break;
9475       case LibFunc_sinh:
9476       case LibFunc_sinhf:
9477       case LibFunc_sinhl:
9478         if (visitUnaryFloatCall(I, ISD::FSINH))
9479           return;
9480         break;
9481       case LibFunc_cosh:
9482       case LibFunc_coshf:
9483       case LibFunc_coshl:
9484         if (visitUnaryFloatCall(I, ISD::FCOSH))
9485           return;
9486         break;
9487       case LibFunc_tanh:
9488       case LibFunc_tanhf:
9489       case LibFunc_tanhl:
9490         if (visitUnaryFloatCall(I, ISD::FTANH))
9491           return;
9492         break;
9493       case LibFunc_sqrt:
9494       case LibFunc_sqrtf:
9495       case LibFunc_sqrtl:
9496       case LibFunc_sqrt_finite:
9497       case LibFunc_sqrtf_finite:
9498       case LibFunc_sqrtl_finite:
9499         if (visitUnaryFloatCall(I, ISD::FSQRT))
9500           return;
9501         break;
9502       case LibFunc_floor:
9503       case LibFunc_floorf:
9504       case LibFunc_floorl:
9505         if (visitUnaryFloatCall(I, ISD::FFLOOR))
9506           return;
9507         break;
9508       case LibFunc_nearbyint:
9509       case LibFunc_nearbyintf:
9510       case LibFunc_nearbyintl:
9511         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
9512           return;
9513         break;
9514       case LibFunc_ceil:
9515       case LibFunc_ceilf:
9516       case LibFunc_ceill:
9517         if (visitUnaryFloatCall(I, ISD::FCEIL))
9518           return;
9519         break;
9520       case LibFunc_rint:
9521       case LibFunc_rintf:
9522       case LibFunc_rintl:
9523         if (visitUnaryFloatCall(I, ISD::FRINT))
9524           return;
9525         break;
9526       case LibFunc_round:
9527       case LibFunc_roundf:
9528       case LibFunc_roundl:
9529         if (visitUnaryFloatCall(I, ISD::FROUND))
9530           return;
9531         break;
9532       case LibFunc_trunc:
9533       case LibFunc_truncf:
9534       case LibFunc_truncl:
9535         if (visitUnaryFloatCall(I, ISD::FTRUNC))
9536           return;
9537         break;
9538       case LibFunc_log2:
9539       case LibFunc_log2f:
9540       case LibFunc_log2l:
9541         if (visitUnaryFloatCall(I, ISD::FLOG2))
9542           return;
9543         break;
9544       case LibFunc_exp2:
9545       case LibFunc_exp2f:
9546       case LibFunc_exp2l:
9547         if (visitUnaryFloatCall(I, ISD::FEXP2))
9548           return;
9549         break;
9550       case LibFunc_exp10:
9551       case LibFunc_exp10f:
9552       case LibFunc_exp10l:
9553         if (visitUnaryFloatCall(I, ISD::FEXP10))
9554           return;
9555         break;
9556       case LibFunc_ldexp:
9557       case LibFunc_ldexpf:
9558       case LibFunc_ldexpl:
9559         if (visitBinaryFloatCall(I, ISD::FLDEXP))
9560           return;
9561         break;
9562       case LibFunc_memcmp:
9563         if (visitMemCmpBCmpCall(I))
9564           return;
9565         break;
9566       case LibFunc_mempcpy:
9567         if (visitMemPCpyCall(I))
9568           return;
9569         break;
9570       case LibFunc_memchr:
9571         if (visitMemChrCall(I))
9572           return;
9573         break;
9574       case LibFunc_strcpy:
9575         if (visitStrCpyCall(I, false))
9576           return;
9577         break;
9578       case LibFunc_stpcpy:
9579         if (visitStrCpyCall(I, true))
9580           return;
9581         break;
9582       case LibFunc_strcmp:
9583         if (visitStrCmpCall(I))
9584           return;
9585         break;
9586       case LibFunc_strlen:
9587         if (visitStrLenCall(I))
9588           return;
9589         break;
9590       case LibFunc_strnlen:
9591         if (visitStrNLenCall(I))
9592           return;
9593         break;
9594       }
9595     }
9596   }
9597 
9598   if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
9599     LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), /*EHPadBB=*/nullptr);
9600     return;
9601   }
9602 
9603   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
9604   // have to do anything here to lower funclet bundles.
9605   // CFGuardTarget bundles are lowered in LowerCallTo.
9606   assert(!I.hasOperandBundlesOtherThan(
9607              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
9608               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
9609               LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi,
9610               LLVMContext::OB_convergencectrl}) &&
9611          "Cannot lower calls with arbitrary operand bundles!");
9612 
9613   SDValue Callee = getValue(I.getCalledOperand());
9614 
9615   if (I.hasDeoptState())
9616     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
9617   else
9618     // Check if we can potentially perform a tail call. More detailed checking
9619     // is be done within LowerCallTo, after more information about the call is
9620     // known.
9621     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
9622 }
9623 
9624 void SelectionDAGBuilder::LowerCallSiteWithPtrAuthBundle(
9625     const CallBase &CB, const BasicBlock *EHPadBB) {
9626   auto PAB = CB.getOperandBundle("ptrauth");
9627   const Value *CalleeV = CB.getCalledOperand();
9628 
9629   // Gather the call ptrauth data from the operand bundle:
9630   //   [ i32 <key>, i64 <discriminator> ]
9631   const auto *Key = cast<ConstantInt>(PAB->Inputs[0]);
9632   const Value *Discriminator = PAB->Inputs[1];
9633 
9634   assert(Key->getType()->isIntegerTy(32) && "Invalid ptrauth key");
9635   assert(Discriminator->getType()->isIntegerTy(64) &&
9636          "Invalid ptrauth discriminator");
9637 
9638   // Look through ptrauth constants to find the raw callee.
9639   // Do a direct unauthenticated call if we found it and everything matches.
9640   if (const auto *CalleeCPA = dyn_cast<ConstantPtrAuth>(CalleeV))
9641     if (CalleeCPA->isKnownCompatibleWith(Key, Discriminator,
9642                                          DAG.getDataLayout()))
9643       return LowerCallTo(CB, getValue(CalleeCPA->getPointer()), CB.isTailCall(),
9644                          CB.isMustTailCall(), EHPadBB);
9645 
9646   // Functions should never be ptrauth-called directly.
9647   assert(!isa<Function>(CalleeV) && "invalid direct ptrauth call");
9648 
9649   // Otherwise, do an authenticated indirect call.
9650   TargetLowering::PtrAuthInfo PAI = {Key->getZExtValue(),
9651                                      getValue(Discriminator)};
9652 
9653   LowerCallTo(CB, getValue(CalleeV), CB.isTailCall(), CB.isMustTailCall(),
9654               EHPadBB, &PAI);
9655 }
9656 
9657 namespace {
9658 
9659 /// AsmOperandInfo - This contains information for each constraint that we are
9660 /// lowering.
9661 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
9662 public:
9663   /// CallOperand - If this is the result output operand or a clobber
9664   /// this is null, otherwise it is the incoming operand to the CallInst.
9665   /// This gets modified as the asm is processed.
9666   SDValue CallOperand;
9667 
9668   /// AssignedRegs - If this is a register or register class operand, this
9669   /// contains the set of register corresponding to the operand.
9670   RegsForValue AssignedRegs;
9671 
9672   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
9673     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
9674   }
9675 
9676   /// Whether or not this operand accesses memory
9677   bool hasMemory(const TargetLowering &TLI) const {
9678     // Indirect operand accesses access memory.
9679     if (isIndirect)
9680       return true;
9681 
9682     for (const auto &Code : Codes)
9683       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
9684         return true;
9685 
9686     return false;
9687   }
9688 };
9689 
9690 
9691 } // end anonymous namespace
9692 
9693 /// Make sure that the output operand \p OpInfo and its corresponding input
9694 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
9695 /// out).
9696 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
9697                                SDISelAsmOperandInfo &MatchingOpInfo,
9698                                SelectionDAG &DAG) {
9699   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
9700     return;
9701 
9702   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
9703   const auto &TLI = DAG.getTargetLoweringInfo();
9704 
9705   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
9706       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
9707                                        OpInfo.ConstraintVT);
9708   std::pair<unsigned, const TargetRegisterClass *> InputRC =
9709       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
9710                                        MatchingOpInfo.ConstraintVT);
9711   const bool OutOpIsIntOrFP =
9712       OpInfo.ConstraintVT.isInteger() || OpInfo.ConstraintVT.isFloatingPoint();
9713   const bool InOpIsIntOrFP = MatchingOpInfo.ConstraintVT.isInteger() ||
9714                              MatchingOpInfo.ConstraintVT.isFloatingPoint();
9715   if ((OutOpIsIntOrFP != InOpIsIntOrFP) || (MatchRC.second != InputRC.second)) {
9716     // FIXME: error out in a more elegant fashion
9717     report_fatal_error("Unsupported asm: input constraint"
9718                        " with a matching output constraint of"
9719                        " incompatible type!");
9720   }
9721   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
9722 }
9723 
9724 /// Get a direct memory input to behave well as an indirect operand.
9725 /// This may introduce stores, hence the need for a \p Chain.
9726 /// \return The (possibly updated) chain.
9727 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
9728                                         SDISelAsmOperandInfo &OpInfo,
9729                                         SelectionDAG &DAG) {
9730   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9731 
9732   // If we don't have an indirect input, put it in the constpool if we can,
9733   // otherwise spill it to a stack slot.
9734   // TODO: This isn't quite right. We need to handle these according to
9735   // the addressing mode that the constraint wants. Also, this may take
9736   // an additional register for the computation and we don't want that
9737   // either.
9738 
9739   // If the operand is a float, integer, or vector constant, spill to a
9740   // constant pool entry to get its address.
9741   const Value *OpVal = OpInfo.CallOperandVal;
9742   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
9743       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
9744     OpInfo.CallOperand = DAG.getConstantPool(
9745         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
9746     return Chain;
9747   }
9748 
9749   // Otherwise, create a stack slot and emit a store to it before the asm.
9750   Type *Ty = OpVal->getType();
9751   auto &DL = DAG.getDataLayout();
9752   TypeSize TySize = DL.getTypeAllocSize(Ty);
9753   MachineFunction &MF = DAG.getMachineFunction();
9754   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
9755   int StackID = 0;
9756   if (TySize.isScalable())
9757     StackID = TFI->getStackIDForScalableVectors();
9758   int SSFI = MF.getFrameInfo().CreateStackObject(TySize.getKnownMinValue(),
9759                                                  DL.getPrefTypeAlign(Ty), false,
9760                                                  nullptr, StackID);
9761   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
9762   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
9763                             MachinePointerInfo::getFixedStack(MF, SSFI),
9764                             TLI.getMemValueType(DL, Ty));
9765   OpInfo.CallOperand = StackSlot;
9766 
9767   return Chain;
9768 }
9769 
9770 /// GetRegistersForValue - Assign registers (virtual or physical) for the
9771 /// specified operand.  We prefer to assign virtual registers, to allow the
9772 /// register allocator to handle the assignment process.  However, if the asm
9773 /// uses features that we can't model on machineinstrs, we have SDISel do the
9774 /// allocation.  This produces generally horrible, but correct, code.
9775 ///
9776 ///   OpInfo describes the operand
9777 ///   RefOpInfo describes the matching operand if any, the operand otherwise
9778 static std::optional<unsigned>
9779 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
9780                      SDISelAsmOperandInfo &OpInfo,
9781                      SDISelAsmOperandInfo &RefOpInfo) {
9782   LLVMContext &Context = *DAG.getContext();
9783   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9784 
9785   MachineFunction &MF = DAG.getMachineFunction();
9786   SmallVector<Register, 4> Regs;
9787   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9788 
9789   // No work to do for memory/address operands.
9790   if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9791       OpInfo.ConstraintType == TargetLowering::C_Address)
9792     return std::nullopt;
9793 
9794   // If this is a constraint for a single physreg, or a constraint for a
9795   // register class, find it.
9796   unsigned AssignedReg;
9797   const TargetRegisterClass *RC;
9798   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
9799       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
9800   // RC is unset only on failure. Return immediately.
9801   if (!RC)
9802     return std::nullopt;
9803 
9804   // Get the actual register value type.  This is important, because the user
9805   // may have asked for (e.g.) the AX register in i32 type.  We need to
9806   // remember that AX is actually i16 to get the right extension.
9807   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
9808 
9809   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
9810     // If this is an FP operand in an integer register (or visa versa), or more
9811     // generally if the operand value disagrees with the register class we plan
9812     // to stick it in, fix the operand type.
9813     //
9814     // If this is an input value, the bitcast to the new type is done now.
9815     // Bitcast for output value is done at the end of visitInlineAsm().
9816     if ((OpInfo.Type == InlineAsm::isOutput ||
9817          OpInfo.Type == InlineAsm::isInput) &&
9818         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
9819       // Try to convert to the first EVT that the reg class contains.  If the
9820       // types are identical size, use a bitcast to convert (e.g. two differing
9821       // vector types).  Note: output bitcast is done at the end of
9822       // visitInlineAsm().
9823       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
9824         // Exclude indirect inputs while they are unsupported because the code
9825         // to perform the load is missing and thus OpInfo.CallOperand still
9826         // refers to the input address rather than the pointed-to value.
9827         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
9828           OpInfo.CallOperand =
9829               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
9830         OpInfo.ConstraintVT = RegVT;
9831         // If the operand is an FP value and we want it in integer registers,
9832         // use the corresponding integer type. This turns an f64 value into
9833         // i64, which can be passed with two i32 values on a 32-bit machine.
9834       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
9835         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
9836         if (OpInfo.Type == InlineAsm::isInput)
9837           OpInfo.CallOperand =
9838               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
9839         OpInfo.ConstraintVT = VT;
9840       }
9841     }
9842   }
9843 
9844   // No need to allocate a matching input constraint since the constraint it's
9845   // matching to has already been allocated.
9846   if (OpInfo.isMatchingInputConstraint())
9847     return std::nullopt;
9848 
9849   EVT ValueVT = OpInfo.ConstraintVT;
9850   if (OpInfo.ConstraintVT == MVT::Other)
9851     ValueVT = RegVT;
9852 
9853   // Initialize NumRegs.
9854   unsigned NumRegs = 1;
9855   if (OpInfo.ConstraintVT != MVT::Other)
9856     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
9857 
9858   // If this is a constraint for a specific physical register, like {r17},
9859   // assign it now.
9860 
9861   // If this associated to a specific register, initialize iterator to correct
9862   // place. If virtual, make sure we have enough registers
9863 
9864   // Initialize iterator if necessary
9865   TargetRegisterClass::iterator I = RC->begin();
9866   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9867 
9868   // Do not check for single registers.
9869   if (AssignedReg) {
9870     I = std::find(I, RC->end(), AssignedReg);
9871     if (I == RC->end()) {
9872       // RC does not contain the selected register, which indicates a
9873       // mismatch between the register and the required type/bitwidth.
9874       return {AssignedReg};
9875     }
9876   }
9877 
9878   for (; NumRegs; --NumRegs, ++I) {
9879     assert(I != RC->end() && "Ran out of registers to allocate!");
9880     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
9881     Regs.push_back(R);
9882   }
9883 
9884   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
9885   return std::nullopt;
9886 }
9887 
9888 static unsigned
9889 findMatchingInlineAsmOperand(unsigned OperandNo,
9890                              const std::vector<SDValue> &AsmNodeOperands) {
9891   // Scan until we find the definition we already emitted of this operand.
9892   unsigned CurOp = InlineAsm::Op_FirstOperand;
9893   for (; OperandNo; --OperandNo) {
9894     // Advance to the next operand.
9895     unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal();
9896     const InlineAsm::Flag F(OpFlag);
9897     assert(
9898         (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) &&
9899         "Skipped past definitions?");
9900     CurOp += F.getNumOperandRegisters() + 1;
9901   }
9902   return CurOp;
9903 }
9904 
9905 namespace {
9906 
9907 class ExtraFlags {
9908   unsigned Flags = 0;
9909 
9910 public:
9911   explicit ExtraFlags(const CallBase &Call) {
9912     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9913     if (IA->hasSideEffects())
9914       Flags |= InlineAsm::Extra_HasSideEffects;
9915     if (IA->isAlignStack())
9916       Flags |= InlineAsm::Extra_IsAlignStack;
9917     if (Call.isConvergent())
9918       Flags |= InlineAsm::Extra_IsConvergent;
9919     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
9920   }
9921 
9922   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
9923     // Ideally, we would only check against memory constraints.  However, the
9924     // meaning of an Other constraint can be target-specific and we can't easily
9925     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
9926     // for Other constraints as well.
9927     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9928         OpInfo.ConstraintType == TargetLowering::C_Other) {
9929       if (OpInfo.Type == InlineAsm::isInput)
9930         Flags |= InlineAsm::Extra_MayLoad;
9931       else if (OpInfo.Type == InlineAsm::isOutput)
9932         Flags |= InlineAsm::Extra_MayStore;
9933       else if (OpInfo.Type == InlineAsm::isClobber)
9934         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
9935     }
9936   }
9937 
9938   unsigned get() const { return Flags; }
9939 };
9940 
9941 } // end anonymous namespace
9942 
9943 static bool isFunction(SDValue Op) {
9944   if (Op && Op.getOpcode() == ISD::GlobalAddress) {
9945     if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
9946       auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
9947 
9948       // In normal "call dllimport func" instruction (non-inlineasm) it force
9949       // indirect access by specifing call opcode. And usually specially print
9950       // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
9951       // not do in this way now. (In fact, this is similar with "Data Access"
9952       // action). So here we ignore dllimport function.
9953       if (Fn && !Fn->hasDLLImportStorageClass())
9954         return true;
9955     }
9956   }
9957   return false;
9958 }
9959 
9960 /// visitInlineAsm - Handle a call to an InlineAsm object.
9961 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
9962                                          const BasicBlock *EHPadBB) {
9963   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9964 
9965   /// ConstraintOperands - Information about all of the constraints.
9966   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
9967 
9968   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9969   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
9970       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
9971 
9972   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
9973   // AsmDialect, MayLoad, MayStore).
9974   bool HasSideEffect = IA->hasSideEffects();
9975   ExtraFlags ExtraInfo(Call);
9976 
9977   for (auto &T : TargetConstraints) {
9978     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
9979     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
9980 
9981     if (OpInfo.CallOperandVal)
9982       OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
9983 
9984     if (!HasSideEffect)
9985       HasSideEffect = OpInfo.hasMemory(TLI);
9986 
9987     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
9988     // FIXME: Could we compute this on OpInfo rather than T?
9989 
9990     // Compute the constraint code and ConstraintType to use.
9991     TLI.ComputeConstraintToUse(T, SDValue());
9992 
9993     if (T.ConstraintType == TargetLowering::C_Immediate &&
9994         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
9995       // We've delayed emitting a diagnostic like the "n" constraint because
9996       // inlining could cause an integer showing up.
9997       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
9998                                           "' expects an integer constant "
9999                                           "expression");
10000 
10001     ExtraInfo.update(T);
10002   }
10003 
10004   // We won't need to flush pending loads if this asm doesn't touch
10005   // memory and is nonvolatile.
10006   SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
10007 
10008   bool EmitEHLabels = isa<InvokeInst>(Call);
10009   if (EmitEHLabels) {
10010     assert(EHPadBB && "InvokeInst must have an EHPadBB");
10011   }
10012   bool IsCallBr = isa<CallBrInst>(Call);
10013 
10014   if (IsCallBr || EmitEHLabels) {
10015     // If this is a callbr or invoke we need to flush pending exports since
10016     // inlineasm_br and invoke are terminators.
10017     // We need to do this before nodes are glued to the inlineasm_br node.
10018     Chain = getControlRoot();
10019   }
10020 
10021   MCSymbol *BeginLabel = nullptr;
10022   if (EmitEHLabels) {
10023     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
10024   }
10025 
10026   int OpNo = -1;
10027   SmallVector<StringRef> AsmStrs;
10028   IA->collectAsmStrs(AsmStrs);
10029 
10030   // Second pass over the constraints: compute which constraint option to use.
10031   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
10032     if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
10033       OpNo++;
10034 
10035     // If this is an output operand with a matching input operand, look up the
10036     // matching input. If their types mismatch, e.g. one is an integer, the
10037     // other is floating point, or their sizes are different, flag it as an
10038     // error.
10039     if (OpInfo.hasMatchingInput()) {
10040       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
10041       patchMatchingInput(OpInfo, Input, DAG);
10042     }
10043 
10044     // Compute the constraint code and ConstraintType to use.
10045     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
10046 
10047     if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
10048          OpInfo.Type == InlineAsm::isClobber) ||
10049         OpInfo.ConstraintType == TargetLowering::C_Address)
10050       continue;
10051 
10052     // In Linux PIC model, there are 4 cases about value/label addressing:
10053     //
10054     // 1: Function call or Label jmp inside the module.
10055     // 2: Data access (such as global variable, static variable) inside module.
10056     // 3: Function call or Label jmp outside the module.
10057     // 4: Data access (such as global variable) outside the module.
10058     //
10059     // Due to current llvm inline asm architecture designed to not "recognize"
10060     // the asm code, there are quite troubles for us to treat mem addressing
10061     // differently for same value/adress used in different instuctions.
10062     // For example, in pic model, call a func may in plt way or direclty
10063     // pc-related, but lea/mov a function adress may use got.
10064     //
10065     // Here we try to "recognize" function call for the case 1 and case 3 in
10066     // inline asm. And try to adjust the constraint for them.
10067     //
10068     // TODO: Due to current inline asm didn't encourage to jmp to the outsider
10069     // label, so here we don't handle jmp function label now, but we need to
10070     // enhance it (especilly in PIC model) if we meet meaningful requirements.
10071     if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
10072         TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
10073         TM.getCodeModel() != CodeModel::Large) {
10074       OpInfo.isIndirect = false;
10075       OpInfo.ConstraintType = TargetLowering::C_Address;
10076     }
10077 
10078     // If this is a memory input, and if the operand is not indirect, do what we
10079     // need to provide an address for the memory input.
10080     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
10081         !OpInfo.isIndirect) {
10082       assert((OpInfo.isMultipleAlternative ||
10083               (OpInfo.Type == InlineAsm::isInput)) &&
10084              "Can only indirectify direct input operands!");
10085 
10086       // Memory operands really want the address of the value.
10087       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
10088 
10089       // There is no longer a Value* corresponding to this operand.
10090       OpInfo.CallOperandVal = nullptr;
10091 
10092       // It is now an indirect operand.
10093       OpInfo.isIndirect = true;
10094     }
10095 
10096   }
10097 
10098   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
10099   std::vector<SDValue> AsmNodeOperands;
10100   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
10101   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
10102       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
10103 
10104   // If we have a !srcloc metadata node associated with it, we want to attach
10105   // this to the ultimately generated inline asm machineinstr.  To do this, we
10106   // pass in the third operand as this (potentially null) inline asm MDNode.
10107   const MDNode *SrcLoc = Call.getMetadata("srcloc");
10108   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
10109 
10110   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
10111   // bits as operand 3.
10112   AsmNodeOperands.push_back(DAG.getTargetConstant(
10113       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
10114 
10115   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
10116   // this, assign virtual and physical registers for inputs and otput.
10117   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
10118     // Assign Registers.
10119     SDISelAsmOperandInfo &RefOpInfo =
10120         OpInfo.isMatchingInputConstraint()
10121             ? ConstraintOperands[OpInfo.getMatchedOperand()]
10122             : OpInfo;
10123     const auto RegError =
10124         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
10125     if (RegError) {
10126       const MachineFunction &MF = DAG.getMachineFunction();
10127       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
10128       const char *RegName = TRI.getName(*RegError);
10129       emitInlineAsmError(Call, "register '" + Twine(RegName) +
10130                                    "' allocated for constraint '" +
10131                                    Twine(OpInfo.ConstraintCode) +
10132                                    "' does not match required type");
10133       return;
10134     }
10135 
10136     auto DetectWriteToReservedRegister = [&]() {
10137       const MachineFunction &MF = DAG.getMachineFunction();
10138       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
10139       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
10140         if (Register::isPhysicalRegister(Reg) &&
10141             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
10142           const char *RegName = TRI.getName(Reg);
10143           emitInlineAsmError(Call, "write to reserved register '" +
10144                                        Twine(RegName) + "'");
10145           return true;
10146         }
10147       }
10148       return false;
10149     };
10150     assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
10151             (OpInfo.Type == InlineAsm::isInput &&
10152              !OpInfo.isMatchingInputConstraint())) &&
10153            "Only address as input operand is allowed.");
10154 
10155     switch (OpInfo.Type) {
10156     case InlineAsm::isOutput:
10157       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
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 output.
10164         InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1);
10165         OpFlags.setMemConstraint(ConstraintID);
10166         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
10167                                                         MVT::i32));
10168         AsmNodeOperands.push_back(OpInfo.CallOperand);
10169       } else {
10170         // Otherwise, this outputs to a register (directly for C_Register /
10171         // C_RegisterClass, and a target-defined fashion for
10172         // C_Immediate/C_Other). Find a register that we can use.
10173         if (OpInfo.AssignedRegs.Regs.empty()) {
10174           emitInlineAsmError(
10175               Call, "couldn't allocate output register for constraint '" +
10176                         Twine(OpInfo.ConstraintCode) + "'");
10177           return;
10178         }
10179 
10180         if (DetectWriteToReservedRegister())
10181           return;
10182 
10183         // Add information to the INLINEASM node to know that this register is
10184         // set.
10185         OpInfo.AssignedRegs.AddInlineAsmOperands(
10186             OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber
10187                                   : InlineAsm::Kind::RegDef,
10188             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
10189       }
10190       break;
10191 
10192     case InlineAsm::isInput:
10193     case InlineAsm::isLabel: {
10194       SDValue InOperandVal = OpInfo.CallOperand;
10195 
10196       if (OpInfo.isMatchingInputConstraint()) {
10197         // If this is required to match an output register we have already set,
10198         // just use its register.
10199         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
10200                                                   AsmNodeOperands);
10201         InlineAsm::Flag Flag(AsmNodeOperands[CurOp]->getAsZExtVal());
10202         if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) {
10203           if (OpInfo.isIndirect) {
10204             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
10205             emitInlineAsmError(Call, "inline asm not supported yet: "
10206                                      "don't know how to handle tied "
10207                                      "indirect register inputs");
10208             return;
10209           }
10210 
10211           SmallVector<Register, 4> Regs;
10212           MachineFunction &MF = DAG.getMachineFunction();
10213           MachineRegisterInfo &MRI = MF.getRegInfo();
10214           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
10215           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
10216           Register TiedReg = R->getReg();
10217           MVT RegVT = R->getSimpleValueType(0);
10218           const TargetRegisterClass *RC =
10219               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
10220               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
10221                                       : TRI.getMinimalPhysRegClass(TiedReg);
10222           for (unsigned i = 0, e = Flag.getNumOperandRegisters(); i != e; ++i)
10223             Regs.push_back(MRI.createVirtualRegister(RC));
10224 
10225           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
10226 
10227           SDLoc dl = getCurSDLoc();
10228           // Use the produced MatchedRegs object to
10229           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call);
10230           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, true,
10231                                            OpInfo.getMatchedOperand(), dl, DAG,
10232                                            AsmNodeOperands);
10233           break;
10234         }
10235 
10236         assert(Flag.isMemKind() && "Unknown matching constraint!");
10237         assert(Flag.getNumOperandRegisters() == 1 &&
10238                "Unexpected number of operands");
10239         // Add information to the INLINEASM node to know about this input.
10240         // See InlineAsm.h isUseOperandTiedToDef.
10241         Flag.clearMemConstraint();
10242         Flag.setMatchingOp(OpInfo.getMatchedOperand());
10243         AsmNodeOperands.push_back(DAG.getTargetConstant(
10244             Flag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
10245         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
10246         break;
10247       }
10248 
10249       // Treat indirect 'X' constraint as memory.
10250       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
10251           OpInfo.isIndirect)
10252         OpInfo.ConstraintType = TargetLowering::C_Memory;
10253 
10254       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
10255           OpInfo.ConstraintType == TargetLowering::C_Other) {
10256         std::vector<SDValue> Ops;
10257         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
10258                                           Ops, DAG);
10259         if (Ops.empty()) {
10260           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
10261             if (isa<ConstantSDNode>(InOperandVal)) {
10262               emitInlineAsmError(Call, "value out of range for constraint '" +
10263                                            Twine(OpInfo.ConstraintCode) + "'");
10264               return;
10265             }
10266 
10267           emitInlineAsmError(Call,
10268                              "invalid operand for inline asm constraint '" +
10269                                  Twine(OpInfo.ConstraintCode) + "'");
10270           return;
10271         }
10272 
10273         // Add information to the INLINEASM node to know about this input.
10274         InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size());
10275         AsmNodeOperands.push_back(DAG.getTargetConstant(
10276             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
10277         llvm::append_range(AsmNodeOperands, Ops);
10278         break;
10279       }
10280 
10281       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10282         assert((OpInfo.isIndirect ||
10283                 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
10284                "Operand must be indirect to be a mem!");
10285         assert(InOperandVal.getValueType() ==
10286                    TLI.getPointerTy(DAG.getDataLayout()) &&
10287                "Memory operands expect pointer values");
10288 
10289         const InlineAsm::ConstraintCode ConstraintID =
10290             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10291         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10292                "Failed to convert memory constraint code to constraint id.");
10293 
10294         // Add information to the INLINEASM node to know about this input.
10295         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
10296         ResOpType.setMemConstraint(ConstraintID);
10297         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
10298                                                         getCurSDLoc(),
10299                                                         MVT::i32));
10300         AsmNodeOperands.push_back(InOperandVal);
10301         break;
10302       }
10303 
10304       if (OpInfo.ConstraintType == TargetLowering::C_Address) {
10305         const InlineAsm::ConstraintCode ConstraintID =
10306             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10307         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10308                "Failed to convert memory constraint code to constraint id.");
10309 
10310         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
10311 
10312         SDValue AsmOp = InOperandVal;
10313         if (isFunction(InOperandVal)) {
10314           auto *GA = cast<GlobalAddressSDNode>(InOperandVal);
10315           ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1);
10316           AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(),
10317                                              InOperandVal.getValueType(),
10318                                              GA->getOffset());
10319         }
10320 
10321         // Add information to the INLINEASM node to know about this input.
10322         ResOpType.setMemConstraint(ConstraintID);
10323 
10324         AsmNodeOperands.push_back(
10325             DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32));
10326 
10327         AsmNodeOperands.push_back(AsmOp);
10328         break;
10329       }
10330 
10331       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
10332           OpInfo.ConstraintType != TargetLowering::C_Register) {
10333         emitInlineAsmError(Call, "unknown asm constraint '" +
10334                                      Twine(OpInfo.ConstraintCode) + "'");
10335         return;
10336       }
10337 
10338       // TODO: Support this.
10339       if (OpInfo.isIndirect) {
10340         emitInlineAsmError(
10341             Call, "Don't know how to handle indirect register inputs yet "
10342                   "for constraint '" +
10343                       Twine(OpInfo.ConstraintCode) + "'");
10344         return;
10345       }
10346 
10347       // Copy the input into the appropriate registers.
10348       if (OpInfo.AssignedRegs.Regs.empty()) {
10349         emitInlineAsmError(Call,
10350                            "couldn't allocate input reg for constraint '" +
10351                                Twine(OpInfo.ConstraintCode) + "'");
10352         return;
10353       }
10354 
10355       if (DetectWriteToReservedRegister())
10356         return;
10357 
10358       SDLoc dl = getCurSDLoc();
10359 
10360       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue,
10361                                         &Call);
10362 
10363       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, false,
10364                                                0, dl, DAG, AsmNodeOperands);
10365       break;
10366     }
10367     case InlineAsm::isClobber:
10368       // Add the clobbered value to the operand list, so that the register
10369       // allocator is aware that the physreg got clobbered.
10370       if (!OpInfo.AssignedRegs.Regs.empty())
10371         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::Clobber,
10372                                                  false, 0, getCurSDLoc(), DAG,
10373                                                  AsmNodeOperands);
10374       break;
10375     }
10376   }
10377 
10378   // Finish up input operands.  Set the input chain and add the flag last.
10379   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
10380   if (Glue.getNode()) AsmNodeOperands.push_back(Glue);
10381 
10382   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
10383   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
10384                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
10385   Glue = Chain.getValue(1);
10386 
10387   // Do additional work to generate outputs.
10388 
10389   SmallVector<EVT, 1> ResultVTs;
10390   SmallVector<SDValue, 1> ResultValues;
10391   SmallVector<SDValue, 8> OutChains;
10392 
10393   llvm::Type *CallResultType = Call.getType();
10394   ArrayRef<Type *> ResultTypes;
10395   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
10396     ResultTypes = StructResult->elements();
10397   else if (!CallResultType->isVoidTy())
10398     ResultTypes = ArrayRef(CallResultType);
10399 
10400   auto CurResultType = ResultTypes.begin();
10401   auto handleRegAssign = [&](SDValue V) {
10402     assert(CurResultType != ResultTypes.end() && "Unexpected value");
10403     assert((*CurResultType)->isSized() && "Unexpected unsized type");
10404     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
10405     ++CurResultType;
10406     // If the type of the inline asm call site return value is different but has
10407     // same size as the type of the asm output bitcast it.  One example of this
10408     // is for vectors with different width / number of elements.  This can
10409     // happen for register classes that can contain multiple different value
10410     // types.  The preg or vreg allocated may not have the same VT as was
10411     // expected.
10412     //
10413     // This can also happen for a return value that disagrees with the register
10414     // class it is put in, eg. a double in a general-purpose register on a
10415     // 32-bit machine.
10416     if (ResultVT != V.getValueType() &&
10417         ResultVT.getSizeInBits() == V.getValueSizeInBits())
10418       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
10419     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
10420              V.getValueType().isInteger()) {
10421       // If a result value was tied to an input value, the computed result
10422       // may have a wider width than the expected result.  Extract the
10423       // relevant portion.
10424       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
10425     }
10426     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
10427     ResultVTs.push_back(ResultVT);
10428     ResultValues.push_back(V);
10429   };
10430 
10431   // Deal with output operands.
10432   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
10433     if (OpInfo.Type == InlineAsm::isOutput) {
10434       SDValue Val;
10435       // Skip trivial output operands.
10436       if (OpInfo.AssignedRegs.Regs.empty())
10437         continue;
10438 
10439       switch (OpInfo.ConstraintType) {
10440       case TargetLowering::C_Register:
10441       case TargetLowering::C_RegisterClass:
10442         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
10443                                                   Chain, &Glue, &Call);
10444         break;
10445       case TargetLowering::C_Immediate:
10446       case TargetLowering::C_Other:
10447         Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(),
10448                                               OpInfo, DAG);
10449         break;
10450       case TargetLowering::C_Memory:
10451         break; // Already handled.
10452       case TargetLowering::C_Address:
10453         break; // Silence warning.
10454       case TargetLowering::C_Unknown:
10455         assert(false && "Unexpected unknown constraint");
10456       }
10457 
10458       // Indirect output manifest as stores. Record output chains.
10459       if (OpInfo.isIndirect) {
10460         const Value *Ptr = OpInfo.CallOperandVal;
10461         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
10462         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
10463                                      MachinePointerInfo(Ptr));
10464         OutChains.push_back(Store);
10465       } else {
10466         // generate CopyFromRegs to associated registers.
10467         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
10468         if (Val.getOpcode() == ISD::MERGE_VALUES) {
10469           for (const SDValue &V : Val->op_values())
10470             handleRegAssign(V);
10471         } else
10472           handleRegAssign(Val);
10473       }
10474     }
10475   }
10476 
10477   // Set results.
10478   if (!ResultValues.empty()) {
10479     assert(CurResultType == ResultTypes.end() &&
10480            "Mismatch in number of ResultTypes");
10481     assert(ResultValues.size() == ResultTypes.size() &&
10482            "Mismatch in number of output operands in asm result");
10483 
10484     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
10485                             DAG.getVTList(ResultVTs), ResultValues);
10486     setValue(&Call, V);
10487   }
10488 
10489   // Collect store chains.
10490   if (!OutChains.empty())
10491     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
10492 
10493   if (EmitEHLabels) {
10494     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
10495   }
10496 
10497   // Only Update Root if inline assembly has a memory effect.
10498   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
10499       EmitEHLabels)
10500     DAG.setRoot(Chain);
10501 }
10502 
10503 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
10504                                              const Twine &Message) {
10505   LLVMContext &Ctx = *DAG.getContext();
10506   Ctx.emitError(&Call, Message);
10507 
10508   // Make sure we leave the DAG in a valid state
10509   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10510   SmallVector<EVT, 1> ValueVTs;
10511   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
10512 
10513   if (ValueVTs.empty())
10514     return;
10515 
10516   SmallVector<SDValue, 1> Ops;
10517   for (const EVT &VT : ValueVTs)
10518     Ops.push_back(DAG.getUNDEF(VT));
10519 
10520   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
10521 }
10522 
10523 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
10524   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
10525                           MVT::Other, getRoot(),
10526                           getValue(I.getArgOperand(0)),
10527                           DAG.getSrcValue(I.getArgOperand(0))));
10528 }
10529 
10530 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
10531   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10532   const DataLayout &DL = DAG.getDataLayout();
10533   SDValue V = DAG.getVAArg(
10534       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
10535       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
10536       DL.getABITypeAlign(I.getType()).value());
10537   DAG.setRoot(V.getValue(1));
10538 
10539   if (I.getType()->isPointerTy())
10540     V = DAG.getPtrExtOrTrunc(
10541         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
10542   setValue(&I, V);
10543 }
10544 
10545 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
10546   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
10547                           MVT::Other, getRoot(),
10548                           getValue(I.getArgOperand(0)),
10549                           DAG.getSrcValue(I.getArgOperand(0))));
10550 }
10551 
10552 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
10553   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
10554                           MVT::Other, getRoot(),
10555                           getValue(I.getArgOperand(0)),
10556                           getValue(I.getArgOperand(1)),
10557                           DAG.getSrcValue(I.getArgOperand(0)),
10558                           DAG.getSrcValue(I.getArgOperand(1))));
10559 }
10560 
10561 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
10562                                                     const Instruction &I,
10563                                                     SDValue Op) {
10564   std::optional<ConstantRange> CR = getRange(I);
10565 
10566   if (!CR || CR->isFullSet() || CR->isEmptySet() || CR->isUpperWrapped())
10567     return Op;
10568 
10569   APInt Lo = CR->getUnsignedMin();
10570   if (!Lo.isMinValue())
10571     return Op;
10572 
10573   APInt Hi = CR->getUnsignedMax();
10574   unsigned Bits = std::max(Hi.getActiveBits(),
10575                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
10576 
10577   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
10578 
10579   SDLoc SL = getCurSDLoc();
10580 
10581   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
10582                              DAG.getValueType(SmallVT));
10583   unsigned NumVals = Op.getNode()->getNumValues();
10584   if (NumVals == 1)
10585     return ZExt;
10586 
10587   SmallVector<SDValue, 4> Ops;
10588 
10589   Ops.push_back(ZExt);
10590   for (unsigned I = 1; I != NumVals; ++I)
10591     Ops.push_back(Op.getValue(I));
10592 
10593   return DAG.getMergeValues(Ops, SL);
10594 }
10595 
10596 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
10597 /// the call being lowered.
10598 ///
10599 /// This is a helper for lowering intrinsics that follow a target calling
10600 /// convention or require stack pointer adjustment. Only a subset of the
10601 /// intrinsic's operands need to participate in the calling convention.
10602 void SelectionDAGBuilder::populateCallLoweringInfo(
10603     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
10604     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
10605     AttributeSet RetAttrs, bool IsPatchPoint) {
10606   TargetLowering::ArgListTy Args;
10607   Args.reserve(NumArgs);
10608 
10609   // Populate the argument list.
10610   // Attributes for args start at offset 1, after the return attribute.
10611   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
10612        ArgI != ArgE; ++ArgI) {
10613     const Value *V = Call->getOperand(ArgI);
10614 
10615     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
10616 
10617     TargetLowering::ArgListEntry Entry;
10618     Entry.Node = getValue(V);
10619     Entry.Ty = V->getType();
10620     Entry.setAttributes(Call, ArgI);
10621     Args.push_back(Entry);
10622   }
10623 
10624   CLI.setDebugLoc(getCurSDLoc())
10625       .setChain(getRoot())
10626       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args),
10627                  RetAttrs)
10628       .setDiscardResult(Call->use_empty())
10629       .setIsPatchPoint(IsPatchPoint)
10630       .setIsPreallocated(
10631           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
10632 }
10633 
10634 /// Add a stack map intrinsic call's live variable operands to a stackmap
10635 /// or patchpoint target node's operand list.
10636 ///
10637 /// Constants are converted to TargetConstants purely as an optimization to
10638 /// avoid constant materialization and register allocation.
10639 ///
10640 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
10641 /// generate addess computation nodes, and so FinalizeISel can convert the
10642 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
10643 /// address materialization and register allocation, but may also be required
10644 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
10645 /// alloca in the entry block, then the runtime may assume that the alloca's
10646 /// StackMap location can be read immediately after compilation and that the
10647 /// location is valid at any point during execution (this is similar to the
10648 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
10649 /// only available in a register, then the runtime would need to trap when
10650 /// execution reaches the StackMap in order to read the alloca's location.
10651 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
10652                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
10653                                 SelectionDAGBuilder &Builder) {
10654   SelectionDAG &DAG = Builder.DAG;
10655   for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
10656     SDValue Op = Builder.getValue(Call.getArgOperand(I));
10657 
10658     // Things on the stack are pointer-typed, meaning that they are already
10659     // legal and can be emitted directly to target nodes.
10660     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
10661       Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
10662     } else {
10663       // Otherwise emit a target independent node to be legalised.
10664       Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
10665     }
10666   }
10667 }
10668 
10669 /// Lower llvm.experimental.stackmap.
10670 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
10671   // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
10672   //                                  [live variables...])
10673 
10674   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
10675 
10676   SDValue Chain, InGlue, Callee;
10677   SmallVector<SDValue, 32> Ops;
10678 
10679   SDLoc DL = getCurSDLoc();
10680   Callee = getValue(CI.getCalledOperand());
10681 
10682   // The stackmap intrinsic only records the live variables (the arguments
10683   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
10684   // intrinsic, this won't be lowered to a function call. This means we don't
10685   // have to worry about calling conventions and target specific lowering code.
10686   // Instead we perform the call lowering right here.
10687   //
10688   // chain, flag = CALLSEQ_START(chain, 0, 0)
10689   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
10690   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
10691   //
10692   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
10693   InGlue = Chain.getValue(1);
10694 
10695   // Add the STACKMAP operands, starting with DAG house-keeping.
10696   Ops.push_back(Chain);
10697   Ops.push_back(InGlue);
10698 
10699   // Add the <id>, <numShadowBytes> operands.
10700   //
10701   // These do not require legalisation, and can be emitted directly to target
10702   // constant nodes.
10703   SDValue ID = getValue(CI.getArgOperand(0));
10704   assert(ID.getValueType() == MVT::i64);
10705   SDValue IDConst =
10706       DAG.getTargetConstant(ID->getAsZExtVal(), DL, ID.getValueType());
10707   Ops.push_back(IDConst);
10708 
10709   SDValue Shad = getValue(CI.getArgOperand(1));
10710   assert(Shad.getValueType() == MVT::i32);
10711   SDValue ShadConst =
10712       DAG.getTargetConstant(Shad->getAsZExtVal(), DL, Shad.getValueType());
10713   Ops.push_back(ShadConst);
10714 
10715   // Add the live variables.
10716   addStackMapLiveVars(CI, 2, DL, Ops, *this);
10717 
10718   // Create the STACKMAP node.
10719   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10720   Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
10721   InGlue = Chain.getValue(1);
10722 
10723   Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL);
10724 
10725   // Stackmaps don't generate values, so nothing goes into the NodeMap.
10726 
10727   // Set the root to the target-lowered call chain.
10728   DAG.setRoot(Chain);
10729 
10730   // Inform the Frame Information that we have a stackmap in this function.
10731   FuncInfo.MF->getFrameInfo().setHasStackMap();
10732 }
10733 
10734 /// Lower llvm.experimental.patchpoint directly to its target opcode.
10735 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
10736                                           const BasicBlock *EHPadBB) {
10737   // <ty> @llvm.experimental.patchpoint.<ty>(i64 <id>,
10738   //                                         i32 <numBytes>,
10739   //                                         i8* <target>,
10740   //                                         i32 <numArgs>,
10741   //                                         [Args...],
10742   //                                         [live variables...])
10743 
10744   CallingConv::ID CC = CB.getCallingConv();
10745   bool IsAnyRegCC = CC == CallingConv::AnyReg;
10746   bool HasDef = !CB.getType()->isVoidTy();
10747   SDLoc dl = getCurSDLoc();
10748   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
10749 
10750   // Handle immediate and symbolic callees.
10751   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
10752     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
10753                                    /*isTarget=*/true);
10754   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
10755     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
10756                                          SDLoc(SymbolicCallee),
10757                                          SymbolicCallee->getValueType(0));
10758 
10759   // Get the real number of arguments participating in the call <numArgs>
10760   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
10761   unsigned NumArgs = NArgVal->getAsZExtVal();
10762 
10763   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
10764   // Intrinsics include all meta-operands up to but not including CC.
10765   unsigned NumMetaOpers = PatchPointOpers::CCPos;
10766   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
10767          "Not enough arguments provided to the patchpoint intrinsic");
10768 
10769   // For AnyRegCC the arguments are lowered later on manually.
10770   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
10771   Type *ReturnTy =
10772       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
10773 
10774   TargetLowering::CallLoweringInfo CLI(DAG);
10775   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
10776                            ReturnTy, CB.getAttributes().getRetAttrs(), true);
10777   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
10778 
10779   SDNode *CallEnd = Result.second.getNode();
10780   if (CallEnd->getOpcode() == ISD::EH_LABEL)
10781     CallEnd = CallEnd->getOperand(0).getNode();
10782   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
10783     CallEnd = CallEnd->getOperand(0).getNode();
10784 
10785   /// Get a call instruction from the call sequence chain.
10786   /// Tail calls are not allowed.
10787   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
10788          "Expected a callseq node.");
10789   SDNode *Call = CallEnd->getOperand(0).getNode();
10790   bool HasGlue = Call->getGluedNode();
10791 
10792   // Replace the target specific call node with the patchable intrinsic.
10793   SmallVector<SDValue, 8> Ops;
10794 
10795   // Push the chain.
10796   Ops.push_back(*(Call->op_begin()));
10797 
10798   // Optionally, push the glue (if any).
10799   if (HasGlue)
10800     Ops.push_back(*(Call->op_end() - 1));
10801 
10802   // Push the register mask info.
10803   if (HasGlue)
10804     Ops.push_back(*(Call->op_end() - 2));
10805   else
10806     Ops.push_back(*(Call->op_end() - 1));
10807 
10808   // Add the <id> and <numBytes> constants.
10809   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
10810   Ops.push_back(DAG.getTargetConstant(IDVal->getAsZExtVal(), dl, MVT::i64));
10811   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
10812   Ops.push_back(DAG.getTargetConstant(NBytesVal->getAsZExtVal(), dl, MVT::i32));
10813 
10814   // Add the callee.
10815   Ops.push_back(Callee);
10816 
10817   // Adjust <numArgs> to account for any arguments that have been passed on the
10818   // stack instead.
10819   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
10820   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
10821   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
10822   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
10823 
10824   // Add the calling convention
10825   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
10826 
10827   // Add the arguments we omitted previously. The register allocator should
10828   // place these in any free register.
10829   if (IsAnyRegCC)
10830     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
10831       Ops.push_back(getValue(CB.getArgOperand(i)));
10832 
10833   // Push the arguments from the call instruction.
10834   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
10835   Ops.append(Call->op_begin() + 2, e);
10836 
10837   // Push live variables for the stack map.
10838   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
10839 
10840   SDVTList NodeTys;
10841   if (IsAnyRegCC && HasDef) {
10842     // Create the return types based on the intrinsic definition
10843     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10844     SmallVector<EVT, 3> ValueVTs;
10845     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
10846     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
10847 
10848     // There is always a chain and a glue type at the end
10849     ValueVTs.push_back(MVT::Other);
10850     ValueVTs.push_back(MVT::Glue);
10851     NodeTys = DAG.getVTList(ValueVTs);
10852   } else
10853     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10854 
10855   // Replace the target specific call node with a PATCHPOINT node.
10856   SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
10857 
10858   // Update the NodeMap.
10859   if (HasDef) {
10860     if (IsAnyRegCC)
10861       setValue(&CB, SDValue(PPV.getNode(), 0));
10862     else
10863       setValue(&CB, Result.first);
10864   }
10865 
10866   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
10867   // call sequence. Furthermore the location of the chain and glue can change
10868   // when the AnyReg calling convention is used and the intrinsic returns a
10869   // value.
10870   if (IsAnyRegCC && HasDef) {
10871     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
10872     SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
10873     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10874   } else
10875     DAG.ReplaceAllUsesWith(Call, PPV.getNode());
10876   DAG.DeleteNode(Call);
10877 
10878   // Inform the Frame Information that we have a patchpoint in this function.
10879   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
10880 }
10881 
10882 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
10883                                             unsigned Intrinsic) {
10884   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10885   SDValue Op1 = getValue(I.getArgOperand(0));
10886   SDValue Op2;
10887   if (I.arg_size() > 1)
10888     Op2 = getValue(I.getArgOperand(1));
10889   SDLoc dl = getCurSDLoc();
10890   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
10891   SDValue Res;
10892   SDNodeFlags SDFlags;
10893   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
10894     SDFlags.copyFMF(*FPMO);
10895 
10896   switch (Intrinsic) {
10897   case Intrinsic::vector_reduce_fadd:
10898     if (SDFlags.hasAllowReassociation())
10899       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
10900                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
10901                         SDFlags);
10902     else
10903       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
10904     break;
10905   case Intrinsic::vector_reduce_fmul:
10906     if (SDFlags.hasAllowReassociation())
10907       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
10908                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
10909                         SDFlags);
10910     else
10911       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
10912     break;
10913   case Intrinsic::vector_reduce_add:
10914     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
10915     break;
10916   case Intrinsic::vector_reduce_mul:
10917     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
10918     break;
10919   case Intrinsic::vector_reduce_and:
10920     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
10921     break;
10922   case Intrinsic::vector_reduce_or:
10923     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
10924     break;
10925   case Intrinsic::vector_reduce_xor:
10926     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
10927     break;
10928   case Intrinsic::vector_reduce_smax:
10929     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
10930     break;
10931   case Intrinsic::vector_reduce_smin:
10932     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
10933     break;
10934   case Intrinsic::vector_reduce_umax:
10935     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
10936     break;
10937   case Intrinsic::vector_reduce_umin:
10938     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
10939     break;
10940   case Intrinsic::vector_reduce_fmax:
10941     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
10942     break;
10943   case Intrinsic::vector_reduce_fmin:
10944     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
10945     break;
10946   case Intrinsic::vector_reduce_fmaximum:
10947     Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags);
10948     break;
10949   case Intrinsic::vector_reduce_fminimum:
10950     Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags);
10951     break;
10952   default:
10953     llvm_unreachable("Unhandled vector reduce intrinsic");
10954   }
10955   setValue(&I, Res);
10956 }
10957 
10958 /// Returns an AttributeList representing the attributes applied to the return
10959 /// value of the given call.
10960 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
10961   SmallVector<Attribute::AttrKind, 2> Attrs;
10962   if (CLI.RetSExt)
10963     Attrs.push_back(Attribute::SExt);
10964   if (CLI.RetZExt)
10965     Attrs.push_back(Attribute::ZExt);
10966   if (CLI.IsInReg)
10967     Attrs.push_back(Attribute::InReg);
10968 
10969   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
10970                             Attrs);
10971 }
10972 
10973 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
10974 /// implementation, which just calls LowerCall.
10975 /// FIXME: When all targets are
10976 /// migrated to using LowerCall, this hook should be integrated into SDISel.
10977 std::pair<SDValue, SDValue>
10978 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
10979   // Handle the incoming return values from the call.
10980   CLI.Ins.clear();
10981   SmallVector<EVT, 4> RetTys;
10982   SmallVector<TypeSize, 4> Offsets;
10983   auto &DL = CLI.DAG.getDataLayout();
10984   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
10985 
10986   if (CLI.IsPostTypeLegalization) {
10987     // If we are lowering a libcall after legalization, split the return type.
10988     SmallVector<EVT, 4> OldRetTys;
10989     SmallVector<TypeSize, 4> OldOffsets;
10990     RetTys.swap(OldRetTys);
10991     Offsets.swap(OldOffsets);
10992 
10993     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
10994       EVT RetVT = OldRetTys[i];
10995       uint64_t Offset = OldOffsets[i];
10996       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
10997       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
10998       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
10999       RetTys.append(NumRegs, RegisterVT);
11000       for (unsigned j = 0; j != NumRegs; ++j)
11001         Offsets.push_back(TypeSize::getFixed(Offset + j * RegisterVTByteSZ));
11002     }
11003   }
11004 
11005   SmallVector<ISD::OutputArg, 4> Outs;
11006   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
11007 
11008   bool CanLowerReturn =
11009       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
11010                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
11011 
11012   SDValue DemoteStackSlot;
11013   int DemoteStackIdx = -100;
11014   if (!CanLowerReturn) {
11015     // FIXME: equivalent assert?
11016     // assert(!CS.hasInAllocaArgument() &&
11017     //        "sret demotion is incompatible with inalloca");
11018     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
11019     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
11020     MachineFunction &MF = CLI.DAG.getMachineFunction();
11021     DemoteStackIdx =
11022         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
11023     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
11024                                               DL.getAllocaAddrSpace());
11025 
11026     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
11027     ArgListEntry Entry;
11028     Entry.Node = DemoteStackSlot;
11029     Entry.Ty = StackSlotPtrType;
11030     Entry.IsSExt = false;
11031     Entry.IsZExt = false;
11032     Entry.IsInReg = false;
11033     Entry.IsSRet = true;
11034     Entry.IsNest = false;
11035     Entry.IsByVal = false;
11036     Entry.IsByRef = false;
11037     Entry.IsReturned = false;
11038     Entry.IsSwiftSelf = false;
11039     Entry.IsSwiftAsync = false;
11040     Entry.IsSwiftError = false;
11041     Entry.IsCFGuardTarget = false;
11042     Entry.Alignment = Alignment;
11043     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
11044     CLI.NumFixedArgs += 1;
11045     CLI.getArgs()[0].IndirectType = CLI.RetTy;
11046     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
11047 
11048     // sret demotion isn't compatible with tail-calls, since the sret argument
11049     // points into the callers stack frame.
11050     CLI.IsTailCall = false;
11051   } else {
11052     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
11053         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
11054     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
11055       ISD::ArgFlagsTy Flags;
11056       if (NeedsRegBlock) {
11057         Flags.setInConsecutiveRegs();
11058         if (I == RetTys.size() - 1)
11059           Flags.setInConsecutiveRegsLast();
11060       }
11061       EVT VT = RetTys[I];
11062       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
11063                                                      CLI.CallConv, VT);
11064       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
11065                                                        CLI.CallConv, VT);
11066       for (unsigned i = 0; i != NumRegs; ++i) {
11067         ISD::InputArg MyFlags;
11068         MyFlags.Flags = Flags;
11069         MyFlags.VT = RegisterVT;
11070         MyFlags.ArgVT = VT;
11071         MyFlags.Used = CLI.IsReturnValueUsed;
11072         if (CLI.RetTy->isPointerTy()) {
11073           MyFlags.Flags.setPointer();
11074           MyFlags.Flags.setPointerAddrSpace(
11075               cast<PointerType>(CLI.RetTy)->getAddressSpace());
11076         }
11077         if (CLI.RetSExt)
11078           MyFlags.Flags.setSExt();
11079         if (CLI.RetZExt)
11080           MyFlags.Flags.setZExt();
11081         if (CLI.IsInReg)
11082           MyFlags.Flags.setInReg();
11083         CLI.Ins.push_back(MyFlags);
11084       }
11085     }
11086   }
11087 
11088   // We push in swifterror return as the last element of CLI.Ins.
11089   ArgListTy &Args = CLI.getArgs();
11090   if (supportSwiftError()) {
11091     for (const ArgListEntry &Arg : Args) {
11092       if (Arg.IsSwiftError) {
11093         ISD::InputArg MyFlags;
11094         MyFlags.VT = getPointerTy(DL);
11095         MyFlags.ArgVT = EVT(getPointerTy(DL));
11096         MyFlags.Flags.setSwiftError();
11097         CLI.Ins.push_back(MyFlags);
11098       }
11099     }
11100   }
11101 
11102   // Handle all of the outgoing arguments.
11103   CLI.Outs.clear();
11104   CLI.OutVals.clear();
11105   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
11106     SmallVector<EVT, 4> ValueVTs;
11107     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
11108     // FIXME: Split arguments if CLI.IsPostTypeLegalization
11109     Type *FinalType = Args[i].Ty;
11110     if (Args[i].IsByVal)
11111       FinalType = Args[i].IndirectType;
11112     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
11113         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
11114     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
11115          ++Value) {
11116       EVT VT = ValueVTs[Value];
11117       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
11118       SDValue Op = SDValue(Args[i].Node.getNode(),
11119                            Args[i].Node.getResNo() + Value);
11120       ISD::ArgFlagsTy Flags;
11121 
11122       // Certain targets (such as MIPS), may have a different ABI alignment
11123       // for a type depending on the context. Give the target a chance to
11124       // specify the alignment it wants.
11125       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
11126       Flags.setOrigAlign(OriginalAlignment);
11127 
11128       if (Args[i].Ty->isPointerTy()) {
11129         Flags.setPointer();
11130         Flags.setPointerAddrSpace(
11131             cast<PointerType>(Args[i].Ty)->getAddressSpace());
11132       }
11133       if (Args[i].IsZExt)
11134         Flags.setZExt();
11135       if (Args[i].IsSExt)
11136         Flags.setSExt();
11137       if (Args[i].IsNoExt)
11138         Flags.setNoExt();
11139       if (Args[i].IsInReg) {
11140         // If we are using vectorcall calling convention, a structure that is
11141         // passed InReg - is surely an HVA
11142         if (CLI.CallConv == CallingConv::X86_VectorCall &&
11143             isa<StructType>(FinalType)) {
11144           // The first value of a structure is marked
11145           if (0 == Value)
11146             Flags.setHvaStart();
11147           Flags.setHva();
11148         }
11149         // Set InReg Flag
11150         Flags.setInReg();
11151       }
11152       if (Args[i].IsSRet)
11153         Flags.setSRet();
11154       if (Args[i].IsSwiftSelf)
11155         Flags.setSwiftSelf();
11156       if (Args[i].IsSwiftAsync)
11157         Flags.setSwiftAsync();
11158       if (Args[i].IsSwiftError)
11159         Flags.setSwiftError();
11160       if (Args[i].IsCFGuardTarget)
11161         Flags.setCFGuardTarget();
11162       if (Args[i].IsByVal)
11163         Flags.setByVal();
11164       if (Args[i].IsByRef)
11165         Flags.setByRef();
11166       if (Args[i].IsPreallocated) {
11167         Flags.setPreallocated();
11168         // Set the byval flag for CCAssignFn callbacks that don't know about
11169         // preallocated.  This way we can know how many bytes we should've
11170         // allocated and how many bytes a callee cleanup function will pop.  If
11171         // we port preallocated to more targets, we'll have to add custom
11172         // preallocated handling in the various CC lowering callbacks.
11173         Flags.setByVal();
11174       }
11175       if (Args[i].IsInAlloca) {
11176         Flags.setInAlloca();
11177         // Set the byval flag for CCAssignFn callbacks that don't know about
11178         // inalloca.  This way we can know how many bytes we should've allocated
11179         // and how many bytes a callee cleanup function will pop.  If we port
11180         // inalloca to more targets, we'll have to add custom inalloca handling
11181         // in the various CC lowering callbacks.
11182         Flags.setByVal();
11183       }
11184       Align MemAlign;
11185       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
11186         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
11187         Flags.setByValSize(FrameSize);
11188 
11189         // info is not there but there are cases it cannot get right.
11190         if (auto MA = Args[i].Alignment)
11191           MemAlign = *MA;
11192         else
11193           MemAlign = getByValTypeAlignment(Args[i].IndirectType, DL);
11194       } else if (auto MA = Args[i].Alignment) {
11195         MemAlign = *MA;
11196       } else {
11197         MemAlign = OriginalAlignment;
11198       }
11199       Flags.setMemAlign(MemAlign);
11200       if (Args[i].IsNest)
11201         Flags.setNest();
11202       if (NeedsRegBlock)
11203         Flags.setInConsecutiveRegs();
11204 
11205       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
11206                                                  CLI.CallConv, VT);
11207       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
11208                                                         CLI.CallConv, VT);
11209       SmallVector<SDValue, 4> Parts(NumParts);
11210       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
11211 
11212       if (Args[i].IsSExt)
11213         ExtendKind = ISD::SIGN_EXTEND;
11214       else if (Args[i].IsZExt)
11215         ExtendKind = ISD::ZERO_EXTEND;
11216 
11217       // Conservatively only handle 'returned' on non-vectors that can be lowered,
11218       // for now.
11219       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
11220           CanLowerReturn) {
11221         assert((CLI.RetTy == Args[i].Ty ||
11222                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
11223                  CLI.RetTy->getPointerAddressSpace() ==
11224                      Args[i].Ty->getPointerAddressSpace())) &&
11225                RetTys.size() == NumValues && "unexpected use of 'returned'");
11226         // Before passing 'returned' to the target lowering code, ensure that
11227         // either the register MVT and the actual EVT are the same size or that
11228         // the return value and argument are extended in the same way; in these
11229         // cases it's safe to pass the argument register value unchanged as the
11230         // return register value (although it's at the target's option whether
11231         // to do so)
11232         // TODO: allow code generation to take advantage of partially preserved
11233         // registers rather than clobbering the entire register when the
11234         // parameter extension method is not compatible with the return
11235         // extension method
11236         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
11237             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
11238              CLI.RetZExt == Args[i].IsZExt))
11239           Flags.setReturned();
11240       }
11241 
11242       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
11243                      CLI.CallConv, ExtendKind);
11244 
11245       for (unsigned j = 0; j != NumParts; ++j) {
11246         // if it isn't first piece, alignment must be 1
11247         // For scalable vectors the scalable part is currently handled
11248         // by individual targets, so we just use the known minimum size here.
11249         ISD::OutputArg MyFlags(
11250             Flags, Parts[j].getValueType().getSimpleVT(), VT,
11251             i < CLI.NumFixedArgs, i,
11252             j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
11253         if (NumParts > 1 && j == 0)
11254           MyFlags.Flags.setSplit();
11255         else if (j != 0) {
11256           MyFlags.Flags.setOrigAlign(Align(1));
11257           if (j == NumParts - 1)
11258             MyFlags.Flags.setSplitEnd();
11259         }
11260 
11261         CLI.Outs.push_back(MyFlags);
11262         CLI.OutVals.push_back(Parts[j]);
11263       }
11264 
11265       if (NeedsRegBlock && Value == NumValues - 1)
11266         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
11267     }
11268   }
11269 
11270   SmallVector<SDValue, 4> InVals;
11271   CLI.Chain = LowerCall(CLI, InVals);
11272 
11273   // Update CLI.InVals to use outside of this function.
11274   CLI.InVals = InVals;
11275 
11276   // Verify that the target's LowerCall behaved as expected.
11277   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
11278          "LowerCall didn't return a valid chain!");
11279   assert((!CLI.IsTailCall || InVals.empty()) &&
11280          "LowerCall emitted a return value for a tail call!");
11281   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
11282          "LowerCall didn't emit the correct number of values!");
11283 
11284   // For a tail call, the return value is merely live-out and there aren't
11285   // any nodes in the DAG representing it. Return a special value to
11286   // indicate that a tail call has been emitted and no more Instructions
11287   // should be processed in the current block.
11288   if (CLI.IsTailCall) {
11289     CLI.DAG.setRoot(CLI.Chain);
11290     return std::make_pair(SDValue(), SDValue());
11291   }
11292 
11293 #ifndef NDEBUG
11294   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
11295     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
11296     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
11297            "LowerCall emitted a value with the wrong type!");
11298   }
11299 #endif
11300 
11301   SmallVector<SDValue, 4> ReturnValues;
11302   if (!CanLowerReturn) {
11303     // The instruction result is the result of loading from the
11304     // hidden sret parameter.
11305     MVT PtrVT = getPointerTy(DL, DL.getAllocaAddrSpace());
11306 
11307     unsigned NumValues = RetTys.size();
11308     ReturnValues.resize(NumValues);
11309     SmallVector<SDValue, 4> Chains(NumValues);
11310 
11311     // An aggregate return value cannot wrap around the address space, so
11312     // offsets to its parts don't wrap either.
11313     MachineFunction &MF = CLI.DAG.getMachineFunction();
11314     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
11315     for (unsigned i = 0; i < NumValues; ++i) {
11316       SDValue Add =
11317           CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
11318                           CLI.DAG.getConstant(Offsets[i], CLI.DL, PtrVT),
11319                           SDNodeFlags::NoUnsignedWrap);
11320       SDValue L = CLI.DAG.getLoad(
11321           RetTys[i], CLI.DL, CLI.Chain, Add,
11322           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
11323                                             DemoteStackIdx, Offsets[i]),
11324           HiddenSRetAlign);
11325       ReturnValues[i] = L;
11326       Chains[i] = L.getValue(1);
11327     }
11328 
11329     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
11330   } else {
11331     // Collect the legal value parts into potentially illegal values
11332     // that correspond to the original function's return values.
11333     std::optional<ISD::NodeType> AssertOp;
11334     if (CLI.RetSExt)
11335       AssertOp = ISD::AssertSext;
11336     else if (CLI.RetZExt)
11337       AssertOp = ISD::AssertZext;
11338     unsigned CurReg = 0;
11339     for (EVT VT : RetTys) {
11340       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
11341                                                      CLI.CallConv, VT);
11342       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
11343                                                        CLI.CallConv, VT);
11344 
11345       ReturnValues.push_back(getCopyFromParts(
11346           CLI.DAG, CLI.DL, &InVals[CurReg], NumRegs, RegisterVT, VT, nullptr,
11347           CLI.Chain, CLI.CallConv, AssertOp));
11348       CurReg += NumRegs;
11349     }
11350 
11351     // For a function returning void, there is no return value. We can't create
11352     // such a node, so we just return a null return value in that case. In
11353     // that case, nothing will actually look at the value.
11354     if (ReturnValues.empty())
11355       return std::make_pair(SDValue(), CLI.Chain);
11356   }
11357 
11358   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
11359                                 CLI.DAG.getVTList(RetTys), ReturnValues);
11360   return std::make_pair(Res, CLI.Chain);
11361 }
11362 
11363 /// Places new result values for the node in Results (their number
11364 /// and types must exactly match those of the original return values of
11365 /// the node), or leaves Results empty, which indicates that the node is not
11366 /// to be custom lowered after all.
11367 void TargetLowering::LowerOperationWrapper(SDNode *N,
11368                                            SmallVectorImpl<SDValue> &Results,
11369                                            SelectionDAG &DAG) const {
11370   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
11371 
11372   if (!Res.getNode())
11373     return;
11374 
11375   // If the original node has one result, take the return value from
11376   // LowerOperation as is. It might not be result number 0.
11377   if (N->getNumValues() == 1) {
11378     Results.push_back(Res);
11379     return;
11380   }
11381 
11382   // If the original node has multiple results, then the return node should
11383   // have the same number of results.
11384   assert((N->getNumValues() == Res->getNumValues()) &&
11385       "Lowering returned the wrong number of results!");
11386 
11387   // Places new result values base on N result number.
11388   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
11389     Results.push_back(Res.getValue(I));
11390 }
11391 
11392 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11393   llvm_unreachable("LowerOperation not implemented for this target!");
11394 }
11395 
11396 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
11397                                                      unsigned Reg,
11398                                                      ISD::NodeType ExtendType) {
11399   SDValue Op = getNonRegisterValue(V);
11400   assert((Op.getOpcode() != ISD::CopyFromReg ||
11401           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
11402          "Copy from a reg to the same reg!");
11403   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
11404 
11405   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11406   // If this is an InlineAsm we have to match the registers required, not the
11407   // notional registers required by the type.
11408 
11409   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
11410                    std::nullopt); // This is not an ABI copy.
11411   SDValue Chain = DAG.getEntryNode();
11412 
11413   if (ExtendType == ISD::ANY_EXTEND) {
11414     auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
11415     if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
11416       ExtendType = PreferredExtendIt->second;
11417   }
11418   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
11419   PendingExports.push_back(Chain);
11420 }
11421 
11422 #include "llvm/CodeGen/SelectionDAGISel.h"
11423 
11424 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
11425 /// entry block, return true.  This includes arguments used by switches, since
11426 /// the switch may expand into multiple basic blocks.
11427 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
11428   // With FastISel active, we may be splitting blocks, so force creation
11429   // of virtual registers for all non-dead arguments.
11430   if (FastISel)
11431     return A->use_empty();
11432 
11433   const BasicBlock &Entry = A->getParent()->front();
11434   for (const User *U : A->users())
11435     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
11436       return false;  // Use not in entry block.
11437 
11438   return true;
11439 }
11440 
11441 using ArgCopyElisionMapTy =
11442     DenseMap<const Argument *,
11443              std::pair<const AllocaInst *, const StoreInst *>>;
11444 
11445 /// Scan the entry block of the function in FuncInfo for arguments that look
11446 /// like copies into a local alloca. Record any copied arguments in
11447 /// ArgCopyElisionCandidates.
11448 static void
11449 findArgumentCopyElisionCandidates(const DataLayout &DL,
11450                                   FunctionLoweringInfo *FuncInfo,
11451                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
11452   // Record the state of every static alloca used in the entry block. Argument
11453   // allocas are all used in the entry block, so we need approximately as many
11454   // entries as we have arguments.
11455   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
11456   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
11457   unsigned NumArgs = FuncInfo->Fn->arg_size();
11458   StaticAllocas.reserve(NumArgs * 2);
11459 
11460   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
11461     if (!V)
11462       return nullptr;
11463     V = V->stripPointerCasts();
11464     const auto *AI = dyn_cast<AllocaInst>(V);
11465     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
11466       return nullptr;
11467     auto Iter = StaticAllocas.insert({AI, Unknown});
11468     return &Iter.first->second;
11469   };
11470 
11471   // Look for stores of arguments to static allocas. Look through bitcasts and
11472   // GEPs to handle type coercions, as long as the alloca is fully initialized
11473   // by the store. Any non-store use of an alloca escapes it and any subsequent
11474   // unanalyzed store might write it.
11475   // FIXME: Handle structs initialized with multiple stores.
11476   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
11477     // Look for stores, and handle non-store uses conservatively.
11478     const auto *SI = dyn_cast<StoreInst>(&I);
11479     if (!SI) {
11480       // We will look through cast uses, so ignore them completely.
11481       if (I.isCast())
11482         continue;
11483       // Ignore debug info and pseudo op intrinsics, they don't escape or store
11484       // to allocas.
11485       if (I.isDebugOrPseudoInst())
11486         continue;
11487       // This is an unknown instruction. Assume it escapes or writes to all
11488       // static alloca operands.
11489       for (const Use &U : I.operands()) {
11490         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
11491           *Info = StaticAllocaInfo::Clobbered;
11492       }
11493       continue;
11494     }
11495 
11496     // If the stored value is a static alloca, mark it as escaped.
11497     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
11498       *Info = StaticAllocaInfo::Clobbered;
11499 
11500     // Check if the destination is a static alloca.
11501     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
11502     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
11503     if (!Info)
11504       continue;
11505     const AllocaInst *AI = cast<AllocaInst>(Dst);
11506 
11507     // Skip allocas that have been initialized or clobbered.
11508     if (*Info != StaticAllocaInfo::Unknown)
11509       continue;
11510 
11511     // Check if the stored value is an argument, and that this store fully
11512     // initializes the alloca.
11513     // If the argument type has padding bits we can't directly forward a pointer
11514     // as the upper bits may contain garbage.
11515     // Don't elide copies from the same argument twice.
11516     const Value *Val = SI->getValueOperand()->stripPointerCasts();
11517     const auto *Arg = dyn_cast<Argument>(Val);
11518     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
11519         Arg->getType()->isEmptyTy() ||
11520         DL.getTypeStoreSize(Arg->getType()) !=
11521             DL.getTypeAllocSize(AI->getAllocatedType()) ||
11522         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
11523         ArgCopyElisionCandidates.count(Arg)) {
11524       *Info = StaticAllocaInfo::Clobbered;
11525       continue;
11526     }
11527 
11528     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
11529                       << '\n');
11530 
11531     // Mark this alloca and store for argument copy elision.
11532     *Info = StaticAllocaInfo::Elidable;
11533     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
11534 
11535     // Stop scanning if we've seen all arguments. This will happen early in -O0
11536     // builds, which is useful, because -O0 builds have large entry blocks and
11537     // many allocas.
11538     if (ArgCopyElisionCandidates.size() == NumArgs)
11539       break;
11540   }
11541 }
11542 
11543 /// Try to elide argument copies from memory into a local alloca. Succeeds if
11544 /// ArgVal is a load from a suitable fixed stack object.
11545 static void tryToElideArgumentCopy(
11546     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
11547     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
11548     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
11549     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
11550     ArrayRef<SDValue> ArgVals, bool &ArgHasUses) {
11551   // Check if this is a load from a fixed stack object.
11552   auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]);
11553   if (!LNode)
11554     return;
11555   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
11556   if (!FINode)
11557     return;
11558 
11559   // Check that the fixed stack object is the right size and alignment.
11560   // Look at the alignment that the user wrote on the alloca instead of looking
11561   // at the stack object.
11562   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
11563   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
11564   const AllocaInst *AI = ArgCopyIter->second.first;
11565   int FixedIndex = FINode->getIndex();
11566   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
11567   int OldIndex = AllocaIndex;
11568   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
11569   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
11570     LLVM_DEBUG(
11571         dbgs() << "  argument copy elision failed due to bad fixed stack "
11572                   "object size\n");
11573     return;
11574   }
11575   Align RequiredAlignment = AI->getAlign();
11576   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
11577     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
11578                          "greater than stack argument alignment ("
11579                       << DebugStr(RequiredAlignment) << " vs "
11580                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
11581     return;
11582   }
11583 
11584   // Perform the elision. Delete the old stack object and replace its only use
11585   // in the variable info map. Mark the stack object as mutable and aliased.
11586   LLVM_DEBUG({
11587     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
11588            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
11589            << '\n';
11590   });
11591   MFI.RemoveStackObject(OldIndex);
11592   MFI.setIsImmutableObjectIndex(FixedIndex, false);
11593   MFI.setIsAliasedObjectIndex(FixedIndex, true);
11594   AllocaIndex = FixedIndex;
11595   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
11596   for (SDValue ArgVal : ArgVals)
11597     Chains.push_back(ArgVal.getValue(1));
11598 
11599   // Avoid emitting code for the store implementing the copy.
11600   const StoreInst *SI = ArgCopyIter->second.second;
11601   ElidedArgCopyInstrs.insert(SI);
11602 
11603   // Check for uses of the argument again so that we can avoid exporting ArgVal
11604   // if it is't used by anything other than the store.
11605   for (const Value *U : Arg.users()) {
11606     if (U != SI) {
11607       ArgHasUses = true;
11608       break;
11609     }
11610   }
11611 }
11612 
11613 void SelectionDAGISel::LowerArguments(const Function &F) {
11614   SelectionDAG &DAG = SDB->DAG;
11615   SDLoc dl = SDB->getCurSDLoc();
11616   const DataLayout &DL = DAG.getDataLayout();
11617   SmallVector<ISD::InputArg, 16> Ins;
11618 
11619   // In Naked functions we aren't going to save any registers.
11620   if (F.hasFnAttribute(Attribute::Naked))
11621     return;
11622 
11623   if (!FuncInfo->CanLowerReturn) {
11624     // Put in an sret pointer parameter before all the other parameters.
11625     MVT ValueVT = TLI->getPointerTy(DL, DL.getAllocaAddrSpace());
11626 
11627     ISD::ArgFlagsTy Flags;
11628     Flags.setSRet();
11629     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVT);
11630     ISD::InputArg RetArg(Flags, RegisterVT, ValueVT, true,
11631                          ISD::InputArg::NoArgIndex, 0);
11632     Ins.push_back(RetArg);
11633   }
11634 
11635   // Look for stores of arguments to static allocas. Mark such arguments with a
11636   // flag to ask the target to give us the memory location of that argument if
11637   // available.
11638   ArgCopyElisionMapTy ArgCopyElisionCandidates;
11639   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
11640                                     ArgCopyElisionCandidates);
11641 
11642   // Set up the incoming argument description vector.
11643   for (const Argument &Arg : F.args()) {
11644     unsigned ArgNo = Arg.getArgNo();
11645     SmallVector<EVT, 4> ValueVTs;
11646     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
11647     bool isArgValueUsed = !Arg.use_empty();
11648     unsigned PartBase = 0;
11649     Type *FinalType = Arg.getType();
11650     if (Arg.hasAttribute(Attribute::ByVal))
11651       FinalType = Arg.getParamByValType();
11652     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
11653         FinalType, F.getCallingConv(), F.isVarArg(), DL);
11654     for (unsigned Value = 0, NumValues = ValueVTs.size();
11655          Value != NumValues; ++Value) {
11656       EVT VT = ValueVTs[Value];
11657       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
11658       ISD::ArgFlagsTy Flags;
11659 
11660 
11661       if (Arg.getType()->isPointerTy()) {
11662         Flags.setPointer();
11663         Flags.setPointerAddrSpace(
11664             cast<PointerType>(Arg.getType())->getAddressSpace());
11665       }
11666       if (Arg.hasAttribute(Attribute::ZExt))
11667         Flags.setZExt();
11668       if (Arg.hasAttribute(Attribute::SExt))
11669         Flags.setSExt();
11670       if (Arg.hasAttribute(Attribute::InReg)) {
11671         // If we are using vectorcall calling convention, a structure that is
11672         // passed InReg - is surely an HVA
11673         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
11674             isa<StructType>(Arg.getType())) {
11675           // The first value of a structure is marked
11676           if (0 == Value)
11677             Flags.setHvaStart();
11678           Flags.setHva();
11679         }
11680         // Set InReg Flag
11681         Flags.setInReg();
11682       }
11683       if (Arg.hasAttribute(Attribute::StructRet))
11684         Flags.setSRet();
11685       if (Arg.hasAttribute(Attribute::SwiftSelf))
11686         Flags.setSwiftSelf();
11687       if (Arg.hasAttribute(Attribute::SwiftAsync))
11688         Flags.setSwiftAsync();
11689       if (Arg.hasAttribute(Attribute::SwiftError))
11690         Flags.setSwiftError();
11691       if (Arg.hasAttribute(Attribute::ByVal))
11692         Flags.setByVal();
11693       if (Arg.hasAttribute(Attribute::ByRef))
11694         Flags.setByRef();
11695       if (Arg.hasAttribute(Attribute::InAlloca)) {
11696         Flags.setInAlloca();
11697         // Set the byval flag for CCAssignFn callbacks that don't know about
11698         // inalloca.  This way we can know how many bytes we should've allocated
11699         // and how many bytes a callee cleanup function will pop.  If we port
11700         // inalloca to more targets, we'll have to add custom inalloca handling
11701         // in the various CC lowering callbacks.
11702         Flags.setByVal();
11703       }
11704       if (Arg.hasAttribute(Attribute::Preallocated)) {
11705         Flags.setPreallocated();
11706         // Set the byval flag for CCAssignFn callbacks that don't know about
11707         // preallocated.  This way we can know how many bytes we should've
11708         // allocated and how many bytes a callee cleanup function will pop.  If
11709         // we port preallocated to more targets, we'll have to add custom
11710         // preallocated handling in the various CC lowering callbacks.
11711         Flags.setByVal();
11712       }
11713 
11714       // Certain targets (such as MIPS), may have a different ABI alignment
11715       // for a type depending on the context. Give the target a chance to
11716       // specify the alignment it wants.
11717       const Align OriginalAlignment(
11718           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
11719       Flags.setOrigAlign(OriginalAlignment);
11720 
11721       Align MemAlign;
11722       Type *ArgMemTy = nullptr;
11723       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
11724           Flags.isByRef()) {
11725         if (!ArgMemTy)
11726           ArgMemTy = Arg.getPointeeInMemoryValueType();
11727 
11728         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
11729 
11730         // For in-memory arguments, size and alignment should be passed from FE.
11731         // BE will guess if this info is not there but there are cases it cannot
11732         // get right.
11733         if (auto ParamAlign = Arg.getParamStackAlign())
11734           MemAlign = *ParamAlign;
11735         else if ((ParamAlign = Arg.getParamAlign()))
11736           MemAlign = *ParamAlign;
11737         else
11738           MemAlign = TLI->getByValTypeAlignment(ArgMemTy, DL);
11739         if (Flags.isByRef())
11740           Flags.setByRefSize(MemSize);
11741         else
11742           Flags.setByValSize(MemSize);
11743       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
11744         MemAlign = *ParamAlign;
11745       } else {
11746         MemAlign = OriginalAlignment;
11747       }
11748       Flags.setMemAlign(MemAlign);
11749 
11750       if (Arg.hasAttribute(Attribute::Nest))
11751         Flags.setNest();
11752       if (NeedsRegBlock)
11753         Flags.setInConsecutiveRegs();
11754       if (ArgCopyElisionCandidates.count(&Arg))
11755         Flags.setCopyElisionCandidate();
11756       if (Arg.hasAttribute(Attribute::Returned))
11757         Flags.setReturned();
11758 
11759       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
11760           *CurDAG->getContext(), F.getCallingConv(), VT);
11761       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
11762           *CurDAG->getContext(), F.getCallingConv(), VT);
11763       for (unsigned i = 0; i != NumRegs; ++i) {
11764         // For scalable vectors, use the minimum size; individual targets
11765         // are responsible for handling scalable vector arguments and
11766         // return values.
11767         ISD::InputArg MyFlags(
11768             Flags, RegisterVT, VT, isArgValueUsed, ArgNo,
11769             PartBase + i * RegisterVT.getStoreSize().getKnownMinValue());
11770         if (NumRegs > 1 && i == 0)
11771           MyFlags.Flags.setSplit();
11772         // if it isn't first piece, alignment must be 1
11773         else if (i > 0) {
11774           MyFlags.Flags.setOrigAlign(Align(1));
11775           if (i == NumRegs - 1)
11776             MyFlags.Flags.setSplitEnd();
11777         }
11778         Ins.push_back(MyFlags);
11779       }
11780       if (NeedsRegBlock && Value == NumValues - 1)
11781         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
11782       PartBase += VT.getStoreSize().getKnownMinValue();
11783     }
11784   }
11785 
11786   // Call the target to set up the argument values.
11787   SmallVector<SDValue, 8> InVals;
11788   SDValue NewRoot = TLI->LowerFormalArguments(
11789       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
11790 
11791   // Verify that the target's LowerFormalArguments behaved as expected.
11792   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
11793          "LowerFormalArguments didn't return a valid chain!");
11794   assert(InVals.size() == Ins.size() &&
11795          "LowerFormalArguments didn't emit the correct number of values!");
11796   LLVM_DEBUG({
11797     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
11798       assert(InVals[i].getNode() &&
11799              "LowerFormalArguments emitted a null value!");
11800       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
11801              "LowerFormalArguments emitted a value with the wrong type!");
11802     }
11803   });
11804 
11805   // Update the DAG with the new chain value resulting from argument lowering.
11806   DAG.setRoot(NewRoot);
11807 
11808   // Set up the argument values.
11809   unsigned i = 0;
11810   if (!FuncInfo->CanLowerReturn) {
11811     // Create a virtual register for the sret pointer, and put in a copy
11812     // from the sret argument into it.
11813     MVT VT = TLI->getPointerTy(DL, DL.getAllocaAddrSpace());
11814     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
11815     std::optional<ISD::NodeType> AssertOp;
11816     SDValue ArgValue =
11817         getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, nullptr, NewRoot,
11818                          F.getCallingConv(), AssertOp);
11819 
11820     MachineFunction& MF = SDB->DAG.getMachineFunction();
11821     MachineRegisterInfo& RegInfo = MF.getRegInfo();
11822     Register SRetReg =
11823         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
11824     FuncInfo->DemoteRegister = SRetReg;
11825     NewRoot =
11826         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
11827     DAG.setRoot(NewRoot);
11828 
11829     // i indexes lowered arguments.  Bump it past the hidden sret argument.
11830     ++i;
11831   }
11832 
11833   SmallVector<SDValue, 4> Chains;
11834   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
11835   for (const Argument &Arg : F.args()) {
11836     SmallVector<SDValue, 4> ArgValues;
11837     SmallVector<EVT, 4> ValueVTs;
11838     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
11839     unsigned NumValues = ValueVTs.size();
11840     if (NumValues == 0)
11841       continue;
11842 
11843     bool ArgHasUses = !Arg.use_empty();
11844 
11845     // Elide the copying store if the target loaded this argument from a
11846     // suitable fixed stack object.
11847     if (Ins[i].Flags.isCopyElisionCandidate()) {
11848       unsigned NumParts = 0;
11849       for (EVT VT : ValueVTs)
11850         NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(),
11851                                                        F.getCallingConv(), VT);
11852 
11853       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
11854                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
11855                              ArrayRef(&InVals[i], NumParts), ArgHasUses);
11856     }
11857 
11858     // If this argument is unused then remember its value. It is used to generate
11859     // debugging information.
11860     bool isSwiftErrorArg =
11861         TLI->supportSwiftError() &&
11862         Arg.hasAttribute(Attribute::SwiftError);
11863     if (!ArgHasUses && !isSwiftErrorArg) {
11864       SDB->setUnusedArgValue(&Arg, InVals[i]);
11865 
11866       // Also remember any frame index for use in FastISel.
11867       if (FrameIndexSDNode *FI =
11868           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
11869         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11870     }
11871 
11872     for (unsigned Val = 0; Val != NumValues; ++Val) {
11873       EVT VT = ValueVTs[Val];
11874       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
11875                                                       F.getCallingConv(), VT);
11876       unsigned NumParts = TLI->getNumRegistersForCallingConv(
11877           *CurDAG->getContext(), F.getCallingConv(), VT);
11878 
11879       // Even an apparent 'unused' swifterror argument needs to be returned. So
11880       // we do generate a copy for it that can be used on return from the
11881       // function.
11882       if (ArgHasUses || isSwiftErrorArg) {
11883         std::optional<ISD::NodeType> AssertOp;
11884         if (Arg.hasAttribute(Attribute::SExt))
11885           AssertOp = ISD::AssertSext;
11886         else if (Arg.hasAttribute(Attribute::ZExt))
11887           AssertOp = ISD::AssertZext;
11888 
11889         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
11890                                              PartVT, VT, nullptr, NewRoot,
11891                                              F.getCallingConv(), AssertOp));
11892       }
11893 
11894       i += NumParts;
11895     }
11896 
11897     // We don't need to do anything else for unused arguments.
11898     if (ArgValues.empty())
11899       continue;
11900 
11901     // Note down frame index.
11902     if (FrameIndexSDNode *FI =
11903         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
11904       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11905 
11906     SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues),
11907                                      SDB->getCurSDLoc());
11908 
11909     SDB->setValue(&Arg, Res);
11910     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
11911       // We want to associate the argument with the frame index, among
11912       // involved operands, that correspond to the lowest address. The
11913       // getCopyFromParts function, called earlier, is swapping the order of
11914       // the operands to BUILD_PAIR depending on endianness. The result of
11915       // that swapping is that the least significant bits of the argument will
11916       // be in the first operand of the BUILD_PAIR node, and the most
11917       // significant bits will be in the second operand.
11918       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
11919       if (LoadSDNode *LNode =
11920           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
11921         if (FrameIndexSDNode *FI =
11922             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
11923           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11924     }
11925 
11926     // Analyses past this point are naive and don't expect an assertion.
11927     if (Res.getOpcode() == ISD::AssertZext)
11928       Res = Res.getOperand(0);
11929 
11930     // Update the SwiftErrorVRegDefMap.
11931     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
11932       Register Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11933       if (Reg.isVirtual())
11934         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
11935                                    Reg);
11936     }
11937 
11938     // If this argument is live outside of the entry block, insert a copy from
11939     // wherever we got it to the vreg that other BB's will reference it as.
11940     if (Res.getOpcode() == ISD::CopyFromReg) {
11941       // If we can, though, try to skip creating an unnecessary vreg.
11942       // FIXME: This isn't very clean... it would be nice to make this more
11943       // general.
11944       Register Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11945       if (Reg.isVirtual()) {
11946         FuncInfo->ValueMap[&Arg] = Reg;
11947         continue;
11948       }
11949     }
11950     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
11951       FuncInfo->InitializeRegForValue(&Arg);
11952       SDB->CopyToExportRegsIfNeeded(&Arg);
11953     }
11954   }
11955 
11956   if (!Chains.empty()) {
11957     Chains.push_back(NewRoot);
11958     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
11959   }
11960 
11961   DAG.setRoot(NewRoot);
11962 
11963   assert(i == InVals.size() && "Argument register count mismatch!");
11964 
11965   // If any argument copy elisions occurred and we have debug info, update the
11966   // stale frame indices used in the dbg.declare variable info table.
11967   if (!ArgCopyElisionFrameIndexMap.empty()) {
11968     for (MachineFunction::VariableDbgInfo &VI :
11969          MF->getInStackSlotVariableDbgInfo()) {
11970       auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot());
11971       if (I != ArgCopyElisionFrameIndexMap.end())
11972         VI.updateStackSlot(I->second);
11973     }
11974   }
11975 
11976   // Finally, if the target has anything special to do, allow it to do so.
11977   emitFunctionEntryCode();
11978 }
11979 
11980 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
11981 /// ensure constants are generated when needed.  Remember the virtual registers
11982 /// that need to be added to the Machine PHI nodes as input.  We cannot just
11983 /// directly add them, because expansion might result in multiple MBB's for one
11984 /// BB.  As such, the start of the BB might correspond to a different MBB than
11985 /// the end.
11986 void
11987 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
11988   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11989 
11990   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
11991 
11992   // Check PHI nodes in successors that expect a value to be available from this
11993   // block.
11994   for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
11995     if (!isa<PHINode>(SuccBB->begin())) continue;
11996     MachineBasicBlock *SuccMBB = FuncInfo.getMBB(SuccBB);
11997 
11998     // If this terminator has multiple identical successors (common for
11999     // switches), only handle each succ once.
12000     if (!SuccsHandled.insert(SuccMBB).second)
12001       continue;
12002 
12003     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
12004 
12005     // At this point we know that there is a 1-1 correspondence between LLVM PHI
12006     // nodes and Machine PHI nodes, but the incoming operands have not been
12007     // emitted yet.
12008     for (const PHINode &PN : SuccBB->phis()) {
12009       // Ignore dead phi's.
12010       if (PN.use_empty())
12011         continue;
12012 
12013       // Skip empty types
12014       if (PN.getType()->isEmptyTy())
12015         continue;
12016 
12017       unsigned Reg;
12018       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
12019 
12020       if (const auto *C = dyn_cast<Constant>(PHIOp)) {
12021         unsigned &RegOut = ConstantsOut[C];
12022         if (RegOut == 0) {
12023           RegOut = FuncInfo.CreateRegs(C);
12024           // We need to zero/sign extend ConstantInt phi operands to match
12025           // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
12026           ISD::NodeType ExtendType = ISD::ANY_EXTEND;
12027           if (auto *CI = dyn_cast<ConstantInt>(C))
12028             ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
12029                                                     : ISD::ZERO_EXTEND;
12030           CopyValueToVirtualRegister(C, RegOut, ExtendType);
12031         }
12032         Reg = RegOut;
12033       } else {
12034         DenseMap<const Value *, Register>::iterator I =
12035           FuncInfo.ValueMap.find(PHIOp);
12036         if (I != FuncInfo.ValueMap.end())
12037           Reg = I->second;
12038         else {
12039           assert(isa<AllocaInst>(PHIOp) &&
12040                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
12041                  "Didn't codegen value into a register!??");
12042           Reg = FuncInfo.CreateRegs(PHIOp);
12043           CopyValueToVirtualRegister(PHIOp, Reg);
12044         }
12045       }
12046 
12047       // Remember that this register needs to added to the machine PHI node as
12048       // the input for this MBB.
12049       SmallVector<EVT, 4> ValueVTs;
12050       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
12051       for (EVT VT : ValueVTs) {
12052         const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
12053         for (unsigned i = 0; i != NumRegisters; ++i)
12054           FuncInfo.PHINodesToUpdate.push_back(
12055               std::make_pair(&*MBBI++, Reg + i));
12056         Reg += NumRegisters;
12057       }
12058     }
12059   }
12060 
12061   ConstantsOut.clear();
12062 }
12063 
12064 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
12065   MachineFunction::iterator I(MBB);
12066   if (++I == FuncInfo.MF->end())
12067     return nullptr;
12068   return &*I;
12069 }
12070 
12071 /// During lowering new call nodes can be created (such as memset, etc.).
12072 /// Those will become new roots of the current DAG, but complications arise
12073 /// when they are tail calls. In such cases, the call lowering will update
12074 /// the root, but the builder still needs to know that a tail call has been
12075 /// lowered in order to avoid generating an additional return.
12076 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
12077   // If the node is null, we do have a tail call.
12078   if (MaybeTC.getNode() != nullptr)
12079     DAG.setRoot(MaybeTC);
12080   else
12081     HasTailCall = true;
12082 }
12083 
12084 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
12085                                         MachineBasicBlock *SwitchMBB,
12086                                         MachineBasicBlock *DefaultMBB) {
12087   MachineFunction *CurMF = FuncInfo.MF;
12088   MachineBasicBlock *NextMBB = nullptr;
12089   MachineFunction::iterator BBI(W.MBB);
12090   if (++BBI != FuncInfo.MF->end())
12091     NextMBB = &*BBI;
12092 
12093   unsigned Size = W.LastCluster - W.FirstCluster + 1;
12094 
12095   BranchProbabilityInfo *BPI = FuncInfo.BPI;
12096 
12097   if (Size == 2 && W.MBB == SwitchMBB) {
12098     // If any two of the cases has the same destination, and if one value
12099     // is the same as the other, but has one bit unset that the other has set,
12100     // use bit manipulation to do two compares at once.  For example:
12101     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
12102     // TODO: This could be extended to merge any 2 cases in switches with 3
12103     // cases.
12104     // TODO: Handle cases where W.CaseBB != SwitchBB.
12105     CaseCluster &Small = *W.FirstCluster;
12106     CaseCluster &Big = *W.LastCluster;
12107 
12108     if (Small.Low == Small.High && Big.Low == Big.High &&
12109         Small.MBB == Big.MBB) {
12110       const APInt &SmallValue = Small.Low->getValue();
12111       const APInt &BigValue = Big.Low->getValue();
12112 
12113       // Check that there is only one bit different.
12114       APInt CommonBit = BigValue ^ SmallValue;
12115       if (CommonBit.isPowerOf2()) {
12116         SDValue CondLHS = getValue(Cond);
12117         EVT VT = CondLHS.getValueType();
12118         SDLoc DL = getCurSDLoc();
12119 
12120         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
12121                                  DAG.getConstant(CommonBit, DL, VT));
12122         SDValue Cond = DAG.getSetCC(
12123             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
12124             ISD::SETEQ);
12125 
12126         // Update successor info.
12127         // Both Small and Big will jump to Small.BB, so we sum up the
12128         // probabilities.
12129         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
12130         if (BPI)
12131           addSuccessorWithProb(
12132               SwitchMBB, DefaultMBB,
12133               // The default destination is the first successor in IR.
12134               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
12135         else
12136           addSuccessorWithProb(SwitchMBB, DefaultMBB);
12137 
12138         // Insert the true branch.
12139         SDValue BrCond =
12140             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
12141                         DAG.getBasicBlock(Small.MBB));
12142         // Insert the false branch.
12143         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
12144                              DAG.getBasicBlock(DefaultMBB));
12145 
12146         DAG.setRoot(BrCond);
12147         return;
12148       }
12149     }
12150   }
12151 
12152   if (TM.getOptLevel() != CodeGenOptLevel::None) {
12153     // Here, we order cases by probability so the most likely case will be
12154     // checked first. However, two clusters can have the same probability in
12155     // which case their relative ordering is non-deterministic. So we use Low
12156     // as a tie-breaker as clusters are guaranteed to never overlap.
12157     llvm::sort(W.FirstCluster, W.LastCluster + 1,
12158                [](const CaseCluster &a, const CaseCluster &b) {
12159       return a.Prob != b.Prob ?
12160              a.Prob > b.Prob :
12161              a.Low->getValue().slt(b.Low->getValue());
12162     });
12163 
12164     // Rearrange the case blocks so that the last one falls through if possible
12165     // without changing the order of probabilities.
12166     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
12167       --I;
12168       if (I->Prob > W.LastCluster->Prob)
12169         break;
12170       if (I->Kind == CC_Range && I->MBB == NextMBB) {
12171         std::swap(*I, *W.LastCluster);
12172         break;
12173       }
12174     }
12175   }
12176 
12177   // Compute total probability.
12178   BranchProbability DefaultProb = W.DefaultProb;
12179   BranchProbability UnhandledProbs = DefaultProb;
12180   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
12181     UnhandledProbs += I->Prob;
12182 
12183   MachineBasicBlock *CurMBB = W.MBB;
12184   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
12185     bool FallthroughUnreachable = false;
12186     MachineBasicBlock *Fallthrough;
12187     if (I == W.LastCluster) {
12188       // For the last cluster, fall through to the default destination.
12189       Fallthrough = DefaultMBB;
12190       FallthroughUnreachable = isa<UnreachableInst>(
12191           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
12192     } else {
12193       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
12194       CurMF->insert(BBI, Fallthrough);
12195       // Put Cond in a virtual register to make it available from the new blocks.
12196       ExportFromCurrentBlock(Cond);
12197     }
12198     UnhandledProbs -= I->Prob;
12199 
12200     switch (I->Kind) {
12201       case CC_JumpTable: {
12202         // FIXME: Optimize away range check based on pivot comparisons.
12203         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
12204         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
12205 
12206         // The jump block hasn't been inserted yet; insert it here.
12207         MachineBasicBlock *JumpMBB = JT->MBB;
12208         CurMF->insert(BBI, JumpMBB);
12209 
12210         auto JumpProb = I->Prob;
12211         auto FallthroughProb = UnhandledProbs;
12212 
12213         // If the default statement is a target of the jump table, we evenly
12214         // distribute the default probability to successors of CurMBB. Also
12215         // update the probability on the edge from JumpMBB to Fallthrough.
12216         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
12217                                               SE = JumpMBB->succ_end();
12218              SI != SE; ++SI) {
12219           if (*SI == DefaultMBB) {
12220             JumpProb += DefaultProb / 2;
12221             FallthroughProb -= DefaultProb / 2;
12222             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
12223             JumpMBB->normalizeSuccProbs();
12224             break;
12225           }
12226         }
12227 
12228         // If the default clause is unreachable, propagate that knowledge into
12229         // JTH->FallthroughUnreachable which will use it to suppress the range
12230         // check.
12231         //
12232         // However, don't do this if we're doing branch target enforcement,
12233         // because a table branch _without_ a range check can be a tempting JOP
12234         // gadget - out-of-bounds inputs that are impossible in correct
12235         // execution become possible again if an attacker can influence the
12236         // control flow. So if an attacker doesn't already have a BTI bypass
12237         // available, we don't want them to be able to get one out of this
12238         // table branch.
12239         if (FallthroughUnreachable) {
12240           Function &CurFunc = CurMF->getFunction();
12241           if (!CurFunc.hasFnAttribute("branch-target-enforcement"))
12242             JTH->FallthroughUnreachable = true;
12243         }
12244 
12245         if (!JTH->FallthroughUnreachable)
12246           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
12247         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
12248         CurMBB->normalizeSuccProbs();
12249 
12250         // The jump table header will be inserted in our current block, do the
12251         // range check, and fall through to our fallthrough block.
12252         JTH->HeaderBB = CurMBB;
12253         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
12254 
12255         // If we're in the right place, emit the jump table header right now.
12256         if (CurMBB == SwitchMBB) {
12257           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
12258           JTH->Emitted = true;
12259         }
12260         break;
12261       }
12262       case CC_BitTests: {
12263         // FIXME: Optimize away range check based on pivot comparisons.
12264         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
12265 
12266         // The bit test blocks haven't been inserted yet; insert them here.
12267         for (BitTestCase &BTC : BTB->Cases)
12268           CurMF->insert(BBI, BTC.ThisBB);
12269 
12270         // Fill in fields of the BitTestBlock.
12271         BTB->Parent = CurMBB;
12272         BTB->Default = Fallthrough;
12273 
12274         BTB->DefaultProb = UnhandledProbs;
12275         // If the cases in bit test don't form a contiguous range, we evenly
12276         // distribute the probability on the edge to Fallthrough to two
12277         // successors of CurMBB.
12278         if (!BTB->ContiguousRange) {
12279           BTB->Prob += DefaultProb / 2;
12280           BTB->DefaultProb -= DefaultProb / 2;
12281         }
12282 
12283         if (FallthroughUnreachable)
12284           BTB->FallthroughUnreachable = true;
12285 
12286         // If we're in the right place, emit the bit test header right now.
12287         if (CurMBB == SwitchMBB) {
12288           visitBitTestHeader(*BTB, SwitchMBB);
12289           BTB->Emitted = true;
12290         }
12291         break;
12292       }
12293       case CC_Range: {
12294         const Value *RHS, *LHS, *MHS;
12295         ISD::CondCode CC;
12296         if (I->Low == I->High) {
12297           // Check Cond == I->Low.
12298           CC = ISD::SETEQ;
12299           LHS = Cond;
12300           RHS=I->Low;
12301           MHS = nullptr;
12302         } else {
12303           // Check I->Low <= Cond <= I->High.
12304           CC = ISD::SETLE;
12305           LHS = I->Low;
12306           MHS = Cond;
12307           RHS = I->High;
12308         }
12309 
12310         // If Fallthrough is unreachable, fold away the comparison.
12311         if (FallthroughUnreachable)
12312           CC = ISD::SETTRUE;
12313 
12314         // The false probability is the sum of all unhandled cases.
12315         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
12316                      getCurSDLoc(), I->Prob, UnhandledProbs);
12317 
12318         if (CurMBB == SwitchMBB)
12319           visitSwitchCase(CB, SwitchMBB);
12320         else
12321           SL->SwitchCases.push_back(CB);
12322 
12323         break;
12324       }
12325     }
12326     CurMBB = Fallthrough;
12327   }
12328 }
12329 
12330 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
12331                                         const SwitchWorkListItem &W,
12332                                         Value *Cond,
12333                                         MachineBasicBlock *SwitchMBB) {
12334   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
12335          "Clusters not sorted?");
12336   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
12337 
12338   auto [LastLeft, FirstRight, LeftProb, RightProb] =
12339       SL->computeSplitWorkItemInfo(W);
12340 
12341   // Use the first element on the right as pivot since we will make less-than
12342   // comparisons against it.
12343   CaseClusterIt PivotCluster = FirstRight;
12344   assert(PivotCluster > W.FirstCluster);
12345   assert(PivotCluster <= W.LastCluster);
12346 
12347   CaseClusterIt FirstLeft = W.FirstCluster;
12348   CaseClusterIt LastRight = W.LastCluster;
12349 
12350   const ConstantInt *Pivot = PivotCluster->Low;
12351 
12352   // New blocks will be inserted immediately after the current one.
12353   MachineFunction::iterator BBI(W.MBB);
12354   ++BBI;
12355 
12356   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
12357   // we can branch to its destination directly if it's squeezed exactly in
12358   // between the known lower bound and Pivot - 1.
12359   MachineBasicBlock *LeftMBB;
12360   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
12361       FirstLeft->Low == W.GE &&
12362       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
12363     LeftMBB = FirstLeft->MBB;
12364   } else {
12365     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12366     FuncInfo.MF->insert(BBI, LeftMBB);
12367     WorkList.push_back(
12368         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
12369     // Put Cond in a virtual register to make it available from the new blocks.
12370     ExportFromCurrentBlock(Cond);
12371   }
12372 
12373   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
12374   // single cluster, RHS.Low == Pivot, and we can branch to its destination
12375   // directly if RHS.High equals the current upper bound.
12376   MachineBasicBlock *RightMBB;
12377   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
12378       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
12379     RightMBB = FirstRight->MBB;
12380   } else {
12381     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12382     FuncInfo.MF->insert(BBI, RightMBB);
12383     WorkList.push_back(
12384         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
12385     // Put Cond in a virtual register to make it available from the new blocks.
12386     ExportFromCurrentBlock(Cond);
12387   }
12388 
12389   // Create the CaseBlock record that will be used to lower the branch.
12390   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
12391                getCurSDLoc(), LeftProb, RightProb);
12392 
12393   if (W.MBB == SwitchMBB)
12394     visitSwitchCase(CB, SwitchMBB);
12395   else
12396     SL->SwitchCases.push_back(CB);
12397 }
12398 
12399 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
12400 // from the swith statement.
12401 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
12402                                             BranchProbability PeeledCaseProb) {
12403   if (PeeledCaseProb == BranchProbability::getOne())
12404     return BranchProbability::getZero();
12405   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
12406 
12407   uint32_t Numerator = CaseProb.getNumerator();
12408   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
12409   return BranchProbability(Numerator, std::max(Numerator, Denominator));
12410 }
12411 
12412 // Try to peel the top probability case if it exceeds the threshold.
12413 // Return current MachineBasicBlock for the switch statement if the peeling
12414 // does not occur.
12415 // If the peeling is performed, return the newly created MachineBasicBlock
12416 // for the peeled switch statement. Also update Clusters to remove the peeled
12417 // case. PeeledCaseProb is the BranchProbability for the peeled case.
12418 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
12419     const SwitchInst &SI, CaseClusterVector &Clusters,
12420     BranchProbability &PeeledCaseProb) {
12421   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12422   // Don't perform if there is only one cluster or optimizing for size.
12423   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
12424       TM.getOptLevel() == CodeGenOptLevel::None ||
12425       SwitchMBB->getParent()->getFunction().hasMinSize())
12426     return SwitchMBB;
12427 
12428   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
12429   unsigned PeeledCaseIndex = 0;
12430   bool SwitchPeeled = false;
12431   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
12432     CaseCluster &CC = Clusters[Index];
12433     if (CC.Prob < TopCaseProb)
12434       continue;
12435     TopCaseProb = CC.Prob;
12436     PeeledCaseIndex = Index;
12437     SwitchPeeled = true;
12438   }
12439   if (!SwitchPeeled)
12440     return SwitchMBB;
12441 
12442   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
12443                     << TopCaseProb << "\n");
12444 
12445   // Record the MBB for the peeled switch statement.
12446   MachineFunction::iterator BBI(SwitchMBB);
12447   ++BBI;
12448   MachineBasicBlock *PeeledSwitchMBB =
12449       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
12450   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
12451 
12452   ExportFromCurrentBlock(SI.getCondition());
12453   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
12454   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
12455                           nullptr,   nullptr,      TopCaseProb.getCompl()};
12456   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
12457 
12458   Clusters.erase(PeeledCaseIt);
12459   for (CaseCluster &CC : Clusters) {
12460     LLVM_DEBUG(
12461         dbgs() << "Scale the probablity for one cluster, before scaling: "
12462                << CC.Prob << "\n");
12463     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
12464     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
12465   }
12466   PeeledCaseProb = TopCaseProb;
12467   return PeeledSwitchMBB;
12468 }
12469 
12470 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
12471   // Extract cases from the switch.
12472   BranchProbabilityInfo *BPI = FuncInfo.BPI;
12473   CaseClusterVector Clusters;
12474   Clusters.reserve(SI.getNumCases());
12475   for (auto I : SI.cases()) {
12476     MachineBasicBlock *Succ = FuncInfo.getMBB(I.getCaseSuccessor());
12477     const ConstantInt *CaseVal = I.getCaseValue();
12478     BranchProbability Prob =
12479         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
12480             : BranchProbability(1, SI.getNumCases() + 1);
12481     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
12482   }
12483 
12484   MachineBasicBlock *DefaultMBB = FuncInfo.getMBB(SI.getDefaultDest());
12485 
12486   // Cluster adjacent cases with the same destination. We do this at all
12487   // optimization levels because it's cheap to do and will make codegen faster
12488   // if there are many clusters.
12489   sortAndRangeify(Clusters);
12490 
12491   // The branch probablity of the peeled case.
12492   BranchProbability PeeledCaseProb = BranchProbability::getZero();
12493   MachineBasicBlock *PeeledSwitchMBB =
12494       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
12495 
12496   // If there is only the default destination, jump there directly.
12497   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12498   if (Clusters.empty()) {
12499     assert(PeeledSwitchMBB == SwitchMBB);
12500     SwitchMBB->addSuccessor(DefaultMBB);
12501     if (DefaultMBB != NextBlock(SwitchMBB)) {
12502       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
12503                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
12504     }
12505     return;
12506   }
12507 
12508   SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(),
12509                      DAG.getBFI());
12510   SL->findBitTestClusters(Clusters, &SI);
12511 
12512   LLVM_DEBUG({
12513     dbgs() << "Case clusters: ";
12514     for (const CaseCluster &C : Clusters) {
12515       if (C.Kind == CC_JumpTable)
12516         dbgs() << "JT:";
12517       if (C.Kind == CC_BitTests)
12518         dbgs() << "BT:";
12519 
12520       C.Low->getValue().print(dbgs(), true);
12521       if (C.Low != C.High) {
12522         dbgs() << '-';
12523         C.High->getValue().print(dbgs(), true);
12524       }
12525       dbgs() << ' ';
12526     }
12527     dbgs() << '\n';
12528   });
12529 
12530   assert(!Clusters.empty());
12531   SwitchWorkList WorkList;
12532   CaseClusterIt First = Clusters.begin();
12533   CaseClusterIt Last = Clusters.end() - 1;
12534   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
12535   // Scale the branchprobability for DefaultMBB if the peel occurs and
12536   // DefaultMBB is not replaced.
12537   if (PeeledCaseProb != BranchProbability::getZero() &&
12538       DefaultMBB == FuncInfo.getMBB(SI.getDefaultDest()))
12539     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
12540   WorkList.push_back(
12541       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
12542 
12543   while (!WorkList.empty()) {
12544     SwitchWorkListItem W = WorkList.pop_back_val();
12545     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
12546 
12547     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None &&
12548         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
12549       // For optimized builds, lower large range as a balanced binary tree.
12550       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
12551       continue;
12552     }
12553 
12554     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
12555   }
12556 }
12557 
12558 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
12559   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12560   auto DL = getCurSDLoc();
12561   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12562   setValue(&I, DAG.getStepVector(DL, ResultVT));
12563 }
12564 
12565 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
12566   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12567   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12568 
12569   SDLoc DL = getCurSDLoc();
12570   SDValue V = getValue(I.getOperand(0));
12571   assert(VT == V.getValueType() && "Malformed vector.reverse!");
12572 
12573   if (VT.isScalableVector()) {
12574     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
12575     return;
12576   }
12577 
12578   // Use VECTOR_SHUFFLE for the fixed-length vector
12579   // to maintain existing behavior.
12580   SmallVector<int, 8> Mask;
12581   unsigned NumElts = VT.getVectorMinNumElements();
12582   for (unsigned i = 0; i != NumElts; ++i)
12583     Mask.push_back(NumElts - 1 - i);
12584 
12585   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
12586 }
12587 
12588 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) {
12589   auto DL = getCurSDLoc();
12590   SDValue InVec = getValue(I.getOperand(0));
12591   EVT OutVT =
12592       InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
12593 
12594   unsigned OutNumElts = OutVT.getVectorMinNumElements();
12595 
12596   // ISD Node needs the input vectors split into two equal parts
12597   SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
12598                            DAG.getVectorIdxConstant(0, DL));
12599   SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
12600                            DAG.getVectorIdxConstant(OutNumElts, DL));
12601 
12602   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
12603   // legalisation and combines.
12604   if (OutVT.isFixedLengthVector()) {
12605     SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
12606                                         createStrideMask(0, 2, OutNumElts));
12607     SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
12608                                        createStrideMask(1, 2, OutNumElts));
12609     SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc());
12610     setValue(&I, Res);
12611     return;
12612   }
12613 
12614   SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL,
12615                             DAG.getVTList(OutVT, OutVT), Lo, Hi);
12616   setValue(&I, Res);
12617 }
12618 
12619 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) {
12620   auto DL = getCurSDLoc();
12621   EVT InVT = getValue(I.getOperand(0)).getValueType();
12622   SDValue InVec0 = getValue(I.getOperand(0));
12623   SDValue InVec1 = getValue(I.getOperand(1));
12624   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12625   EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12626 
12627   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
12628   // legalisation and combines.
12629   if (OutVT.isFixedLengthVector()) {
12630     unsigned NumElts = InVT.getVectorMinNumElements();
12631     SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1);
12632     setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT),
12633                                       createInterleaveMask(NumElts, 2)));
12634     return;
12635   }
12636 
12637   SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL,
12638                             DAG.getVTList(InVT, InVT), InVec0, InVec1);
12639   Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0),
12640                     Res.getValue(1));
12641   setValue(&I, Res);
12642 }
12643 
12644 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
12645   SmallVector<EVT, 4> ValueVTs;
12646   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
12647                   ValueVTs);
12648   unsigned NumValues = ValueVTs.size();
12649   if (NumValues == 0) return;
12650 
12651   SmallVector<SDValue, 4> Values(NumValues);
12652   SDValue Op = getValue(I.getOperand(0));
12653 
12654   for (unsigned i = 0; i != NumValues; ++i)
12655     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
12656                             SDValue(Op.getNode(), Op.getResNo() + i));
12657 
12658   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12659                            DAG.getVTList(ValueVTs), Values));
12660 }
12661 
12662 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
12663   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12664   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12665 
12666   SDLoc DL = getCurSDLoc();
12667   SDValue V1 = getValue(I.getOperand(0));
12668   SDValue V2 = getValue(I.getOperand(1));
12669   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
12670 
12671   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
12672   if (VT.isScalableVector()) {
12673     setValue(
12674         &I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
12675                         DAG.getSignedConstant(
12676                             Imm, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))));
12677     return;
12678   }
12679 
12680   unsigned NumElts = VT.getVectorNumElements();
12681 
12682   uint64_t Idx = (NumElts + Imm) % NumElts;
12683 
12684   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
12685   SmallVector<int, 8> Mask;
12686   for (unsigned i = 0; i < NumElts; ++i)
12687     Mask.push_back(Idx + i);
12688   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
12689 }
12690 
12691 // Consider the following MIR after SelectionDAG, which produces output in
12692 // phyregs in the first case or virtregs in the second case.
12693 //
12694 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx
12695 // %5:gr32 = COPY $ebx
12696 // %6:gr32 = COPY $edx
12697 // %1:gr32 = COPY %6:gr32
12698 // %0:gr32 = COPY %5:gr32
12699 //
12700 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32
12701 // %1:gr32 = COPY %6:gr32
12702 // %0:gr32 = COPY %5:gr32
12703 //
12704 // Given %0, we'd like to return $ebx in the first case and %5 in the second.
12705 // Given %1, we'd like to return $edx in the first case and %6 in the second.
12706 //
12707 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap
12708 // to a single virtreg (such as %0). The remaining outputs monotonically
12709 // increase in virtreg number from there. If a callbr has no outputs, then it
12710 // should not have a corresponding callbr landingpad; in fact, the callbr
12711 // landingpad would not even be able to refer to such a callbr.
12712 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) {
12713   MachineInstr *MI = MRI.def_begin(Reg)->getParent();
12714   // There is definitely at least one copy.
12715   assert(MI->getOpcode() == TargetOpcode::COPY &&
12716          "start of copy chain MUST be COPY");
12717   Reg = MI->getOperand(1).getReg();
12718   MI = MRI.def_begin(Reg)->getParent();
12719   // There may be an optional second copy.
12720   if (MI->getOpcode() == TargetOpcode::COPY) {
12721     assert(Reg.isVirtual() && "expected COPY of virtual register");
12722     Reg = MI->getOperand(1).getReg();
12723     assert(Reg.isPhysical() && "expected COPY of physical register");
12724     MI = MRI.def_begin(Reg)->getParent();
12725   }
12726   // The start of the chain must be an INLINEASM_BR.
12727   assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR &&
12728          "end of copy chain MUST be INLINEASM_BR");
12729   return Reg;
12730 }
12731 
12732 // We must do this walk rather than the simpler
12733 //   setValue(&I, getCopyFromRegs(CBR, CBR->getType()));
12734 // otherwise we will end up with copies of virtregs only valid along direct
12735 // edges.
12736 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) {
12737   SmallVector<EVT, 8> ResultVTs;
12738   SmallVector<SDValue, 8> ResultValues;
12739   const auto *CBR =
12740       cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator());
12741 
12742   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12743   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
12744   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
12745 
12746   unsigned InitialDef = FuncInfo.ValueMap[CBR];
12747   SDValue Chain = DAG.getRoot();
12748 
12749   // Re-parse the asm constraints string.
12750   TargetLowering::AsmOperandInfoVector TargetConstraints =
12751       TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR);
12752   for (auto &T : TargetConstraints) {
12753     SDISelAsmOperandInfo OpInfo(T);
12754     if (OpInfo.Type != InlineAsm::isOutput)
12755       continue;
12756 
12757     // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the
12758     // individual constraint.
12759     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
12760 
12761     switch (OpInfo.ConstraintType) {
12762     case TargetLowering::C_Register:
12763     case TargetLowering::C_RegisterClass: {
12764       // Fill in OpInfo.AssignedRegs.Regs.
12765       getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo);
12766 
12767       // getRegistersForValue may produce 1 to many registers based on whether
12768       // the OpInfo.ConstraintVT is legal on the target or not.
12769       for (Register &Reg : OpInfo.AssignedRegs.Regs) {
12770         Register OriginalDef = FollowCopyChain(MRI, InitialDef++);
12771         if (Register::isPhysicalRegister(OriginalDef))
12772           FuncInfo.MBB->addLiveIn(OriginalDef);
12773         // Update the assigned registers to use the original defs.
12774         Reg = OriginalDef;
12775       }
12776 
12777       SDValue V = OpInfo.AssignedRegs.getCopyFromRegs(
12778           DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR);
12779       ResultValues.push_back(V);
12780       ResultVTs.push_back(OpInfo.ConstraintVT);
12781       break;
12782     }
12783     case TargetLowering::C_Other: {
12784       SDValue Flag;
12785       SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
12786                                                   OpInfo, DAG);
12787       ++InitialDef;
12788       ResultValues.push_back(V);
12789       ResultVTs.push_back(OpInfo.ConstraintVT);
12790       break;
12791     }
12792     default:
12793       break;
12794     }
12795   }
12796   SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12797                           DAG.getVTList(ResultVTs), ResultValues);
12798   setValue(&I, V);
12799 }
12800