xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 4048c64306e23b622443bbe7293057a9b07a13bb)
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     VectorType *VecTy = cast<VectorType>(V->getType());
1900 
1901     // Now that we know the number and type of the elements, get that number of
1902     // elements into the Ops array based on what kind of constant it is.
1903     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1904       SmallVector<SDValue, 16> Ops;
1905       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1906       for (unsigned i = 0; i != NumElements; ++i)
1907         Ops.push_back(getValue(CV->getOperand(i)));
1908 
1909       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1910     }
1911 
1912     if (isa<ConstantAggregateZero>(C)) {
1913       EVT EltVT =
1914           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1915 
1916       SDValue Op;
1917       if (EltVT.isFloatingPoint())
1918         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1919       else
1920         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1921 
1922       return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op);
1923     }
1924 
1925     llvm_unreachable("Unknown vector constant");
1926   }
1927 
1928   // If this is a static alloca, generate it as the frameindex instead of
1929   // computation.
1930   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1931     DenseMap<const AllocaInst*, int>::iterator SI =
1932       FuncInfo.StaticAllocaMap.find(AI);
1933     if (SI != FuncInfo.StaticAllocaMap.end())
1934       return DAG.getFrameIndex(
1935           SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType()));
1936   }
1937 
1938   // If this is an instruction which fast-isel has deferred, select it now.
1939   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1940     Register InReg = FuncInfo.InitializeRegForValue(Inst);
1941 
1942     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1943                      Inst->getType(), std::nullopt);
1944     SDValue Chain = DAG.getEntryNode();
1945     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1946   }
1947 
1948   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V))
1949     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1950 
1951   if (const auto *BB = dyn_cast<BasicBlock>(V))
1952     return DAG.getBasicBlock(FuncInfo.getMBB(BB));
1953 
1954   llvm_unreachable("Can't get register for value!");
1955 }
1956 
1957 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1958   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1959   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1960   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1961   bool IsSEH = isAsynchronousEHPersonality(Pers);
1962   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1963   if (!IsSEH)
1964     CatchPadMBB->setIsEHScopeEntry();
1965   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1966   if (IsMSVCCXX || IsCoreCLR)
1967     CatchPadMBB->setIsEHFuncletEntry();
1968 }
1969 
1970 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1971   // Update machine-CFG edge.
1972   MachineBasicBlock *TargetMBB = FuncInfo.getMBB(I.getSuccessor());
1973   FuncInfo.MBB->addSuccessor(TargetMBB);
1974   TargetMBB->setIsEHCatchretTarget(true);
1975   DAG.getMachineFunction().setHasEHCatchret(true);
1976 
1977   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1978   bool IsSEH = isAsynchronousEHPersonality(Pers);
1979   if (IsSEH) {
1980     // If this is not a fall-through branch or optimizations are switched off,
1981     // emit the branch.
1982     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1983         TM.getOptLevel() == CodeGenOptLevel::None)
1984       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1985                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1986     return;
1987   }
1988 
1989   // Figure out the funclet membership for the catchret's successor.
1990   // This will be used by the FuncletLayout pass to determine how to order the
1991   // BB's.
1992   // A 'catchret' returns to the outer scope's color.
1993   Value *ParentPad = I.getCatchSwitchParentPad();
1994   const BasicBlock *SuccessorColor;
1995   if (isa<ConstantTokenNone>(ParentPad))
1996     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1997   else
1998     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1999   assert(SuccessorColor && "No parent funclet for catchret!");
2000   MachineBasicBlock *SuccessorColorMBB = FuncInfo.getMBB(SuccessorColor);
2001   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
2002 
2003   // Create the terminator node.
2004   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
2005                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
2006                             DAG.getBasicBlock(SuccessorColorMBB));
2007   DAG.setRoot(Ret);
2008 }
2009 
2010 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
2011   // Don't emit any special code for the cleanuppad instruction. It just marks
2012   // the start of an EH scope/funclet.
2013   FuncInfo.MBB->setIsEHScopeEntry();
2014   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
2015   if (Pers != EHPersonality::Wasm_CXX) {
2016     FuncInfo.MBB->setIsEHFuncletEntry();
2017     FuncInfo.MBB->setIsCleanupFuncletEntry();
2018   }
2019 }
2020 
2021 // In wasm EH, even though a catchpad may not catch an exception if a tag does
2022 // not match, it is OK to add only the first unwind destination catchpad to the
2023 // successors, because there will be at least one invoke instruction within the
2024 // catch scope that points to the next unwind destination, if one exists, so
2025 // CFGSort cannot mess up with BB sorting order.
2026 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
2027 // call within them, and catchpads only consisting of 'catch (...)' have a
2028 // '__cxa_end_catch' call within them, both of which generate invokes in case
2029 // the next unwind destination exists, i.e., the next unwind destination is not
2030 // the caller.)
2031 //
2032 // Having at most one EH pad successor is also simpler and helps later
2033 // transformations.
2034 //
2035 // For example,
2036 // current:
2037 //   invoke void @foo to ... unwind label %catch.dispatch
2038 // catch.dispatch:
2039 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
2040 // catch.start:
2041 //   ...
2042 //   ... in this BB or some other child BB dominated by this BB there will be an
2043 //   invoke that points to 'next' BB as an unwind destination
2044 //
2045 // next: ; We don't need to add this to 'current' BB's successor
2046 //   ...
2047 static void findWasmUnwindDestinations(
2048     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2049     BranchProbability Prob,
2050     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2051         &UnwindDests) {
2052   while (EHPadBB) {
2053     const Instruction *Pad = EHPadBB->getFirstNonPHI();
2054     if (isa<CleanupPadInst>(Pad)) {
2055       // Stop on cleanup pads.
2056       UnwindDests.emplace_back(FuncInfo.getMBB(EHPadBB), Prob);
2057       UnwindDests.back().first->setIsEHScopeEntry();
2058       break;
2059     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
2060       // Add the catchpad handlers to the possible destinations. We don't
2061       // continue to the unwind destination of the catchswitch for wasm.
2062       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2063         UnwindDests.emplace_back(FuncInfo.getMBB(CatchPadBB), Prob);
2064         UnwindDests.back().first->setIsEHScopeEntry();
2065       }
2066       break;
2067     } else {
2068       continue;
2069     }
2070   }
2071 }
2072 
2073 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
2074 /// many places it could ultimately go. In the IR, we have a single unwind
2075 /// destination, but in the machine CFG, we enumerate all the possible blocks.
2076 /// This function skips over imaginary basic blocks that hold catchswitch
2077 /// instructions, and finds all the "real" machine
2078 /// basic block destinations. As those destinations may not be successors of
2079 /// EHPadBB, here we also calculate the edge probability to those destinations.
2080 /// The passed-in Prob is the edge probability to EHPadBB.
2081 static void findUnwindDestinations(
2082     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2083     BranchProbability Prob,
2084     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2085         &UnwindDests) {
2086   EHPersonality Personality =
2087     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
2088   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
2089   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
2090   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
2091   bool IsSEH = isAsynchronousEHPersonality(Personality);
2092 
2093   if (IsWasmCXX) {
2094     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
2095     assert(UnwindDests.size() <= 1 &&
2096            "There should be at most one unwind destination for wasm");
2097     return;
2098   }
2099 
2100   while (EHPadBB) {
2101     const Instruction *Pad = EHPadBB->getFirstNonPHI();
2102     BasicBlock *NewEHPadBB = nullptr;
2103     if (isa<LandingPadInst>(Pad)) {
2104       // Stop on landingpads. They are not funclets.
2105       UnwindDests.emplace_back(FuncInfo.getMBB(EHPadBB), Prob);
2106       break;
2107     } else if (isa<CleanupPadInst>(Pad)) {
2108       // Stop on cleanup pads. Cleanups are always funclet entries for all known
2109       // personalities.
2110       UnwindDests.emplace_back(FuncInfo.getMBB(EHPadBB), Prob);
2111       UnwindDests.back().first->setIsEHScopeEntry();
2112       UnwindDests.back().first->setIsEHFuncletEntry();
2113       break;
2114     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
2115       // Add the catchpad handlers to the possible destinations.
2116       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2117         UnwindDests.emplace_back(FuncInfo.getMBB(CatchPadBB), Prob);
2118         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
2119         if (IsMSVCCXX || IsCoreCLR)
2120           UnwindDests.back().first->setIsEHFuncletEntry();
2121         if (!IsSEH)
2122           UnwindDests.back().first->setIsEHScopeEntry();
2123       }
2124       NewEHPadBB = CatchSwitch->getUnwindDest();
2125     } else {
2126       continue;
2127     }
2128 
2129     BranchProbabilityInfo *BPI = FuncInfo.BPI;
2130     if (BPI && NewEHPadBB)
2131       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
2132     EHPadBB = NewEHPadBB;
2133   }
2134 }
2135 
2136 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
2137   // Update successor info.
2138   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2139   auto UnwindDest = I.getUnwindDest();
2140   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2141   BranchProbability UnwindDestProb =
2142       (BPI && UnwindDest)
2143           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
2144           : BranchProbability::getZero();
2145   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
2146   for (auto &UnwindDest : UnwindDests) {
2147     UnwindDest.first->setIsEHPad();
2148     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
2149   }
2150   FuncInfo.MBB->normalizeSuccProbs();
2151 
2152   // Create the terminator node.
2153   MachineBasicBlock *CleanupPadMBB =
2154       FuncInfo.getMBB(I.getCleanupPad()->getParent());
2155   SDValue Ret = DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other,
2156                             getControlRoot(), DAG.getBasicBlock(CleanupPadMBB));
2157   DAG.setRoot(Ret);
2158 }
2159 
2160 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
2161   report_fatal_error("visitCatchSwitch not yet implemented!");
2162 }
2163 
2164 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
2165   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2166   auto &DL = DAG.getDataLayout();
2167   SDValue Chain = getControlRoot();
2168   SmallVector<ISD::OutputArg, 8> Outs;
2169   SmallVector<SDValue, 8> OutVals;
2170 
2171   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
2172   // lower
2173   //
2174   //   %val = call <ty> @llvm.experimental.deoptimize()
2175   //   ret <ty> %val
2176   //
2177   // differently.
2178   if (I.getParent()->getTerminatingDeoptimizeCall()) {
2179     LowerDeoptimizingReturn();
2180     return;
2181   }
2182 
2183   if (!FuncInfo.CanLowerReturn) {
2184     Register DemoteReg = FuncInfo.DemoteRegister;
2185     const Function *F = I.getParent()->getParent();
2186 
2187     // Emit a store of the return value through the virtual register.
2188     // Leave Outs empty so that LowerReturn won't try to load return
2189     // registers the usual way.
2190     SmallVector<EVT, 1> PtrValueVTs;
2191     ComputeValueVTs(TLI, DL,
2192                     PointerType::get(F->getContext(),
2193                                      DAG.getDataLayout().getAllocaAddrSpace()),
2194                     PtrValueVTs);
2195 
2196     SDValue RetPtr =
2197         DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]);
2198     SDValue RetOp = getValue(I.getOperand(0));
2199 
2200     SmallVector<EVT, 4> ValueVTs, MemVTs;
2201     SmallVector<uint64_t, 4> Offsets;
2202     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
2203                     &Offsets, 0);
2204     unsigned NumValues = ValueVTs.size();
2205 
2206     SmallVector<SDValue, 4> Chains(NumValues);
2207     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
2208     for (unsigned i = 0; i != NumValues; ++i) {
2209       // An aggregate return value cannot wrap around the address space, so
2210       // offsets to its parts don't wrap either.
2211       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
2212                                            TypeSize::getFixed(Offsets[i]));
2213 
2214       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
2215       if (MemVTs[i] != ValueVTs[i])
2216         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
2217       Chains[i] = DAG.getStore(
2218           Chain, getCurSDLoc(), Val,
2219           // FIXME: better loc info would be nice.
2220           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
2221           commonAlignment(BaseAlign, Offsets[i]));
2222     }
2223 
2224     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
2225                         MVT::Other, Chains);
2226   } else if (I.getNumOperands() != 0) {
2227     SmallVector<EVT, 4> ValueVTs;
2228     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
2229     unsigned NumValues = ValueVTs.size();
2230     if (NumValues) {
2231       SDValue RetOp = getValue(I.getOperand(0));
2232 
2233       const Function *F = I.getParent()->getParent();
2234 
2235       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
2236           I.getOperand(0)->getType(), F->getCallingConv(),
2237           /*IsVarArg*/ false, DL);
2238 
2239       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
2240       if (F->getAttributes().hasRetAttr(Attribute::SExt))
2241         ExtendKind = ISD::SIGN_EXTEND;
2242       else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
2243         ExtendKind = ISD::ZERO_EXTEND;
2244 
2245       LLVMContext &Context = F->getContext();
2246       bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
2247 
2248       for (unsigned j = 0; j != NumValues; ++j) {
2249         EVT VT = ValueVTs[j];
2250 
2251         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2252           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
2253 
2254         CallingConv::ID CC = F->getCallingConv();
2255 
2256         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
2257         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2258         SmallVector<SDValue, 4> Parts(NumParts);
2259         getCopyToParts(DAG, getCurSDLoc(),
2260                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2261                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
2262 
2263         // 'inreg' on function refers to return value
2264         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2265         if (RetInReg)
2266           Flags.setInReg();
2267 
2268         if (I.getOperand(0)->getType()->isPointerTy()) {
2269           Flags.setPointer();
2270           Flags.setPointerAddrSpace(
2271               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2272         }
2273 
2274         if (NeedsRegBlock) {
2275           Flags.setInConsecutiveRegs();
2276           if (j == NumValues - 1)
2277             Flags.setInConsecutiveRegsLast();
2278         }
2279 
2280         // Propagate extension type if any
2281         if (ExtendKind == ISD::SIGN_EXTEND)
2282           Flags.setSExt();
2283         else if (ExtendKind == ISD::ZERO_EXTEND)
2284           Flags.setZExt();
2285         else if (F->getAttributes().hasRetAttr(Attribute::NoExt))
2286           Flags.setNoExt();
2287 
2288         for (unsigned i = 0; i < NumParts; ++i) {
2289           Outs.push_back(ISD::OutputArg(Flags,
2290                                         Parts[i].getValueType().getSimpleVT(),
2291                                         VT, /*isfixed=*/true, 0, 0));
2292           OutVals.push_back(Parts[i]);
2293         }
2294       }
2295     }
2296   }
2297 
2298   // Push in swifterror virtual register as the last element of Outs. This makes
2299   // sure swifterror virtual register will be returned in the swifterror
2300   // physical register.
2301   const Function *F = I.getParent()->getParent();
2302   if (TLI.supportSwiftError() &&
2303       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2304     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2305     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2306     Flags.setSwiftError();
2307     Outs.push_back(ISD::OutputArg(
2308         Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
2309         /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
2310     // Create SDNode for the swifterror virtual register.
2311     OutVals.push_back(
2312         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2313                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2314                         EVT(TLI.getPointerTy(DL))));
2315   }
2316 
2317   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2318   CallingConv::ID CallConv =
2319     DAG.getMachineFunction().getFunction().getCallingConv();
2320   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2321       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2322 
2323   // Verify that the target's LowerReturn behaved as expected.
2324   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2325          "LowerReturn didn't return a valid chain!");
2326 
2327   // Update the DAG with the new chain value resulting from return lowering.
2328   DAG.setRoot(Chain);
2329 }
2330 
2331 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2332 /// created for it, emit nodes to copy the value into the virtual
2333 /// registers.
2334 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2335   // Skip empty types
2336   if (V->getType()->isEmptyTy())
2337     return;
2338 
2339   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2340   if (VMI != FuncInfo.ValueMap.end()) {
2341     assert((!V->use_empty() || isa<CallBrInst>(V)) &&
2342            "Unused value assigned virtual registers!");
2343     CopyValueToVirtualRegister(V, VMI->second);
2344   }
2345 }
2346 
2347 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2348 /// the current basic block, add it to ValueMap now so that we'll get a
2349 /// CopyTo/FromReg.
2350 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2351   // No need to export constants.
2352   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2353 
2354   // Already exported?
2355   if (FuncInfo.isExportedInst(V)) return;
2356 
2357   Register Reg = FuncInfo.InitializeRegForValue(V);
2358   CopyValueToVirtualRegister(V, Reg);
2359 }
2360 
2361 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2362                                                      const BasicBlock *FromBB) {
2363   // The operands of the setcc have to be in this block.  We don't know
2364   // how to export them from some other block.
2365   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2366     // Can export from current BB.
2367     if (VI->getParent() == FromBB)
2368       return true;
2369 
2370     // Is already exported, noop.
2371     return FuncInfo.isExportedInst(V);
2372   }
2373 
2374   // If this is an argument, we can export it if the BB is the entry block or
2375   // if it is already exported.
2376   if (isa<Argument>(V)) {
2377     if (FromBB->isEntryBlock())
2378       return true;
2379 
2380     // Otherwise, can only export this if it is already exported.
2381     return FuncInfo.isExportedInst(V);
2382   }
2383 
2384   // Otherwise, constants can always be exported.
2385   return true;
2386 }
2387 
2388 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2389 BranchProbability
2390 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2391                                         const MachineBasicBlock *Dst) const {
2392   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2393   const BasicBlock *SrcBB = Src->getBasicBlock();
2394   const BasicBlock *DstBB = Dst->getBasicBlock();
2395   if (!BPI) {
2396     // If BPI is not available, set the default probability as 1 / N, where N is
2397     // the number of successors.
2398     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2399     return BranchProbability(1, SuccSize);
2400   }
2401   return BPI->getEdgeProbability(SrcBB, DstBB);
2402 }
2403 
2404 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2405                                                MachineBasicBlock *Dst,
2406                                                BranchProbability Prob) {
2407   if (!FuncInfo.BPI)
2408     Src->addSuccessorWithoutProb(Dst);
2409   else {
2410     if (Prob.isUnknown())
2411       Prob = getEdgeProbability(Src, Dst);
2412     Src->addSuccessor(Dst, Prob);
2413   }
2414 }
2415 
2416 static bool InBlock(const Value *V, const BasicBlock *BB) {
2417   if (const Instruction *I = dyn_cast<Instruction>(V))
2418     return I->getParent() == BB;
2419   return true;
2420 }
2421 
2422 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2423 /// This function emits a branch and is used at the leaves of an OR or an
2424 /// AND operator tree.
2425 void
2426 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2427                                                   MachineBasicBlock *TBB,
2428                                                   MachineBasicBlock *FBB,
2429                                                   MachineBasicBlock *CurBB,
2430                                                   MachineBasicBlock *SwitchBB,
2431                                                   BranchProbability TProb,
2432                                                   BranchProbability FProb,
2433                                                   bool InvertCond) {
2434   const BasicBlock *BB = CurBB->getBasicBlock();
2435 
2436   // If the leaf of the tree is a comparison, merge the condition into
2437   // the caseblock.
2438   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2439     // The operands of the cmp have to be in this block.  We don't know
2440     // how to export them from some other block.  If this is the first block
2441     // of the sequence, no exporting is needed.
2442     if (CurBB == SwitchBB ||
2443         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2444          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2445       ISD::CondCode Condition;
2446       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2447         ICmpInst::Predicate Pred =
2448             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2449         Condition = getICmpCondCode(Pred);
2450       } else {
2451         const FCmpInst *FC = cast<FCmpInst>(Cond);
2452         FCmpInst::Predicate Pred =
2453             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2454         Condition = getFCmpCondCode(Pred);
2455         if (TM.Options.NoNaNsFPMath)
2456           Condition = getFCmpCodeWithoutNaN(Condition);
2457       }
2458 
2459       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2460                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2461       SL->SwitchCases.push_back(CB);
2462       return;
2463     }
2464   }
2465 
2466   // Create a CaseBlock record representing this branch.
2467   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2468   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2469                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2470   SL->SwitchCases.push_back(CB);
2471 }
2472 
2473 // Collect dependencies on V recursively. This is used for the cost analysis in
2474 // `shouldKeepJumpConditionsTogether`.
2475 static bool collectInstructionDeps(
2476     SmallMapVector<const Instruction *, bool, 8> *Deps, const Value *V,
2477     SmallMapVector<const Instruction *, bool, 8> *Necessary = nullptr,
2478     unsigned Depth = 0) {
2479   // Return false if we have an incomplete count.
2480   if (Depth >= SelectionDAG::MaxRecursionDepth)
2481     return false;
2482 
2483   auto *I = dyn_cast<Instruction>(V);
2484   if (I == nullptr)
2485     return true;
2486 
2487   if (Necessary != nullptr) {
2488     // This instruction is necessary for the other side of the condition so
2489     // don't count it.
2490     if (Necessary->contains(I))
2491       return true;
2492   }
2493 
2494   // Already added this dep.
2495   if (!Deps->try_emplace(I, false).second)
2496     return true;
2497 
2498   for (unsigned OpIdx = 0, E = I->getNumOperands(); OpIdx < E; ++OpIdx)
2499     if (!collectInstructionDeps(Deps, I->getOperand(OpIdx), Necessary,
2500                                 Depth + 1))
2501       return false;
2502   return true;
2503 }
2504 
2505 bool SelectionDAGBuilder::shouldKeepJumpConditionsTogether(
2506     const FunctionLoweringInfo &FuncInfo, const BranchInst &I,
2507     Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs,
2508     TargetLoweringBase::CondMergingParams Params) const {
2509   if (I.getNumSuccessors() != 2)
2510     return false;
2511 
2512   if (!I.isConditional())
2513     return false;
2514 
2515   if (Params.BaseCost < 0)
2516     return false;
2517 
2518   // Baseline cost.
2519   InstructionCost CostThresh = Params.BaseCost;
2520 
2521   BranchProbabilityInfo *BPI = nullptr;
2522   if (Params.LikelyBias || Params.UnlikelyBias)
2523     BPI = FuncInfo.BPI;
2524   if (BPI != nullptr) {
2525     // See if we are either likely to get an early out or compute both lhs/rhs
2526     // of the condition.
2527     BasicBlock *IfFalse = I.getSuccessor(0);
2528     BasicBlock *IfTrue = I.getSuccessor(1);
2529 
2530     std::optional<bool> Likely;
2531     if (BPI->isEdgeHot(I.getParent(), IfTrue))
2532       Likely = true;
2533     else if (BPI->isEdgeHot(I.getParent(), IfFalse))
2534       Likely = false;
2535 
2536     if (Likely) {
2537       if (Opc == (*Likely ? Instruction::And : Instruction::Or))
2538         // Its likely we will have to compute both lhs and rhs of condition
2539         CostThresh += Params.LikelyBias;
2540       else {
2541         if (Params.UnlikelyBias < 0)
2542           return false;
2543         // Its likely we will get an early out.
2544         CostThresh -= Params.UnlikelyBias;
2545       }
2546     }
2547   }
2548 
2549   if (CostThresh <= 0)
2550     return false;
2551 
2552   // Collect "all" instructions that lhs condition is dependent on.
2553   // Use map for stable iteration (to avoid non-determanism of iteration of
2554   // SmallPtrSet). The `bool` value is just a dummy.
2555   SmallMapVector<const Instruction *, bool, 8> LhsDeps, RhsDeps;
2556   collectInstructionDeps(&LhsDeps, Lhs);
2557   // Collect "all" instructions that rhs condition is dependent on AND are
2558   // dependencies of lhs. This gives us an estimate on which instructions we
2559   // stand to save by splitting the condition.
2560   if (!collectInstructionDeps(&RhsDeps, Rhs, &LhsDeps))
2561     return false;
2562   // Add the compare instruction itself unless its a dependency on the LHS.
2563   if (const auto *RhsI = dyn_cast<Instruction>(Rhs))
2564     if (!LhsDeps.contains(RhsI))
2565       RhsDeps.try_emplace(RhsI, false);
2566 
2567   const auto &TLI = DAG.getTargetLoweringInfo();
2568   const auto &TTI =
2569       TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction());
2570 
2571   InstructionCost CostOfIncluding = 0;
2572   // See if this instruction will need to computed independently of whether RHS
2573   // is.
2574   Value *BrCond = I.getCondition();
2575   auto ShouldCountInsn = [&RhsDeps, &BrCond](const Instruction *Ins) {
2576     for (const auto *U : Ins->users()) {
2577       // If user is independent of RHS calculation we don't need to count it.
2578       if (auto *UIns = dyn_cast<Instruction>(U))
2579         if (UIns != BrCond && !RhsDeps.contains(UIns))
2580           return false;
2581     }
2582     return true;
2583   };
2584 
2585   // Prune instructions from RHS Deps that are dependencies of unrelated
2586   // instructions. The value (SelectionDAG::MaxRecursionDepth) is fairly
2587   // arbitrary and just meant to cap the how much time we spend in the pruning
2588   // loop. Its highly unlikely to come into affect.
2589   const unsigned MaxPruneIters = SelectionDAG::MaxRecursionDepth;
2590   // Stop after a certain point. No incorrectness from including too many
2591   // instructions.
2592   for (unsigned PruneIters = 0; PruneIters < MaxPruneIters; ++PruneIters) {
2593     const Instruction *ToDrop = nullptr;
2594     for (const auto &InsPair : RhsDeps) {
2595       if (!ShouldCountInsn(InsPair.first)) {
2596         ToDrop = InsPair.first;
2597         break;
2598       }
2599     }
2600     if (ToDrop == nullptr)
2601       break;
2602     RhsDeps.erase(ToDrop);
2603   }
2604 
2605   for (const auto &InsPair : RhsDeps) {
2606     // Finally accumulate latency that we can only attribute to computing the
2607     // RHS condition. Use latency because we are essentially trying to calculate
2608     // the cost of the dependency chain.
2609     // Possible TODO: We could try to estimate ILP and make this more precise.
2610     CostOfIncluding +=
2611         TTI.getInstructionCost(InsPair.first, TargetTransformInfo::TCK_Latency);
2612 
2613     if (CostOfIncluding > CostThresh)
2614       return false;
2615   }
2616   return true;
2617 }
2618 
2619 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2620                                                MachineBasicBlock *TBB,
2621                                                MachineBasicBlock *FBB,
2622                                                MachineBasicBlock *CurBB,
2623                                                MachineBasicBlock *SwitchBB,
2624                                                Instruction::BinaryOps Opc,
2625                                                BranchProbability TProb,
2626                                                BranchProbability FProb,
2627                                                bool InvertCond) {
2628   // Skip over not part of the tree and remember to invert op and operands at
2629   // next level.
2630   Value *NotCond;
2631   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2632       InBlock(NotCond, CurBB->getBasicBlock())) {
2633     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2634                          !InvertCond);
2635     return;
2636   }
2637 
2638   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2639   const Value *BOpOp0, *BOpOp1;
2640   // Compute the effective opcode for Cond, taking into account whether it needs
2641   // to be inverted, e.g.
2642   //   and (not (or A, B)), C
2643   // gets lowered as
2644   //   and (and (not A, not B), C)
2645   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2646   if (BOp) {
2647     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2648                ? Instruction::And
2649                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2650                       ? Instruction::Or
2651                       : (Instruction::BinaryOps)0);
2652     if (InvertCond) {
2653       if (BOpc == Instruction::And)
2654         BOpc = Instruction::Or;
2655       else if (BOpc == Instruction::Or)
2656         BOpc = Instruction::And;
2657     }
2658   }
2659 
2660   // If this node is not part of the or/and tree, emit it as a branch.
2661   // Note that all nodes in the tree should have same opcode.
2662   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2663   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2664       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2665       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2666     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2667                                  TProb, FProb, InvertCond);
2668     return;
2669   }
2670 
2671   //  Create TmpBB after CurBB.
2672   MachineFunction::iterator BBI(CurBB);
2673   MachineFunction &MF = DAG.getMachineFunction();
2674   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2675   CurBB->getParent()->insert(++BBI, TmpBB);
2676 
2677   if (Opc == Instruction::Or) {
2678     // Codegen X | Y as:
2679     // BB1:
2680     //   jmp_if_X TBB
2681     //   jmp TmpBB
2682     // TmpBB:
2683     //   jmp_if_Y TBB
2684     //   jmp FBB
2685     //
2686 
2687     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2688     // The requirement is that
2689     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2690     //     = TrueProb for original BB.
2691     // Assuming the original probabilities are A and B, one choice is to set
2692     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2693     // A/(1+B) and 2B/(1+B). This choice assumes that
2694     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2695     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2696     // TmpBB, but the math is more complicated.
2697 
2698     auto NewTrueProb = TProb / 2;
2699     auto NewFalseProb = TProb / 2 + FProb;
2700     // Emit the LHS condition.
2701     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2702                          NewFalseProb, InvertCond);
2703 
2704     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2705     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2706     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2707     // Emit the RHS condition into TmpBB.
2708     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2709                          Probs[1], InvertCond);
2710   } else {
2711     assert(Opc == Instruction::And && "Unknown merge op!");
2712     // Codegen X & Y as:
2713     // BB1:
2714     //   jmp_if_X TmpBB
2715     //   jmp FBB
2716     // TmpBB:
2717     //   jmp_if_Y TBB
2718     //   jmp FBB
2719     //
2720     //  This requires creation of TmpBB after CurBB.
2721 
2722     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2723     // The requirement is that
2724     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2725     //     = FalseProb for original BB.
2726     // Assuming the original probabilities are A and B, one choice is to set
2727     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2728     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2729     // TrueProb for BB1 * FalseProb for TmpBB.
2730 
2731     auto NewTrueProb = TProb + FProb / 2;
2732     auto NewFalseProb = FProb / 2;
2733     // Emit the LHS condition.
2734     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2735                          NewFalseProb, InvertCond);
2736 
2737     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2738     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2739     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2740     // Emit the RHS condition into TmpBB.
2741     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2742                          Probs[1], InvertCond);
2743   }
2744 }
2745 
2746 /// If the set of cases should be emitted as a series of branches, return true.
2747 /// If we should emit this as a bunch of and/or'd together conditions, return
2748 /// false.
2749 bool
2750 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2751   if (Cases.size() != 2) return true;
2752 
2753   // If this is two comparisons of the same values or'd or and'd together, they
2754   // will get folded into a single comparison, so don't emit two blocks.
2755   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2756        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2757       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2758        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2759     return false;
2760   }
2761 
2762   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2763   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2764   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2765       Cases[0].CC == Cases[1].CC &&
2766       isa<Constant>(Cases[0].CmpRHS) &&
2767       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2768     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2769       return false;
2770     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2771       return false;
2772   }
2773 
2774   return true;
2775 }
2776 
2777 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2778   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2779 
2780   // Update machine-CFG edges.
2781   MachineBasicBlock *Succ0MBB = FuncInfo.getMBB(I.getSuccessor(0));
2782 
2783   if (I.isUnconditional()) {
2784     // Update machine-CFG edges.
2785     BrMBB->addSuccessor(Succ0MBB);
2786 
2787     // If this is not a fall-through branch or optimizations are switched off,
2788     // emit the branch.
2789     if (Succ0MBB != NextBlock(BrMBB) ||
2790         TM.getOptLevel() == CodeGenOptLevel::None) {
2791       auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
2792                             getControlRoot(), DAG.getBasicBlock(Succ0MBB));
2793       setValue(&I, Br);
2794       DAG.setRoot(Br);
2795     }
2796 
2797     return;
2798   }
2799 
2800   // If this condition is one of the special cases we handle, do special stuff
2801   // now.
2802   const Value *CondVal = I.getCondition();
2803   MachineBasicBlock *Succ1MBB = FuncInfo.getMBB(I.getSuccessor(1));
2804 
2805   // If this is a series of conditions that are or'd or and'd together, emit
2806   // this as a sequence of branches instead of setcc's with and/or operations.
2807   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2808   // unpredictable branches, and vector extracts because those jumps are likely
2809   // expensive for any target), this should improve performance.
2810   // For example, instead of something like:
2811   //     cmp A, B
2812   //     C = seteq
2813   //     cmp D, E
2814   //     F = setle
2815   //     or C, F
2816   //     jnz foo
2817   // Emit:
2818   //     cmp A, B
2819   //     je foo
2820   //     cmp D, E
2821   //     jle foo
2822   bool IsUnpredictable = I.hasMetadata(LLVMContext::MD_unpredictable);
2823   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2824   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2825       BOp->hasOneUse() && !IsUnpredictable) {
2826     Value *Vec;
2827     const Value *BOp0, *BOp1;
2828     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2829     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2830       Opcode = Instruction::And;
2831     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2832       Opcode = Instruction::Or;
2833 
2834     if (Opcode &&
2835         !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2836           match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value()))) &&
2837         !shouldKeepJumpConditionsTogether(
2838             FuncInfo, I, Opcode, BOp0, BOp1,
2839             DAG.getTargetLoweringInfo().getJumpConditionMergingParams(
2840                 Opcode, BOp0, BOp1))) {
2841       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2842                            getEdgeProbability(BrMBB, Succ0MBB),
2843                            getEdgeProbability(BrMBB, Succ1MBB),
2844                            /*InvertCond=*/false);
2845       // If the compares in later blocks need to use values not currently
2846       // exported from this block, export them now.  This block should always
2847       // be the first entry.
2848       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2849 
2850       // Allow some cases to be rejected.
2851       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2852         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2853           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2854           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2855         }
2856 
2857         // Emit the branch for this block.
2858         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2859         SL->SwitchCases.erase(SL->SwitchCases.begin());
2860         return;
2861       }
2862 
2863       // Okay, we decided not to do this, remove any inserted MBB's and clear
2864       // SwitchCases.
2865       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2866         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2867 
2868       SL->SwitchCases.clear();
2869     }
2870   }
2871 
2872   // Create a CaseBlock record representing this branch.
2873   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2874                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc(),
2875                BranchProbability::getUnknown(), BranchProbability::getUnknown(),
2876                IsUnpredictable);
2877 
2878   // Use visitSwitchCase to actually insert the fast branch sequence for this
2879   // cond branch.
2880   visitSwitchCase(CB, BrMBB);
2881 }
2882 
2883 /// visitSwitchCase - Emits the necessary code to represent a single node in
2884 /// the binary search tree resulting from lowering a switch instruction.
2885 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2886                                           MachineBasicBlock *SwitchBB) {
2887   SDValue Cond;
2888   SDValue CondLHS = getValue(CB.CmpLHS);
2889   SDLoc dl = CB.DL;
2890 
2891   if (CB.CC == ISD::SETTRUE) {
2892     // Branch or fall through to TrueBB.
2893     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2894     SwitchBB->normalizeSuccProbs();
2895     if (CB.TrueBB != NextBlock(SwitchBB)) {
2896       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2897                               DAG.getBasicBlock(CB.TrueBB)));
2898     }
2899     return;
2900   }
2901 
2902   auto &TLI = DAG.getTargetLoweringInfo();
2903   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2904 
2905   // Build the setcc now.
2906   if (!CB.CmpMHS) {
2907     // Fold "(X == true)" to X and "(X == false)" to !X to
2908     // handle common cases produced by branch lowering.
2909     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2910         CB.CC == ISD::SETEQ)
2911       Cond = CondLHS;
2912     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2913              CB.CC == ISD::SETEQ) {
2914       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2915       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2916     } else {
2917       SDValue CondRHS = getValue(CB.CmpRHS);
2918 
2919       // If a pointer's DAG type is larger than its memory type then the DAG
2920       // values are zero-extended. This breaks signed comparisons so truncate
2921       // back to the underlying type before doing the compare.
2922       if (CondLHS.getValueType() != MemVT) {
2923         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2924         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2925       }
2926       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2927     }
2928   } else {
2929     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2930 
2931     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2932     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2933 
2934     SDValue CmpOp = getValue(CB.CmpMHS);
2935     EVT VT = CmpOp.getValueType();
2936 
2937     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2938       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2939                           ISD::SETLE);
2940     } else {
2941       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2942                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2943       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2944                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2945     }
2946   }
2947 
2948   // Update successor info
2949   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2950   // TrueBB and FalseBB are always different unless the incoming IR is
2951   // degenerate. This only happens when running llc on weird IR.
2952   if (CB.TrueBB != CB.FalseBB)
2953     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2954   SwitchBB->normalizeSuccProbs();
2955 
2956   // If the lhs block is the next block, invert the condition so that we can
2957   // fall through to the lhs instead of the rhs block.
2958   if (CB.TrueBB == NextBlock(SwitchBB)) {
2959     std::swap(CB.TrueBB, CB.FalseBB);
2960     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2961     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2962   }
2963 
2964   SDNodeFlags Flags;
2965   Flags.setUnpredictable(CB.IsUnpredictable);
2966   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, MVT::Other, getControlRoot(),
2967                                Cond, DAG.getBasicBlock(CB.TrueBB), Flags);
2968 
2969   setValue(CurInst, BrCond);
2970 
2971   // Insert the false branch. Do this even if it's a fall through branch,
2972   // this makes it easier to do DAG optimizations which require inverting
2973   // the branch condition.
2974   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2975                        DAG.getBasicBlock(CB.FalseBB));
2976 
2977   DAG.setRoot(BrCond);
2978 }
2979 
2980 /// visitJumpTable - Emit JumpTable node in the current MBB
2981 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2982   // Emit the code for the jump table
2983   assert(JT.SL && "Should set SDLoc for SelectionDAG!");
2984   assert(JT.Reg && "Should lower JT Header first!");
2985   EVT PTy = DAG.getTargetLoweringInfo().getJumpTableRegTy(DAG.getDataLayout());
2986   SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy);
2987   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2988   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other,
2989                                     Index.getValue(1), Table, Index);
2990   DAG.setRoot(BrJumpTable);
2991 }
2992 
2993 /// visitJumpTableHeader - This function emits necessary code to produce index
2994 /// in the JumpTable from switch case.
2995 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2996                                                JumpTableHeader &JTH,
2997                                                MachineBasicBlock *SwitchBB) {
2998   assert(JT.SL && "Should set SDLoc for SelectionDAG!");
2999   const SDLoc &dl = *JT.SL;
3000 
3001   // Subtract the lowest switch case value from the value being switched on.
3002   SDValue SwitchOp = getValue(JTH.SValue);
3003   EVT VT = SwitchOp.getValueType();
3004   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
3005                             DAG.getConstant(JTH.First, dl, VT));
3006 
3007   // The SDNode we just created, which holds the value being switched on minus
3008   // the smallest case value, needs to be copied to a virtual register so it
3009   // can be used as an index into the jump table in a subsequent basic block.
3010   // This value may be smaller or larger than the target's pointer type, and
3011   // therefore require extension or truncating.
3012   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3013   SwitchOp =
3014       DAG.getZExtOrTrunc(Sub, dl, TLI.getJumpTableRegTy(DAG.getDataLayout()));
3015 
3016   Register JumpTableReg =
3017       FuncInfo.CreateReg(TLI.getJumpTableRegTy(DAG.getDataLayout()));
3018   SDValue CopyTo =
3019       DAG.getCopyToReg(getControlRoot(), dl, JumpTableReg, SwitchOp);
3020   JT.Reg = JumpTableReg;
3021 
3022   if (!JTH.FallthroughUnreachable) {
3023     // Emit the range check for the jump table, and branch to the default block
3024     // for the switch statement if the value being switched on exceeds the
3025     // largest case in the switch.
3026     SDValue CMP = DAG.getSetCC(
3027         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3028                                    Sub.getValueType()),
3029         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
3030 
3031     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
3032                                  MVT::Other, CopyTo, CMP,
3033                                  DAG.getBasicBlock(JT.Default));
3034 
3035     // Avoid emitting unnecessary branches to the next block.
3036     if (JT.MBB != NextBlock(SwitchBB))
3037       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
3038                            DAG.getBasicBlock(JT.MBB));
3039 
3040     DAG.setRoot(BrCond);
3041   } else {
3042     // Avoid emitting unnecessary branches to the next block.
3043     if (JT.MBB != NextBlock(SwitchBB))
3044       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
3045                               DAG.getBasicBlock(JT.MBB)));
3046     else
3047       DAG.setRoot(CopyTo);
3048   }
3049 }
3050 
3051 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
3052 /// variable if there exists one.
3053 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
3054                                  SDValue &Chain) {
3055   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3056   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
3057   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
3058   MachineFunction &MF = DAG.getMachineFunction();
3059   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
3060   MachineSDNode *Node =
3061       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
3062   if (Global) {
3063     MachinePointerInfo MPInfo(Global);
3064     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
3065                  MachineMemOperand::MODereferenceable;
3066     MachineMemOperand *MemRef = MF.getMachineMemOperand(
3067         MPInfo, Flags, LocationSize::precise(PtrTy.getSizeInBits() / 8),
3068         DAG.getEVTAlign(PtrTy));
3069     DAG.setNodeMemRefs(Node, {MemRef});
3070   }
3071   if (PtrTy != PtrMemTy)
3072     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
3073   return SDValue(Node, 0);
3074 }
3075 
3076 /// Codegen a new tail for a stack protector check ParentMBB which has had its
3077 /// tail spliced into a stack protector check success bb.
3078 ///
3079 /// For a high level explanation of how this fits into the stack protector
3080 /// generation see the comment on the declaration of class
3081 /// StackProtectorDescriptor.
3082 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
3083                                                   MachineBasicBlock *ParentBB) {
3084 
3085   // First create the loads to the guard/stack slot for the comparison.
3086   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3087   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
3088   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
3089 
3090   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3091   int FI = MFI.getStackProtectorIndex();
3092 
3093   SDValue Guard;
3094   SDLoc dl = getCurSDLoc();
3095   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
3096   const Module &M = *ParentBB->getParent()->getFunction().getParent();
3097   Align Align =
3098       DAG.getDataLayout().getPrefTypeAlign(PointerType::get(M.getContext(), 0));
3099 
3100   // Generate code to load the content of the guard slot.
3101   SDValue GuardVal = DAG.getLoad(
3102       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
3103       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
3104       MachineMemOperand::MOVolatile);
3105 
3106   if (TLI.useStackGuardXorFP())
3107     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
3108 
3109   // Retrieve guard check function, nullptr if instrumentation is inlined.
3110   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
3111     // The target provides a guard check function to validate the guard value.
3112     // Generate a call to that function with the content of the guard slot as
3113     // argument.
3114     FunctionType *FnTy = GuardCheckFn->getFunctionType();
3115     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3116 
3117     TargetLowering::ArgListTy Args;
3118     TargetLowering::ArgListEntry Entry;
3119     Entry.Node = GuardVal;
3120     Entry.Ty = FnTy->getParamType(0);
3121     if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
3122       Entry.IsInReg = true;
3123     Args.push_back(Entry);
3124 
3125     TargetLowering::CallLoweringInfo CLI(DAG);
3126     CLI.setDebugLoc(getCurSDLoc())
3127         .setChain(DAG.getEntryNode())
3128         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
3129                    getValue(GuardCheckFn), std::move(Args));
3130 
3131     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
3132     DAG.setRoot(Result.second);
3133     return;
3134   }
3135 
3136   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
3137   // Otherwise, emit a volatile load to retrieve the stack guard value.
3138   SDValue Chain = DAG.getEntryNode();
3139   if (TLI.useLoadStackGuardNode(M)) {
3140     Guard = getLoadStackGuard(DAG, dl, Chain);
3141   } else {
3142     const Value *IRGuard = TLI.getSDagStackGuard(M);
3143     SDValue GuardPtr = getValue(IRGuard);
3144 
3145     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
3146                         MachinePointerInfo(IRGuard, 0), Align,
3147                         MachineMemOperand::MOVolatile);
3148   }
3149 
3150   // Perform the comparison via a getsetcc.
3151   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
3152                                                         *DAG.getContext(),
3153                                                         Guard.getValueType()),
3154                              Guard, GuardVal, ISD::SETNE);
3155 
3156   // If the guard/stackslot do not equal, branch to failure MBB.
3157   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
3158                                MVT::Other, GuardVal.getOperand(0),
3159                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
3160   // Otherwise branch to success MBB.
3161   SDValue Br = DAG.getNode(ISD::BR, dl,
3162                            MVT::Other, BrCond,
3163                            DAG.getBasicBlock(SPD.getSuccessMBB()));
3164 
3165   DAG.setRoot(Br);
3166 }
3167 
3168 /// Codegen the failure basic block for a stack protector check.
3169 ///
3170 /// A failure stack protector machine basic block consists simply of a call to
3171 /// __stack_chk_fail().
3172 ///
3173 /// For a high level explanation of how this fits into the stack protector
3174 /// generation see the comment on the declaration of class
3175 /// StackProtectorDescriptor.
3176 void
3177 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
3178   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3179   TargetLowering::MakeLibCallOptions CallOptions;
3180   CallOptions.setDiscardResult(true);
3181   SDValue Chain = TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL,
3182                                   MVT::isVoid, {}, CallOptions, getCurSDLoc())
3183                       .second;
3184 
3185   // Emit a trap instruction if we are required to do so.
3186   const TargetOptions &TargetOpts = DAG.getTarget().Options;
3187   if (TargetOpts.TrapUnreachable && !TargetOpts.NoTrapAfterNoreturn)
3188     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
3189 
3190   DAG.setRoot(Chain);
3191 }
3192 
3193 /// visitBitTestHeader - This function emits necessary code to produce value
3194 /// suitable for "bit tests"
3195 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
3196                                              MachineBasicBlock *SwitchBB) {
3197   SDLoc dl = getCurSDLoc();
3198 
3199   // Subtract the minimum value.
3200   SDValue SwitchOp = getValue(B.SValue);
3201   EVT VT = SwitchOp.getValueType();
3202   SDValue RangeSub =
3203       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
3204 
3205   // Determine the type of the test operands.
3206   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3207   bool UsePtrType = false;
3208   if (!TLI.isTypeLegal(VT)) {
3209     UsePtrType = true;
3210   } else {
3211     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
3212       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
3213         // Switch table case range are encoded into series of masks.
3214         // Just use pointer type, it's guaranteed to fit.
3215         UsePtrType = true;
3216         break;
3217       }
3218   }
3219   SDValue Sub = RangeSub;
3220   if (UsePtrType) {
3221     VT = TLI.getPointerTy(DAG.getDataLayout());
3222     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
3223   }
3224 
3225   B.RegVT = VT.getSimpleVT();
3226   B.Reg = FuncInfo.CreateReg(B.RegVT);
3227   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
3228 
3229   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
3230 
3231   if (!B.FallthroughUnreachable)
3232     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
3233   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
3234   SwitchBB->normalizeSuccProbs();
3235 
3236   SDValue Root = CopyTo;
3237   if (!B.FallthroughUnreachable) {
3238     // Conditional branch to the default block.
3239     SDValue RangeCmp = DAG.getSetCC(dl,
3240         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3241                                RangeSub.getValueType()),
3242         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
3243         ISD::SETUGT);
3244 
3245     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
3246                        DAG.getBasicBlock(B.Default));
3247   }
3248 
3249   // Avoid emitting unnecessary branches to the next block.
3250   if (MBB != NextBlock(SwitchBB))
3251     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
3252 
3253   DAG.setRoot(Root);
3254 }
3255 
3256 /// visitBitTestCase - this function produces one "bit test"
3257 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
3258                                            MachineBasicBlock *NextMBB,
3259                                            BranchProbability BranchProbToNext,
3260                                            Register Reg, BitTestCase &B,
3261                                            MachineBasicBlock *SwitchBB) {
3262   SDLoc dl = getCurSDLoc();
3263   MVT VT = BB.RegVT;
3264   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
3265   SDValue Cmp;
3266   unsigned PopCount = llvm::popcount(B.Mask);
3267   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3268   if (PopCount == 1) {
3269     // Testing for a single bit; just compare the shift count with what it
3270     // would need to be to shift a 1 bit in that position.
3271     Cmp = DAG.getSetCC(
3272         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3273         ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT),
3274         ISD::SETEQ);
3275   } else if (PopCount == BB.Range) {
3276     // There is only one zero bit in the range, test for it directly.
3277     Cmp = DAG.getSetCC(
3278         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3279         ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE);
3280   } else {
3281     // Make desired shift
3282     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
3283                                     DAG.getConstant(1, dl, VT), ShiftOp);
3284 
3285     // Emit bit tests and jumps
3286     SDValue AndOp = DAG.getNode(ISD::AND, dl,
3287                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
3288     Cmp = DAG.getSetCC(
3289         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3290         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
3291   }
3292 
3293   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
3294   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
3295   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
3296   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
3297   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
3298   // one as they are relative probabilities (and thus work more like weights),
3299   // and hence we need to normalize them to let the sum of them become one.
3300   SwitchBB->normalizeSuccProbs();
3301 
3302   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
3303                               MVT::Other, getControlRoot(),
3304                               Cmp, DAG.getBasicBlock(B.TargetBB));
3305 
3306   // Avoid emitting unnecessary branches to the next block.
3307   if (NextMBB != NextBlock(SwitchBB))
3308     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
3309                         DAG.getBasicBlock(NextMBB));
3310 
3311   DAG.setRoot(BrAnd);
3312 }
3313 
3314 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
3315   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
3316 
3317   // Retrieve successors. Look through artificial IR level blocks like
3318   // catchswitch for successors.
3319   MachineBasicBlock *Return = FuncInfo.getMBB(I.getSuccessor(0));
3320   const BasicBlock *EHPadBB = I.getSuccessor(1);
3321   MachineBasicBlock *EHPadMBB = FuncInfo.getMBB(EHPadBB);
3322 
3323   // Deopt and ptrauth bundles are lowered in helper functions, and we don't
3324   // have to do anything here to lower funclet bundles.
3325   assert(!I.hasOperandBundlesOtherThan(
3326              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
3327               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
3328               LLVMContext::OB_cfguardtarget, LLVMContext::OB_ptrauth,
3329               LLVMContext::OB_clang_arc_attachedcall}) &&
3330          "Cannot lower invokes with arbitrary operand bundles yet!");
3331 
3332   const Value *Callee(I.getCalledOperand());
3333   const Function *Fn = dyn_cast<Function>(Callee);
3334   if (isa<InlineAsm>(Callee))
3335     visitInlineAsm(I, EHPadBB);
3336   else if (Fn && Fn->isIntrinsic()) {
3337     switch (Fn->getIntrinsicID()) {
3338     default:
3339       llvm_unreachable("Cannot invoke this intrinsic");
3340     case Intrinsic::donothing:
3341       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
3342     case Intrinsic::seh_try_begin:
3343     case Intrinsic::seh_scope_begin:
3344     case Intrinsic::seh_try_end:
3345     case Intrinsic::seh_scope_end:
3346       if (EHPadMBB)
3347           // a block referenced by EH table
3348           // so dtor-funclet not removed by opts
3349           EHPadMBB->setMachineBlockAddressTaken();
3350       break;
3351     case Intrinsic::experimental_patchpoint_void:
3352     case Intrinsic::experimental_patchpoint:
3353       visitPatchpoint(I, EHPadBB);
3354       break;
3355     case Intrinsic::experimental_gc_statepoint:
3356       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
3357       break;
3358     case Intrinsic::wasm_rethrow: {
3359       // This is usually done in visitTargetIntrinsic, but this intrinsic is
3360       // special because it can be invoked, so we manually lower it to a DAG
3361       // node here.
3362       SmallVector<SDValue, 8> Ops;
3363       Ops.push_back(getControlRoot()); // inchain for the terminator node
3364       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3365       Ops.push_back(
3366           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
3367                                 TLI.getPointerTy(DAG.getDataLayout())));
3368       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3369       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3370       break;
3371     }
3372     }
3373   } else if (I.hasDeoptState()) {
3374     // Currently we do not lower any intrinsic calls with deopt operand bundles.
3375     // Eventually we will support lowering the @llvm.experimental.deoptimize
3376     // intrinsic, and right now there are no plans to support other intrinsics
3377     // with deopt state.
3378     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
3379   } else if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
3380     LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), EHPadBB);
3381   } else {
3382     LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
3383   }
3384 
3385   // If the value of the invoke is used outside of its defining block, make it
3386   // available as a virtual register.
3387   // We already took care of the exported value for the statepoint instruction
3388   // during call to the LowerStatepoint.
3389   if (!isa<GCStatepointInst>(I)) {
3390     CopyToExportRegsIfNeeded(&I);
3391   }
3392 
3393   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
3394   BranchProbabilityInfo *BPI = FuncInfo.BPI;
3395   BranchProbability EHPadBBProb =
3396       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3397           : BranchProbability::getZero();
3398   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
3399 
3400   // Update successor info.
3401   addSuccessorWithProb(InvokeMBB, Return);
3402   for (auto &UnwindDest : UnwindDests) {
3403     UnwindDest.first->setIsEHPad();
3404     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3405   }
3406   InvokeMBB->normalizeSuccProbs();
3407 
3408   // Drop into normal successor.
3409   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
3410                           DAG.getBasicBlock(Return)));
3411 }
3412 
3413 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3414   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3415 
3416   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3417   // have to do anything here to lower funclet bundles.
3418   assert(!I.hasOperandBundlesOtherThan(
3419              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
3420          "Cannot lower callbrs with arbitrary operand bundles yet!");
3421 
3422   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
3423   visitInlineAsm(I);
3424   CopyToExportRegsIfNeeded(&I);
3425 
3426   // Retrieve successors.
3427   SmallPtrSet<BasicBlock *, 8> Dests;
3428   Dests.insert(I.getDefaultDest());
3429   MachineBasicBlock *Return = FuncInfo.getMBB(I.getDefaultDest());
3430 
3431   // Update successor info.
3432   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3433   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
3434     BasicBlock *Dest = I.getIndirectDest(i);
3435     MachineBasicBlock *Target = FuncInfo.getMBB(Dest);
3436     Target->setIsInlineAsmBrIndirectTarget();
3437     Target->setMachineBlockAddressTaken();
3438     Target->setLabelMustBeEmitted();
3439     // Don't add duplicate machine successors.
3440     if (Dests.insert(Dest).second)
3441       addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3442   }
3443   CallBrMBB->normalizeSuccProbs();
3444 
3445   // Drop into default successor.
3446   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3447                           MVT::Other, getControlRoot(),
3448                           DAG.getBasicBlock(Return)));
3449 }
3450 
3451 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3452   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3453 }
3454 
3455 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3456   assert(FuncInfo.MBB->isEHPad() &&
3457          "Call to landingpad not in landing pad!");
3458 
3459   // If there aren't registers to copy the values into (e.g., during SjLj
3460   // exceptions), then don't bother to create these DAG nodes.
3461   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3462   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3463   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3464       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3465     return;
3466 
3467   // If landingpad's return type is token type, we don't create DAG nodes
3468   // for its exception pointer and selector value. The extraction of exception
3469   // pointer or selector value from token type landingpads is not currently
3470   // supported.
3471   if (LP.getType()->isTokenTy())
3472     return;
3473 
3474   SmallVector<EVT, 2> ValueVTs;
3475   SDLoc dl = getCurSDLoc();
3476   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3477   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3478 
3479   // Get the two live-in registers as SDValues. The physregs have already been
3480   // copied into virtual registers.
3481   SDValue Ops[2];
3482   if (FuncInfo.ExceptionPointerVirtReg) {
3483     Ops[0] = DAG.getZExtOrTrunc(
3484         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3485                            FuncInfo.ExceptionPointerVirtReg,
3486                            TLI.getPointerTy(DAG.getDataLayout())),
3487         dl, ValueVTs[0]);
3488   } else {
3489     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3490   }
3491   Ops[1] = DAG.getZExtOrTrunc(
3492       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3493                          FuncInfo.ExceptionSelectorVirtReg,
3494                          TLI.getPointerTy(DAG.getDataLayout())),
3495       dl, ValueVTs[1]);
3496 
3497   // Merge into one.
3498   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3499                             DAG.getVTList(ValueVTs), Ops);
3500   setValue(&LP, Res);
3501 }
3502 
3503 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3504                                            MachineBasicBlock *Last) {
3505   // Update JTCases.
3506   for (JumpTableBlock &JTB : SL->JTCases)
3507     if (JTB.first.HeaderBB == First)
3508       JTB.first.HeaderBB = Last;
3509 
3510   // Update BitTestCases.
3511   for (BitTestBlock &BTB : SL->BitTestCases)
3512     if (BTB.Parent == First)
3513       BTB.Parent = Last;
3514 }
3515 
3516 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3517   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3518 
3519   // Update machine-CFG edges with unique successors.
3520   SmallSet<BasicBlock*, 32> Done;
3521   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3522     BasicBlock *BB = I.getSuccessor(i);
3523     bool Inserted = Done.insert(BB).second;
3524     if (!Inserted)
3525         continue;
3526 
3527     MachineBasicBlock *Succ = FuncInfo.getMBB(BB);
3528     addSuccessorWithProb(IndirectBrMBB, Succ);
3529   }
3530   IndirectBrMBB->normalizeSuccProbs();
3531 
3532   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3533                           MVT::Other, getControlRoot(),
3534                           getValue(I.getAddress())));
3535 }
3536 
3537 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3538   if (!DAG.getTarget().Options.TrapUnreachable)
3539     return;
3540 
3541   // We may be able to ignore unreachable behind a noreturn call.
3542   if (const CallInst *Call = dyn_cast_or_null<CallInst>(I.getPrevNode());
3543       Call && Call->doesNotReturn()) {
3544     if (DAG.getTarget().Options.NoTrapAfterNoreturn)
3545       return;
3546     // Do not emit an additional trap instruction.
3547     if (Call->isNonContinuableTrap())
3548       return;
3549   }
3550 
3551   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3552 }
3553 
3554 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3555   SDNodeFlags Flags;
3556   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3557     Flags.copyFMF(*FPOp);
3558 
3559   SDValue Op = getValue(I.getOperand(0));
3560   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3561                                     Op, Flags);
3562   setValue(&I, UnNodeValue);
3563 }
3564 
3565 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3566   SDNodeFlags Flags;
3567   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3568     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3569     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3570   }
3571   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3572     Flags.setExact(ExactOp->isExact());
3573   if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&I))
3574     Flags.setDisjoint(DisjointOp->isDisjoint());
3575   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3576     Flags.copyFMF(*FPOp);
3577 
3578   SDValue Op1 = getValue(I.getOperand(0));
3579   SDValue Op2 = getValue(I.getOperand(1));
3580   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3581                                      Op1, Op2, Flags);
3582   setValue(&I, BinNodeValue);
3583 }
3584 
3585 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3586   SDValue Op1 = getValue(I.getOperand(0));
3587   SDValue Op2 = getValue(I.getOperand(1));
3588 
3589   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3590       Op1.getValueType(), DAG.getDataLayout());
3591 
3592   // Coerce the shift amount to the right type if we can. This exposes the
3593   // truncate or zext to optimization early.
3594   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3595     assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) &&
3596            "Unexpected shift type");
3597     Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3598   }
3599 
3600   bool nuw = false;
3601   bool nsw = false;
3602   bool exact = false;
3603 
3604   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3605 
3606     if (const OverflowingBinaryOperator *OFBinOp =
3607             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3608       nuw = OFBinOp->hasNoUnsignedWrap();
3609       nsw = OFBinOp->hasNoSignedWrap();
3610     }
3611     if (const PossiblyExactOperator *ExactOp =
3612             dyn_cast<const PossiblyExactOperator>(&I))
3613       exact = ExactOp->isExact();
3614   }
3615   SDNodeFlags Flags;
3616   Flags.setExact(exact);
3617   Flags.setNoSignedWrap(nsw);
3618   Flags.setNoUnsignedWrap(nuw);
3619   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3620                             Flags);
3621   setValue(&I, Res);
3622 }
3623 
3624 void SelectionDAGBuilder::visitSDiv(const User &I) {
3625   SDValue Op1 = getValue(I.getOperand(0));
3626   SDValue Op2 = getValue(I.getOperand(1));
3627 
3628   SDNodeFlags Flags;
3629   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3630                  cast<PossiblyExactOperator>(&I)->isExact());
3631   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3632                            Op2, Flags));
3633 }
3634 
3635 void SelectionDAGBuilder::visitICmp(const ICmpInst &I) {
3636   ICmpInst::Predicate predicate = I.getPredicate();
3637   SDValue Op1 = getValue(I.getOperand(0));
3638   SDValue Op2 = getValue(I.getOperand(1));
3639   ISD::CondCode Opcode = getICmpCondCode(predicate);
3640 
3641   auto &TLI = DAG.getTargetLoweringInfo();
3642   EVT MemVT =
3643       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3644 
3645   // If a pointer's DAG type is larger than its memory type then the DAG values
3646   // are zero-extended. This breaks signed comparisons so truncate back to the
3647   // underlying type before doing the compare.
3648   if (Op1.getValueType() != MemVT) {
3649     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3650     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3651   }
3652 
3653   SDNodeFlags Flags;
3654   Flags.setSameSign(I.hasSameSign());
3655   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3656 
3657   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3658                                                         I.getType());
3659   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3660 }
3661 
3662 void SelectionDAGBuilder::visitFCmp(const FCmpInst &I) {
3663   FCmpInst::Predicate predicate = I.getPredicate();
3664   SDValue Op1 = getValue(I.getOperand(0));
3665   SDValue Op2 = getValue(I.getOperand(1));
3666 
3667   ISD::CondCode Condition = getFCmpCondCode(predicate);
3668   auto *FPMO = cast<FPMathOperator>(&I);
3669   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3670     Condition = getFCmpCodeWithoutNaN(Condition);
3671 
3672   SDNodeFlags Flags;
3673   Flags.copyFMF(*FPMO);
3674   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3675 
3676   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3677                                                         I.getType());
3678   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3679 }
3680 
3681 // Check if the condition of the select has one use or two users that are both
3682 // selects with the same condition.
3683 static bool hasOnlySelectUsers(const Value *Cond) {
3684   return llvm::all_of(Cond->users(), [](const Value *V) {
3685     return isa<SelectInst>(V);
3686   });
3687 }
3688 
3689 void SelectionDAGBuilder::visitSelect(const User &I) {
3690   SmallVector<EVT, 4> ValueVTs;
3691   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3692                   ValueVTs);
3693   unsigned NumValues = ValueVTs.size();
3694   if (NumValues == 0) return;
3695 
3696   SmallVector<SDValue, 4> Values(NumValues);
3697   SDValue Cond     = getValue(I.getOperand(0));
3698   SDValue LHSVal   = getValue(I.getOperand(1));
3699   SDValue RHSVal   = getValue(I.getOperand(2));
3700   SmallVector<SDValue, 1> BaseOps(1, Cond);
3701   ISD::NodeType OpCode =
3702       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3703 
3704   bool IsUnaryAbs = false;
3705   bool Negate = false;
3706 
3707   SDNodeFlags Flags;
3708   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3709     Flags.copyFMF(*FPOp);
3710 
3711   Flags.setUnpredictable(
3712       cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable));
3713 
3714   // Min/max matching is only viable if all output VTs are the same.
3715   if (all_equal(ValueVTs)) {
3716     EVT VT = ValueVTs[0];
3717     LLVMContext &Ctx = *DAG.getContext();
3718     auto &TLI = DAG.getTargetLoweringInfo();
3719 
3720     // We care about the legality of the operation after it has been type
3721     // legalized.
3722     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3723       VT = TLI.getTypeToTransformTo(Ctx, VT);
3724 
3725     // If the vselect is legal, assume we want to leave this as a vector setcc +
3726     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3727     // min/max is legal on the scalar type.
3728     bool UseScalarMinMax = VT.isVector() &&
3729       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3730 
3731     // ValueTracking's select pattern matching does not account for -0.0,
3732     // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that
3733     // -0.0 is less than +0.0.
3734     const Value *LHS, *RHS;
3735     auto SPR = matchSelectPattern(&I, LHS, RHS);
3736     ISD::NodeType Opc = ISD::DELETED_NODE;
3737     switch (SPR.Flavor) {
3738     case SPF_UMAX:    Opc = ISD::UMAX; break;
3739     case SPF_UMIN:    Opc = ISD::UMIN; break;
3740     case SPF_SMAX:    Opc = ISD::SMAX; break;
3741     case SPF_SMIN:    Opc = ISD::SMIN; break;
3742     case SPF_FMINNUM:
3743       switch (SPR.NaNBehavior) {
3744       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3745       case SPNB_RETURNS_NAN: break;
3746       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3747       case SPNB_RETURNS_ANY:
3748         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) ||
3749             (UseScalarMinMax &&
3750              TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType())))
3751           Opc = ISD::FMINNUM;
3752         break;
3753       }
3754       break;
3755     case SPF_FMAXNUM:
3756       switch (SPR.NaNBehavior) {
3757       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3758       case SPNB_RETURNS_NAN: break;
3759       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3760       case SPNB_RETURNS_ANY:
3761         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) ||
3762             (UseScalarMinMax &&
3763              TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType())))
3764           Opc = ISD::FMAXNUM;
3765         break;
3766       }
3767       break;
3768     case SPF_NABS:
3769       Negate = true;
3770       [[fallthrough]];
3771     case SPF_ABS:
3772       IsUnaryAbs = true;
3773       Opc = ISD::ABS;
3774       break;
3775     default: break;
3776     }
3777 
3778     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3779         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3780          (UseScalarMinMax &&
3781           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3782         // If the underlying comparison instruction is used by any other
3783         // instruction, the consumed instructions won't be destroyed, so it is
3784         // not profitable to convert to a min/max.
3785         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3786       OpCode = Opc;
3787       LHSVal = getValue(LHS);
3788       RHSVal = getValue(RHS);
3789       BaseOps.clear();
3790     }
3791 
3792     if (IsUnaryAbs) {
3793       OpCode = Opc;
3794       LHSVal = getValue(LHS);
3795       BaseOps.clear();
3796     }
3797   }
3798 
3799   if (IsUnaryAbs) {
3800     for (unsigned i = 0; i != NumValues; ++i) {
3801       SDLoc dl = getCurSDLoc();
3802       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3803       Values[i] =
3804           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3805       if (Negate)
3806         Values[i] = DAG.getNegative(Values[i], dl, VT);
3807     }
3808   } else {
3809     for (unsigned i = 0; i != NumValues; ++i) {
3810       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3811       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3812       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3813       Values[i] = DAG.getNode(
3814           OpCode, getCurSDLoc(),
3815           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3816     }
3817   }
3818 
3819   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3820                            DAG.getVTList(ValueVTs), Values));
3821 }
3822 
3823 void SelectionDAGBuilder::visitTrunc(const User &I) {
3824   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3825   SDValue N = getValue(I.getOperand(0));
3826   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3827                                                         I.getType());
3828   SDNodeFlags Flags;
3829   if (auto *Trunc = dyn_cast<TruncInst>(&I)) {
3830     Flags.setNoSignedWrap(Trunc->hasNoSignedWrap());
3831     Flags.setNoUnsignedWrap(Trunc->hasNoUnsignedWrap());
3832   }
3833 
3834   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N, Flags));
3835 }
3836 
3837 void SelectionDAGBuilder::visitZExt(const User &I) {
3838   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3839   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3840   SDValue N = getValue(I.getOperand(0));
3841   auto &TLI = DAG.getTargetLoweringInfo();
3842   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3843 
3844   SDNodeFlags Flags;
3845   if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
3846     Flags.setNonNeg(PNI->hasNonNeg());
3847 
3848   // Eagerly use nonneg information to canonicalize towards sign_extend if
3849   // that is the target's preference.
3850   // TODO: Let the target do this later.
3851   if (Flags.hasNonNeg() &&
3852       TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) {
3853     setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3854     return;
3855   }
3856 
3857   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags));
3858 }
3859 
3860 void SelectionDAGBuilder::visitSExt(const User &I) {
3861   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3862   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3863   SDValue N = getValue(I.getOperand(0));
3864   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3865                                                         I.getType());
3866   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3867 }
3868 
3869 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3870   // FPTrunc is never a no-op cast, no need to check
3871   SDValue N = getValue(I.getOperand(0));
3872   SDLoc dl = getCurSDLoc();
3873   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3874   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3875   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3876                            DAG.getTargetConstant(
3877                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3878 }
3879 
3880 void SelectionDAGBuilder::visitFPExt(const User &I) {
3881   // FPExt is never a no-op cast, no need to check
3882   SDValue N = getValue(I.getOperand(0));
3883   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3884                                                         I.getType());
3885   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3886 }
3887 
3888 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3889   // FPToUI is never a no-op cast, no need to check
3890   SDValue N = getValue(I.getOperand(0));
3891   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3892                                                         I.getType());
3893   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3894 }
3895 
3896 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3897   // FPToSI is never a no-op cast, no need to check
3898   SDValue N = getValue(I.getOperand(0));
3899   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3900                                                         I.getType());
3901   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3902 }
3903 
3904 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3905   // UIToFP is never a no-op cast, no need to check
3906   SDValue N = getValue(I.getOperand(0));
3907   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3908                                                         I.getType());
3909   SDNodeFlags Flags;
3910   if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
3911     Flags.setNonNeg(PNI->hasNonNeg());
3912 
3913   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N, Flags));
3914 }
3915 
3916 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3917   // SIToFP is never a no-op cast, no need to check
3918   SDValue N = getValue(I.getOperand(0));
3919   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3920                                                         I.getType());
3921   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3922 }
3923 
3924 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3925   // What to do depends on the size of the integer and the size of the pointer.
3926   // We can either truncate, zero extend, or no-op, accordingly.
3927   SDValue N = getValue(I.getOperand(0));
3928   auto &TLI = DAG.getTargetLoweringInfo();
3929   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3930                                                         I.getType());
3931   EVT PtrMemVT =
3932       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3933   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3934   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3935   setValue(&I, N);
3936 }
3937 
3938 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3939   // What to do depends on the size of the integer and the size of the pointer.
3940   // We can either truncate, zero extend, or no-op, accordingly.
3941   SDValue N = getValue(I.getOperand(0));
3942   auto &TLI = DAG.getTargetLoweringInfo();
3943   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3944   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3945   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3946   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3947   setValue(&I, N);
3948 }
3949 
3950 void SelectionDAGBuilder::visitBitCast(const User &I) {
3951   SDValue N = getValue(I.getOperand(0));
3952   SDLoc dl = getCurSDLoc();
3953   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3954                                                         I.getType());
3955 
3956   // BitCast assures us that source and destination are the same size so this is
3957   // either a BITCAST or a no-op.
3958   if (DestVT != N.getValueType())
3959     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3960                              DestVT, N)); // convert types.
3961   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3962   // might fold any kind of constant expression to an integer constant and that
3963   // is not what we are looking for. Only recognize a bitcast of a genuine
3964   // constant integer as an opaque constant.
3965   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3966     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3967                                  /*isOpaque*/true));
3968   else
3969     setValue(&I, N);            // noop cast.
3970 }
3971 
3972 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3973   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3974   const Value *SV = I.getOperand(0);
3975   SDValue N = getValue(SV);
3976   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3977 
3978   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3979   unsigned DestAS = I.getType()->getPointerAddressSpace();
3980 
3981   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3982     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3983 
3984   setValue(&I, N);
3985 }
3986 
3987 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3988   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3989   SDValue InVec = getValue(I.getOperand(0));
3990   SDValue InVal = getValue(I.getOperand(1));
3991   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3992                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3993   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3994                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3995                            InVec, InVal, InIdx));
3996 }
3997 
3998 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3999   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4000   SDValue InVec = getValue(I.getOperand(0));
4001   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
4002                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
4003   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
4004                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
4005                            InVec, InIdx));
4006 }
4007 
4008 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
4009   SDValue Src1 = getValue(I.getOperand(0));
4010   SDValue Src2 = getValue(I.getOperand(1));
4011   ArrayRef<int> Mask;
4012   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
4013     Mask = SVI->getShuffleMask();
4014   else
4015     Mask = cast<ConstantExpr>(I).getShuffleMask();
4016   SDLoc DL = getCurSDLoc();
4017   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4018   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4019   EVT SrcVT = Src1.getValueType();
4020 
4021   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
4022       VT.isScalableVector()) {
4023     // Canonical splat form of first element of first input vector.
4024     SDValue FirstElt =
4025         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
4026                     DAG.getVectorIdxConstant(0, DL));
4027     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
4028     return;
4029   }
4030 
4031   // For now, we only handle splats for scalable vectors.
4032   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
4033   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
4034   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
4035 
4036   unsigned SrcNumElts = SrcVT.getVectorNumElements();
4037   unsigned MaskNumElts = Mask.size();
4038 
4039   if (SrcNumElts == MaskNumElts) {
4040     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
4041     return;
4042   }
4043 
4044   // Normalize the shuffle vector since mask and vector length don't match.
4045   if (SrcNumElts < MaskNumElts) {
4046     // Mask is longer than the source vectors. We can use concatenate vector to
4047     // make the mask and vectors lengths match.
4048 
4049     if (MaskNumElts % SrcNumElts == 0) {
4050       // Mask length is a multiple of the source vector length.
4051       // Check if the shuffle is some kind of concatenation of the input
4052       // vectors.
4053       unsigned NumConcat = MaskNumElts / SrcNumElts;
4054       bool IsConcat = true;
4055       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
4056       for (unsigned i = 0; i != MaskNumElts; ++i) {
4057         int Idx = Mask[i];
4058         if (Idx < 0)
4059           continue;
4060         // Ensure the indices in each SrcVT sized piece are sequential and that
4061         // the same source is used for the whole piece.
4062         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
4063             (ConcatSrcs[i / SrcNumElts] >= 0 &&
4064              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
4065           IsConcat = false;
4066           break;
4067         }
4068         // Remember which source this index came from.
4069         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
4070       }
4071 
4072       // The shuffle is concatenating multiple vectors together. Just emit
4073       // a CONCAT_VECTORS operation.
4074       if (IsConcat) {
4075         SmallVector<SDValue, 8> ConcatOps;
4076         for (auto Src : ConcatSrcs) {
4077           if (Src < 0)
4078             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
4079           else if (Src == 0)
4080             ConcatOps.push_back(Src1);
4081           else
4082             ConcatOps.push_back(Src2);
4083         }
4084         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
4085         return;
4086       }
4087     }
4088 
4089     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
4090     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
4091     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
4092                                     PaddedMaskNumElts);
4093 
4094     // Pad both vectors with undefs to make them the same length as the mask.
4095     SDValue UndefVal = DAG.getUNDEF(SrcVT);
4096 
4097     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
4098     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
4099     MOps1[0] = Src1;
4100     MOps2[0] = Src2;
4101 
4102     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
4103     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
4104 
4105     // Readjust mask for new input vector length.
4106     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
4107     for (unsigned i = 0; i != MaskNumElts; ++i) {
4108       int Idx = Mask[i];
4109       if (Idx >= (int)SrcNumElts)
4110         Idx -= SrcNumElts - PaddedMaskNumElts;
4111       MappedOps[i] = Idx;
4112     }
4113 
4114     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
4115 
4116     // If the concatenated vector was padded, extract a subvector with the
4117     // correct number of elements.
4118     if (MaskNumElts != PaddedMaskNumElts)
4119       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
4120                            DAG.getVectorIdxConstant(0, DL));
4121 
4122     setValue(&I, Result);
4123     return;
4124   }
4125 
4126   assert(SrcNumElts > MaskNumElts);
4127 
4128   // Analyze the access pattern of the vector to see if we can extract
4129   // two subvectors and do the shuffle.
4130   int StartIdx[2] = {-1, -1}; // StartIdx to extract from
4131   bool CanExtract = true;
4132   for (int Idx : Mask) {
4133     unsigned Input = 0;
4134     if (Idx < 0)
4135       continue;
4136 
4137     if (Idx >= (int)SrcNumElts) {
4138       Input = 1;
4139       Idx -= SrcNumElts;
4140     }
4141 
4142     // If all the indices come from the same MaskNumElts sized portion of
4143     // the sources we can use extract. Also make sure the extract wouldn't
4144     // extract past the end of the source.
4145     int NewStartIdx = alignDown(Idx, MaskNumElts);
4146     if (NewStartIdx + MaskNumElts > SrcNumElts ||
4147         (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
4148       CanExtract = false;
4149     // Make sure we always update StartIdx as we use it to track if all
4150     // elements are undef.
4151     StartIdx[Input] = NewStartIdx;
4152   }
4153 
4154   if (StartIdx[0] < 0 && StartIdx[1] < 0) {
4155     setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
4156     return;
4157   }
4158   if (CanExtract) {
4159     // Extract appropriate subvector and generate a vector shuffle
4160     for (unsigned Input = 0; Input < 2; ++Input) {
4161       SDValue &Src = Input == 0 ? Src1 : Src2;
4162       if (StartIdx[Input] < 0)
4163         Src = DAG.getUNDEF(VT);
4164       else {
4165         Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
4166                           DAG.getVectorIdxConstant(StartIdx[Input], DL));
4167       }
4168     }
4169 
4170     // Calculate new mask.
4171     SmallVector<int, 8> MappedOps(Mask);
4172     for (int &Idx : MappedOps) {
4173       if (Idx >= (int)SrcNumElts)
4174         Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
4175       else if (Idx >= 0)
4176         Idx -= StartIdx[0];
4177     }
4178 
4179     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
4180     return;
4181   }
4182 
4183   // We can't use either concat vectors or extract subvectors so fall back to
4184   // replacing the shuffle with extract and build vector.
4185   // to insert and build vector.
4186   EVT EltVT = VT.getVectorElementType();
4187   SmallVector<SDValue,8> Ops;
4188   for (int Idx : Mask) {
4189     SDValue Res;
4190 
4191     if (Idx < 0) {
4192       Res = DAG.getUNDEF(EltVT);
4193     } else {
4194       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
4195       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
4196 
4197       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
4198                         DAG.getVectorIdxConstant(Idx, DL));
4199     }
4200 
4201     Ops.push_back(Res);
4202   }
4203 
4204   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
4205 }
4206 
4207 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
4208   ArrayRef<unsigned> Indices = I.getIndices();
4209   const Value *Op0 = I.getOperand(0);
4210   const Value *Op1 = I.getOperand(1);
4211   Type *AggTy = I.getType();
4212   Type *ValTy = Op1->getType();
4213   bool IntoUndef = isa<UndefValue>(Op0);
4214   bool FromUndef = isa<UndefValue>(Op1);
4215 
4216   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4217 
4218   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4219   SmallVector<EVT, 4> AggValueVTs;
4220   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
4221   SmallVector<EVT, 4> ValValueVTs;
4222   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4223 
4224   unsigned NumAggValues = AggValueVTs.size();
4225   unsigned NumValValues = ValValueVTs.size();
4226   SmallVector<SDValue, 4> Values(NumAggValues);
4227 
4228   // Ignore an insertvalue that produces an empty object
4229   if (!NumAggValues) {
4230     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4231     return;
4232   }
4233 
4234   SDValue Agg = getValue(Op0);
4235   unsigned i = 0;
4236   // Copy the beginning value(s) from the original aggregate.
4237   for (; i != LinearIndex; ++i)
4238     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4239                 SDValue(Agg.getNode(), Agg.getResNo() + i);
4240   // Copy values from the inserted value(s).
4241   if (NumValValues) {
4242     SDValue Val = getValue(Op1);
4243     for (; i != LinearIndex + NumValValues; ++i)
4244       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4245                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
4246   }
4247   // Copy remaining value(s) from the original aggregate.
4248   for (; i != NumAggValues; ++i)
4249     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4250                 SDValue(Agg.getNode(), Agg.getResNo() + i);
4251 
4252   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
4253                            DAG.getVTList(AggValueVTs), Values));
4254 }
4255 
4256 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
4257   ArrayRef<unsigned> Indices = I.getIndices();
4258   const Value *Op0 = I.getOperand(0);
4259   Type *AggTy = Op0->getType();
4260   Type *ValTy = I.getType();
4261   bool OutOfUndef = isa<UndefValue>(Op0);
4262 
4263   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4264 
4265   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4266   SmallVector<EVT, 4> ValValueVTs;
4267   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4268 
4269   unsigned NumValValues = ValValueVTs.size();
4270 
4271   // Ignore a extractvalue that produces an empty object
4272   if (!NumValValues) {
4273     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4274     return;
4275   }
4276 
4277   SmallVector<SDValue, 4> Values(NumValValues);
4278 
4279   SDValue Agg = getValue(Op0);
4280   // Copy out the selected value(s).
4281   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
4282     Values[i - LinearIndex] =
4283       OutOfUndef ?
4284         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
4285         SDValue(Agg.getNode(), Agg.getResNo() + i);
4286 
4287   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
4288                            DAG.getVTList(ValValueVTs), Values));
4289 }
4290 
4291 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
4292   Value *Op0 = I.getOperand(0);
4293   // Note that the pointer operand may be a vector of pointers. Take the scalar
4294   // element which holds a pointer.
4295   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
4296   SDValue N = getValue(Op0);
4297   SDLoc dl = getCurSDLoc();
4298   auto &TLI = DAG.getTargetLoweringInfo();
4299   GEPNoWrapFlags NW = cast<GEPOperator>(I).getNoWrapFlags();
4300 
4301   // Normalize Vector GEP - all scalar operands should be converted to the
4302   // splat vector.
4303   bool IsVectorGEP = I.getType()->isVectorTy();
4304   ElementCount VectorElementCount =
4305       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
4306                   : ElementCount::getFixed(0);
4307 
4308   if (IsVectorGEP && !N.getValueType().isVector()) {
4309     LLVMContext &Context = *DAG.getContext();
4310     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
4311     N = DAG.getSplat(VT, dl, N);
4312   }
4313 
4314   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
4315        GTI != E; ++GTI) {
4316     const Value *Idx = GTI.getOperand();
4317     if (StructType *StTy = GTI.getStructTypeOrNull()) {
4318       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
4319       if (Field) {
4320         // N = N + Offset
4321         uint64_t Offset =
4322             DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
4323 
4324         // In an inbounds GEP with an offset that is nonnegative even when
4325         // interpreted as signed, assume there is no unsigned overflow.
4326         SDNodeFlags Flags;
4327         if (NW.hasNoUnsignedWrap() ||
4328             (int64_t(Offset) >= 0 && NW.hasNoUnsignedSignedWrap()))
4329           Flags |= SDNodeFlags::NoUnsignedWrap;
4330 
4331         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
4332                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
4333       }
4334     } else {
4335       // IdxSize is the width of the arithmetic according to IR semantics.
4336       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
4337       // (and fix up the result later).
4338       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
4339       MVT IdxTy = MVT::getIntegerVT(IdxSize);
4340       TypeSize ElementSize =
4341           GTI.getSequentialElementStride(DAG.getDataLayout());
4342       // We intentionally mask away the high bits here; ElementSize may not
4343       // fit in IdxTy.
4344       APInt ElementMul(IdxSize, ElementSize.getKnownMinValue(),
4345                        /*isSigned=*/false, /*implicitTrunc=*/true);
4346       bool ElementScalable = ElementSize.isScalable();
4347 
4348       // If this is a scalar constant or a splat vector of constants,
4349       // handle it quickly.
4350       const auto *C = dyn_cast<Constant>(Idx);
4351       if (C && isa<VectorType>(C->getType()))
4352         C = C->getSplatValue();
4353 
4354       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
4355       if (CI && CI->isZero())
4356         continue;
4357       if (CI && !ElementScalable) {
4358         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
4359         LLVMContext &Context = *DAG.getContext();
4360         SDValue OffsVal;
4361         if (IsVectorGEP)
4362           OffsVal = DAG.getConstant(
4363               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
4364         else
4365           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
4366 
4367         // In an inbounds GEP with an offset that is nonnegative even when
4368         // interpreted as signed, assume there is no unsigned overflow.
4369         SDNodeFlags Flags;
4370         if (NW.hasNoUnsignedWrap() ||
4371             (Offs.isNonNegative() && NW.hasNoUnsignedSignedWrap()))
4372           Flags.setNoUnsignedWrap(true);
4373 
4374         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
4375 
4376         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
4377         continue;
4378       }
4379 
4380       // N = N + Idx * ElementMul;
4381       SDValue IdxN = getValue(Idx);
4382 
4383       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
4384         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
4385                                   VectorElementCount);
4386         IdxN = DAG.getSplat(VT, dl, IdxN);
4387       }
4388 
4389       // If the index is smaller or larger than intptr_t, truncate or extend
4390       // it.
4391       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
4392 
4393       SDNodeFlags ScaleFlags;
4394       // The multiplication of an index by the type size does not wrap the
4395       // pointer index type in a signed sense (mul nsw).
4396       ScaleFlags.setNoSignedWrap(NW.hasNoUnsignedSignedWrap());
4397 
4398       // The multiplication of an index by the type size does not wrap the
4399       // pointer index type in an unsigned sense (mul nuw).
4400       ScaleFlags.setNoUnsignedWrap(NW.hasNoUnsignedWrap());
4401 
4402       if (ElementScalable) {
4403         EVT VScaleTy = N.getValueType().getScalarType();
4404         SDValue VScale = DAG.getNode(
4405             ISD::VSCALE, dl, VScaleTy,
4406             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
4407         if (IsVectorGEP)
4408           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
4409         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale,
4410                            ScaleFlags);
4411       } else {
4412         // If this is a multiply by a power of two, turn it into a shl
4413         // immediately.  This is a very common case.
4414         if (ElementMul != 1) {
4415           if (ElementMul.isPowerOf2()) {
4416             unsigned Amt = ElementMul.logBase2();
4417             IdxN = DAG.getNode(ISD::SHL, dl, N.getValueType(), IdxN,
4418                                DAG.getConstant(Amt, dl, IdxN.getValueType()),
4419                                ScaleFlags);
4420           } else {
4421             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
4422                                             IdxN.getValueType());
4423             IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, Scale,
4424                                ScaleFlags);
4425           }
4426         }
4427       }
4428 
4429       // The successive addition of the current address, truncated to the
4430       // pointer index type and interpreted as an unsigned number, and each
4431       // offset, also interpreted as an unsigned number, does not wrap the
4432       // pointer index type (add nuw).
4433       SDNodeFlags AddFlags;
4434       AddFlags.setNoUnsignedWrap(NW.hasNoUnsignedWrap());
4435 
4436       N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, IdxN, AddFlags);
4437     }
4438   }
4439 
4440   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4441   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4442   if (IsVectorGEP) {
4443     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4444     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4445   }
4446 
4447   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4448     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4449 
4450   setValue(&I, N);
4451 }
4452 
4453 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4454   // If this is a fixed sized alloca in the entry block of the function,
4455   // allocate it statically on the stack.
4456   if (FuncInfo.StaticAllocaMap.count(&I))
4457     return;   // getValue will auto-populate this.
4458 
4459   SDLoc dl = getCurSDLoc();
4460   Type *Ty = I.getAllocatedType();
4461   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4462   auto &DL = DAG.getDataLayout();
4463   TypeSize TySize = DL.getTypeAllocSize(Ty);
4464   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4465 
4466   SDValue AllocSize = getValue(I.getArraySize());
4467 
4468   EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace());
4469   if (AllocSize.getValueType() != IntPtr)
4470     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4471 
4472   if (TySize.isScalable())
4473     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4474                             DAG.getVScale(dl, IntPtr,
4475                                           APInt(IntPtr.getScalarSizeInBits(),
4476                                                 TySize.getKnownMinValue())));
4477   else {
4478     SDValue TySizeValue =
4479         DAG.getConstant(TySize.getFixedValue(), dl, MVT::getIntegerVT(64));
4480     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4481                             DAG.getZExtOrTrunc(TySizeValue, dl, IntPtr));
4482   }
4483 
4484   // Handle alignment.  If the requested alignment is less than or equal to
4485   // the stack alignment, ignore it.  If the size is greater than or equal to
4486   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4487   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4488   if (*Alignment <= StackAlign)
4489     Alignment = std::nullopt;
4490 
4491   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4492   // Round the size of the allocation up to the stack alignment size
4493   // by add SA-1 to the size. This doesn't overflow because we're computing
4494   // an address inside an alloca.
4495   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4496                           DAG.getConstant(StackAlignMask, dl, IntPtr),
4497                           SDNodeFlags::NoUnsignedWrap);
4498 
4499   // Mask out the low bits for alignment purposes.
4500   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4501                           DAG.getSignedConstant(~StackAlignMask, dl, IntPtr));
4502 
4503   SDValue Ops[] = {
4504       getRoot(), AllocSize,
4505       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4506   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4507   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4508   setValue(&I, DSA);
4509   DAG.setRoot(DSA.getValue(1));
4510 
4511   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4512 }
4513 
4514 static const MDNode *getRangeMetadata(const Instruction &I) {
4515   // If !noundef is not present, then !range violation results in a poison
4516   // value rather than immediate undefined behavior. In theory, transferring
4517   // these annotations to SDAG is fine, but in practice there are key SDAG
4518   // transforms that are known not to be poison-safe, such as folding logical
4519   // and/or to bitwise and/or. For now, only transfer !range if !noundef is
4520   // also present.
4521   if (!I.hasMetadata(LLVMContext::MD_noundef))
4522     return nullptr;
4523   return I.getMetadata(LLVMContext::MD_range);
4524 }
4525 
4526 static std::optional<ConstantRange> getRange(const Instruction &I) {
4527   if (const auto *CB = dyn_cast<CallBase>(&I)) {
4528     // see comment in getRangeMetadata about this check
4529     if (CB->hasRetAttr(Attribute::NoUndef))
4530       return CB->getRange();
4531   }
4532   if (const MDNode *Range = getRangeMetadata(I))
4533     return getConstantRangeFromMetadata(*Range);
4534   return std::nullopt;
4535 }
4536 
4537 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4538   if (I.isAtomic())
4539     return visitAtomicLoad(I);
4540 
4541   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4542   const Value *SV = I.getOperand(0);
4543   if (TLI.supportSwiftError()) {
4544     // Swifterror values can come from either a function parameter with
4545     // swifterror attribute or an alloca with swifterror attribute.
4546     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4547       if (Arg->hasSwiftErrorAttr())
4548         return visitLoadFromSwiftError(I);
4549     }
4550 
4551     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4552       if (Alloca->isSwiftError())
4553         return visitLoadFromSwiftError(I);
4554     }
4555   }
4556 
4557   SDValue Ptr = getValue(SV);
4558 
4559   Type *Ty = I.getType();
4560   SmallVector<EVT, 4> ValueVTs, MemVTs;
4561   SmallVector<TypeSize, 4> Offsets;
4562   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4563   unsigned NumValues = ValueVTs.size();
4564   if (NumValues == 0)
4565     return;
4566 
4567   Align Alignment = I.getAlign();
4568   AAMDNodes AAInfo = I.getAAMetadata();
4569   const MDNode *Ranges = getRangeMetadata(I);
4570   bool isVolatile = I.isVolatile();
4571   MachineMemOperand::Flags MMOFlags =
4572       TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4573 
4574   SDValue Root;
4575   bool ConstantMemory = false;
4576   if (isVolatile)
4577     // Serialize volatile loads with other side effects.
4578     Root = getRoot();
4579   else if (NumValues > MaxParallelChains)
4580     Root = getMemoryRoot();
4581   else if (AA &&
4582            AA->pointsToConstantMemory(MemoryLocation(
4583                SV,
4584                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4585                AAInfo))) {
4586     // Do not serialize (non-volatile) loads of constant memory with anything.
4587     Root = DAG.getEntryNode();
4588     ConstantMemory = true;
4589     MMOFlags |= MachineMemOperand::MOInvariant;
4590   } else {
4591     // Do not serialize non-volatile loads against each other.
4592     Root = DAG.getRoot();
4593   }
4594 
4595   SDLoc dl = getCurSDLoc();
4596 
4597   if (isVolatile)
4598     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4599 
4600   SmallVector<SDValue, 4> Values(NumValues);
4601   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4602 
4603   unsigned ChainI = 0;
4604   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4605     // Serializing loads here may result in excessive register pressure, and
4606     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4607     // could recover a bit by hoisting nodes upward in the chain by recognizing
4608     // they are side-effect free or do not alias. The optimizer should really
4609     // avoid this case by converting large object/array copies to llvm.memcpy
4610     // (MaxParallelChains should always remain as failsafe).
4611     if (ChainI == MaxParallelChains) {
4612       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4613       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4614                                   ArrayRef(Chains.data(), ChainI));
4615       Root = Chain;
4616       ChainI = 0;
4617     }
4618 
4619     // TODO: MachinePointerInfo only supports a fixed length offset.
4620     MachinePointerInfo PtrInfo =
4621         !Offsets[i].isScalable() || Offsets[i].isZero()
4622             ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue())
4623             : MachinePointerInfo();
4624 
4625     SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4626     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment,
4627                             MMOFlags, AAInfo, Ranges);
4628     Chains[ChainI] = L.getValue(1);
4629 
4630     if (MemVTs[i] != ValueVTs[i])
4631       L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]);
4632 
4633     Values[i] = L;
4634   }
4635 
4636   if (!ConstantMemory) {
4637     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4638                                 ArrayRef(Chains.data(), ChainI));
4639     if (isVolatile)
4640       DAG.setRoot(Chain);
4641     else
4642       PendingLoads.push_back(Chain);
4643   }
4644 
4645   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4646                            DAG.getVTList(ValueVTs), Values));
4647 }
4648 
4649 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4650   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4651          "call visitStoreToSwiftError when backend supports swifterror");
4652 
4653   SmallVector<EVT, 4> ValueVTs;
4654   SmallVector<uint64_t, 4> Offsets;
4655   const Value *SrcV = I.getOperand(0);
4656   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4657                   SrcV->getType(), ValueVTs, &Offsets, 0);
4658   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4659          "expect a single EVT for swifterror");
4660 
4661   SDValue Src = getValue(SrcV);
4662   // Create a virtual register, then update the virtual register.
4663   Register VReg =
4664       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4665   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4666   // Chain can be getRoot or getControlRoot.
4667   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4668                                       SDValue(Src.getNode(), Src.getResNo()));
4669   DAG.setRoot(CopyNode);
4670 }
4671 
4672 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4673   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4674          "call visitLoadFromSwiftError when backend supports swifterror");
4675 
4676   assert(!I.isVolatile() &&
4677          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4678          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4679          "Support volatile, non temporal, invariant for load_from_swift_error");
4680 
4681   const Value *SV = I.getOperand(0);
4682   Type *Ty = I.getType();
4683   assert(
4684       (!AA ||
4685        !AA->pointsToConstantMemory(MemoryLocation(
4686            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4687            I.getAAMetadata()))) &&
4688       "load_from_swift_error should not be constant memory");
4689 
4690   SmallVector<EVT, 4> ValueVTs;
4691   SmallVector<uint64_t, 4> Offsets;
4692   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4693                   ValueVTs, &Offsets, 0);
4694   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4695          "expect a single EVT for swifterror");
4696 
4697   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4698   SDValue L = DAG.getCopyFromReg(
4699       getRoot(), getCurSDLoc(),
4700       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4701 
4702   setValue(&I, L);
4703 }
4704 
4705 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4706   if (I.isAtomic())
4707     return visitAtomicStore(I);
4708 
4709   const Value *SrcV = I.getOperand(0);
4710   const Value *PtrV = I.getOperand(1);
4711 
4712   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4713   if (TLI.supportSwiftError()) {
4714     // Swifterror values can come from either a function parameter with
4715     // swifterror attribute or an alloca with swifterror attribute.
4716     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4717       if (Arg->hasSwiftErrorAttr())
4718         return visitStoreToSwiftError(I);
4719     }
4720 
4721     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4722       if (Alloca->isSwiftError())
4723         return visitStoreToSwiftError(I);
4724     }
4725   }
4726 
4727   SmallVector<EVT, 4> ValueVTs, MemVTs;
4728   SmallVector<TypeSize, 4> Offsets;
4729   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4730                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4731   unsigned NumValues = ValueVTs.size();
4732   if (NumValues == 0)
4733     return;
4734 
4735   // Get the lowered operands. Note that we do this after
4736   // checking if NumResults is zero, because with zero results
4737   // the operands won't have values in the map.
4738   SDValue Src = getValue(SrcV);
4739   SDValue Ptr = getValue(PtrV);
4740 
4741   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4742   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4743   SDLoc dl = getCurSDLoc();
4744   Align Alignment = I.getAlign();
4745   AAMDNodes AAInfo = I.getAAMetadata();
4746 
4747   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4748 
4749   unsigned ChainI = 0;
4750   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4751     // See visitLoad comments.
4752     if (ChainI == MaxParallelChains) {
4753       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4754                                   ArrayRef(Chains.data(), ChainI));
4755       Root = Chain;
4756       ChainI = 0;
4757     }
4758 
4759     // TODO: MachinePointerInfo only supports a fixed length offset.
4760     MachinePointerInfo PtrInfo =
4761         !Offsets[i].isScalable() || Offsets[i].isZero()
4762             ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue())
4763             : MachinePointerInfo();
4764 
4765     SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4766     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4767     if (MemVTs[i] != ValueVTs[i])
4768       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4769     SDValue St =
4770         DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags, AAInfo);
4771     Chains[ChainI] = St;
4772   }
4773 
4774   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4775                                   ArrayRef(Chains.data(), ChainI));
4776   setValue(&I, StoreNode);
4777   DAG.setRoot(StoreNode);
4778 }
4779 
4780 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4781                                            bool IsCompressing) {
4782   SDLoc sdl = getCurSDLoc();
4783 
4784   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4785                                Align &Alignment) {
4786     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4787     Src0 = I.getArgOperand(0);
4788     Ptr = I.getArgOperand(1);
4789     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getAlignValue();
4790     Mask = I.getArgOperand(3);
4791   };
4792   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4793                                     Align &Alignment) {
4794     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4795     Src0 = I.getArgOperand(0);
4796     Ptr = I.getArgOperand(1);
4797     Mask = I.getArgOperand(2);
4798     Alignment = I.getParamAlign(1).valueOrOne();
4799   };
4800 
4801   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4802   Align Alignment;
4803   if (IsCompressing)
4804     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4805   else
4806     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4807 
4808   SDValue Ptr = getValue(PtrOperand);
4809   SDValue Src0 = getValue(Src0Operand);
4810   SDValue Mask = getValue(MaskOperand);
4811   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4812 
4813   EVT VT = Src0.getValueType();
4814 
4815   auto MMOFlags = MachineMemOperand::MOStore;
4816   if (I.hasMetadata(LLVMContext::MD_nontemporal))
4817     MMOFlags |= MachineMemOperand::MONonTemporal;
4818 
4819   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4820       MachinePointerInfo(PtrOperand), MMOFlags,
4821       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata());
4822 
4823   const auto &TLI = DAG.getTargetLoweringInfo();
4824   const auto &TTI =
4825       TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction());
4826   SDValue StoreNode =
4827       !IsCompressing &&
4828               TTI.hasConditionalLoadStoreForType(I.getArgOperand(0)->getType())
4829           ? TLI.visitMaskedStore(DAG, sdl, getMemoryRoot(), MMO, Ptr, Src0,
4830                                  Mask)
4831           : DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask,
4832                                VT, MMO, ISD::UNINDEXED, /*Truncating=*/false,
4833                                IsCompressing);
4834   DAG.setRoot(StoreNode);
4835   setValue(&I, StoreNode);
4836 }
4837 
4838 // Get a uniform base for the Gather/Scatter intrinsic.
4839 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4840 // We try to represent it as a base pointer + vector of indices.
4841 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4842 // The first operand of the GEP may be a single pointer or a vector of pointers
4843 // Example:
4844 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4845 //  or
4846 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4847 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4848 //
4849 // When the first GEP operand is a single pointer - it is the uniform base we
4850 // are looking for. If first operand of the GEP is a splat vector - we
4851 // extract the splat value and use it as a uniform base.
4852 // In all other cases the function returns 'false'.
4853 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4854                            ISD::MemIndexType &IndexType, SDValue &Scale,
4855                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB,
4856                            uint64_t ElemSize) {
4857   SelectionDAG& DAG = SDB->DAG;
4858   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4859   const DataLayout &DL = DAG.getDataLayout();
4860 
4861   assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4862 
4863   // Handle splat constant pointer.
4864   if (auto *C = dyn_cast<Constant>(Ptr)) {
4865     C = C->getSplatValue();
4866     if (!C)
4867       return false;
4868 
4869     Base = SDB->getValue(C);
4870 
4871     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4872     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4873     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4874     IndexType = ISD::SIGNED_SCALED;
4875     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4876     return true;
4877   }
4878 
4879   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4880   if (!GEP || GEP->getParent() != CurBB)
4881     return false;
4882 
4883   if (GEP->getNumOperands() != 2)
4884     return false;
4885 
4886   const Value *BasePtr = GEP->getPointerOperand();
4887   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4888 
4889   // Make sure the base is scalar and the index is a vector.
4890   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4891     return false;
4892 
4893   TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
4894   if (ScaleVal.isScalable())
4895     return false;
4896 
4897   // Target may not support the required addressing mode.
4898   if (ScaleVal != 1 &&
4899       !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize))
4900     return false;
4901 
4902   Base = SDB->getValue(BasePtr);
4903   Index = SDB->getValue(IndexVal);
4904   IndexType = ISD::SIGNED_SCALED;
4905 
4906   Scale =
4907       DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4908   return true;
4909 }
4910 
4911 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4912   SDLoc sdl = getCurSDLoc();
4913 
4914   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4915   const Value *Ptr = I.getArgOperand(1);
4916   SDValue Src0 = getValue(I.getArgOperand(0));
4917   SDValue Mask = getValue(I.getArgOperand(3));
4918   EVT VT = Src0.getValueType();
4919   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4920                         ->getMaybeAlignValue()
4921                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4922   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4923 
4924   SDValue Base;
4925   SDValue Index;
4926   ISD::MemIndexType IndexType;
4927   SDValue Scale;
4928   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4929                                     I.getParent(), VT.getScalarStoreSize());
4930 
4931   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4932   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4933       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4934       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata());
4935   if (!UniformBase) {
4936     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4937     Index = getValue(Ptr);
4938     IndexType = ISD::SIGNED_SCALED;
4939     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4940   }
4941 
4942   EVT IdxVT = Index.getValueType();
4943   EVT EltTy = IdxVT.getVectorElementType();
4944   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4945     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4946     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4947   }
4948 
4949   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4950   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4951                                          Ops, MMO, IndexType, false);
4952   DAG.setRoot(Scatter);
4953   setValue(&I, Scatter);
4954 }
4955 
4956 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4957   SDLoc sdl = getCurSDLoc();
4958 
4959   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4960                               Align &Alignment) {
4961     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4962     Ptr = I.getArgOperand(0);
4963     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getAlignValue();
4964     Mask = I.getArgOperand(2);
4965     Src0 = I.getArgOperand(3);
4966   };
4967   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4968                                  Align &Alignment) {
4969     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4970     Ptr = I.getArgOperand(0);
4971     Alignment = I.getParamAlign(0).valueOrOne();
4972     Mask = I.getArgOperand(1);
4973     Src0 = I.getArgOperand(2);
4974   };
4975 
4976   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4977   Align Alignment;
4978   if (IsExpanding)
4979     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4980   else
4981     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4982 
4983   SDValue Ptr = getValue(PtrOperand);
4984   SDValue Src0 = getValue(Src0Operand);
4985   SDValue Mask = getValue(MaskOperand);
4986   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4987 
4988   EVT VT = Src0.getValueType();
4989   AAMDNodes AAInfo = I.getAAMetadata();
4990   const MDNode *Ranges = getRangeMetadata(I);
4991 
4992   // Do not serialize masked loads of constant memory with anything.
4993   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
4994   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4995 
4996   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4997 
4998   auto MMOFlags = MachineMemOperand::MOLoad;
4999   if (I.hasMetadata(LLVMContext::MD_nontemporal))
5000     MMOFlags |= MachineMemOperand::MONonTemporal;
5001 
5002   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5003       MachinePointerInfo(PtrOperand), MMOFlags,
5004       LocationSize::beforeOrAfterPointer(), Alignment, AAInfo, Ranges);
5005 
5006   const auto &TLI = DAG.getTargetLoweringInfo();
5007   const auto &TTI =
5008       TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction());
5009   // The Load/Res may point to different values and both of them are output
5010   // variables.
5011   SDValue Load;
5012   SDValue Res;
5013   if (!IsExpanding &&
5014       TTI.hasConditionalLoadStoreForType(Src0Operand->getType()))
5015     Res = TLI.visitMaskedLoad(DAG, sdl, InChain, MMO, Load, Ptr, Src0, Mask);
5016   else
5017     Res = Load =
5018         DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
5019                           ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
5020   if (AddToChain)
5021     PendingLoads.push_back(Load.getValue(1));
5022   setValue(&I, Res);
5023 }
5024 
5025 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
5026   SDLoc sdl = getCurSDLoc();
5027 
5028   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
5029   const Value *Ptr = I.getArgOperand(0);
5030   SDValue Src0 = getValue(I.getArgOperand(3));
5031   SDValue Mask = getValue(I.getArgOperand(2));
5032 
5033   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5034   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5035   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
5036                         ->getMaybeAlignValue()
5037                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
5038 
5039   const MDNode *Ranges = getRangeMetadata(I);
5040 
5041   SDValue Root = DAG.getRoot();
5042   SDValue Base;
5043   SDValue Index;
5044   ISD::MemIndexType IndexType;
5045   SDValue Scale;
5046   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
5047                                     I.getParent(), VT.getScalarStoreSize());
5048   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
5049   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5050       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
5051       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata(),
5052       Ranges);
5053 
5054   if (!UniformBase) {
5055     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5056     Index = getValue(Ptr);
5057     IndexType = ISD::SIGNED_SCALED;
5058     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5059   }
5060 
5061   EVT IdxVT = Index.getValueType();
5062   EVT EltTy = IdxVT.getVectorElementType();
5063   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
5064     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
5065     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
5066   }
5067 
5068   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
5069   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
5070                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
5071 
5072   PendingLoads.push_back(Gather.getValue(1));
5073   setValue(&I, Gather);
5074 }
5075 
5076 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
5077   SDLoc dl = getCurSDLoc();
5078   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
5079   AtomicOrdering FailureOrdering = I.getFailureOrdering();
5080   SyncScope::ID SSID = I.getSyncScopeID();
5081 
5082   SDValue InChain = getRoot();
5083 
5084   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
5085   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
5086 
5087   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5088   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5089 
5090   MachineFunction &MF = DAG.getMachineFunction();
5091   MachineMemOperand *MMO = MF.getMachineMemOperand(
5092       MachinePointerInfo(I.getPointerOperand()), Flags,
5093       LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT),
5094       AAMDNodes(), nullptr, SSID, SuccessOrdering, FailureOrdering);
5095 
5096   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
5097                                    dl, MemVT, VTs, InChain,
5098                                    getValue(I.getPointerOperand()),
5099                                    getValue(I.getCompareOperand()),
5100                                    getValue(I.getNewValOperand()), MMO);
5101 
5102   SDValue OutChain = L.getValue(2);
5103 
5104   setValue(&I, L);
5105   DAG.setRoot(OutChain);
5106 }
5107 
5108 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
5109   SDLoc dl = getCurSDLoc();
5110   ISD::NodeType NT;
5111   switch (I.getOperation()) {
5112   default: llvm_unreachable("Unknown atomicrmw operation");
5113   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
5114   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
5115   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
5116   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
5117   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
5118   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
5119   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
5120   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
5121   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
5122   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
5123   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
5124   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
5125   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
5126   case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break;
5127   case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break;
5128   case AtomicRMWInst::UIncWrap:
5129     NT = ISD::ATOMIC_LOAD_UINC_WRAP;
5130     break;
5131   case AtomicRMWInst::UDecWrap:
5132     NT = ISD::ATOMIC_LOAD_UDEC_WRAP;
5133     break;
5134   case AtomicRMWInst::USubCond:
5135     NT = ISD::ATOMIC_LOAD_USUB_COND;
5136     break;
5137   case AtomicRMWInst::USubSat:
5138     NT = ISD::ATOMIC_LOAD_USUB_SAT;
5139     break;
5140   }
5141   AtomicOrdering Ordering = I.getOrdering();
5142   SyncScope::ID SSID = I.getSyncScopeID();
5143 
5144   SDValue InChain = getRoot();
5145 
5146   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
5147   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5148   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5149 
5150   MachineFunction &MF = DAG.getMachineFunction();
5151   MachineMemOperand *MMO = MF.getMachineMemOperand(
5152       MachinePointerInfo(I.getPointerOperand()), Flags,
5153       LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT),
5154       AAMDNodes(), nullptr, SSID, Ordering);
5155 
5156   SDValue L =
5157     DAG.getAtomic(NT, dl, MemVT, InChain,
5158                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
5159                   MMO);
5160 
5161   SDValue OutChain = L.getValue(1);
5162 
5163   setValue(&I, L);
5164   DAG.setRoot(OutChain);
5165 }
5166 
5167 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
5168   SDLoc dl = getCurSDLoc();
5169   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5170   SDValue Ops[3];
5171   Ops[0] = getRoot();
5172   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
5173                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
5174   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
5175                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
5176   SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
5177   setValue(&I, N);
5178   DAG.setRoot(N);
5179 }
5180 
5181 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
5182   SDLoc dl = getCurSDLoc();
5183   AtomicOrdering Order = I.getOrdering();
5184   SyncScope::ID SSID = I.getSyncScopeID();
5185 
5186   SDValue InChain = getRoot();
5187 
5188   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5189   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5190   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
5191 
5192   if (!TLI.supportsUnalignedAtomics() &&
5193       I.getAlign().value() < MemVT.getSizeInBits() / 8)
5194     report_fatal_error("Cannot generate unaligned atomic load");
5195 
5196   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
5197 
5198   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5199       MachinePointerInfo(I.getPointerOperand()), Flags,
5200       LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(),
5201       nullptr, SSID, Order);
5202 
5203   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
5204 
5205   SDValue Ptr = getValue(I.getPointerOperand());
5206   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
5207                             Ptr, MMO);
5208 
5209   SDValue OutChain = L.getValue(1);
5210   if (MemVT != VT)
5211     L = DAG.getPtrExtOrTrunc(L, dl, VT);
5212 
5213   setValue(&I, L);
5214   DAG.setRoot(OutChain);
5215 }
5216 
5217 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
5218   SDLoc dl = getCurSDLoc();
5219 
5220   AtomicOrdering Ordering = I.getOrdering();
5221   SyncScope::ID SSID = I.getSyncScopeID();
5222 
5223   SDValue InChain = getRoot();
5224 
5225   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5226   EVT MemVT =
5227       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
5228 
5229   if (!TLI.supportsUnalignedAtomics() &&
5230       I.getAlign().value() < MemVT.getSizeInBits() / 8)
5231     report_fatal_error("Cannot generate unaligned atomic store");
5232 
5233   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
5234 
5235   MachineFunction &MF = DAG.getMachineFunction();
5236   MachineMemOperand *MMO = MF.getMachineMemOperand(
5237       MachinePointerInfo(I.getPointerOperand()), Flags,
5238       LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(),
5239       nullptr, SSID, Ordering);
5240 
5241   SDValue Val = getValue(I.getValueOperand());
5242   if (Val.getValueType() != MemVT)
5243     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
5244   SDValue Ptr = getValue(I.getPointerOperand());
5245 
5246   SDValue OutChain =
5247       DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO);
5248 
5249   setValue(&I, OutChain);
5250   DAG.setRoot(OutChain);
5251 }
5252 
5253 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
5254 /// node.
5255 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
5256                                                unsigned Intrinsic) {
5257   // Ignore the callsite's attributes. A specific call site may be marked with
5258   // readnone, but the lowering code will expect the chain based on the
5259   // definition.
5260   const Function *F = I.getCalledFunction();
5261   bool HasChain = !F->doesNotAccessMemory();
5262   bool OnlyLoad =
5263       HasChain && F->onlyReadsMemory() && F->willReturn() && F->doesNotThrow();
5264 
5265   // Build the operand list.
5266   SmallVector<SDValue, 8> Ops;
5267   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
5268     if (OnlyLoad) {
5269       // We don't need to serialize loads against other loads.
5270       Ops.push_back(DAG.getRoot());
5271     } else {
5272       Ops.push_back(getRoot());
5273     }
5274   }
5275 
5276   // Info is set by getTgtMemIntrinsic
5277   TargetLowering::IntrinsicInfo Info;
5278   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5279   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
5280                                                DAG.getMachineFunction(),
5281                                                Intrinsic);
5282 
5283   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
5284   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
5285       Info.opc == ISD::INTRINSIC_W_CHAIN)
5286     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
5287                                         TLI.getPointerTy(DAG.getDataLayout())));
5288 
5289   // Add all operands of the call to the operand list.
5290   for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
5291     const Value *Arg = I.getArgOperand(i);
5292     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
5293       Ops.push_back(getValue(Arg));
5294       continue;
5295     }
5296 
5297     // Use TargetConstant instead of a regular constant for immarg.
5298     EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
5299     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
5300       assert(CI->getBitWidth() <= 64 &&
5301              "large intrinsic immediates not handled");
5302       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
5303     } else {
5304       Ops.push_back(
5305           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
5306     }
5307   }
5308 
5309   SmallVector<EVT, 4> ValueVTs;
5310   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
5311 
5312   if (HasChain)
5313     ValueVTs.push_back(MVT::Other);
5314 
5315   SDVTList VTs = DAG.getVTList(ValueVTs);
5316 
5317   // Propagate fast-math-flags from IR to node(s).
5318   SDNodeFlags Flags;
5319   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
5320     Flags.copyFMF(*FPMO);
5321   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
5322 
5323   // Create the node.
5324   SDValue Result;
5325 
5326   if (auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl)) {
5327     auto *Token = Bundle->Inputs[0].get();
5328     SDValue ConvControlToken = getValue(Token);
5329     assert(Ops.back().getValueType() != MVT::Glue &&
5330            "Did not expected another glue node here.");
5331     ConvControlToken =
5332         DAG.getNode(ISD::CONVERGENCECTRL_GLUE, {}, MVT::Glue, ConvControlToken);
5333     Ops.push_back(ConvControlToken);
5334   }
5335 
5336   // In some cases, custom collection of operands from CallInst I may be needed.
5337   TLI.CollectTargetIntrinsicOperands(I, Ops, DAG);
5338   if (IsTgtIntrinsic) {
5339     // This is target intrinsic that touches memory
5340     //
5341     // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic
5342     //       didn't yield anything useful.
5343     MachinePointerInfo MPI;
5344     if (Info.ptrVal)
5345       MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
5346     else if (Info.fallbackAddressSpace)
5347       MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
5348     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops,
5349                                      Info.memVT, MPI, Info.align, Info.flags,
5350                                      Info.size, I.getAAMetadata());
5351   } else if (!HasChain) {
5352     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
5353   } else if (!I.getType()->isVoidTy()) {
5354     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
5355   } else {
5356     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
5357   }
5358 
5359   if (HasChain) {
5360     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
5361     if (OnlyLoad)
5362       PendingLoads.push_back(Chain);
5363     else
5364       DAG.setRoot(Chain);
5365   }
5366 
5367   if (!I.getType()->isVoidTy()) {
5368     if (!isa<VectorType>(I.getType()))
5369       Result = lowerRangeToAssertZExt(DAG, I, Result);
5370 
5371     MaybeAlign Alignment = I.getRetAlign();
5372 
5373     // Insert `assertalign` node if there's an alignment.
5374     if (InsertAssertAlign && Alignment) {
5375       Result =
5376           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
5377     }
5378   }
5379 
5380   setValue(&I, Result);
5381 }
5382 
5383 /// GetSignificand - Get the significand and build it into a floating-point
5384 /// number with exponent of 1:
5385 ///
5386 ///   Op = (Op & 0x007fffff) | 0x3f800000;
5387 ///
5388 /// where Op is the hexadecimal representation of floating point value.
5389 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
5390   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5391                            DAG.getConstant(0x007fffff, dl, MVT::i32));
5392   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
5393                            DAG.getConstant(0x3f800000, dl, MVT::i32));
5394   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
5395 }
5396 
5397 /// GetExponent - Get the exponent:
5398 ///
5399 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
5400 ///
5401 /// where Op is the hexadecimal representation of floating point value.
5402 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
5403                            const TargetLowering &TLI, const SDLoc &dl) {
5404   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5405                            DAG.getConstant(0x7f800000, dl, MVT::i32));
5406   SDValue t1 = DAG.getNode(
5407       ISD::SRL, dl, MVT::i32, t0,
5408       DAG.getConstant(23, dl,
5409                       TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout())));
5410   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
5411                            DAG.getConstant(127, dl, MVT::i32));
5412   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
5413 }
5414 
5415 /// getF32Constant - Get 32-bit floating point constant.
5416 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
5417                               const SDLoc &dl) {
5418   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
5419                            MVT::f32);
5420 }
5421 
5422 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
5423                                        SelectionDAG &DAG) {
5424   // TODO: What fast-math-flags should be set on the floating-point nodes?
5425 
5426   //   IntegerPartOfX = ((int32_t)(t0);
5427   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
5428 
5429   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
5430   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
5431   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
5432 
5433   //   IntegerPartOfX <<= 23;
5434   IntegerPartOfX =
5435       DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
5436                   DAG.getConstant(23, dl,
5437                                   DAG.getTargetLoweringInfo().getShiftAmountTy(
5438                                       MVT::i32, DAG.getDataLayout())));
5439 
5440   SDValue TwoToFractionalPartOfX;
5441   if (LimitFloatPrecision <= 6) {
5442     // For floating-point precision of 6:
5443     //
5444     //   TwoToFractionalPartOfX =
5445     //     0.997535578f +
5446     //       (0.735607626f + 0.252464424f * x) * x;
5447     //
5448     // error 0.0144103317, which is 6 bits
5449     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5450                              getF32Constant(DAG, 0x3e814304, dl));
5451     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5452                              getF32Constant(DAG, 0x3f3c50c8, dl));
5453     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5454     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5455                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
5456   } else if (LimitFloatPrecision <= 12) {
5457     // For floating-point precision of 12:
5458     //
5459     //   TwoToFractionalPartOfX =
5460     //     0.999892986f +
5461     //       (0.696457318f +
5462     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
5463     //
5464     // error 0.000107046256, which is 13 to 14 bits
5465     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5466                              getF32Constant(DAG, 0x3da235e3, dl));
5467     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5468                              getF32Constant(DAG, 0x3e65b8f3, dl));
5469     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5470     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5471                              getF32Constant(DAG, 0x3f324b07, dl));
5472     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5473     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5474                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
5475   } else { // LimitFloatPrecision <= 18
5476     // For floating-point precision of 18:
5477     //
5478     //   TwoToFractionalPartOfX =
5479     //     0.999999982f +
5480     //       (0.693148872f +
5481     //         (0.240227044f +
5482     //           (0.554906021e-1f +
5483     //             (0.961591928e-2f +
5484     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5485     // error 2.47208000*10^(-7), which is better than 18 bits
5486     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5487                              getF32Constant(DAG, 0x3924b03e, dl));
5488     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5489                              getF32Constant(DAG, 0x3ab24b87, dl));
5490     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5491     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5492                              getF32Constant(DAG, 0x3c1d8c17, dl));
5493     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5494     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5495                              getF32Constant(DAG, 0x3d634a1d, dl));
5496     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5497     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5498                              getF32Constant(DAG, 0x3e75fe14, dl));
5499     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5500     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5501                               getF32Constant(DAG, 0x3f317234, dl));
5502     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5503     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5504                                          getF32Constant(DAG, 0x3f800000, dl));
5505   }
5506 
5507   // Add the exponent into the result in integer domain.
5508   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5509   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5510                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5511 }
5512 
5513 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5514 /// limited-precision mode.
5515 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5516                          const TargetLowering &TLI, SDNodeFlags Flags) {
5517   if (Op.getValueType() == MVT::f32 &&
5518       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5519 
5520     // Put the exponent in the right bit position for later addition to the
5521     // final result:
5522     //
5523     // t0 = Op * log2(e)
5524 
5525     // TODO: What fast-math-flags should be set here?
5526     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5527                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5528     return getLimitedPrecisionExp2(t0, dl, DAG);
5529   }
5530 
5531   // No special expansion.
5532   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5533 }
5534 
5535 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5536 /// limited-precision mode.
5537 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5538                          const TargetLowering &TLI, SDNodeFlags Flags) {
5539   // TODO: What fast-math-flags should be set on the floating-point nodes?
5540 
5541   if (Op.getValueType() == MVT::f32 &&
5542       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5543     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5544 
5545     // Scale the exponent by log(2).
5546     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5547     SDValue LogOfExponent =
5548         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5549                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5550 
5551     // Get the significand and build it into a floating-point number with
5552     // exponent of 1.
5553     SDValue X = GetSignificand(DAG, Op1, dl);
5554 
5555     SDValue LogOfMantissa;
5556     if (LimitFloatPrecision <= 6) {
5557       // For floating-point precision of 6:
5558       //
5559       //   LogofMantissa =
5560       //     -1.1609546f +
5561       //       (1.4034025f - 0.23903021f * x) * x;
5562       //
5563       // error 0.0034276066, which is better than 8 bits
5564       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5565                                getF32Constant(DAG, 0xbe74c456, dl));
5566       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5567                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5568       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5569       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5570                                   getF32Constant(DAG, 0x3f949a29, dl));
5571     } else if (LimitFloatPrecision <= 12) {
5572       // For floating-point precision of 12:
5573       //
5574       //   LogOfMantissa =
5575       //     -1.7417939f +
5576       //       (2.8212026f +
5577       //         (-1.4699568f +
5578       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5579       //
5580       // error 0.000061011436, which is 14 bits
5581       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5582                                getF32Constant(DAG, 0xbd67b6d6, dl));
5583       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5584                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5585       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5586       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5587                                getF32Constant(DAG, 0x3fbc278b, dl));
5588       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5589       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5590                                getF32Constant(DAG, 0x40348e95, dl));
5591       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5592       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5593                                   getF32Constant(DAG, 0x3fdef31a, dl));
5594     } else { // LimitFloatPrecision <= 18
5595       // For floating-point precision of 18:
5596       //
5597       //   LogOfMantissa =
5598       //     -2.1072184f +
5599       //       (4.2372794f +
5600       //         (-3.7029485f +
5601       //           (2.2781945f +
5602       //             (-0.87823314f +
5603       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5604       //
5605       // error 0.0000023660568, which is better than 18 bits
5606       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5607                                getF32Constant(DAG, 0xbc91e5ac, dl));
5608       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5609                                getF32Constant(DAG, 0x3e4350aa, dl));
5610       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5611       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5612                                getF32Constant(DAG, 0x3f60d3e3, dl));
5613       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5614       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5615                                getF32Constant(DAG, 0x4011cdf0, dl));
5616       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5617       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5618                                getF32Constant(DAG, 0x406cfd1c, dl));
5619       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5620       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5621                                getF32Constant(DAG, 0x408797cb, dl));
5622       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5623       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5624                                   getF32Constant(DAG, 0x4006dcab, dl));
5625     }
5626 
5627     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5628   }
5629 
5630   // No special expansion.
5631   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5632 }
5633 
5634 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5635 /// limited-precision mode.
5636 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5637                           const TargetLowering &TLI, SDNodeFlags Flags) {
5638   // TODO: What fast-math-flags should be set on the floating-point nodes?
5639 
5640   if (Op.getValueType() == MVT::f32 &&
5641       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5642     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5643 
5644     // Get the exponent.
5645     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5646 
5647     // Get the significand and build it into a floating-point number with
5648     // exponent of 1.
5649     SDValue X = GetSignificand(DAG, Op1, dl);
5650 
5651     // Different possible minimax approximations of significand in
5652     // floating-point for various degrees of accuracy over [1,2].
5653     SDValue Log2ofMantissa;
5654     if (LimitFloatPrecision <= 6) {
5655       // For floating-point precision of 6:
5656       //
5657       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5658       //
5659       // error 0.0049451742, which is more than 7 bits
5660       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5661                                getF32Constant(DAG, 0xbeb08fe0, dl));
5662       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5663                                getF32Constant(DAG, 0x40019463, dl));
5664       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5665       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5666                                    getF32Constant(DAG, 0x3fd6633d, dl));
5667     } else if (LimitFloatPrecision <= 12) {
5668       // For floating-point precision of 12:
5669       //
5670       //   Log2ofMantissa =
5671       //     -2.51285454f +
5672       //       (4.07009056f +
5673       //         (-2.12067489f +
5674       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5675       //
5676       // error 0.0000876136000, which is better than 13 bits
5677       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5678                                getF32Constant(DAG, 0xbda7262e, dl));
5679       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5680                                getF32Constant(DAG, 0x3f25280b, dl));
5681       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5682       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5683                                getF32Constant(DAG, 0x4007b923, dl));
5684       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5685       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5686                                getF32Constant(DAG, 0x40823e2f, dl));
5687       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5688       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5689                                    getF32Constant(DAG, 0x4020d29c, dl));
5690     } else { // LimitFloatPrecision <= 18
5691       // For floating-point precision of 18:
5692       //
5693       //   Log2ofMantissa =
5694       //     -3.0400495f +
5695       //       (6.1129976f +
5696       //         (-5.3420409f +
5697       //           (3.2865683f +
5698       //             (-1.2669343f +
5699       //               (0.27515199f -
5700       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5701       //
5702       // error 0.0000018516, which is better than 18 bits
5703       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5704                                getF32Constant(DAG, 0xbcd2769e, dl));
5705       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5706                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5707       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5708       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5709                                getF32Constant(DAG, 0x3fa22ae7, dl));
5710       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5711       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5712                                getF32Constant(DAG, 0x40525723, dl));
5713       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5714       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5715                                getF32Constant(DAG, 0x40aaf200, dl));
5716       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5717       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5718                                getF32Constant(DAG, 0x40c39dad, dl));
5719       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5720       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5721                                    getF32Constant(DAG, 0x4042902c, dl));
5722     }
5723 
5724     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5725   }
5726 
5727   // No special expansion.
5728   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5729 }
5730 
5731 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5732 /// limited-precision mode.
5733 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5734                            const TargetLowering &TLI, SDNodeFlags Flags) {
5735   // TODO: What fast-math-flags should be set on the floating-point nodes?
5736 
5737   if (Op.getValueType() == MVT::f32 &&
5738       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5739     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5740 
5741     // Scale the exponent by log10(2) [0.30102999f].
5742     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5743     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5744                                         getF32Constant(DAG, 0x3e9a209a, dl));
5745 
5746     // Get the significand and build it into a floating-point number with
5747     // exponent of 1.
5748     SDValue X = GetSignificand(DAG, Op1, dl);
5749 
5750     SDValue Log10ofMantissa;
5751     if (LimitFloatPrecision <= 6) {
5752       // For floating-point precision of 6:
5753       //
5754       //   Log10ofMantissa =
5755       //     -0.50419619f +
5756       //       (0.60948995f - 0.10380950f * x) * x;
5757       //
5758       // error 0.0014886165, which is 6 bits
5759       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5760                                getF32Constant(DAG, 0xbdd49a13, dl));
5761       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5762                                getF32Constant(DAG, 0x3f1c0789, dl));
5763       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5764       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5765                                     getF32Constant(DAG, 0x3f011300, dl));
5766     } else if (LimitFloatPrecision <= 12) {
5767       // For floating-point precision of 12:
5768       //
5769       //   Log10ofMantissa =
5770       //     -0.64831180f +
5771       //       (0.91751397f +
5772       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5773       //
5774       // error 0.00019228036, which is better than 12 bits
5775       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5776                                getF32Constant(DAG, 0x3d431f31, dl));
5777       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5778                                getF32Constant(DAG, 0x3ea21fb2, dl));
5779       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5780       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5781                                getF32Constant(DAG, 0x3f6ae232, dl));
5782       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5783       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5784                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5785     } else { // LimitFloatPrecision <= 18
5786       // For floating-point precision of 18:
5787       //
5788       //   Log10ofMantissa =
5789       //     -0.84299375f +
5790       //       (1.5327582f +
5791       //         (-1.0688956f +
5792       //           (0.49102474f +
5793       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5794       //
5795       // error 0.0000037995730, which is better than 18 bits
5796       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5797                                getF32Constant(DAG, 0x3c5d51ce, dl));
5798       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5799                                getF32Constant(DAG, 0x3e00685a, dl));
5800       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5801       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5802                                getF32Constant(DAG, 0x3efb6798, dl));
5803       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5804       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5805                                getF32Constant(DAG, 0x3f88d192, dl));
5806       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5807       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5808                                getF32Constant(DAG, 0x3fc4316c, dl));
5809       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5810       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5811                                     getF32Constant(DAG, 0x3f57ce70, dl));
5812     }
5813 
5814     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5815   }
5816 
5817   // No special expansion.
5818   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5819 }
5820 
5821 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5822 /// limited-precision mode.
5823 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5824                           const TargetLowering &TLI, SDNodeFlags Flags) {
5825   if (Op.getValueType() == MVT::f32 &&
5826       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5827     return getLimitedPrecisionExp2(Op, dl, DAG);
5828 
5829   // No special expansion.
5830   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5831 }
5832 
5833 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5834 /// limited-precision mode with x == 10.0f.
5835 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5836                          SelectionDAG &DAG, const TargetLowering &TLI,
5837                          SDNodeFlags Flags) {
5838   bool IsExp10 = false;
5839   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5840       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5841     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5842       APFloat Ten(10.0f);
5843       IsExp10 = LHSC->isExactlyValue(Ten);
5844     }
5845   }
5846 
5847   // TODO: What fast-math-flags should be set on the FMUL node?
5848   if (IsExp10) {
5849     // Put the exponent in the right bit position for later addition to the
5850     // final result:
5851     //
5852     //   #define LOG2OF10 3.3219281f
5853     //   t0 = Op * LOG2OF10;
5854     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5855                              getF32Constant(DAG, 0x40549a78, dl));
5856     return getLimitedPrecisionExp2(t0, dl, DAG);
5857   }
5858 
5859   // No special expansion.
5860   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5861 }
5862 
5863 /// ExpandPowI - Expand a llvm.powi intrinsic.
5864 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5865                           SelectionDAG &DAG) {
5866   // If RHS is a constant, we can expand this out to a multiplication tree if
5867   // it's beneficial on the target, otherwise we end up lowering to a call to
5868   // __powidf2 (for example).
5869   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5870     unsigned Val = RHSC->getSExtValue();
5871 
5872     // powi(x, 0) -> 1.0
5873     if (Val == 0)
5874       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5875 
5876     if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI(
5877             Val, DAG.shouldOptForSize())) {
5878       // Get the exponent as a positive value.
5879       if ((int)Val < 0)
5880         Val = -Val;
5881       // We use the simple binary decomposition method to generate the multiply
5882       // sequence.  There are more optimal ways to do this (for example,
5883       // powi(x,15) generates one more multiply than it should), but this has
5884       // the benefit of being both really simple and much better than a libcall.
5885       SDValue Res; // Logically starts equal to 1.0
5886       SDValue CurSquare = LHS;
5887       // TODO: Intrinsics should have fast-math-flags that propagate to these
5888       // nodes.
5889       while (Val) {
5890         if (Val & 1) {
5891           if (Res.getNode())
5892             Res =
5893                 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
5894           else
5895             Res = CurSquare; // 1.0*CurSquare.
5896         }
5897 
5898         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5899                                 CurSquare, CurSquare);
5900         Val >>= 1;
5901       }
5902 
5903       // If the original was negative, invert the result, producing 1/(x*x*x).
5904       if (RHSC->getSExtValue() < 0)
5905         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5906                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5907       return Res;
5908     }
5909   }
5910 
5911   // Otherwise, expand to a libcall.
5912   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5913 }
5914 
5915 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5916                             SDValue LHS, SDValue RHS, SDValue Scale,
5917                             SelectionDAG &DAG, const TargetLowering &TLI) {
5918   EVT VT = LHS.getValueType();
5919   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5920   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5921   LLVMContext &Ctx = *DAG.getContext();
5922 
5923   // If the type is legal but the operation isn't, this node might survive all
5924   // the way to operation legalization. If we end up there and we do not have
5925   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5926   // node.
5927 
5928   // Coax the legalizer into expanding the node during type legalization instead
5929   // by bumping the size by one bit. This will force it to Promote, enabling the
5930   // early expansion and avoiding the need to expand later.
5931 
5932   // We don't have to do this if Scale is 0; that can always be expanded, unless
5933   // it's a saturating signed operation. Those can experience true integer
5934   // division overflow, a case which we must avoid.
5935 
5936   // FIXME: We wouldn't have to do this (or any of the early
5937   // expansion/promotion) if it was possible to expand a libcall of an
5938   // illegal type during operation legalization. But it's not, so things
5939   // get a bit hacky.
5940   unsigned ScaleInt = Scale->getAsZExtVal();
5941   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5942       (TLI.isTypeLegal(VT) ||
5943        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5944     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5945         Opcode, VT, ScaleInt);
5946     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5947       EVT PromVT;
5948       if (VT.isScalarInteger())
5949         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5950       else if (VT.isVector()) {
5951         PromVT = VT.getVectorElementType();
5952         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5953         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5954       } else
5955         llvm_unreachable("Wrong VT for DIVFIX?");
5956       LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT);
5957       RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT);
5958       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5959       // For saturating operations, we need to shift up the LHS to get the
5960       // proper saturation width, and then shift down again afterwards.
5961       if (Saturating)
5962         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5963                           DAG.getConstant(1, DL, ShiftTy));
5964       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5965       if (Saturating)
5966         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5967                           DAG.getConstant(1, DL, ShiftTy));
5968       return DAG.getZExtOrTrunc(Res, DL, VT);
5969     }
5970   }
5971 
5972   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5973 }
5974 
5975 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5976 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5977 static void
5978 getUnderlyingArgRegs(SmallVectorImpl<std::pair<Register, TypeSize>> &Regs,
5979                      const SDValue &N) {
5980   switch (N.getOpcode()) {
5981   case ISD::CopyFromReg: {
5982     SDValue Op = N.getOperand(1);
5983     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5984                       Op.getValueType().getSizeInBits());
5985     return;
5986   }
5987   case ISD::BITCAST:
5988   case ISD::AssertZext:
5989   case ISD::AssertSext:
5990   case ISD::TRUNCATE:
5991     getUnderlyingArgRegs(Regs, N.getOperand(0));
5992     return;
5993   case ISD::BUILD_PAIR:
5994   case ISD::BUILD_VECTOR:
5995   case ISD::CONCAT_VECTORS:
5996     for (SDValue Op : N->op_values())
5997       getUnderlyingArgRegs(Regs, Op);
5998     return;
5999   default:
6000     return;
6001   }
6002 }
6003 
6004 /// If the DbgValueInst is a dbg_value of a function argument, create the
6005 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
6006 /// instruction selection, they will be inserted to the entry BB.
6007 /// We don't currently support this for variadic dbg_values, as they shouldn't
6008 /// appear for function arguments or in the prologue.
6009 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
6010     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
6011     DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
6012   const Argument *Arg = dyn_cast<Argument>(V);
6013   if (!Arg)
6014     return false;
6015 
6016   MachineFunction &MF = DAG.getMachineFunction();
6017   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6018 
6019   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
6020   // we've been asked to pursue.
6021   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
6022                               bool Indirect) {
6023     if (Reg.isVirtual() && MF.useDebugInstrRef()) {
6024       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
6025       // pointing at the VReg, which will be patched up later.
6026       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
6027       SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg(
6028           /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
6029           /* isKill */ false, /* isDead */ false,
6030           /* isUndef */ false, /* isEarlyClobber */ false,
6031           /* SubReg */ 0, /* isDebug */ true)});
6032 
6033       auto *NewDIExpr = FragExpr;
6034       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
6035       // the DIExpression.
6036       if (Indirect)
6037         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
6038       SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0});
6039       NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops);
6040       return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr);
6041     } else {
6042       // Create a completely standard DBG_VALUE.
6043       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
6044       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
6045     }
6046   };
6047 
6048   if (Kind == FuncArgumentDbgValueKind::Value) {
6049     // ArgDbgValues are hoisted to the beginning of the entry block. So we
6050     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
6051     // the entry block.
6052     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
6053     if (!IsInEntryBlock)
6054       return false;
6055 
6056     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
6057     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
6058     // variable that also is a param.
6059     //
6060     // Although, if we are at the top of the entry block already, we can still
6061     // emit using ArgDbgValue. This might catch some situations when the
6062     // dbg.value refers to an argument that isn't used in the entry block, so
6063     // any CopyToReg node would be optimized out and the only way to express
6064     // this DBG_VALUE is by using the physical reg (or FI) as done in this
6065     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
6066     // we should only emit as ArgDbgValue if the Variable is an argument to the
6067     // current function, and the dbg.value intrinsic is found in the entry
6068     // block.
6069     bool VariableIsFunctionInputArg = Variable->isParameter() &&
6070         !DL->getInlinedAt();
6071     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
6072     if (!IsInPrologue && !VariableIsFunctionInputArg)
6073       return false;
6074 
6075     // Here we assume that a function argument on IR level only can be used to
6076     // describe one input parameter on source level. If we for example have
6077     // source code like this
6078     //
6079     //    struct A { long x, y; };
6080     //    void foo(struct A a, long b) {
6081     //      ...
6082     //      b = a.x;
6083     //      ...
6084     //    }
6085     //
6086     // and IR like this
6087     //
6088     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
6089     //  entry:
6090     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
6091     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
6092     //    call void @llvm.dbg.value(metadata i32 %b, "b",
6093     //    ...
6094     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
6095     //    ...
6096     //
6097     // then the last dbg.value is describing a parameter "b" using a value that
6098     // is an argument. But since we already has used %a1 to describe a parameter
6099     // we should not handle that last dbg.value here (that would result in an
6100     // incorrect hoisting of the DBG_VALUE to the function entry).
6101     // Notice that we allow one dbg.value per IR level argument, to accommodate
6102     // for the situation with fragments above.
6103     // If there is no node for the value being handled, we return true to skip
6104     // the normal generation of debug info, as it would kill existing debug
6105     // info for the parameter in case of duplicates.
6106     if (VariableIsFunctionInputArg) {
6107       unsigned ArgNo = Arg->getArgNo();
6108       if (ArgNo >= FuncInfo.DescribedArgs.size())
6109         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
6110       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
6111         return !NodeMap[V].getNode();
6112       FuncInfo.DescribedArgs.set(ArgNo);
6113     }
6114   }
6115 
6116   bool IsIndirect = false;
6117   std::optional<MachineOperand> Op;
6118   // Some arguments' frame index is recorded during argument lowering.
6119   int FI = FuncInfo.getArgumentFrameIndex(Arg);
6120   if (FI != std::numeric_limits<int>::max())
6121     Op = MachineOperand::CreateFI(FI);
6122 
6123   SmallVector<std::pair<Register, TypeSize>, 8> ArgRegsAndSizes;
6124   if (!Op && N.getNode()) {
6125     getUnderlyingArgRegs(ArgRegsAndSizes, N);
6126     Register Reg;
6127     if (ArgRegsAndSizes.size() == 1)
6128       Reg = ArgRegsAndSizes.front().first;
6129 
6130     if (Reg && Reg.isVirtual()) {
6131       MachineRegisterInfo &RegInfo = MF.getRegInfo();
6132       Register PR = RegInfo.getLiveInPhysReg(Reg);
6133       if (PR)
6134         Reg = PR;
6135     }
6136     if (Reg) {
6137       Op = MachineOperand::CreateReg(Reg, false);
6138       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6139     }
6140   }
6141 
6142   if (!Op && N.getNode()) {
6143     // Check if frame index is available.
6144     SDValue LCandidate = peekThroughBitcasts(N);
6145     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
6146       if (FrameIndexSDNode *FINode =
6147           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
6148         Op = MachineOperand::CreateFI(FINode->getIndex());
6149   }
6150 
6151   if (!Op) {
6152     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
6153     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<Register, TypeSize>>
6154                                          SplitRegs) {
6155       unsigned Offset = 0;
6156       for (const auto &RegAndSize : SplitRegs) {
6157         // If the expression is already a fragment, the current register
6158         // offset+size might extend beyond the fragment. In this case, only
6159         // the register bits that are inside the fragment are relevant.
6160         int RegFragmentSizeInBits = RegAndSize.second;
6161         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
6162           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
6163           // The register is entirely outside the expression fragment,
6164           // so is irrelevant for debug info.
6165           if (Offset >= ExprFragmentSizeInBits)
6166             break;
6167           // The register is partially outside the expression fragment, only
6168           // the low bits within the fragment are relevant for debug info.
6169           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
6170             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
6171           }
6172         }
6173 
6174         auto FragmentExpr = DIExpression::createFragmentExpression(
6175             Expr, Offset, RegFragmentSizeInBits);
6176         Offset += RegAndSize.second;
6177         // If a valid fragment expression cannot be created, the variable's
6178         // correct value cannot be determined and so it is set as Undef.
6179         if (!FragmentExpr) {
6180           SDDbgValue *SDV = DAG.getConstantDbgValue(
6181               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
6182           DAG.AddDbgValue(SDV, false);
6183           continue;
6184         }
6185         MachineInstr *NewMI =
6186             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr,
6187                              Kind != FuncArgumentDbgValueKind::Value);
6188         FuncInfo.ArgDbgValues.push_back(NewMI);
6189       }
6190     };
6191 
6192     // Check if ValueMap has reg number.
6193     DenseMap<const Value *, Register>::const_iterator
6194       VMI = FuncInfo.ValueMap.find(V);
6195     if (VMI != FuncInfo.ValueMap.end()) {
6196       const auto &TLI = DAG.getTargetLoweringInfo();
6197       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
6198                        V->getType(), std::nullopt);
6199       if (RFV.occupiesMultipleRegs()) {
6200         splitMultiRegDbgValue(RFV.getRegsAndSizes());
6201         return true;
6202       }
6203 
6204       Op = MachineOperand::CreateReg(VMI->second, false);
6205       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6206     } else if (ArgRegsAndSizes.size() > 1) {
6207       // This was split due to the calling convention, and no virtual register
6208       // mapping exists for the value.
6209       splitMultiRegDbgValue(ArgRegsAndSizes);
6210       return true;
6211     }
6212   }
6213 
6214   if (!Op)
6215     return false;
6216 
6217   assert(Variable->isValidLocationForIntrinsic(DL) &&
6218          "Expected inlined-at fields to agree");
6219   MachineInstr *NewMI = nullptr;
6220 
6221   if (Op->isReg())
6222     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
6223   else
6224     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
6225                     Variable, Expr);
6226 
6227   // Otherwise, use ArgDbgValues.
6228   FuncInfo.ArgDbgValues.push_back(NewMI);
6229   return true;
6230 }
6231 
6232 /// Return the appropriate SDDbgValue based on N.
6233 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
6234                                              DILocalVariable *Variable,
6235                                              DIExpression *Expr,
6236                                              const DebugLoc &dl,
6237                                              unsigned DbgSDNodeOrder) {
6238   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
6239     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
6240     // stack slot locations.
6241     //
6242     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
6243     // debug values here after optimization:
6244     //
6245     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
6246     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
6247     //
6248     // Both describe the direct values of their associated variables.
6249     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
6250                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6251   }
6252   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
6253                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6254 }
6255 
6256 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
6257   switch (Intrinsic) {
6258   case Intrinsic::smul_fix:
6259     return ISD::SMULFIX;
6260   case Intrinsic::umul_fix:
6261     return ISD::UMULFIX;
6262   case Intrinsic::smul_fix_sat:
6263     return ISD::SMULFIXSAT;
6264   case Intrinsic::umul_fix_sat:
6265     return ISD::UMULFIXSAT;
6266   case Intrinsic::sdiv_fix:
6267     return ISD::SDIVFIX;
6268   case Intrinsic::udiv_fix:
6269     return ISD::UDIVFIX;
6270   case Intrinsic::sdiv_fix_sat:
6271     return ISD::SDIVFIXSAT;
6272   case Intrinsic::udiv_fix_sat:
6273     return ISD::UDIVFIXSAT;
6274   default:
6275     llvm_unreachable("Unhandled fixed point intrinsic");
6276   }
6277 }
6278 
6279 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
6280                                            const char *FunctionName) {
6281   assert(FunctionName && "FunctionName must not be nullptr");
6282   SDValue Callee = DAG.getExternalSymbol(
6283       FunctionName,
6284       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6285   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
6286 }
6287 
6288 /// Given a @llvm.call.preallocated.setup, return the corresponding
6289 /// preallocated call.
6290 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
6291   assert(cast<CallBase>(PreallocatedSetup)
6292                  ->getCalledFunction()
6293                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
6294          "expected call_preallocated_setup Value");
6295   for (const auto *U : PreallocatedSetup->users()) {
6296     auto *UseCall = cast<CallBase>(U);
6297     const Function *Fn = UseCall->getCalledFunction();
6298     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
6299       return UseCall;
6300     }
6301   }
6302   llvm_unreachable("expected corresponding call to preallocated setup/arg");
6303 }
6304 
6305 /// If DI is a debug value with an EntryValue expression, lower it using the
6306 /// corresponding physical register of the associated Argument value
6307 /// (guaranteed to exist by the verifier).
6308 bool SelectionDAGBuilder::visitEntryValueDbgValue(
6309     ArrayRef<const Value *> Values, DILocalVariable *Variable,
6310     DIExpression *Expr, DebugLoc DbgLoc) {
6311   if (!Expr->isEntryValue() || !hasSingleElement(Values))
6312     return false;
6313 
6314   // These properties are guaranteed by the verifier.
6315   const Argument *Arg = cast<Argument>(Values[0]);
6316   assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync));
6317 
6318   auto ArgIt = FuncInfo.ValueMap.find(Arg);
6319   if (ArgIt == FuncInfo.ValueMap.end()) {
6320     LLVM_DEBUG(
6321         dbgs() << "Dropping dbg.value: expression is entry_value but "
6322                   "couldn't find an associated register for the Argument\n");
6323     return true;
6324   }
6325   Register ArgVReg = ArgIt->getSecond();
6326 
6327   for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
6328     if (ArgVReg == VirtReg || ArgVReg == PhysReg) {
6329       SDDbgValue *SDV = DAG.getVRegDbgValue(
6330           Variable, Expr, PhysReg, false /*IsIndidrect*/, DbgLoc, SDNodeOrder);
6331       DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/);
6332       return true;
6333     }
6334   LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but "
6335                        "couldn't find a physical register\n");
6336   return true;
6337 }
6338 
6339 /// Lower the call to the specified intrinsic function.
6340 void SelectionDAGBuilder::visitConvergenceControl(const CallInst &I,
6341                                                   unsigned Intrinsic) {
6342   SDLoc sdl = getCurSDLoc();
6343   switch (Intrinsic) {
6344   case Intrinsic::experimental_convergence_anchor:
6345     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ANCHOR, sdl, MVT::Untyped));
6346     break;
6347   case Intrinsic::experimental_convergence_entry:
6348     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ENTRY, sdl, MVT::Untyped));
6349     break;
6350   case Intrinsic::experimental_convergence_loop: {
6351     auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl);
6352     auto *Token = Bundle->Inputs[0].get();
6353     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_LOOP, sdl, MVT::Untyped,
6354                              getValue(Token)));
6355     break;
6356   }
6357   }
6358 }
6359 
6360 void SelectionDAGBuilder::visitVectorHistogram(const CallInst &I,
6361                                                unsigned IntrinsicID) {
6362   // For now, we're only lowering an 'add' histogram.
6363   // We can add others later, e.g. saturating adds, min/max.
6364   assert(IntrinsicID == Intrinsic::experimental_vector_histogram_add &&
6365          "Tried to lower unsupported histogram type");
6366   SDLoc sdl = getCurSDLoc();
6367   Value *Ptr = I.getOperand(0);
6368   SDValue Inc = getValue(I.getOperand(1));
6369   SDValue Mask = getValue(I.getOperand(2));
6370 
6371   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6372   DataLayout TargetDL = DAG.getDataLayout();
6373   EVT VT = Inc.getValueType();
6374   Align Alignment = DAG.getEVTAlign(VT);
6375 
6376   const MDNode *Ranges = getRangeMetadata(I);
6377 
6378   SDValue Root = DAG.getRoot();
6379   SDValue Base;
6380   SDValue Index;
6381   ISD::MemIndexType IndexType;
6382   SDValue Scale;
6383   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
6384                                     I.getParent(), VT.getScalarStoreSize());
6385 
6386   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
6387 
6388   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6389       MachinePointerInfo(AS),
6390       MachineMemOperand::MOLoad | MachineMemOperand::MOStore,
6391       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
6392 
6393   if (!UniformBase) {
6394     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6395     Index = getValue(Ptr);
6396     IndexType = ISD::SIGNED_SCALED;
6397     Scale =
6398         DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6399   }
6400 
6401   EVT IdxVT = Index.getValueType();
6402   EVT EltTy = IdxVT.getVectorElementType();
6403   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
6404     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
6405     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
6406   }
6407 
6408   SDValue ID = DAG.getTargetConstant(IntrinsicID, sdl, MVT::i32);
6409 
6410   SDValue Ops[] = {Root, Inc, Mask, Base, Index, Scale, ID};
6411   SDValue Histogram = DAG.getMaskedHistogram(DAG.getVTList(MVT::Other), VT, sdl,
6412                                              Ops, MMO, IndexType);
6413 
6414   setValue(&I, Histogram);
6415   DAG.setRoot(Histogram);
6416 }
6417 
6418 /// Lower the call to the specified intrinsic function.
6419 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
6420                                              unsigned Intrinsic) {
6421   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6422   SDLoc sdl = getCurSDLoc();
6423   DebugLoc dl = getCurDebugLoc();
6424   SDValue Res;
6425 
6426   SDNodeFlags Flags;
6427   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
6428     Flags.copyFMF(*FPOp);
6429 
6430   switch (Intrinsic) {
6431   default:
6432     // By default, turn this into a target intrinsic node.
6433     visitTargetIntrinsic(I, Intrinsic);
6434     return;
6435   case Intrinsic::vscale: {
6436     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6437     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
6438     return;
6439   }
6440   case Intrinsic::vastart:  visitVAStart(I); return;
6441   case Intrinsic::vaend:    visitVAEnd(I); return;
6442   case Intrinsic::vacopy:   visitVACopy(I); return;
6443   case Intrinsic::returnaddress:
6444     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
6445                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6446                              getValue(I.getArgOperand(0))));
6447     return;
6448   case Intrinsic::addressofreturnaddress:
6449     setValue(&I,
6450              DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
6451                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6452     return;
6453   case Intrinsic::sponentry:
6454     setValue(&I,
6455              DAG.getNode(ISD::SPONENTRY, sdl,
6456                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6457     return;
6458   case Intrinsic::frameaddress:
6459     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
6460                              TLI.getFrameIndexTy(DAG.getDataLayout()),
6461                              getValue(I.getArgOperand(0))));
6462     return;
6463   case Intrinsic::read_volatile_register:
6464   case Intrinsic::read_register: {
6465     Value *Reg = I.getArgOperand(0);
6466     SDValue Chain = getRoot();
6467     SDValue RegName =
6468         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6469     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6470     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
6471       DAG.getVTList(VT, MVT::Other), Chain, RegName);
6472     setValue(&I, Res);
6473     DAG.setRoot(Res.getValue(1));
6474     return;
6475   }
6476   case Intrinsic::write_register: {
6477     Value *Reg = I.getArgOperand(0);
6478     Value *RegValue = I.getArgOperand(1);
6479     SDValue Chain = getRoot();
6480     SDValue RegName =
6481         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6482     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
6483                             RegName, getValue(RegValue)));
6484     return;
6485   }
6486   case Intrinsic::memcpy: {
6487     const auto &MCI = cast<MemCpyInst>(I);
6488     SDValue Op1 = getValue(I.getArgOperand(0));
6489     SDValue Op2 = getValue(I.getArgOperand(1));
6490     SDValue Op3 = getValue(I.getArgOperand(2));
6491     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
6492     Align DstAlign = MCI.getDestAlign().valueOrOne();
6493     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6494     Align Alignment = std::min(DstAlign, SrcAlign);
6495     bool isVol = MCI.isVolatile();
6496     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6497     // node.
6498     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6499     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6500                                /* AlwaysInline */ false, &I, std::nullopt,
6501                                MachinePointerInfo(I.getArgOperand(0)),
6502                                MachinePointerInfo(I.getArgOperand(1)),
6503                                I.getAAMetadata(), AA);
6504     updateDAGForMaybeTailCall(MC);
6505     return;
6506   }
6507   case Intrinsic::memcpy_inline: {
6508     const auto &MCI = cast<MemCpyInlineInst>(I);
6509     SDValue Dst = getValue(I.getArgOperand(0));
6510     SDValue Src = getValue(I.getArgOperand(1));
6511     SDValue Size = getValue(I.getArgOperand(2));
6512     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
6513     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
6514     Align DstAlign = MCI.getDestAlign().valueOrOne();
6515     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6516     Align Alignment = std::min(DstAlign, SrcAlign);
6517     bool isVol = MCI.isVolatile();
6518     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6519     // node.
6520     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
6521                                /* AlwaysInline */ true, &I, std::nullopt,
6522                                MachinePointerInfo(I.getArgOperand(0)),
6523                                MachinePointerInfo(I.getArgOperand(1)),
6524                                I.getAAMetadata(), AA);
6525     updateDAGForMaybeTailCall(MC);
6526     return;
6527   }
6528   case Intrinsic::memset: {
6529     const auto &MSI = cast<MemSetInst>(I);
6530     SDValue Op1 = getValue(I.getArgOperand(0));
6531     SDValue Op2 = getValue(I.getArgOperand(1));
6532     SDValue Op3 = getValue(I.getArgOperand(2));
6533     // @llvm.memset defines 0 and 1 to both mean no alignment.
6534     Align Alignment = MSI.getDestAlign().valueOrOne();
6535     bool isVol = MSI.isVolatile();
6536     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6537     SDValue MS = DAG.getMemset(
6538         Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false,
6539         &I, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
6540     updateDAGForMaybeTailCall(MS);
6541     return;
6542   }
6543   case Intrinsic::memset_inline: {
6544     const auto &MSII = cast<MemSetInlineInst>(I);
6545     SDValue Dst = getValue(I.getArgOperand(0));
6546     SDValue Value = getValue(I.getArgOperand(1));
6547     SDValue Size = getValue(I.getArgOperand(2));
6548     assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size");
6549     // @llvm.memset defines 0 and 1 to both mean no alignment.
6550     Align DstAlign = MSII.getDestAlign().valueOrOne();
6551     bool isVol = MSII.isVolatile();
6552     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6553     SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol,
6554                                /* AlwaysInline */ true, &I,
6555                                MachinePointerInfo(I.getArgOperand(0)),
6556                                I.getAAMetadata());
6557     updateDAGForMaybeTailCall(MC);
6558     return;
6559   }
6560   case Intrinsic::memmove: {
6561     const auto &MMI = cast<MemMoveInst>(I);
6562     SDValue Op1 = getValue(I.getArgOperand(0));
6563     SDValue Op2 = getValue(I.getArgOperand(1));
6564     SDValue Op3 = getValue(I.getArgOperand(2));
6565     // @llvm.memmove defines 0 and 1 to both mean no alignment.
6566     Align DstAlign = MMI.getDestAlign().valueOrOne();
6567     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
6568     Align Alignment = std::min(DstAlign, SrcAlign);
6569     bool isVol = MMI.isVolatile();
6570     // FIXME: Support passing different dest/src alignments to the memmove DAG
6571     // node.
6572     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6573     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, &I,
6574                                 /* OverrideTailCall */ std::nullopt,
6575                                 MachinePointerInfo(I.getArgOperand(0)),
6576                                 MachinePointerInfo(I.getArgOperand(1)),
6577                                 I.getAAMetadata(), AA);
6578     updateDAGForMaybeTailCall(MM);
6579     return;
6580   }
6581   case Intrinsic::memcpy_element_unordered_atomic: {
6582     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
6583     SDValue Dst = getValue(MI.getRawDest());
6584     SDValue Src = getValue(MI.getRawSource());
6585     SDValue Length = getValue(MI.getLength());
6586 
6587     Type *LengthTy = MI.getLength()->getType();
6588     unsigned ElemSz = MI.getElementSizeInBytes();
6589     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6590     SDValue MC =
6591         DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6592                             isTC, MachinePointerInfo(MI.getRawDest()),
6593                             MachinePointerInfo(MI.getRawSource()));
6594     updateDAGForMaybeTailCall(MC);
6595     return;
6596   }
6597   case Intrinsic::memmove_element_unordered_atomic: {
6598     auto &MI = cast<AtomicMemMoveInst>(I);
6599     SDValue Dst = getValue(MI.getRawDest());
6600     SDValue Src = getValue(MI.getRawSource());
6601     SDValue Length = getValue(MI.getLength());
6602 
6603     Type *LengthTy = MI.getLength()->getType();
6604     unsigned ElemSz = MI.getElementSizeInBytes();
6605     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6606     SDValue MC =
6607         DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6608                              isTC, MachinePointerInfo(MI.getRawDest()),
6609                              MachinePointerInfo(MI.getRawSource()));
6610     updateDAGForMaybeTailCall(MC);
6611     return;
6612   }
6613   case Intrinsic::memset_element_unordered_atomic: {
6614     auto &MI = cast<AtomicMemSetInst>(I);
6615     SDValue Dst = getValue(MI.getRawDest());
6616     SDValue Val = getValue(MI.getValue());
6617     SDValue Length = getValue(MI.getLength());
6618 
6619     Type *LengthTy = MI.getLength()->getType();
6620     unsigned ElemSz = MI.getElementSizeInBytes();
6621     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6622     SDValue MC =
6623         DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
6624                             isTC, MachinePointerInfo(MI.getRawDest()));
6625     updateDAGForMaybeTailCall(MC);
6626     return;
6627   }
6628   case Intrinsic::call_preallocated_setup: {
6629     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
6630     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6631     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
6632                               getRoot(), SrcValue);
6633     setValue(&I, Res);
6634     DAG.setRoot(Res);
6635     return;
6636   }
6637   case Intrinsic::call_preallocated_arg: {
6638     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6639     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6640     SDValue Ops[3];
6641     Ops[0] = getRoot();
6642     Ops[1] = SrcValue;
6643     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6644                                    MVT::i32); // arg index
6645     SDValue Res = DAG.getNode(
6646         ISD::PREALLOCATED_ARG, sdl,
6647         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6648     setValue(&I, Res);
6649     DAG.setRoot(Res.getValue(1));
6650     return;
6651   }
6652   case Intrinsic::dbg_declare: {
6653     const auto &DI = cast<DbgDeclareInst>(I);
6654     // Debug intrinsics are handled separately in assignment tracking mode.
6655     // Some intrinsics are handled right after Argument lowering.
6656     if (AssignmentTrackingEnabled ||
6657         FuncInfo.PreprocessedDbgDeclares.count(&DI))
6658       return;
6659     LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DI << "\n");
6660     DILocalVariable *Variable = DI.getVariable();
6661     DIExpression *Expression = DI.getExpression();
6662     dropDanglingDebugInfo(Variable, Expression);
6663     // Assume dbg.declare can not currently use DIArgList, i.e.
6664     // it is non-variadic.
6665     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6666     handleDebugDeclare(DI.getVariableLocationOp(0), Variable, Expression,
6667                        DI.getDebugLoc());
6668     return;
6669   }
6670   case Intrinsic::dbg_label: {
6671     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6672     DILabel *Label = DI.getLabel();
6673     assert(Label && "Missing label");
6674 
6675     SDDbgLabel *SDV;
6676     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6677     DAG.AddDbgLabel(SDV);
6678     return;
6679   }
6680   case Intrinsic::dbg_assign: {
6681     // Debug intrinsics are handled separately in assignment tracking mode.
6682     if (AssignmentTrackingEnabled)
6683       return;
6684     // If assignment tracking hasn't been enabled then fall through and treat
6685     // the dbg.assign as a dbg.value.
6686     [[fallthrough]];
6687   }
6688   case Intrinsic::dbg_value: {
6689     // Debug intrinsics are handled separately in assignment tracking mode.
6690     if (AssignmentTrackingEnabled)
6691       return;
6692     const DbgValueInst &DI = cast<DbgValueInst>(I);
6693     assert(DI.getVariable() && "Missing variable");
6694 
6695     DILocalVariable *Variable = DI.getVariable();
6696     DIExpression *Expression = DI.getExpression();
6697     dropDanglingDebugInfo(Variable, Expression);
6698 
6699     if (DI.isKillLocation()) {
6700       handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder);
6701       return;
6702     }
6703 
6704     SmallVector<Value *, 4> Values(DI.getValues());
6705     if (Values.empty())
6706       return;
6707 
6708     bool IsVariadic = DI.hasArgList();
6709     if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(),
6710                           SDNodeOrder, IsVariadic))
6711       addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
6712                            DI.getDebugLoc(), SDNodeOrder);
6713     return;
6714   }
6715 
6716   case Intrinsic::eh_typeid_for: {
6717     // Find the type id for the given typeinfo.
6718     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6719     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6720     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6721     setValue(&I, Res);
6722     return;
6723   }
6724 
6725   case Intrinsic::eh_return_i32:
6726   case Intrinsic::eh_return_i64:
6727     DAG.getMachineFunction().setCallsEHReturn(true);
6728     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6729                             MVT::Other,
6730                             getControlRoot(),
6731                             getValue(I.getArgOperand(0)),
6732                             getValue(I.getArgOperand(1))));
6733     return;
6734   case Intrinsic::eh_unwind_init:
6735     DAG.getMachineFunction().setCallsUnwindInit(true);
6736     return;
6737   case Intrinsic::eh_dwarf_cfa:
6738     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6739                              TLI.getPointerTy(DAG.getDataLayout()),
6740                              getValue(I.getArgOperand(0))));
6741     return;
6742   case Intrinsic::eh_sjlj_callsite: {
6743     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
6744     assert(FuncInfo.getCurrentCallSite() == 0 && "Overlapping call sites!");
6745 
6746     FuncInfo.setCurrentCallSite(CI->getZExtValue());
6747     return;
6748   }
6749   case Intrinsic::eh_sjlj_functioncontext: {
6750     // Get and store the index of the function context.
6751     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6752     AllocaInst *FnCtx =
6753       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6754     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6755     MFI.setFunctionContextIndex(FI);
6756     return;
6757   }
6758   case Intrinsic::eh_sjlj_setjmp: {
6759     SDValue Ops[2];
6760     Ops[0] = getRoot();
6761     Ops[1] = getValue(I.getArgOperand(0));
6762     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6763                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6764     setValue(&I, Op.getValue(0));
6765     DAG.setRoot(Op.getValue(1));
6766     return;
6767   }
6768   case Intrinsic::eh_sjlj_longjmp:
6769     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6770                             getRoot(), getValue(I.getArgOperand(0))));
6771     return;
6772   case Intrinsic::eh_sjlj_setup_dispatch:
6773     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6774                             getRoot()));
6775     return;
6776   case Intrinsic::masked_gather:
6777     visitMaskedGather(I);
6778     return;
6779   case Intrinsic::masked_load:
6780     visitMaskedLoad(I);
6781     return;
6782   case Intrinsic::masked_scatter:
6783     visitMaskedScatter(I);
6784     return;
6785   case Intrinsic::masked_store:
6786     visitMaskedStore(I);
6787     return;
6788   case Intrinsic::masked_expandload:
6789     visitMaskedLoad(I, true /* IsExpanding */);
6790     return;
6791   case Intrinsic::masked_compressstore:
6792     visitMaskedStore(I, true /* IsCompressing */);
6793     return;
6794   case Intrinsic::powi:
6795     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6796                             getValue(I.getArgOperand(1)), DAG));
6797     return;
6798   case Intrinsic::log:
6799     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6800     return;
6801   case Intrinsic::log2:
6802     setValue(&I,
6803              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6804     return;
6805   case Intrinsic::log10:
6806     setValue(&I,
6807              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6808     return;
6809   case Intrinsic::exp:
6810     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6811     return;
6812   case Intrinsic::exp2:
6813     setValue(&I,
6814              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6815     return;
6816   case Intrinsic::pow:
6817     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6818                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6819     return;
6820   case Intrinsic::sqrt:
6821   case Intrinsic::fabs:
6822   case Intrinsic::sin:
6823   case Intrinsic::cos:
6824   case Intrinsic::tan:
6825   case Intrinsic::asin:
6826   case Intrinsic::acos:
6827   case Intrinsic::atan:
6828   case Intrinsic::sinh:
6829   case Intrinsic::cosh:
6830   case Intrinsic::tanh:
6831   case Intrinsic::exp10:
6832   case Intrinsic::floor:
6833   case Intrinsic::ceil:
6834   case Intrinsic::trunc:
6835   case Intrinsic::rint:
6836   case Intrinsic::nearbyint:
6837   case Intrinsic::round:
6838   case Intrinsic::roundeven:
6839   case Intrinsic::canonicalize: {
6840     unsigned Opcode;
6841     // clang-format off
6842     switch (Intrinsic) {
6843     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6844     case Intrinsic::sqrt:         Opcode = ISD::FSQRT;         break;
6845     case Intrinsic::fabs:         Opcode = ISD::FABS;          break;
6846     case Intrinsic::sin:          Opcode = ISD::FSIN;          break;
6847     case Intrinsic::cos:          Opcode = ISD::FCOS;          break;
6848     case Intrinsic::tan:          Opcode = ISD::FTAN;          break;
6849     case Intrinsic::asin:         Opcode = ISD::FASIN;         break;
6850     case Intrinsic::acos:         Opcode = ISD::FACOS;         break;
6851     case Intrinsic::atan:         Opcode = ISD::FATAN;         break;
6852     case Intrinsic::sinh:         Opcode = ISD::FSINH;         break;
6853     case Intrinsic::cosh:         Opcode = ISD::FCOSH;         break;
6854     case Intrinsic::tanh:         Opcode = ISD::FTANH;         break;
6855     case Intrinsic::exp10:        Opcode = ISD::FEXP10;        break;
6856     case Intrinsic::floor:        Opcode = ISD::FFLOOR;        break;
6857     case Intrinsic::ceil:         Opcode = ISD::FCEIL;         break;
6858     case Intrinsic::trunc:        Opcode = ISD::FTRUNC;        break;
6859     case Intrinsic::rint:         Opcode = ISD::FRINT;         break;
6860     case Intrinsic::nearbyint:    Opcode = ISD::FNEARBYINT;    break;
6861     case Intrinsic::round:        Opcode = ISD::FROUND;        break;
6862     case Intrinsic::roundeven:    Opcode = ISD::FROUNDEVEN;    break;
6863     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6864     }
6865     // clang-format on
6866 
6867     setValue(&I, DAG.getNode(Opcode, sdl,
6868                              getValue(I.getArgOperand(0)).getValueType(),
6869                              getValue(I.getArgOperand(0)), Flags));
6870     return;
6871   }
6872   case Intrinsic::atan2:
6873     setValue(&I, DAG.getNode(ISD::FATAN2, sdl,
6874                              getValue(I.getArgOperand(0)).getValueType(),
6875                              getValue(I.getArgOperand(0)),
6876                              getValue(I.getArgOperand(1)), Flags));
6877     return;
6878   case Intrinsic::lround:
6879   case Intrinsic::llround:
6880   case Intrinsic::lrint:
6881   case Intrinsic::llrint: {
6882     unsigned Opcode;
6883     // clang-format off
6884     switch (Intrinsic) {
6885     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6886     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6887     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6888     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6889     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6890     }
6891     // clang-format on
6892 
6893     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6894     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6895                              getValue(I.getArgOperand(0))));
6896     return;
6897   }
6898   case Intrinsic::minnum:
6899     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6900                              getValue(I.getArgOperand(0)).getValueType(),
6901                              getValue(I.getArgOperand(0)),
6902                              getValue(I.getArgOperand(1)), Flags));
6903     return;
6904   case Intrinsic::maxnum:
6905     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6906                              getValue(I.getArgOperand(0)).getValueType(),
6907                              getValue(I.getArgOperand(0)),
6908                              getValue(I.getArgOperand(1)), Flags));
6909     return;
6910   case Intrinsic::minimum:
6911     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6912                              getValue(I.getArgOperand(0)).getValueType(),
6913                              getValue(I.getArgOperand(0)),
6914                              getValue(I.getArgOperand(1)), Flags));
6915     return;
6916   case Intrinsic::maximum:
6917     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6918                              getValue(I.getArgOperand(0)).getValueType(),
6919                              getValue(I.getArgOperand(0)),
6920                              getValue(I.getArgOperand(1)), Flags));
6921     return;
6922   case Intrinsic::minimumnum:
6923     setValue(&I, DAG.getNode(ISD::FMINIMUMNUM, sdl,
6924                              getValue(I.getArgOperand(0)).getValueType(),
6925                              getValue(I.getArgOperand(0)),
6926                              getValue(I.getArgOperand(1)), Flags));
6927     return;
6928   case Intrinsic::maximumnum:
6929     setValue(&I, DAG.getNode(ISD::FMAXIMUMNUM, sdl,
6930                              getValue(I.getArgOperand(0)).getValueType(),
6931                              getValue(I.getArgOperand(0)),
6932                              getValue(I.getArgOperand(1)), Flags));
6933     return;
6934   case Intrinsic::copysign:
6935     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6936                              getValue(I.getArgOperand(0)).getValueType(),
6937                              getValue(I.getArgOperand(0)),
6938                              getValue(I.getArgOperand(1)), Flags));
6939     return;
6940   case Intrinsic::ldexp:
6941     setValue(&I, DAG.getNode(ISD::FLDEXP, sdl,
6942                              getValue(I.getArgOperand(0)).getValueType(),
6943                              getValue(I.getArgOperand(0)),
6944                              getValue(I.getArgOperand(1)), Flags));
6945     return;
6946   case Intrinsic::sincos:
6947   case Intrinsic::frexp: {
6948     unsigned Opcode;
6949     switch (Intrinsic) {
6950     default:
6951       llvm_unreachable("unexpected intrinsic");
6952     case Intrinsic::sincos:
6953       Opcode = ISD::FSINCOS;
6954       break;
6955     case Intrinsic::frexp:
6956       Opcode = ISD::FFREXP;
6957       break;
6958     }
6959     SmallVector<EVT, 2> ValueVTs;
6960     ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
6961     SDVTList VTs = DAG.getVTList(ValueVTs);
6962     setValue(
6963         &I, DAG.getNode(Opcode, sdl, VTs, getValue(I.getArgOperand(0)), Flags));
6964     return;
6965   }
6966   case Intrinsic::arithmetic_fence: {
6967     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6968                              getValue(I.getArgOperand(0)).getValueType(),
6969                              getValue(I.getArgOperand(0)), Flags));
6970     return;
6971   }
6972   case Intrinsic::fma:
6973     setValue(&I, DAG.getNode(
6974                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6975                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6976                      getValue(I.getArgOperand(2)), Flags));
6977     return;
6978 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6979   case Intrinsic::INTRINSIC:
6980 #include "llvm/IR/ConstrainedOps.def"
6981     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6982     return;
6983 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6984 #include "llvm/IR/VPIntrinsics.def"
6985     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6986     return;
6987   case Intrinsic::fptrunc_round: {
6988     // Get the last argument, the metadata and convert it to an integer in the
6989     // call
6990     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
6991     std::optional<RoundingMode> RoundMode =
6992         convertStrToRoundingMode(cast<MDString>(MD)->getString());
6993 
6994     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6995 
6996     // Propagate fast-math-flags from IR to node(s).
6997     SDNodeFlags Flags;
6998     Flags.copyFMF(*cast<FPMathOperator>(&I));
6999     SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
7000 
7001     SDValue Result;
7002     Result = DAG.getNode(
7003         ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
7004         DAG.getTargetConstant((int)*RoundMode, sdl, MVT::i32));
7005     setValue(&I, Result);
7006 
7007     return;
7008   }
7009   case Intrinsic::fmuladd: {
7010     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7011     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
7012         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
7013       setValue(&I, DAG.getNode(ISD::FMA, sdl,
7014                                getValue(I.getArgOperand(0)).getValueType(),
7015                                getValue(I.getArgOperand(0)),
7016                                getValue(I.getArgOperand(1)),
7017                                getValue(I.getArgOperand(2)), Flags));
7018     } else {
7019       // TODO: Intrinsic calls should have fast-math-flags.
7020       SDValue Mul = DAG.getNode(
7021           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
7022           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
7023       SDValue Add = DAG.getNode(ISD::FADD, sdl,
7024                                 getValue(I.getArgOperand(0)).getValueType(),
7025                                 Mul, getValue(I.getArgOperand(2)), Flags);
7026       setValue(&I, Add);
7027     }
7028     return;
7029   }
7030   case Intrinsic::convert_to_fp16:
7031     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
7032                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
7033                                          getValue(I.getArgOperand(0)),
7034                                          DAG.getTargetConstant(0, sdl,
7035                                                                MVT::i32))));
7036     return;
7037   case Intrinsic::convert_from_fp16:
7038     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
7039                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
7040                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
7041                                          getValue(I.getArgOperand(0)))));
7042     return;
7043   case Intrinsic::fptosi_sat: {
7044     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7045     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
7046                              getValue(I.getArgOperand(0)),
7047                              DAG.getValueType(VT.getScalarType())));
7048     return;
7049   }
7050   case Intrinsic::fptoui_sat: {
7051     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7052     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
7053                              getValue(I.getArgOperand(0)),
7054                              DAG.getValueType(VT.getScalarType())));
7055     return;
7056   }
7057   case Intrinsic::set_rounding:
7058     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
7059                       {getRoot(), getValue(I.getArgOperand(0))});
7060     setValue(&I, Res);
7061     DAG.setRoot(Res.getValue(0));
7062     return;
7063   case Intrinsic::is_fpclass: {
7064     const DataLayout DLayout = DAG.getDataLayout();
7065     EVT DestVT = TLI.getValueType(DLayout, I.getType());
7066     EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
7067     FPClassTest Test = static_cast<FPClassTest>(
7068         cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
7069     MachineFunction &MF = DAG.getMachineFunction();
7070     const Function &F = MF.getFunction();
7071     SDValue Op = getValue(I.getArgOperand(0));
7072     SDNodeFlags Flags;
7073     Flags.setNoFPExcept(
7074         !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
7075     // If ISD::IS_FPCLASS should be expanded, do it right now, because the
7076     // expansion can use illegal types. Making expansion early allows
7077     // legalizing these types prior to selection.
7078     if (!TLI.isOperationLegal(ISD::IS_FPCLASS, ArgVT) &&
7079         !TLI.isOperationCustom(ISD::IS_FPCLASS, ArgVT)) {
7080       SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
7081       setValue(&I, Result);
7082       return;
7083     }
7084 
7085     SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
7086     SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
7087     setValue(&I, V);
7088     return;
7089   }
7090   case Intrinsic::get_fpenv: {
7091     const DataLayout DLayout = DAG.getDataLayout();
7092     EVT EnvVT = TLI.getValueType(DLayout, I.getType());
7093     Align TempAlign = DAG.getEVTAlign(EnvVT);
7094     SDValue Chain = getRoot();
7095     // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node
7096     // and temporary storage in stack.
7097     if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) {
7098       Res = DAG.getNode(
7099           ISD::GET_FPENV, sdl,
7100           DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7101                         MVT::Other),
7102           Chain);
7103     } else {
7104       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7105       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7106       auto MPI =
7107           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7108       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7109           MPI, MachineMemOperand::MOStore, LocationSize::beforeOrAfterPointer(),
7110           TempAlign);
7111       Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7112       Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI);
7113     }
7114     setValue(&I, Res);
7115     DAG.setRoot(Res.getValue(1));
7116     return;
7117   }
7118   case Intrinsic::set_fpenv: {
7119     const DataLayout DLayout = DAG.getDataLayout();
7120     SDValue Env = getValue(I.getArgOperand(0));
7121     EVT EnvVT = Env.getValueType();
7122     Align TempAlign = DAG.getEVTAlign(EnvVT);
7123     SDValue Chain = getRoot();
7124     // If SET_FPENV is custom or legal, use it. Otherwise use loading
7125     // environment from memory.
7126     if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) {
7127       Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env);
7128     } else {
7129       // Allocate space in stack, copy environment bits into it and use this
7130       // memory in SET_FPENV_MEM.
7131       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7132       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7133       auto MPI =
7134           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7135       Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign,
7136                            MachineMemOperand::MOStore);
7137       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7138           MPI, MachineMemOperand::MOLoad, LocationSize::beforeOrAfterPointer(),
7139           TempAlign);
7140       Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7141     }
7142     DAG.setRoot(Chain);
7143     return;
7144   }
7145   case Intrinsic::reset_fpenv:
7146     DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot()));
7147     return;
7148   case Intrinsic::get_fpmode:
7149     Res = DAG.getNode(
7150         ISD::GET_FPMODE, sdl,
7151         DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7152                       MVT::Other),
7153         DAG.getRoot());
7154     setValue(&I, Res);
7155     DAG.setRoot(Res.getValue(1));
7156     return;
7157   case Intrinsic::set_fpmode:
7158     Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()},
7159                       getValue(I.getArgOperand(0)));
7160     DAG.setRoot(Res);
7161     return;
7162   case Intrinsic::reset_fpmode: {
7163     Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot());
7164     DAG.setRoot(Res);
7165     return;
7166   }
7167   case Intrinsic::pcmarker: {
7168     SDValue Tmp = getValue(I.getArgOperand(0));
7169     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
7170     return;
7171   }
7172   case Intrinsic::readcyclecounter: {
7173     SDValue Op = getRoot();
7174     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
7175                       DAG.getVTList(MVT::i64, MVT::Other), Op);
7176     setValue(&I, Res);
7177     DAG.setRoot(Res.getValue(1));
7178     return;
7179   }
7180   case Intrinsic::readsteadycounter: {
7181     SDValue Op = getRoot();
7182     Res = DAG.getNode(ISD::READSTEADYCOUNTER, sdl,
7183                       DAG.getVTList(MVT::i64, MVT::Other), Op);
7184     setValue(&I, Res);
7185     DAG.setRoot(Res.getValue(1));
7186     return;
7187   }
7188   case Intrinsic::bitreverse:
7189     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
7190                              getValue(I.getArgOperand(0)).getValueType(),
7191                              getValue(I.getArgOperand(0))));
7192     return;
7193   case Intrinsic::bswap:
7194     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
7195                              getValue(I.getArgOperand(0)).getValueType(),
7196                              getValue(I.getArgOperand(0))));
7197     return;
7198   case Intrinsic::cttz: {
7199     SDValue Arg = getValue(I.getArgOperand(0));
7200     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7201     EVT Ty = Arg.getValueType();
7202     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
7203                              sdl, Ty, Arg));
7204     return;
7205   }
7206   case Intrinsic::ctlz: {
7207     SDValue Arg = getValue(I.getArgOperand(0));
7208     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7209     EVT Ty = Arg.getValueType();
7210     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
7211                              sdl, Ty, Arg));
7212     return;
7213   }
7214   case Intrinsic::ctpop: {
7215     SDValue Arg = getValue(I.getArgOperand(0));
7216     EVT Ty = Arg.getValueType();
7217     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
7218     return;
7219   }
7220   case Intrinsic::fshl:
7221   case Intrinsic::fshr: {
7222     bool IsFSHL = Intrinsic == Intrinsic::fshl;
7223     SDValue X = getValue(I.getArgOperand(0));
7224     SDValue Y = getValue(I.getArgOperand(1));
7225     SDValue Z = getValue(I.getArgOperand(2));
7226     EVT VT = X.getValueType();
7227 
7228     if (X == Y) {
7229       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
7230       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
7231     } else {
7232       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
7233       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
7234     }
7235     return;
7236   }
7237   case Intrinsic::sadd_sat: {
7238     SDValue Op1 = getValue(I.getArgOperand(0));
7239     SDValue Op2 = getValue(I.getArgOperand(1));
7240     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7241     return;
7242   }
7243   case Intrinsic::uadd_sat: {
7244     SDValue Op1 = getValue(I.getArgOperand(0));
7245     SDValue Op2 = getValue(I.getArgOperand(1));
7246     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7247     return;
7248   }
7249   case Intrinsic::ssub_sat: {
7250     SDValue Op1 = getValue(I.getArgOperand(0));
7251     SDValue Op2 = getValue(I.getArgOperand(1));
7252     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7253     return;
7254   }
7255   case Intrinsic::usub_sat: {
7256     SDValue Op1 = getValue(I.getArgOperand(0));
7257     SDValue Op2 = getValue(I.getArgOperand(1));
7258     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7259     return;
7260   }
7261   case Intrinsic::sshl_sat: {
7262     SDValue Op1 = getValue(I.getArgOperand(0));
7263     SDValue Op2 = getValue(I.getArgOperand(1));
7264     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
7265     return;
7266   }
7267   case Intrinsic::ushl_sat: {
7268     SDValue Op1 = getValue(I.getArgOperand(0));
7269     SDValue Op2 = getValue(I.getArgOperand(1));
7270     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
7271     return;
7272   }
7273   case Intrinsic::smul_fix:
7274   case Intrinsic::umul_fix:
7275   case Intrinsic::smul_fix_sat:
7276   case Intrinsic::umul_fix_sat: {
7277     SDValue Op1 = getValue(I.getArgOperand(0));
7278     SDValue Op2 = getValue(I.getArgOperand(1));
7279     SDValue Op3 = getValue(I.getArgOperand(2));
7280     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7281                              Op1.getValueType(), Op1, Op2, Op3));
7282     return;
7283   }
7284   case Intrinsic::sdiv_fix:
7285   case Intrinsic::udiv_fix:
7286   case Intrinsic::sdiv_fix_sat:
7287   case Intrinsic::udiv_fix_sat: {
7288     SDValue Op1 = getValue(I.getArgOperand(0));
7289     SDValue Op2 = getValue(I.getArgOperand(1));
7290     SDValue Op3 = getValue(I.getArgOperand(2));
7291     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7292                               Op1, Op2, Op3, DAG, TLI));
7293     return;
7294   }
7295   case Intrinsic::smax: {
7296     SDValue Op1 = getValue(I.getArgOperand(0));
7297     SDValue Op2 = getValue(I.getArgOperand(1));
7298     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
7299     return;
7300   }
7301   case Intrinsic::smin: {
7302     SDValue Op1 = getValue(I.getArgOperand(0));
7303     SDValue Op2 = getValue(I.getArgOperand(1));
7304     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
7305     return;
7306   }
7307   case Intrinsic::umax: {
7308     SDValue Op1 = getValue(I.getArgOperand(0));
7309     SDValue Op2 = getValue(I.getArgOperand(1));
7310     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
7311     return;
7312   }
7313   case Intrinsic::umin: {
7314     SDValue Op1 = getValue(I.getArgOperand(0));
7315     SDValue Op2 = getValue(I.getArgOperand(1));
7316     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
7317     return;
7318   }
7319   case Intrinsic::abs: {
7320     // TODO: Preserve "int min is poison" arg in SDAG?
7321     SDValue Op1 = getValue(I.getArgOperand(0));
7322     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
7323     return;
7324   }
7325   case Intrinsic::scmp: {
7326     SDValue Op1 = getValue(I.getArgOperand(0));
7327     SDValue Op2 = getValue(I.getArgOperand(1));
7328     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7329     setValue(&I, DAG.getNode(ISD::SCMP, sdl, DestVT, Op1, Op2));
7330     break;
7331   }
7332   case Intrinsic::ucmp: {
7333     SDValue Op1 = getValue(I.getArgOperand(0));
7334     SDValue Op2 = getValue(I.getArgOperand(1));
7335     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7336     setValue(&I, DAG.getNode(ISD::UCMP, sdl, DestVT, Op1, Op2));
7337     break;
7338   }
7339   case Intrinsic::stacksave: {
7340     SDValue Op = getRoot();
7341     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7342     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
7343     setValue(&I, Res);
7344     DAG.setRoot(Res.getValue(1));
7345     return;
7346   }
7347   case Intrinsic::stackrestore:
7348     Res = getValue(I.getArgOperand(0));
7349     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
7350     return;
7351   case Intrinsic::get_dynamic_area_offset: {
7352     SDValue Op = getRoot();
7353     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7354     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7355     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
7356     // target.
7357     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
7358       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
7359                          " intrinsic!");
7360     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
7361                       Op);
7362     DAG.setRoot(Op);
7363     setValue(&I, Res);
7364     return;
7365   }
7366   case Intrinsic::stackguard: {
7367     MachineFunction &MF = DAG.getMachineFunction();
7368     const Module &M = *MF.getFunction().getParent();
7369     EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7370     SDValue Chain = getRoot();
7371     if (TLI.useLoadStackGuardNode(M)) {
7372       Res = getLoadStackGuard(DAG, sdl, Chain);
7373       Res = DAG.getPtrExtOrTrunc(Res, sdl, PtrTy);
7374     } else {
7375       const Value *Global = TLI.getSDagStackGuard(M);
7376       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
7377       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
7378                         MachinePointerInfo(Global, 0), Align,
7379                         MachineMemOperand::MOVolatile);
7380     }
7381     if (TLI.useStackGuardXorFP())
7382       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
7383     DAG.setRoot(Chain);
7384     setValue(&I, Res);
7385     return;
7386   }
7387   case Intrinsic::stackprotector: {
7388     // Emit code into the DAG to store the stack guard onto the stack.
7389     MachineFunction &MF = DAG.getMachineFunction();
7390     MachineFrameInfo &MFI = MF.getFrameInfo();
7391     const Module &M = *MF.getFunction().getParent();
7392     SDValue Src, Chain = getRoot();
7393 
7394     if (TLI.useLoadStackGuardNode(M))
7395       Src = getLoadStackGuard(DAG, sdl, Chain);
7396     else
7397       Src = getValue(I.getArgOperand(0));   // The guard's value.
7398 
7399     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
7400 
7401     int FI = FuncInfo.StaticAllocaMap[Slot];
7402     MFI.setStackProtectorIndex(FI);
7403     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7404 
7405     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
7406 
7407     // Store the stack protector onto the stack.
7408     Res = DAG.getStore(
7409         Chain, sdl, Src, FIN,
7410         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
7411         MaybeAlign(), MachineMemOperand::MOVolatile);
7412     setValue(&I, Res);
7413     DAG.setRoot(Res);
7414     return;
7415   }
7416   case Intrinsic::objectsize:
7417     llvm_unreachable("llvm.objectsize.* should have been lowered already");
7418 
7419   case Intrinsic::is_constant:
7420     llvm_unreachable("llvm.is.constant.* should have been lowered already");
7421 
7422   case Intrinsic::annotation:
7423   case Intrinsic::ptr_annotation:
7424   case Intrinsic::launder_invariant_group:
7425   case Intrinsic::strip_invariant_group:
7426     // Drop the intrinsic, but forward the value
7427     setValue(&I, getValue(I.getOperand(0)));
7428     return;
7429 
7430   case Intrinsic::assume:
7431   case Intrinsic::experimental_noalias_scope_decl:
7432   case Intrinsic::var_annotation:
7433   case Intrinsic::sideeffect:
7434     // Discard annotate attributes, noalias scope declarations, assumptions, and
7435     // artificial side-effects.
7436     return;
7437 
7438   case Intrinsic::codeview_annotation: {
7439     // Emit a label associated with this metadata.
7440     MachineFunction &MF = DAG.getMachineFunction();
7441     MCSymbol *Label = MF.getContext().createTempSymbol("annotation", true);
7442     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
7443     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
7444     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
7445     DAG.setRoot(Res);
7446     return;
7447   }
7448 
7449   case Intrinsic::init_trampoline: {
7450     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
7451 
7452     SDValue Ops[6];
7453     Ops[0] = getRoot();
7454     Ops[1] = getValue(I.getArgOperand(0));
7455     Ops[2] = getValue(I.getArgOperand(1));
7456     Ops[3] = getValue(I.getArgOperand(2));
7457     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
7458     Ops[5] = DAG.getSrcValue(F);
7459 
7460     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
7461 
7462     DAG.setRoot(Res);
7463     return;
7464   }
7465   case Intrinsic::adjust_trampoline:
7466     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
7467                              TLI.getPointerTy(DAG.getDataLayout()),
7468                              getValue(I.getArgOperand(0))));
7469     return;
7470   case Intrinsic::gcroot: {
7471     assert(DAG.getMachineFunction().getFunction().hasGC() &&
7472            "only valid in functions with gc specified, enforced by Verifier");
7473     assert(GFI && "implied by previous");
7474     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
7475     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
7476 
7477     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
7478     GFI->addStackRoot(FI->getIndex(), TypeMap);
7479     return;
7480   }
7481   case Intrinsic::gcread:
7482   case Intrinsic::gcwrite:
7483     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
7484   case Intrinsic::get_rounding:
7485     Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot());
7486     setValue(&I, Res);
7487     DAG.setRoot(Res.getValue(1));
7488     return;
7489 
7490   case Intrinsic::expect:
7491     // Just replace __builtin_expect(exp, c) with EXP.
7492     setValue(&I, getValue(I.getArgOperand(0)));
7493     return;
7494 
7495   case Intrinsic::ubsantrap:
7496   case Intrinsic::debugtrap:
7497   case Intrinsic::trap: {
7498     StringRef TrapFuncName =
7499         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
7500     if (TrapFuncName.empty()) {
7501       switch (Intrinsic) {
7502       case Intrinsic::trap:
7503         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
7504         break;
7505       case Intrinsic::debugtrap:
7506         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
7507         break;
7508       case Intrinsic::ubsantrap:
7509         DAG.setRoot(DAG.getNode(
7510             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
7511             DAG.getTargetConstant(
7512                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
7513                 MVT::i32)));
7514         break;
7515       default: llvm_unreachable("unknown trap intrinsic");
7516       }
7517       DAG.addNoMergeSiteInfo(DAG.getRoot().getNode(),
7518                              I.hasFnAttr(Attribute::NoMerge));
7519       return;
7520     }
7521     TargetLowering::ArgListTy Args;
7522     if (Intrinsic == Intrinsic::ubsantrap) {
7523       Args.push_back(TargetLoweringBase::ArgListEntry());
7524       Args[0].Val = I.getArgOperand(0);
7525       Args[0].Node = getValue(Args[0].Val);
7526       Args[0].Ty = Args[0].Val->getType();
7527     }
7528 
7529     TargetLowering::CallLoweringInfo CLI(DAG);
7530     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
7531         CallingConv::C, I.getType(),
7532         DAG.getExternalSymbol(TrapFuncName.data(),
7533                               TLI.getPointerTy(DAG.getDataLayout())),
7534         std::move(Args));
7535     CLI.NoMerge = I.hasFnAttr(Attribute::NoMerge);
7536     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7537     DAG.setRoot(Result.second);
7538     return;
7539   }
7540 
7541   case Intrinsic::allow_runtime_check:
7542   case Intrinsic::allow_ubsan_check:
7543     setValue(&I, getValue(ConstantInt::getTrue(I.getType())));
7544     return;
7545 
7546   case Intrinsic::uadd_with_overflow:
7547   case Intrinsic::sadd_with_overflow:
7548   case Intrinsic::usub_with_overflow:
7549   case Intrinsic::ssub_with_overflow:
7550   case Intrinsic::umul_with_overflow:
7551   case Intrinsic::smul_with_overflow: {
7552     ISD::NodeType Op;
7553     switch (Intrinsic) {
7554     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7555     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
7556     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
7557     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
7558     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
7559     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
7560     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
7561     }
7562     SDValue Op1 = getValue(I.getArgOperand(0));
7563     SDValue Op2 = getValue(I.getArgOperand(1));
7564 
7565     EVT ResultVT = Op1.getValueType();
7566     EVT OverflowVT = MVT::i1;
7567     if (ResultVT.isVector())
7568       OverflowVT = EVT::getVectorVT(
7569           *Context, OverflowVT, ResultVT.getVectorElementCount());
7570 
7571     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
7572     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
7573     return;
7574   }
7575   case Intrinsic::prefetch: {
7576     SDValue Ops[5];
7577     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7578     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
7579     Ops[0] = DAG.getRoot();
7580     Ops[1] = getValue(I.getArgOperand(0));
7581     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
7582                                    MVT::i32);
7583     Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl,
7584                                    MVT::i32);
7585     Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl,
7586                                    MVT::i32);
7587     SDValue Result = DAG.getMemIntrinsicNode(
7588         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
7589         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
7590         /* align */ std::nullopt, Flags);
7591 
7592     // Chain the prefetch in parallel with any pending loads, to stay out of
7593     // the way of later optimizations.
7594     PendingLoads.push_back(Result);
7595     Result = getRoot();
7596     DAG.setRoot(Result);
7597     return;
7598   }
7599   case Intrinsic::lifetime_start:
7600   case Intrinsic::lifetime_end: {
7601     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
7602     // Stack coloring is not enabled in O0, discard region information.
7603     if (TM.getOptLevel() == CodeGenOptLevel::None)
7604       return;
7605 
7606     const int64_t ObjectSize =
7607         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
7608     Value *const ObjectPtr = I.getArgOperand(1);
7609     SmallVector<const Value *, 4> Allocas;
7610     getUnderlyingObjects(ObjectPtr, Allocas);
7611 
7612     for (const Value *Alloca : Allocas) {
7613       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
7614 
7615       // Could not find an Alloca.
7616       if (!LifetimeObject)
7617         continue;
7618 
7619       // First check that the Alloca is static, otherwise it won't have a
7620       // valid frame index.
7621       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
7622       if (SI == FuncInfo.StaticAllocaMap.end())
7623         return;
7624 
7625       const int FrameIndex = SI->second;
7626       int64_t Offset;
7627       if (GetPointerBaseWithConstantOffset(
7628               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
7629         Offset = -1; // Cannot determine offset from alloca to lifetime object.
7630       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
7631                                 Offset);
7632       DAG.setRoot(Res);
7633     }
7634     return;
7635   }
7636   case Intrinsic::pseudoprobe: {
7637     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
7638     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7639     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
7640     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
7641     DAG.setRoot(Res);
7642     return;
7643   }
7644   case Intrinsic::invariant_start:
7645     // Discard region information.
7646     setValue(&I,
7647              DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
7648     return;
7649   case Intrinsic::invariant_end:
7650     // Discard region information.
7651     return;
7652   case Intrinsic::clear_cache: {
7653     SDValue InputChain = DAG.getRoot();
7654     SDValue StartVal = getValue(I.getArgOperand(0));
7655     SDValue EndVal = getValue(I.getArgOperand(1));
7656     Res = DAG.getNode(ISD::CLEAR_CACHE, sdl, DAG.getVTList(MVT::Other),
7657                       {InputChain, StartVal, EndVal});
7658     setValue(&I, Res);
7659     DAG.setRoot(Res);
7660     return;
7661   }
7662   case Intrinsic::donothing:
7663   case Intrinsic::seh_try_begin:
7664   case Intrinsic::seh_scope_begin:
7665   case Intrinsic::seh_try_end:
7666   case Intrinsic::seh_scope_end:
7667     // ignore
7668     return;
7669   case Intrinsic::experimental_stackmap:
7670     visitStackmap(I);
7671     return;
7672   case Intrinsic::experimental_patchpoint_void:
7673   case Intrinsic::experimental_patchpoint:
7674     visitPatchpoint(I);
7675     return;
7676   case Intrinsic::experimental_gc_statepoint:
7677     LowerStatepoint(cast<GCStatepointInst>(I));
7678     return;
7679   case Intrinsic::experimental_gc_result:
7680     visitGCResult(cast<GCResultInst>(I));
7681     return;
7682   case Intrinsic::experimental_gc_relocate:
7683     visitGCRelocate(cast<GCRelocateInst>(I));
7684     return;
7685   case Intrinsic::instrprof_cover:
7686     llvm_unreachable("instrprof failed to lower a cover");
7687   case Intrinsic::instrprof_increment:
7688     llvm_unreachable("instrprof failed to lower an increment");
7689   case Intrinsic::instrprof_timestamp:
7690     llvm_unreachable("instrprof failed to lower a timestamp");
7691   case Intrinsic::instrprof_value_profile:
7692     llvm_unreachable("instrprof failed to lower a value profiling call");
7693   case Intrinsic::instrprof_mcdc_parameters:
7694     llvm_unreachable("instrprof failed to lower mcdc parameters");
7695   case Intrinsic::instrprof_mcdc_tvbitmap_update:
7696     llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update");
7697   case Intrinsic::localescape: {
7698     MachineFunction &MF = DAG.getMachineFunction();
7699     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
7700 
7701     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
7702     // is the same on all targets.
7703     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
7704       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
7705       if (isa<ConstantPointerNull>(Arg))
7706         continue; // Skip null pointers. They represent a hole in index space.
7707       AllocaInst *Slot = cast<AllocaInst>(Arg);
7708       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
7709              "can only escape static allocas");
7710       int FI = FuncInfo.StaticAllocaMap[Slot];
7711       MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
7712           GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
7713       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
7714               TII->get(TargetOpcode::LOCAL_ESCAPE))
7715           .addSym(FrameAllocSym)
7716           .addFrameIndex(FI);
7717     }
7718 
7719     return;
7720   }
7721 
7722   case Intrinsic::localrecover: {
7723     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
7724     MachineFunction &MF = DAG.getMachineFunction();
7725 
7726     // Get the symbol that defines the frame offset.
7727     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
7728     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
7729     unsigned IdxVal =
7730         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
7731     MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
7732         GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
7733 
7734     Value *FP = I.getArgOperand(1);
7735     SDValue FPVal = getValue(FP);
7736     EVT PtrVT = FPVal.getValueType();
7737 
7738     // Create a MCSymbol for the label to avoid any target lowering
7739     // that would make this PC relative.
7740     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
7741     SDValue OffsetVal =
7742         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
7743 
7744     // Add the offset to the FP.
7745     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
7746     setValue(&I, Add);
7747 
7748     return;
7749   }
7750 
7751   case Intrinsic::fake_use: {
7752     Value *V = I.getArgOperand(0);
7753     SDValue Ops[2];
7754     // For Values not declared or previously used in this basic block, the
7755     // NodeMap will not have an entry, and `getValue` will assert if V has no
7756     // valid register value.
7757     auto FakeUseValue = [&]() -> SDValue {
7758       SDValue &N = NodeMap[V];
7759       if (N.getNode())
7760         return N;
7761 
7762       // If there's a virtual register allocated and initialized for this
7763       // value, use it.
7764       if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
7765         return copyFromReg;
7766       // FIXME: Do we want to preserve constants? It seems pointless.
7767       if (isa<Constant>(V))
7768         return getValue(V);
7769       return SDValue();
7770     }();
7771     if (!FakeUseValue || FakeUseValue.isUndef())
7772       return;
7773     Ops[0] = getRoot();
7774     Ops[1] = FakeUseValue;
7775     // Also, do not translate a fake use with an undef operand, or any other
7776     // empty SDValues.
7777     if (!Ops[1] || Ops[1].isUndef())
7778       return;
7779     DAG.setRoot(DAG.getNode(ISD::FAKE_USE, sdl, MVT::Other, Ops));
7780     return;
7781   }
7782 
7783   case Intrinsic::eh_exceptionpointer:
7784   case Intrinsic::eh_exceptioncode: {
7785     // Get the exception pointer vreg, copy from it, and resize it to fit.
7786     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
7787     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
7788     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
7789     Register VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
7790     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
7791     if (Intrinsic == Intrinsic::eh_exceptioncode)
7792       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
7793     setValue(&I, N);
7794     return;
7795   }
7796   case Intrinsic::xray_customevent: {
7797     // Here we want to make sure that the intrinsic behaves as if it has a
7798     // specific calling convention.
7799     const auto &Triple = DAG.getTarget().getTargetTriple();
7800     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7801       return;
7802 
7803     SmallVector<SDValue, 8> Ops;
7804 
7805     // We want to say that we always want the arguments in registers.
7806     SDValue LogEntryVal = getValue(I.getArgOperand(0));
7807     SDValue StrSizeVal = getValue(I.getArgOperand(1));
7808     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7809     SDValue Chain = getRoot();
7810     Ops.push_back(LogEntryVal);
7811     Ops.push_back(StrSizeVal);
7812     Ops.push_back(Chain);
7813 
7814     // We need to enforce the calling convention for the callsite, so that
7815     // argument ordering is enforced correctly, and that register allocation can
7816     // see that some registers may be assumed clobbered and have to preserve
7817     // them across calls to the intrinsic.
7818     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
7819                                            sdl, NodeTys, Ops);
7820     SDValue patchableNode = SDValue(MN, 0);
7821     DAG.setRoot(patchableNode);
7822     setValue(&I, patchableNode);
7823     return;
7824   }
7825   case Intrinsic::xray_typedevent: {
7826     // Here we want to make sure that the intrinsic behaves as if it has a
7827     // specific calling convention.
7828     const auto &Triple = DAG.getTarget().getTargetTriple();
7829     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7830       return;
7831 
7832     SmallVector<SDValue, 8> Ops;
7833 
7834     // We want to say that we always want the arguments in registers.
7835     // It's unclear to me how manipulating the selection DAG here forces callers
7836     // to provide arguments in registers instead of on the stack.
7837     SDValue LogTypeId = getValue(I.getArgOperand(0));
7838     SDValue LogEntryVal = getValue(I.getArgOperand(1));
7839     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7840     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7841     SDValue Chain = getRoot();
7842     Ops.push_back(LogTypeId);
7843     Ops.push_back(LogEntryVal);
7844     Ops.push_back(StrSizeVal);
7845     Ops.push_back(Chain);
7846 
7847     // We need to enforce the calling convention for the callsite, so that
7848     // argument ordering is enforced correctly, and that register allocation can
7849     // see that some registers may be assumed clobbered and have to preserve
7850     // them across calls to the intrinsic.
7851     MachineSDNode *MN = DAG.getMachineNode(
7852         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7853     SDValue patchableNode = SDValue(MN, 0);
7854     DAG.setRoot(patchableNode);
7855     setValue(&I, patchableNode);
7856     return;
7857   }
7858   case Intrinsic::experimental_deoptimize:
7859     LowerDeoptimizeCall(&I);
7860     return;
7861   case Intrinsic::stepvector:
7862     visitStepVector(I);
7863     return;
7864   case Intrinsic::vector_reduce_fadd:
7865   case Intrinsic::vector_reduce_fmul:
7866   case Intrinsic::vector_reduce_add:
7867   case Intrinsic::vector_reduce_mul:
7868   case Intrinsic::vector_reduce_and:
7869   case Intrinsic::vector_reduce_or:
7870   case Intrinsic::vector_reduce_xor:
7871   case Intrinsic::vector_reduce_smax:
7872   case Intrinsic::vector_reduce_smin:
7873   case Intrinsic::vector_reduce_umax:
7874   case Intrinsic::vector_reduce_umin:
7875   case Intrinsic::vector_reduce_fmax:
7876   case Intrinsic::vector_reduce_fmin:
7877   case Intrinsic::vector_reduce_fmaximum:
7878   case Intrinsic::vector_reduce_fminimum:
7879     visitVectorReduce(I, Intrinsic);
7880     return;
7881 
7882   case Intrinsic::icall_branch_funnel: {
7883     SmallVector<SDValue, 16> Ops;
7884     Ops.push_back(getValue(I.getArgOperand(0)));
7885 
7886     int64_t Offset;
7887     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7888         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7889     if (!Base)
7890       report_fatal_error(
7891           "llvm.icall.branch.funnel operand must be a GlobalValue");
7892     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7893 
7894     struct BranchFunnelTarget {
7895       int64_t Offset;
7896       SDValue Target;
7897     };
7898     SmallVector<BranchFunnelTarget, 8> Targets;
7899 
7900     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7901       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7902           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7903       if (ElemBase != Base)
7904         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7905                            "to the same GlobalValue");
7906 
7907       SDValue Val = getValue(I.getArgOperand(Op + 1));
7908       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7909       if (!GA)
7910         report_fatal_error(
7911             "llvm.icall.branch.funnel operand must be a GlobalValue");
7912       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7913                                      GA->getGlobal(), sdl, Val.getValueType(),
7914                                      GA->getOffset())});
7915     }
7916     llvm::sort(Targets,
7917                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7918                  return T1.Offset < T2.Offset;
7919                });
7920 
7921     for (auto &T : Targets) {
7922       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7923       Ops.push_back(T.Target);
7924     }
7925 
7926     Ops.push_back(DAG.getRoot()); // Chain
7927     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7928                                  MVT::Other, Ops),
7929               0);
7930     DAG.setRoot(N);
7931     setValue(&I, N);
7932     HasTailCall = true;
7933     return;
7934   }
7935 
7936   case Intrinsic::wasm_landingpad_index:
7937     // Information this intrinsic contained has been transferred to
7938     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7939     // delete it now.
7940     return;
7941 
7942   case Intrinsic::aarch64_settag:
7943   case Intrinsic::aarch64_settag_zero: {
7944     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7945     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7946     SDValue Val = TSI.EmitTargetCodeForSetTag(
7947         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7948         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7949         ZeroMemory);
7950     DAG.setRoot(Val);
7951     setValue(&I, Val);
7952     return;
7953   }
7954   case Intrinsic::amdgcn_cs_chain: {
7955     assert(I.arg_size() == 5 && "Additional args not supported yet");
7956     assert(cast<ConstantInt>(I.getOperand(4))->isZero() &&
7957            "Non-zero flags not supported yet");
7958 
7959     // At this point we don't care if it's amdgpu_cs_chain or
7960     // amdgpu_cs_chain_preserve.
7961     CallingConv::ID CC = CallingConv::AMDGPU_CS_Chain;
7962 
7963     Type *RetTy = I.getType();
7964     assert(RetTy->isVoidTy() && "Should not return");
7965 
7966     SDValue Callee = getValue(I.getOperand(0));
7967 
7968     // We only have 2 actual args: one for the SGPRs and one for the VGPRs.
7969     // We'll also tack the value of the EXEC mask at the end.
7970     TargetLowering::ArgListTy Args;
7971     Args.reserve(3);
7972 
7973     for (unsigned Idx : {2, 3, 1}) {
7974       TargetLowering::ArgListEntry Arg;
7975       Arg.Node = getValue(I.getOperand(Idx));
7976       Arg.Ty = I.getOperand(Idx)->getType();
7977       Arg.setAttributes(&I, Idx);
7978       Args.push_back(Arg);
7979     }
7980 
7981     assert(Args[0].IsInReg && "SGPR args should be marked inreg");
7982     assert(!Args[1].IsInReg && "VGPR args should not be marked inreg");
7983     Args[2].IsInReg = true; // EXEC should be inreg
7984 
7985     TargetLowering::CallLoweringInfo CLI(DAG);
7986     CLI.setDebugLoc(getCurSDLoc())
7987         .setChain(getRoot())
7988         .setCallee(CC, RetTy, Callee, std::move(Args))
7989         .setNoReturn(true)
7990         .setTailCall(true)
7991         .setConvergent(I.isConvergent());
7992     CLI.CB = &I;
7993     std::pair<SDValue, SDValue> Result =
7994         lowerInvokable(CLI, /*EHPadBB*/ nullptr);
7995     (void)Result;
7996     assert(!Result.first.getNode() && !Result.second.getNode() &&
7997            "Should've lowered as tail call");
7998 
7999     HasTailCall = true;
8000     return;
8001   }
8002   case Intrinsic::ptrmask: {
8003     SDValue Ptr = getValue(I.getOperand(0));
8004     SDValue Mask = getValue(I.getOperand(1));
8005 
8006     // On arm64_32, pointers are 32 bits when stored in memory, but
8007     // zero-extended to 64 bits when in registers.  Thus the mask is 32 bits to
8008     // match the index type, but the pointer is 64 bits, so the the mask must be
8009     // zero-extended up to 64 bits to match the pointer.
8010     EVT PtrVT =
8011         TLI.getValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
8012     EVT MemVT =
8013         TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
8014     assert(PtrVT == Ptr.getValueType());
8015     assert(MemVT == Mask.getValueType());
8016     if (MemVT != PtrVT)
8017       Mask = DAG.getPtrExtOrTrunc(Mask, sdl, PtrVT);
8018 
8019     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask));
8020     return;
8021   }
8022   case Intrinsic::threadlocal_address: {
8023     setValue(&I, getValue(I.getOperand(0)));
8024     return;
8025   }
8026   case Intrinsic::get_active_lane_mask: {
8027     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8028     SDValue Index = getValue(I.getOperand(0));
8029     EVT ElementVT = Index.getValueType();
8030 
8031     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
8032       visitTargetIntrinsic(I, Intrinsic);
8033       return;
8034     }
8035 
8036     SDValue TripCount = getValue(I.getOperand(1));
8037     EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT,
8038                                  CCVT.getVectorElementCount());
8039 
8040     SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
8041     SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
8042     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
8043     SDValue VectorInduction = DAG.getNode(
8044         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
8045     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
8046                                  VectorTripCount, ISD::CondCode::SETULT);
8047     setValue(&I, SetCC);
8048     return;
8049   }
8050   case Intrinsic::experimental_get_vector_length: {
8051     assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 &&
8052            "Expected positive VF");
8053     unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue();
8054     bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne();
8055 
8056     SDValue Count = getValue(I.getOperand(0));
8057     EVT CountVT = Count.getValueType();
8058 
8059     if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) {
8060       visitTargetIntrinsic(I, Intrinsic);
8061       return;
8062     }
8063 
8064     // Expand to a umin between the trip count and the maximum elements the type
8065     // can hold.
8066     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8067 
8068     // Extend the trip count to at least the result VT.
8069     if (CountVT.bitsLT(VT)) {
8070       Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count);
8071       CountVT = VT;
8072     }
8073 
8074     SDValue MaxEVL = DAG.getElementCount(sdl, CountVT,
8075                                          ElementCount::get(VF, IsScalable));
8076 
8077     SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL);
8078     // Clip to the result type if needed.
8079     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin);
8080 
8081     setValue(&I, Trunc);
8082     return;
8083   }
8084   case Intrinsic::experimental_vector_partial_reduce_add: {
8085 
8086     if (!TLI.shouldExpandPartialReductionIntrinsic(cast<IntrinsicInst>(&I))) {
8087       visitTargetIntrinsic(I, Intrinsic);
8088       return;
8089     }
8090 
8091     setValue(&I, DAG.getPartialReduceAdd(sdl, EVT::getEVT(I.getType()),
8092                                          getValue(I.getOperand(0)),
8093                                          getValue(I.getOperand(1))));
8094     return;
8095   }
8096   case Intrinsic::experimental_cttz_elts: {
8097     auto DL = getCurSDLoc();
8098     SDValue Op = getValue(I.getOperand(0));
8099     EVT OpVT = Op.getValueType();
8100 
8101     if (!TLI.shouldExpandCttzElements(OpVT)) {
8102       visitTargetIntrinsic(I, Intrinsic);
8103       return;
8104     }
8105 
8106     if (OpVT.getScalarType() != MVT::i1) {
8107       // Compare the input vector elements to zero & use to count trailing zeros
8108       SDValue AllZero = DAG.getConstant(0, DL, OpVT);
8109       OpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
8110                               OpVT.getVectorElementCount());
8111       Op = DAG.getSetCC(DL, OpVT, Op, AllZero, ISD::SETNE);
8112     }
8113 
8114     // If the zero-is-poison flag is set, we can assume the upper limit
8115     // of the result is VF-1.
8116     bool ZeroIsPoison =
8117         !cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero();
8118     ConstantRange VScaleRange(1, true); // Dummy value.
8119     if (isa<ScalableVectorType>(I.getOperand(0)->getType()))
8120       VScaleRange = getVScaleRange(I.getCaller(), 64);
8121     unsigned EltWidth = TLI.getBitWidthForCttzElements(
8122         I.getType(), OpVT.getVectorElementCount(), ZeroIsPoison, &VScaleRange);
8123 
8124     MVT NewEltTy = MVT::getIntegerVT(EltWidth);
8125 
8126     // Create the new vector type & get the vector length
8127     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), NewEltTy,
8128                                  OpVT.getVectorElementCount());
8129 
8130     SDValue VL =
8131         DAG.getElementCount(DL, NewEltTy, OpVT.getVectorElementCount());
8132 
8133     SDValue StepVec = DAG.getStepVector(DL, NewVT);
8134     SDValue SplatVL = DAG.getSplat(NewVT, DL, VL);
8135     SDValue StepVL = DAG.getNode(ISD::SUB, DL, NewVT, SplatVL, StepVec);
8136     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, Op);
8137     SDValue And = DAG.getNode(ISD::AND, DL, NewVT, StepVL, Ext);
8138     SDValue Max = DAG.getNode(ISD::VECREDUCE_UMAX, DL, NewEltTy, And);
8139     SDValue Sub = DAG.getNode(ISD::SUB, DL, NewEltTy, VL, Max);
8140 
8141     EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
8142     SDValue Ret = DAG.getZExtOrTrunc(Sub, DL, RetTy);
8143 
8144     setValue(&I, Ret);
8145     return;
8146   }
8147   case Intrinsic::vector_insert: {
8148     SDValue Vec = getValue(I.getOperand(0));
8149     SDValue SubVec = getValue(I.getOperand(1));
8150     SDValue Index = getValue(I.getOperand(2));
8151 
8152     // The intrinsic's index type is i64, but the SDNode requires an index type
8153     // suitable for the target. Convert the index as required.
8154     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8155     if (Index.getValueType() != VectorIdxTy)
8156       Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8157 
8158     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8159     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
8160                              Index));
8161     return;
8162   }
8163   case Intrinsic::vector_extract: {
8164     SDValue Vec = getValue(I.getOperand(0));
8165     SDValue Index = getValue(I.getOperand(1));
8166     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8167 
8168     // The intrinsic's index type is i64, but the SDNode requires an index type
8169     // suitable for the target. Convert the index as required.
8170     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8171     if (Index.getValueType() != VectorIdxTy)
8172       Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8173 
8174     setValue(&I,
8175              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
8176     return;
8177   }
8178   case Intrinsic::vector_reverse:
8179     visitVectorReverse(I);
8180     return;
8181   case Intrinsic::vector_splice:
8182     visitVectorSplice(I);
8183     return;
8184   case Intrinsic::callbr_landingpad:
8185     visitCallBrLandingPad(I);
8186     return;
8187   case Intrinsic::vector_interleave2:
8188     visitVectorInterleave(I);
8189     return;
8190   case Intrinsic::vector_deinterleave2:
8191     visitVectorDeinterleave(I);
8192     return;
8193   case Intrinsic::experimental_vector_compress:
8194     setValue(&I, DAG.getNode(ISD::VECTOR_COMPRESS, sdl,
8195                              getValue(I.getArgOperand(0)).getValueType(),
8196                              getValue(I.getArgOperand(0)),
8197                              getValue(I.getArgOperand(1)),
8198                              getValue(I.getArgOperand(2)), Flags));
8199     return;
8200   case Intrinsic::experimental_convergence_anchor:
8201   case Intrinsic::experimental_convergence_entry:
8202   case Intrinsic::experimental_convergence_loop:
8203     visitConvergenceControl(I, Intrinsic);
8204     return;
8205   case Intrinsic::experimental_vector_histogram_add: {
8206     visitVectorHistogram(I, Intrinsic);
8207     return;
8208   }
8209   }
8210 }
8211 
8212 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
8213     const ConstrainedFPIntrinsic &FPI) {
8214   SDLoc sdl = getCurSDLoc();
8215 
8216   // We do not need to serialize constrained FP intrinsics against
8217   // each other or against (nonvolatile) loads, so they can be
8218   // chained like loads.
8219   SDValue Chain = DAG.getRoot();
8220   SmallVector<SDValue, 4> Opers;
8221   Opers.push_back(Chain);
8222   for (unsigned I = 0, E = FPI.getNonMetadataArgCount(); I != E; ++I)
8223     Opers.push_back(getValue(FPI.getArgOperand(I)));
8224 
8225   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
8226     assert(Result.getNode()->getNumValues() == 2);
8227 
8228     // Push node to the appropriate list so that future instructions can be
8229     // chained up correctly.
8230     SDValue OutChain = Result.getValue(1);
8231     switch (EB) {
8232     case fp::ExceptionBehavior::ebIgnore:
8233       // The only reason why ebIgnore nodes still need to be chained is that
8234       // they might depend on the current rounding mode, and therefore must
8235       // not be moved across instruction that may change that mode.
8236       [[fallthrough]];
8237     case fp::ExceptionBehavior::ebMayTrap:
8238       // These must not be moved across calls or instructions that may change
8239       // floating-point exception masks.
8240       PendingConstrainedFP.push_back(OutChain);
8241       break;
8242     case fp::ExceptionBehavior::ebStrict:
8243       // These must not be moved across calls or instructions that may change
8244       // floating-point exception masks or read floating-point exception flags.
8245       // In addition, they cannot be optimized out even if unused.
8246       PendingConstrainedFPStrict.push_back(OutChain);
8247       break;
8248     }
8249   };
8250 
8251   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8252   EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
8253   SDVTList VTs = DAG.getVTList(VT, MVT::Other);
8254   fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
8255 
8256   SDNodeFlags Flags;
8257   if (EB == fp::ExceptionBehavior::ebIgnore)
8258     Flags.setNoFPExcept(true);
8259 
8260   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
8261     Flags.copyFMF(*FPOp);
8262 
8263   unsigned Opcode;
8264   switch (FPI.getIntrinsicID()) {
8265   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
8266 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8267   case Intrinsic::INTRINSIC:                                                   \
8268     Opcode = ISD::STRICT_##DAGN;                                               \
8269     break;
8270 #include "llvm/IR/ConstrainedOps.def"
8271   case Intrinsic::experimental_constrained_fmuladd: {
8272     Opcode = ISD::STRICT_FMA;
8273     // Break fmuladd into fmul and fadd.
8274     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
8275         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
8276       Opers.pop_back();
8277       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
8278       pushOutChain(Mul, EB);
8279       Opcode = ISD::STRICT_FADD;
8280       Opers.clear();
8281       Opers.push_back(Mul.getValue(1));
8282       Opers.push_back(Mul.getValue(0));
8283       Opers.push_back(getValue(FPI.getArgOperand(2)));
8284     }
8285     break;
8286   }
8287   }
8288 
8289   // A few strict DAG nodes carry additional operands that are not
8290   // set up by the default code above.
8291   switch (Opcode) {
8292   default: break;
8293   case ISD::STRICT_FP_ROUND:
8294     Opers.push_back(
8295         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
8296     break;
8297   case ISD::STRICT_FSETCC:
8298   case ISD::STRICT_FSETCCS: {
8299     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
8300     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
8301     if (TM.Options.NoNaNsFPMath)
8302       Condition = getFCmpCodeWithoutNaN(Condition);
8303     Opers.push_back(DAG.getCondCode(Condition));
8304     break;
8305   }
8306   }
8307 
8308   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
8309   pushOutChain(Result, EB);
8310 
8311   SDValue FPResult = Result.getValue(0);
8312   setValue(&FPI, FPResult);
8313 }
8314 
8315 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
8316   std::optional<unsigned> ResOPC;
8317   switch (VPIntrin.getIntrinsicID()) {
8318   case Intrinsic::vp_ctlz: {
8319     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8320     ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ;
8321     break;
8322   }
8323   case Intrinsic::vp_cttz: {
8324     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8325     ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ;
8326     break;
8327   }
8328   case Intrinsic::vp_cttz_elts: {
8329     bool IsZeroPoison = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8330     ResOPC = IsZeroPoison ? ISD::VP_CTTZ_ELTS_ZERO_UNDEF : ISD::VP_CTTZ_ELTS;
8331     break;
8332   }
8333 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD)                                    \
8334   case Intrinsic::VPID:                                                        \
8335     ResOPC = ISD::VPSD;                                                        \
8336     break;
8337 #include "llvm/IR/VPIntrinsics.def"
8338   }
8339 
8340   if (!ResOPC)
8341     llvm_unreachable(
8342         "Inconsistency: no SDNode available for this VPIntrinsic!");
8343 
8344   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
8345       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
8346     if (VPIntrin.getFastMathFlags().allowReassoc())
8347       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
8348                                                 : ISD::VP_REDUCE_FMUL;
8349   }
8350 
8351   return *ResOPC;
8352 }
8353 
8354 void SelectionDAGBuilder::visitVPLoad(
8355     const VPIntrinsic &VPIntrin, EVT VT,
8356     const SmallVectorImpl<SDValue> &OpValues) {
8357   SDLoc DL = getCurSDLoc();
8358   Value *PtrOperand = VPIntrin.getArgOperand(0);
8359   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8360   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8361   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8362   SDValue LD;
8363   // Do not serialize variable-length loads of constant memory with
8364   // anything.
8365   if (!Alignment)
8366     Alignment = DAG.getEVTAlign(VT);
8367   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
8368   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
8369   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8370   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8371       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
8372       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8373   LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
8374                      MMO, false /*IsExpanding */);
8375   if (AddToChain)
8376     PendingLoads.push_back(LD.getValue(1));
8377   setValue(&VPIntrin, LD);
8378 }
8379 
8380 void SelectionDAGBuilder::visitVPGather(
8381     const VPIntrinsic &VPIntrin, EVT VT,
8382     const SmallVectorImpl<SDValue> &OpValues) {
8383   SDLoc DL = getCurSDLoc();
8384   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8385   Value *PtrOperand = VPIntrin.getArgOperand(0);
8386   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8387   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8388   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8389   SDValue LD;
8390   if (!Alignment)
8391     Alignment = DAG.getEVTAlign(VT.getScalarType());
8392   unsigned AS =
8393     PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8394   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8395       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
8396       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8397   SDValue Base, Index, Scale;
8398   ISD::MemIndexType IndexType;
8399   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
8400                                     this, VPIntrin.getParent(),
8401                                     VT.getScalarStoreSize());
8402   if (!UniformBase) {
8403     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
8404     Index = getValue(PtrOperand);
8405     IndexType = ISD::SIGNED_SCALED;
8406     Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
8407   }
8408   EVT IdxVT = Index.getValueType();
8409   EVT EltTy = IdxVT.getVectorElementType();
8410   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
8411     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
8412     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
8413   }
8414   LD = DAG.getGatherVP(
8415       DAG.getVTList(VT, MVT::Other), VT, DL,
8416       {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
8417       IndexType);
8418   PendingLoads.push_back(LD.getValue(1));
8419   setValue(&VPIntrin, LD);
8420 }
8421 
8422 void SelectionDAGBuilder::visitVPStore(
8423     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8424   SDLoc DL = getCurSDLoc();
8425   Value *PtrOperand = VPIntrin.getArgOperand(1);
8426   EVT VT = OpValues[0].getValueType();
8427   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8428   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8429   SDValue ST;
8430   if (!Alignment)
8431     Alignment = DAG.getEVTAlign(VT);
8432   SDValue Ptr = OpValues[1];
8433   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
8434   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8435       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
8436       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8437   ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
8438                       OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
8439                       /* IsTruncating */ false, /*IsCompressing*/ false);
8440   DAG.setRoot(ST);
8441   setValue(&VPIntrin, ST);
8442 }
8443 
8444 void SelectionDAGBuilder::visitVPScatter(
8445     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8446   SDLoc DL = getCurSDLoc();
8447   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8448   Value *PtrOperand = VPIntrin.getArgOperand(1);
8449   EVT VT = OpValues[0].getValueType();
8450   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8451   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8452   SDValue ST;
8453   if (!Alignment)
8454     Alignment = DAG.getEVTAlign(VT.getScalarType());
8455   unsigned AS =
8456       PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8457   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8458       MachinePointerInfo(AS), MachineMemOperand::MOStore,
8459       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8460   SDValue Base, Index, Scale;
8461   ISD::MemIndexType IndexType;
8462   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
8463                                     this, VPIntrin.getParent(),
8464                                     VT.getScalarStoreSize());
8465   if (!UniformBase) {
8466     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
8467     Index = getValue(PtrOperand);
8468     IndexType = ISD::SIGNED_SCALED;
8469     Scale =
8470       DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
8471   }
8472   EVT IdxVT = Index.getValueType();
8473   EVT EltTy = IdxVT.getVectorElementType();
8474   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
8475     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
8476     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
8477   }
8478   ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
8479                         {getMemoryRoot(), OpValues[0], Base, Index, Scale,
8480                          OpValues[2], OpValues[3]},
8481                         MMO, IndexType);
8482   DAG.setRoot(ST);
8483   setValue(&VPIntrin, ST);
8484 }
8485 
8486 void SelectionDAGBuilder::visitVPStridedLoad(
8487     const VPIntrinsic &VPIntrin, EVT VT,
8488     const SmallVectorImpl<SDValue> &OpValues) {
8489   SDLoc DL = getCurSDLoc();
8490   Value *PtrOperand = VPIntrin.getArgOperand(0);
8491   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8492   if (!Alignment)
8493     Alignment = DAG.getEVTAlign(VT.getScalarType());
8494   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8495   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8496   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
8497   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
8498   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8499   unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8500   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8501       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
8502       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8503 
8504   SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
8505                                     OpValues[2], OpValues[3], MMO,
8506                                     false /*IsExpanding*/);
8507 
8508   if (AddToChain)
8509     PendingLoads.push_back(LD.getValue(1));
8510   setValue(&VPIntrin, LD);
8511 }
8512 
8513 void SelectionDAGBuilder::visitVPStridedStore(
8514     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8515   SDLoc DL = getCurSDLoc();
8516   Value *PtrOperand = VPIntrin.getArgOperand(1);
8517   EVT VT = OpValues[0].getValueType();
8518   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8519   if (!Alignment)
8520     Alignment = DAG.getEVTAlign(VT.getScalarType());
8521   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8522   unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8523   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8524       MachinePointerInfo(AS), MachineMemOperand::MOStore,
8525       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8526 
8527   SDValue ST = DAG.getStridedStoreVP(
8528       getMemoryRoot(), DL, OpValues[0], OpValues[1],
8529       DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3],
8530       OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
8531       /*IsCompressing*/ false);
8532 
8533   DAG.setRoot(ST);
8534   setValue(&VPIntrin, ST);
8535 }
8536 
8537 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) {
8538   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8539   SDLoc DL = getCurSDLoc();
8540 
8541   ISD::CondCode Condition;
8542   CmpInst::Predicate CondCode = VPIntrin.getPredicate();
8543   bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy();
8544   if (IsFP) {
8545     // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan)
8546     // flags, but calls that don't return floating-point types can't be
8547     // FPMathOperators, like vp.fcmp. This affects constrained fcmp too.
8548     Condition = getFCmpCondCode(CondCode);
8549     if (TM.Options.NoNaNsFPMath)
8550       Condition = getFCmpCodeWithoutNaN(Condition);
8551   } else {
8552     Condition = getICmpCondCode(CondCode);
8553   }
8554 
8555   SDValue Op1 = getValue(VPIntrin.getOperand(0));
8556   SDValue Op2 = getValue(VPIntrin.getOperand(1));
8557   // #2 is the condition code
8558   SDValue MaskOp = getValue(VPIntrin.getOperand(3));
8559   SDValue EVL = getValue(VPIntrin.getOperand(4));
8560   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8561   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8562          "Unexpected target EVL type");
8563   EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL);
8564 
8565   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8566                                                         VPIntrin.getType());
8567   setValue(&VPIntrin,
8568            DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL));
8569 }
8570 
8571 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
8572     const VPIntrinsic &VPIntrin) {
8573   SDLoc DL = getCurSDLoc();
8574   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
8575 
8576   auto IID = VPIntrin.getIntrinsicID();
8577 
8578   if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin))
8579     return visitVPCmp(*CmpI);
8580 
8581   SmallVector<EVT, 4> ValueVTs;
8582   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8583   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
8584   SDVTList VTs = DAG.getVTList(ValueVTs);
8585 
8586   auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
8587 
8588   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8589   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8590          "Unexpected target EVL type");
8591 
8592   // Request operands.
8593   SmallVector<SDValue, 7> OpValues;
8594   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
8595     auto Op = getValue(VPIntrin.getArgOperand(I));
8596     if (I == EVLParamPos)
8597       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
8598     OpValues.push_back(Op);
8599   }
8600 
8601   switch (Opcode) {
8602   default: {
8603     SDNodeFlags SDFlags;
8604     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8605       SDFlags.copyFMF(*FPMO);
8606     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
8607     setValue(&VPIntrin, Result);
8608     break;
8609   }
8610   case ISD::VP_LOAD:
8611     visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
8612     break;
8613   case ISD::VP_GATHER:
8614     visitVPGather(VPIntrin, ValueVTs[0], OpValues);
8615     break;
8616   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
8617     visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
8618     break;
8619   case ISD::VP_STORE:
8620     visitVPStore(VPIntrin, OpValues);
8621     break;
8622   case ISD::VP_SCATTER:
8623     visitVPScatter(VPIntrin, OpValues);
8624     break;
8625   case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
8626     visitVPStridedStore(VPIntrin, OpValues);
8627     break;
8628   case ISD::VP_FMULADD: {
8629     assert(OpValues.size() == 5 && "Unexpected number of operands");
8630     SDNodeFlags SDFlags;
8631     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8632       SDFlags.copyFMF(*FPMO);
8633     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
8634         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) {
8635       setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags));
8636     } else {
8637       SDValue Mul = DAG.getNode(
8638           ISD::VP_FMUL, DL, VTs,
8639           {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags);
8640       SDValue Add =
8641           DAG.getNode(ISD::VP_FADD, DL, VTs,
8642                       {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags);
8643       setValue(&VPIntrin, Add);
8644     }
8645     break;
8646   }
8647   case ISD::VP_IS_FPCLASS: {
8648     const DataLayout DLayout = DAG.getDataLayout();
8649     EVT DestVT = TLI.getValueType(DLayout, VPIntrin.getType());
8650     auto Constant = OpValues[1]->getAsZExtVal();
8651     SDValue Check = DAG.getTargetConstant(Constant, DL, MVT::i32);
8652     SDValue V = DAG.getNode(ISD::VP_IS_FPCLASS, DL, DestVT,
8653                             {OpValues[0], Check, OpValues[2], OpValues[3]});
8654     setValue(&VPIntrin, V);
8655     return;
8656   }
8657   case ISD::VP_INTTOPTR: {
8658     SDValue N = OpValues[0];
8659     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType());
8660     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType());
8661     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8662                                OpValues[2]);
8663     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8664                              OpValues[2]);
8665     setValue(&VPIntrin, N);
8666     break;
8667   }
8668   case ISD::VP_PTRTOINT: {
8669     SDValue N = OpValues[0];
8670     EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8671                                                           VPIntrin.getType());
8672     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(),
8673                                        VPIntrin.getOperand(0)->getType());
8674     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8675                                OpValues[2]);
8676     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8677                              OpValues[2]);
8678     setValue(&VPIntrin, N);
8679     break;
8680   }
8681   case ISD::VP_ABS:
8682   case ISD::VP_CTLZ:
8683   case ISD::VP_CTLZ_ZERO_UNDEF:
8684   case ISD::VP_CTTZ:
8685   case ISD::VP_CTTZ_ZERO_UNDEF:
8686   case ISD::VP_CTTZ_ELTS_ZERO_UNDEF:
8687   case ISD::VP_CTTZ_ELTS: {
8688     SDValue Result =
8689         DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]});
8690     setValue(&VPIntrin, Result);
8691     break;
8692   }
8693   }
8694 }
8695 
8696 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
8697                                           const BasicBlock *EHPadBB,
8698                                           MCSymbol *&BeginLabel) {
8699   MachineFunction &MF = DAG.getMachineFunction();
8700 
8701   // Insert a label before the invoke call to mark the try range.  This can be
8702   // used to detect deletion of the invoke via the MachineModuleInfo.
8703   BeginLabel = MF.getContext().createTempSymbol();
8704 
8705   // For SjLj, keep track of which landing pads go with which invokes
8706   // so as to maintain the ordering of pads in the LSDA.
8707   unsigned CallSiteIndex = FuncInfo.getCurrentCallSite();
8708   if (CallSiteIndex) {
8709     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
8710     LPadToCallSiteMap[FuncInfo.getMBB(EHPadBB)].push_back(CallSiteIndex);
8711 
8712     // Now that the call site is handled, stop tracking it.
8713     FuncInfo.setCurrentCallSite(0);
8714   }
8715 
8716   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
8717 }
8718 
8719 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
8720                                         const BasicBlock *EHPadBB,
8721                                         MCSymbol *BeginLabel) {
8722   assert(BeginLabel && "BeginLabel should've been set");
8723 
8724   MachineFunction &MF = DAG.getMachineFunction();
8725 
8726   // Insert a label at the end of the invoke call to mark the try range.  This
8727   // can be used to detect deletion of the invoke via the MachineModuleInfo.
8728   MCSymbol *EndLabel = MF.getContext().createTempSymbol();
8729   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
8730 
8731   // Inform MachineModuleInfo of range.
8732   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
8733   // There is a platform (e.g. wasm) that uses funclet style IR but does not
8734   // actually use outlined funclets and their LSDA info style.
8735   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
8736     assert(II && "II should've been set");
8737     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
8738     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
8739   } else if (!isScopedEHPersonality(Pers)) {
8740     assert(EHPadBB);
8741     MF.addInvoke(FuncInfo.getMBB(EHPadBB), BeginLabel, EndLabel);
8742   }
8743 
8744   return Chain;
8745 }
8746 
8747 std::pair<SDValue, SDValue>
8748 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
8749                                     const BasicBlock *EHPadBB) {
8750   MCSymbol *BeginLabel = nullptr;
8751 
8752   if (EHPadBB) {
8753     // Both PendingLoads and PendingExports must be flushed here;
8754     // this call might not return.
8755     (void)getRoot();
8756     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
8757     CLI.setChain(getRoot());
8758   }
8759 
8760   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8761   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
8762 
8763   assert((CLI.IsTailCall || Result.second.getNode()) &&
8764          "Non-null chain expected with non-tail call!");
8765   assert((Result.second.getNode() || !Result.first.getNode()) &&
8766          "Null value expected with tail call!");
8767 
8768   if (!Result.second.getNode()) {
8769     // As a special case, a null chain means that a tail call has been emitted
8770     // and the DAG root is already updated.
8771     HasTailCall = true;
8772 
8773     // Since there's no actual continuation from this block, nothing can be
8774     // relying on us setting vregs for them.
8775     PendingExports.clear();
8776   } else {
8777     DAG.setRoot(Result.second);
8778   }
8779 
8780   if (EHPadBB) {
8781     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
8782                            BeginLabel));
8783     Result.second = getRoot();
8784   }
8785 
8786   return Result;
8787 }
8788 
8789 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
8790                                       bool isTailCall, bool isMustTailCall,
8791                                       const BasicBlock *EHPadBB,
8792                                       const TargetLowering::PtrAuthInfo *PAI) {
8793   auto &DL = DAG.getDataLayout();
8794   FunctionType *FTy = CB.getFunctionType();
8795   Type *RetTy = CB.getType();
8796 
8797   TargetLowering::ArgListTy Args;
8798   Args.reserve(CB.arg_size());
8799 
8800   const Value *SwiftErrorVal = nullptr;
8801   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8802 
8803   if (isTailCall) {
8804     // Avoid emitting tail calls in functions with the disable-tail-calls
8805     // attribute.
8806     auto *Caller = CB.getParent()->getParent();
8807     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
8808         "true" && !isMustTailCall)
8809       isTailCall = false;
8810 
8811     // We can't tail call inside a function with a swifterror argument. Lowering
8812     // does not support this yet. It would have to move into the swifterror
8813     // register before the call.
8814     if (TLI.supportSwiftError() &&
8815         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
8816       isTailCall = false;
8817   }
8818 
8819   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
8820     TargetLowering::ArgListEntry Entry;
8821     const Value *V = *I;
8822 
8823     // Skip empty types
8824     if (V->getType()->isEmptyTy())
8825       continue;
8826 
8827     SDValue ArgNode = getValue(V);
8828     Entry.Node = ArgNode; Entry.Ty = V->getType();
8829 
8830     Entry.setAttributes(&CB, I - CB.arg_begin());
8831 
8832     // Use swifterror virtual register as input to the call.
8833     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
8834       SwiftErrorVal = V;
8835       // We find the virtual register for the actual swifterror argument.
8836       // Instead of using the Value, we use the virtual register instead.
8837       Entry.Node =
8838           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
8839                           EVT(TLI.getPointerTy(DL)));
8840     }
8841 
8842     Args.push_back(Entry);
8843 
8844     // If we have an explicit sret argument that is an Instruction, (i.e., it
8845     // might point to function-local memory), we can't meaningfully tail-call.
8846     if (Entry.IsSRet && isa<Instruction>(V))
8847       isTailCall = false;
8848   }
8849 
8850   // If call site has a cfguardtarget operand bundle, create and add an
8851   // additional ArgListEntry.
8852   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
8853     TargetLowering::ArgListEntry Entry;
8854     Value *V = Bundle->Inputs[0];
8855     SDValue ArgNode = getValue(V);
8856     Entry.Node = ArgNode;
8857     Entry.Ty = V->getType();
8858     Entry.IsCFGuardTarget = true;
8859     Args.push_back(Entry);
8860   }
8861 
8862   // Check if target-independent constraints permit a tail call here.
8863   // Target-dependent constraints are checked within TLI->LowerCallTo.
8864   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
8865     isTailCall = false;
8866 
8867   // Disable tail calls if there is an swifterror argument. Targets have not
8868   // been updated to support tail calls.
8869   if (TLI.supportSwiftError() && SwiftErrorVal)
8870     isTailCall = false;
8871 
8872   ConstantInt *CFIType = nullptr;
8873   if (CB.isIndirectCall()) {
8874     if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
8875       if (!TLI.supportKCFIBundles())
8876         report_fatal_error(
8877             "Target doesn't support calls with kcfi operand bundles.");
8878       CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
8879       assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
8880     }
8881   }
8882 
8883   SDValue ConvControlToken;
8884   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_convergencectrl)) {
8885     auto *Token = Bundle->Inputs[0].get();
8886     ConvControlToken = getValue(Token);
8887   }
8888 
8889   TargetLowering::CallLoweringInfo CLI(DAG);
8890   CLI.setDebugLoc(getCurSDLoc())
8891       .setChain(getRoot())
8892       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
8893       .setTailCall(isTailCall)
8894       .setConvergent(CB.isConvergent())
8895       .setIsPreallocated(
8896           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
8897       .setCFIType(CFIType)
8898       .setConvergenceControlToken(ConvControlToken);
8899 
8900   // Set the pointer authentication info if we have it.
8901   if (PAI) {
8902     if (!TLI.supportPtrAuthBundles())
8903       report_fatal_error(
8904           "This target doesn't support calls with ptrauth operand bundles.");
8905     CLI.setPtrAuth(*PAI);
8906   }
8907 
8908   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8909 
8910   if (Result.first.getNode()) {
8911     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
8912     setValue(&CB, Result.first);
8913   }
8914 
8915   // The last element of CLI.InVals has the SDValue for swifterror return.
8916   // Here we copy it to a virtual register and update SwiftErrorMap for
8917   // book-keeping.
8918   if (SwiftErrorVal && TLI.supportSwiftError()) {
8919     // Get the last element of InVals.
8920     SDValue Src = CLI.InVals.back();
8921     Register VReg =
8922         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
8923     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
8924     DAG.setRoot(CopyNode);
8925   }
8926 }
8927 
8928 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
8929                              SelectionDAGBuilder &Builder) {
8930   // Check to see if this load can be trivially constant folded, e.g. if the
8931   // input is from a string literal.
8932   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
8933     // Cast pointer to the type we really want to load.
8934     Type *LoadTy =
8935         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
8936     if (LoadVT.isVector())
8937       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
8938 
8939     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
8940                                          PointerType::getUnqual(LoadTy));
8941 
8942     if (const Constant *LoadCst =
8943             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
8944                                          LoadTy, Builder.DAG.getDataLayout()))
8945       return Builder.getValue(LoadCst);
8946   }
8947 
8948   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
8949   // still constant memory, the input chain can be the entry node.
8950   SDValue Root;
8951   bool ConstantMemory = false;
8952 
8953   // Do not serialize (non-volatile) loads of constant memory with anything.
8954   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
8955     Root = Builder.DAG.getEntryNode();
8956     ConstantMemory = true;
8957   } else {
8958     // Do not serialize non-volatile loads against each other.
8959     Root = Builder.DAG.getRoot();
8960   }
8961 
8962   SDValue Ptr = Builder.getValue(PtrVal);
8963   SDValue LoadVal =
8964       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
8965                           MachinePointerInfo(PtrVal), Align(1));
8966 
8967   if (!ConstantMemory)
8968     Builder.PendingLoads.push_back(LoadVal.getValue(1));
8969   return LoadVal;
8970 }
8971 
8972 /// Record the value for an instruction that produces an integer result,
8973 /// converting the type where necessary.
8974 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
8975                                                   SDValue Value,
8976                                                   bool IsSigned) {
8977   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8978                                                     I.getType(), true);
8979   Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT);
8980   setValue(&I, Value);
8981 }
8982 
8983 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
8984 /// true and lower it. Otherwise return false, and it will be lowered like a
8985 /// normal call.
8986 /// The caller already checked that \p I calls the appropriate LibFunc with a
8987 /// correct prototype.
8988 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
8989   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
8990   const Value *Size = I.getArgOperand(2);
8991   const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
8992   if (CSize && CSize->getZExtValue() == 0) {
8993     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8994                                                           I.getType(), true);
8995     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
8996     return true;
8997   }
8998 
8999   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9000   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
9001       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
9002       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
9003   if (Res.first.getNode()) {
9004     processIntegerCallValue(I, Res.first, true);
9005     PendingLoads.push_back(Res.second);
9006     return true;
9007   }
9008 
9009   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
9010   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
9011   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
9012     return false;
9013 
9014   // If the target has a fast compare for the given size, it will return a
9015   // preferred load type for that size. Require that the load VT is legal and
9016   // that the target supports unaligned loads of that type. Otherwise, return
9017   // INVALID.
9018   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
9019     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9020     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
9021     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
9022       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
9023       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
9024       // TODO: Check alignment of src and dest ptrs.
9025       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
9026       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
9027       if (!TLI.isTypeLegal(LVT) ||
9028           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
9029           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
9030         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
9031     }
9032 
9033     return LVT;
9034   };
9035 
9036   // This turns into unaligned loads. We only do this if the target natively
9037   // supports the MVT we'll be loading or if it is small enough (<= 4) that
9038   // we'll only produce a small number of byte loads.
9039   MVT LoadVT;
9040   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
9041   switch (NumBitsToCompare) {
9042   default:
9043     return false;
9044   case 16:
9045     LoadVT = MVT::i16;
9046     break;
9047   case 32:
9048     LoadVT = MVT::i32;
9049     break;
9050   case 64:
9051   case 128:
9052   case 256:
9053     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
9054     break;
9055   }
9056 
9057   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
9058     return false;
9059 
9060   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
9061   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
9062 
9063   // Bitcast to a wide integer type if the loads are vectors.
9064   if (LoadVT.isVector()) {
9065     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
9066     LoadL = DAG.getBitcast(CmpVT, LoadL);
9067     LoadR = DAG.getBitcast(CmpVT, LoadR);
9068   }
9069 
9070   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
9071   processIntegerCallValue(I, Cmp, false);
9072   return true;
9073 }
9074 
9075 /// See if we can lower a memchr call into an optimized form. If so, return
9076 /// true and lower it. Otherwise return false, and it will be lowered like a
9077 /// normal call.
9078 /// The caller already checked that \p I calls the appropriate LibFunc with a
9079 /// correct prototype.
9080 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
9081   const Value *Src = I.getArgOperand(0);
9082   const Value *Char = I.getArgOperand(1);
9083   const Value *Length = I.getArgOperand(2);
9084 
9085   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9086   std::pair<SDValue, SDValue> Res =
9087     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
9088                                 getValue(Src), getValue(Char), getValue(Length),
9089                                 MachinePointerInfo(Src));
9090   if (Res.first.getNode()) {
9091     setValue(&I, Res.first);
9092     PendingLoads.push_back(Res.second);
9093     return true;
9094   }
9095 
9096   return false;
9097 }
9098 
9099 /// See if we can lower a mempcpy call into an optimized form. If so, return
9100 /// true and lower it. Otherwise return false, and it will be lowered like a
9101 /// normal call.
9102 /// The caller already checked that \p I calls the appropriate LibFunc with a
9103 /// correct prototype.
9104 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
9105   SDValue Dst = getValue(I.getArgOperand(0));
9106   SDValue Src = getValue(I.getArgOperand(1));
9107   SDValue Size = getValue(I.getArgOperand(2));
9108 
9109   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
9110   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
9111   // DAG::getMemcpy needs Alignment to be defined.
9112   Align Alignment = std::min(DstAlign, SrcAlign);
9113 
9114   SDLoc sdl = getCurSDLoc();
9115 
9116   // In the mempcpy context we need to pass in a false value for isTailCall
9117   // because the return pointer needs to be adjusted by the size of
9118   // the copied memory.
9119   SDValue Root = getMemoryRoot();
9120   SDValue MC = DAG.getMemcpy(
9121       Root, sdl, Dst, Src, Size, Alignment, false, false, /*CI=*/nullptr,
9122       std::nullopt, MachinePointerInfo(I.getArgOperand(0)),
9123       MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata());
9124   assert(MC.getNode() != nullptr &&
9125          "** memcpy should not be lowered as TailCall in mempcpy context **");
9126   DAG.setRoot(MC);
9127 
9128   // Check if Size needs to be truncated or extended.
9129   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
9130 
9131   // Adjust return pointer to point just past the last dst byte.
9132   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
9133                                     Dst, Size);
9134   setValue(&I, DstPlusSize);
9135   return true;
9136 }
9137 
9138 /// See if we can lower a strcpy call into an optimized form.  If so, return
9139 /// true and lower it, otherwise return false and it will be lowered like a
9140 /// normal call.
9141 /// The caller already checked that \p I calls the appropriate LibFunc with a
9142 /// correct prototype.
9143 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
9144   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9145 
9146   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9147   std::pair<SDValue, SDValue> Res =
9148     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
9149                                 getValue(Arg0), getValue(Arg1),
9150                                 MachinePointerInfo(Arg0),
9151                                 MachinePointerInfo(Arg1), isStpcpy);
9152   if (Res.first.getNode()) {
9153     setValue(&I, Res.first);
9154     DAG.setRoot(Res.second);
9155     return true;
9156   }
9157 
9158   return false;
9159 }
9160 
9161 /// See if we can lower a strcmp 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::visitStrCmpCall(const CallInst &I) {
9167   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9168 
9169   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9170   std::pair<SDValue, SDValue> Res =
9171     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
9172                                 getValue(Arg0), getValue(Arg1),
9173                                 MachinePointerInfo(Arg0),
9174                                 MachinePointerInfo(Arg1));
9175   if (Res.first.getNode()) {
9176     processIntegerCallValue(I, Res.first, true);
9177     PendingLoads.push_back(Res.second);
9178     return true;
9179   }
9180 
9181   return false;
9182 }
9183 
9184 /// See if we can lower a strlen call into an optimized form.  If so, return
9185 /// true and lower it, otherwise return false and it will be lowered like a
9186 /// normal call.
9187 /// The caller already checked that \p I calls the appropriate LibFunc with a
9188 /// correct prototype.
9189 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
9190   const Value *Arg0 = I.getArgOperand(0);
9191 
9192   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9193   std::pair<SDValue, SDValue> Res =
9194     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
9195                                 getValue(Arg0), MachinePointerInfo(Arg0));
9196   if (Res.first.getNode()) {
9197     processIntegerCallValue(I, Res.first, false);
9198     PendingLoads.push_back(Res.second);
9199     return true;
9200   }
9201 
9202   return false;
9203 }
9204 
9205 /// See if we can lower a strnlen call into an optimized form.  If so, return
9206 /// true and lower it, otherwise return false and it will be lowered like a
9207 /// normal call.
9208 /// The caller already checked that \p I calls the appropriate LibFunc with a
9209 /// correct prototype.
9210 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
9211   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9212 
9213   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9214   std::pair<SDValue, SDValue> Res =
9215     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
9216                                  getValue(Arg0), getValue(Arg1),
9217                                  MachinePointerInfo(Arg0));
9218   if (Res.first.getNode()) {
9219     processIntegerCallValue(I, Res.first, false);
9220     PendingLoads.push_back(Res.second);
9221     return true;
9222   }
9223 
9224   return false;
9225 }
9226 
9227 /// See if we can lower a unary floating-point operation into an SDNode with
9228 /// the specified Opcode.  If so, return true and lower it, otherwise return
9229 /// false and it will be lowered like a normal call.
9230 /// The caller already checked that \p I calls the appropriate LibFunc with a
9231 /// correct prototype.
9232 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
9233                                               unsigned Opcode) {
9234   // We already checked this call's prototype; verify it doesn't modify errno.
9235   if (!I.onlyReadsMemory())
9236     return false;
9237 
9238   SDNodeFlags Flags;
9239   Flags.copyFMF(cast<FPMathOperator>(I));
9240 
9241   SDValue Tmp = getValue(I.getArgOperand(0));
9242   setValue(&I,
9243            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
9244   return true;
9245 }
9246 
9247 /// See if we can lower a binary floating-point operation into an SDNode with
9248 /// the specified Opcode. If so, return true and lower it. Otherwise return
9249 /// false, and it will be lowered like a normal call.
9250 /// The caller already checked that \p I calls the appropriate LibFunc with a
9251 /// correct prototype.
9252 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
9253                                                unsigned Opcode) {
9254   // We already checked this call's prototype; verify it doesn't modify errno.
9255   if (!I.onlyReadsMemory())
9256     return false;
9257 
9258   SDNodeFlags Flags;
9259   Flags.copyFMF(cast<FPMathOperator>(I));
9260 
9261   SDValue Tmp0 = getValue(I.getArgOperand(0));
9262   SDValue Tmp1 = getValue(I.getArgOperand(1));
9263   EVT VT = Tmp0.getValueType();
9264   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
9265   return true;
9266 }
9267 
9268 void SelectionDAGBuilder::visitCall(const CallInst &I) {
9269   // Handle inline assembly differently.
9270   if (I.isInlineAsm()) {
9271     visitInlineAsm(I);
9272     return;
9273   }
9274 
9275   diagnoseDontCall(I);
9276 
9277   if (Function *F = I.getCalledFunction()) {
9278     if (F->isDeclaration()) {
9279       // Is this an LLVM intrinsic or a target-specific intrinsic?
9280       unsigned IID = F->getIntrinsicID();
9281       if (!IID)
9282         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
9283           IID = II->getIntrinsicID(F);
9284 
9285       if (IID) {
9286         visitIntrinsicCall(I, IID);
9287         return;
9288       }
9289     }
9290 
9291     // Check for well-known libc/libm calls.  If the function is internal, it
9292     // can't be a library call.  Don't do the check if marked as nobuiltin for
9293     // some reason or the call site requires strict floating point semantics.
9294     LibFunc Func;
9295     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
9296         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
9297         LibInfo->hasOptimizedCodeGen(Func)) {
9298       switch (Func) {
9299       default: break;
9300       case LibFunc_bcmp:
9301         if (visitMemCmpBCmpCall(I))
9302           return;
9303         break;
9304       case LibFunc_copysign:
9305       case LibFunc_copysignf:
9306       case LibFunc_copysignl:
9307         // We already checked this call's prototype; verify it doesn't modify
9308         // errno.
9309         if (I.onlyReadsMemory()) {
9310           SDValue LHS = getValue(I.getArgOperand(0));
9311           SDValue RHS = getValue(I.getArgOperand(1));
9312           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
9313                                    LHS.getValueType(), LHS, RHS));
9314           return;
9315         }
9316         break;
9317       case LibFunc_fabs:
9318       case LibFunc_fabsf:
9319       case LibFunc_fabsl:
9320         if (visitUnaryFloatCall(I, ISD::FABS))
9321           return;
9322         break;
9323       case LibFunc_fmin:
9324       case LibFunc_fminf:
9325       case LibFunc_fminl:
9326         if (visitBinaryFloatCall(I, ISD::FMINNUM))
9327           return;
9328         break;
9329       case LibFunc_fmax:
9330       case LibFunc_fmaxf:
9331       case LibFunc_fmaxl:
9332         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
9333           return;
9334         break;
9335       case LibFunc_fminimum_num:
9336       case LibFunc_fminimum_numf:
9337       case LibFunc_fminimum_numl:
9338         if (visitBinaryFloatCall(I, ISD::FMINIMUMNUM))
9339           return;
9340         break;
9341       case LibFunc_fmaximum_num:
9342       case LibFunc_fmaximum_numf:
9343       case LibFunc_fmaximum_numl:
9344         if (visitBinaryFloatCall(I, ISD::FMAXIMUMNUM))
9345           return;
9346         break;
9347       case LibFunc_sin:
9348       case LibFunc_sinf:
9349       case LibFunc_sinl:
9350         if (visitUnaryFloatCall(I, ISD::FSIN))
9351           return;
9352         break;
9353       case LibFunc_cos:
9354       case LibFunc_cosf:
9355       case LibFunc_cosl:
9356         if (visitUnaryFloatCall(I, ISD::FCOS))
9357           return;
9358         break;
9359       case LibFunc_tan:
9360       case LibFunc_tanf:
9361       case LibFunc_tanl:
9362         if (visitUnaryFloatCall(I, ISD::FTAN))
9363           return;
9364         break;
9365       case LibFunc_asin:
9366       case LibFunc_asinf:
9367       case LibFunc_asinl:
9368         if (visitUnaryFloatCall(I, ISD::FASIN))
9369           return;
9370         break;
9371       case LibFunc_acos:
9372       case LibFunc_acosf:
9373       case LibFunc_acosl:
9374         if (visitUnaryFloatCall(I, ISD::FACOS))
9375           return;
9376         break;
9377       case LibFunc_atan:
9378       case LibFunc_atanf:
9379       case LibFunc_atanl:
9380         if (visitUnaryFloatCall(I, ISD::FATAN))
9381           return;
9382         break;
9383       case LibFunc_atan2:
9384       case LibFunc_atan2f:
9385       case LibFunc_atan2l:
9386         if (visitBinaryFloatCall(I, ISD::FATAN2))
9387           return;
9388         break;
9389       case LibFunc_sinh:
9390       case LibFunc_sinhf:
9391       case LibFunc_sinhl:
9392         if (visitUnaryFloatCall(I, ISD::FSINH))
9393           return;
9394         break;
9395       case LibFunc_cosh:
9396       case LibFunc_coshf:
9397       case LibFunc_coshl:
9398         if (visitUnaryFloatCall(I, ISD::FCOSH))
9399           return;
9400         break;
9401       case LibFunc_tanh:
9402       case LibFunc_tanhf:
9403       case LibFunc_tanhl:
9404         if (visitUnaryFloatCall(I, ISD::FTANH))
9405           return;
9406         break;
9407       case LibFunc_sqrt:
9408       case LibFunc_sqrtf:
9409       case LibFunc_sqrtl:
9410       case LibFunc_sqrt_finite:
9411       case LibFunc_sqrtf_finite:
9412       case LibFunc_sqrtl_finite:
9413         if (visitUnaryFloatCall(I, ISD::FSQRT))
9414           return;
9415         break;
9416       case LibFunc_floor:
9417       case LibFunc_floorf:
9418       case LibFunc_floorl:
9419         if (visitUnaryFloatCall(I, ISD::FFLOOR))
9420           return;
9421         break;
9422       case LibFunc_nearbyint:
9423       case LibFunc_nearbyintf:
9424       case LibFunc_nearbyintl:
9425         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
9426           return;
9427         break;
9428       case LibFunc_ceil:
9429       case LibFunc_ceilf:
9430       case LibFunc_ceill:
9431         if (visitUnaryFloatCall(I, ISD::FCEIL))
9432           return;
9433         break;
9434       case LibFunc_rint:
9435       case LibFunc_rintf:
9436       case LibFunc_rintl:
9437         if (visitUnaryFloatCall(I, ISD::FRINT))
9438           return;
9439         break;
9440       case LibFunc_round:
9441       case LibFunc_roundf:
9442       case LibFunc_roundl:
9443         if (visitUnaryFloatCall(I, ISD::FROUND))
9444           return;
9445         break;
9446       case LibFunc_trunc:
9447       case LibFunc_truncf:
9448       case LibFunc_truncl:
9449         if (visitUnaryFloatCall(I, ISD::FTRUNC))
9450           return;
9451         break;
9452       case LibFunc_log2:
9453       case LibFunc_log2f:
9454       case LibFunc_log2l:
9455         if (visitUnaryFloatCall(I, ISD::FLOG2))
9456           return;
9457         break;
9458       case LibFunc_exp2:
9459       case LibFunc_exp2f:
9460       case LibFunc_exp2l:
9461         if (visitUnaryFloatCall(I, ISD::FEXP2))
9462           return;
9463         break;
9464       case LibFunc_exp10:
9465       case LibFunc_exp10f:
9466       case LibFunc_exp10l:
9467         if (visitUnaryFloatCall(I, ISD::FEXP10))
9468           return;
9469         break;
9470       case LibFunc_ldexp:
9471       case LibFunc_ldexpf:
9472       case LibFunc_ldexpl:
9473         if (visitBinaryFloatCall(I, ISD::FLDEXP))
9474           return;
9475         break;
9476       case LibFunc_memcmp:
9477         if (visitMemCmpBCmpCall(I))
9478           return;
9479         break;
9480       case LibFunc_mempcpy:
9481         if (visitMemPCpyCall(I))
9482           return;
9483         break;
9484       case LibFunc_memchr:
9485         if (visitMemChrCall(I))
9486           return;
9487         break;
9488       case LibFunc_strcpy:
9489         if (visitStrCpyCall(I, false))
9490           return;
9491         break;
9492       case LibFunc_stpcpy:
9493         if (visitStrCpyCall(I, true))
9494           return;
9495         break;
9496       case LibFunc_strcmp:
9497         if (visitStrCmpCall(I))
9498           return;
9499         break;
9500       case LibFunc_strlen:
9501         if (visitStrLenCall(I))
9502           return;
9503         break;
9504       case LibFunc_strnlen:
9505         if (visitStrNLenCall(I))
9506           return;
9507         break;
9508       }
9509     }
9510   }
9511 
9512   if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
9513     LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), /*EHPadBB=*/nullptr);
9514     return;
9515   }
9516 
9517   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
9518   // have to do anything here to lower funclet bundles.
9519   // CFGuardTarget bundles are lowered in LowerCallTo.
9520   assert(!I.hasOperandBundlesOtherThan(
9521              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
9522               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
9523               LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi,
9524               LLVMContext::OB_convergencectrl}) &&
9525          "Cannot lower calls with arbitrary operand bundles!");
9526 
9527   SDValue Callee = getValue(I.getCalledOperand());
9528 
9529   if (I.hasDeoptState())
9530     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
9531   else
9532     // Check if we can potentially perform a tail call. More detailed checking
9533     // is be done within LowerCallTo, after more information about the call is
9534     // known.
9535     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
9536 }
9537 
9538 void SelectionDAGBuilder::LowerCallSiteWithPtrAuthBundle(
9539     const CallBase &CB, const BasicBlock *EHPadBB) {
9540   auto PAB = CB.getOperandBundle("ptrauth");
9541   const Value *CalleeV = CB.getCalledOperand();
9542 
9543   // Gather the call ptrauth data from the operand bundle:
9544   //   [ i32 <key>, i64 <discriminator> ]
9545   const auto *Key = cast<ConstantInt>(PAB->Inputs[0]);
9546   const Value *Discriminator = PAB->Inputs[1];
9547 
9548   assert(Key->getType()->isIntegerTy(32) && "Invalid ptrauth key");
9549   assert(Discriminator->getType()->isIntegerTy(64) &&
9550          "Invalid ptrauth discriminator");
9551 
9552   // Look through ptrauth constants to find the raw callee.
9553   // Do a direct unauthenticated call if we found it and everything matches.
9554   if (const auto *CalleeCPA = dyn_cast<ConstantPtrAuth>(CalleeV))
9555     if (CalleeCPA->isKnownCompatibleWith(Key, Discriminator,
9556                                          DAG.getDataLayout()))
9557       return LowerCallTo(CB, getValue(CalleeCPA->getPointer()), CB.isTailCall(),
9558                          CB.isMustTailCall(), EHPadBB);
9559 
9560   // Functions should never be ptrauth-called directly.
9561   assert(!isa<Function>(CalleeV) && "invalid direct ptrauth call");
9562 
9563   // Otherwise, do an authenticated indirect call.
9564   TargetLowering::PtrAuthInfo PAI = {Key->getZExtValue(),
9565                                      getValue(Discriminator)};
9566 
9567   LowerCallTo(CB, getValue(CalleeV), CB.isTailCall(), CB.isMustTailCall(),
9568               EHPadBB, &PAI);
9569 }
9570 
9571 namespace {
9572 
9573 /// AsmOperandInfo - This contains information for each constraint that we are
9574 /// lowering.
9575 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
9576 public:
9577   /// CallOperand - If this is the result output operand or a clobber
9578   /// this is null, otherwise it is the incoming operand to the CallInst.
9579   /// This gets modified as the asm is processed.
9580   SDValue CallOperand;
9581 
9582   /// AssignedRegs - If this is a register or register class operand, this
9583   /// contains the set of register corresponding to the operand.
9584   RegsForValue AssignedRegs;
9585 
9586   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
9587     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
9588   }
9589 
9590   /// Whether or not this operand accesses memory
9591   bool hasMemory(const TargetLowering &TLI) const {
9592     // Indirect operand accesses access memory.
9593     if (isIndirect)
9594       return true;
9595 
9596     for (const auto &Code : Codes)
9597       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
9598         return true;
9599 
9600     return false;
9601   }
9602 };
9603 
9604 
9605 } // end anonymous namespace
9606 
9607 /// Make sure that the output operand \p OpInfo and its corresponding input
9608 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
9609 /// out).
9610 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
9611                                SDISelAsmOperandInfo &MatchingOpInfo,
9612                                SelectionDAG &DAG) {
9613   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
9614     return;
9615 
9616   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
9617   const auto &TLI = DAG.getTargetLoweringInfo();
9618 
9619   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
9620       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
9621                                        OpInfo.ConstraintVT);
9622   std::pair<unsigned, const TargetRegisterClass *> InputRC =
9623       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
9624                                        MatchingOpInfo.ConstraintVT);
9625   const bool OutOpIsIntOrFP =
9626       OpInfo.ConstraintVT.isInteger() || OpInfo.ConstraintVT.isFloatingPoint();
9627   const bool InOpIsIntOrFP = MatchingOpInfo.ConstraintVT.isInteger() ||
9628                              MatchingOpInfo.ConstraintVT.isFloatingPoint();
9629   if ((OutOpIsIntOrFP != InOpIsIntOrFP) || (MatchRC.second != InputRC.second)) {
9630     // FIXME: error out in a more elegant fashion
9631     report_fatal_error("Unsupported asm: input constraint"
9632                        " with a matching output constraint of"
9633                        " incompatible type!");
9634   }
9635   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
9636 }
9637 
9638 /// Get a direct memory input to behave well as an indirect operand.
9639 /// This may introduce stores, hence the need for a \p Chain.
9640 /// \return The (possibly updated) chain.
9641 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
9642                                         SDISelAsmOperandInfo &OpInfo,
9643                                         SelectionDAG &DAG) {
9644   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9645 
9646   // If we don't have an indirect input, put it in the constpool if we can,
9647   // otherwise spill it to a stack slot.
9648   // TODO: This isn't quite right. We need to handle these according to
9649   // the addressing mode that the constraint wants. Also, this may take
9650   // an additional register for the computation and we don't want that
9651   // either.
9652 
9653   // If the operand is a float, integer, or vector constant, spill to a
9654   // constant pool entry to get its address.
9655   const Value *OpVal = OpInfo.CallOperandVal;
9656   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
9657       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
9658     OpInfo.CallOperand = DAG.getConstantPool(
9659         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
9660     return Chain;
9661   }
9662 
9663   // Otherwise, create a stack slot and emit a store to it before the asm.
9664   Type *Ty = OpVal->getType();
9665   auto &DL = DAG.getDataLayout();
9666   TypeSize TySize = DL.getTypeAllocSize(Ty);
9667   MachineFunction &MF = DAG.getMachineFunction();
9668   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
9669   int StackID = 0;
9670   if (TySize.isScalable())
9671     StackID = TFI->getStackIDForScalableVectors();
9672   int SSFI = MF.getFrameInfo().CreateStackObject(TySize.getKnownMinValue(),
9673                                                  DL.getPrefTypeAlign(Ty), false,
9674                                                  nullptr, StackID);
9675   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
9676   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
9677                             MachinePointerInfo::getFixedStack(MF, SSFI),
9678                             TLI.getMemValueType(DL, Ty));
9679   OpInfo.CallOperand = StackSlot;
9680 
9681   return Chain;
9682 }
9683 
9684 /// GetRegistersForValue - Assign registers (virtual or physical) for the
9685 /// specified operand.  We prefer to assign virtual registers, to allow the
9686 /// register allocator to handle the assignment process.  However, if the asm
9687 /// uses features that we can't model on machineinstrs, we have SDISel do the
9688 /// allocation.  This produces generally horrible, but correct, code.
9689 ///
9690 ///   OpInfo describes the operand
9691 ///   RefOpInfo describes the matching operand if any, the operand otherwise
9692 static std::optional<unsigned>
9693 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
9694                      SDISelAsmOperandInfo &OpInfo,
9695                      SDISelAsmOperandInfo &RefOpInfo) {
9696   LLVMContext &Context = *DAG.getContext();
9697   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9698 
9699   MachineFunction &MF = DAG.getMachineFunction();
9700   SmallVector<Register, 4> Regs;
9701   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9702 
9703   // No work to do for memory/address operands.
9704   if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9705       OpInfo.ConstraintType == TargetLowering::C_Address)
9706     return std::nullopt;
9707 
9708   // If this is a constraint for a single physreg, or a constraint for a
9709   // register class, find it.
9710   unsigned AssignedReg;
9711   const TargetRegisterClass *RC;
9712   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
9713       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
9714   // RC is unset only on failure. Return immediately.
9715   if (!RC)
9716     return std::nullopt;
9717 
9718   // Get the actual register value type.  This is important, because the user
9719   // may have asked for (e.g.) the AX register in i32 type.  We need to
9720   // remember that AX is actually i16 to get the right extension.
9721   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
9722 
9723   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
9724     // If this is an FP operand in an integer register (or visa versa), or more
9725     // generally if the operand value disagrees with the register class we plan
9726     // to stick it in, fix the operand type.
9727     //
9728     // If this is an input value, the bitcast to the new type is done now.
9729     // Bitcast for output value is done at the end of visitInlineAsm().
9730     if ((OpInfo.Type == InlineAsm::isOutput ||
9731          OpInfo.Type == InlineAsm::isInput) &&
9732         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
9733       // Try to convert to the first EVT that the reg class contains.  If the
9734       // types are identical size, use a bitcast to convert (e.g. two differing
9735       // vector types).  Note: output bitcast is done at the end of
9736       // visitInlineAsm().
9737       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
9738         // Exclude indirect inputs while they are unsupported because the code
9739         // to perform the load is missing and thus OpInfo.CallOperand still
9740         // refers to the input address rather than the pointed-to value.
9741         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
9742           OpInfo.CallOperand =
9743               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
9744         OpInfo.ConstraintVT = RegVT;
9745         // If the operand is an FP value and we want it in integer registers,
9746         // use the corresponding integer type. This turns an f64 value into
9747         // i64, which can be passed with two i32 values on a 32-bit machine.
9748       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
9749         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
9750         if (OpInfo.Type == InlineAsm::isInput)
9751           OpInfo.CallOperand =
9752               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
9753         OpInfo.ConstraintVT = VT;
9754       }
9755     }
9756   }
9757 
9758   // No need to allocate a matching input constraint since the constraint it's
9759   // matching to has already been allocated.
9760   if (OpInfo.isMatchingInputConstraint())
9761     return std::nullopt;
9762 
9763   EVT ValueVT = OpInfo.ConstraintVT;
9764   if (OpInfo.ConstraintVT == MVT::Other)
9765     ValueVT = RegVT;
9766 
9767   // Initialize NumRegs.
9768   unsigned NumRegs = 1;
9769   if (OpInfo.ConstraintVT != MVT::Other)
9770     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
9771 
9772   // If this is a constraint for a specific physical register, like {r17},
9773   // assign it now.
9774 
9775   // If this associated to a specific register, initialize iterator to correct
9776   // place. If virtual, make sure we have enough registers
9777 
9778   // Initialize iterator if necessary
9779   TargetRegisterClass::iterator I = RC->begin();
9780   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9781 
9782   // Do not check for single registers.
9783   if (AssignedReg) {
9784     I = std::find(I, RC->end(), AssignedReg);
9785     if (I == RC->end()) {
9786       // RC does not contain the selected register, which indicates a
9787       // mismatch between the register and the required type/bitwidth.
9788       return {AssignedReg};
9789     }
9790   }
9791 
9792   for (; NumRegs; --NumRegs, ++I) {
9793     assert(I != RC->end() && "Ran out of registers to allocate!");
9794     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
9795     Regs.push_back(R);
9796   }
9797 
9798   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
9799   return std::nullopt;
9800 }
9801 
9802 static unsigned
9803 findMatchingInlineAsmOperand(unsigned OperandNo,
9804                              const std::vector<SDValue> &AsmNodeOperands) {
9805   // Scan until we find the definition we already emitted of this operand.
9806   unsigned CurOp = InlineAsm::Op_FirstOperand;
9807   for (; OperandNo; --OperandNo) {
9808     // Advance to the next operand.
9809     unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal();
9810     const InlineAsm::Flag F(OpFlag);
9811     assert(
9812         (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) &&
9813         "Skipped past definitions?");
9814     CurOp += F.getNumOperandRegisters() + 1;
9815   }
9816   return CurOp;
9817 }
9818 
9819 namespace {
9820 
9821 class ExtraFlags {
9822   unsigned Flags = 0;
9823 
9824 public:
9825   explicit ExtraFlags(const CallBase &Call) {
9826     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9827     if (IA->hasSideEffects())
9828       Flags |= InlineAsm::Extra_HasSideEffects;
9829     if (IA->isAlignStack())
9830       Flags |= InlineAsm::Extra_IsAlignStack;
9831     if (Call.isConvergent())
9832       Flags |= InlineAsm::Extra_IsConvergent;
9833     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
9834   }
9835 
9836   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
9837     // Ideally, we would only check against memory constraints.  However, the
9838     // meaning of an Other constraint can be target-specific and we can't easily
9839     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
9840     // for Other constraints as well.
9841     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9842         OpInfo.ConstraintType == TargetLowering::C_Other) {
9843       if (OpInfo.Type == InlineAsm::isInput)
9844         Flags |= InlineAsm::Extra_MayLoad;
9845       else if (OpInfo.Type == InlineAsm::isOutput)
9846         Flags |= InlineAsm::Extra_MayStore;
9847       else if (OpInfo.Type == InlineAsm::isClobber)
9848         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
9849     }
9850   }
9851 
9852   unsigned get() const { return Flags; }
9853 };
9854 
9855 } // end anonymous namespace
9856 
9857 static bool isFunction(SDValue Op) {
9858   if (Op && Op.getOpcode() == ISD::GlobalAddress) {
9859     if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
9860       auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
9861 
9862       // In normal "call dllimport func" instruction (non-inlineasm) it force
9863       // indirect access by specifing call opcode. And usually specially print
9864       // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
9865       // not do in this way now. (In fact, this is similar with "Data Access"
9866       // action). So here we ignore dllimport function.
9867       if (Fn && !Fn->hasDLLImportStorageClass())
9868         return true;
9869     }
9870   }
9871   return false;
9872 }
9873 
9874 /// visitInlineAsm - Handle a call to an InlineAsm object.
9875 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
9876                                          const BasicBlock *EHPadBB) {
9877   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9878 
9879   /// ConstraintOperands - Information about all of the constraints.
9880   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
9881 
9882   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9883   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
9884       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
9885 
9886   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
9887   // AsmDialect, MayLoad, MayStore).
9888   bool HasSideEffect = IA->hasSideEffects();
9889   ExtraFlags ExtraInfo(Call);
9890 
9891   for (auto &T : TargetConstraints) {
9892     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
9893     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
9894 
9895     if (OpInfo.CallOperandVal)
9896       OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
9897 
9898     if (!HasSideEffect)
9899       HasSideEffect = OpInfo.hasMemory(TLI);
9900 
9901     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
9902     // FIXME: Could we compute this on OpInfo rather than T?
9903 
9904     // Compute the constraint code and ConstraintType to use.
9905     TLI.ComputeConstraintToUse(T, SDValue());
9906 
9907     if (T.ConstraintType == TargetLowering::C_Immediate &&
9908         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
9909       // We've delayed emitting a diagnostic like the "n" constraint because
9910       // inlining could cause an integer showing up.
9911       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
9912                                           "' expects an integer constant "
9913                                           "expression");
9914 
9915     ExtraInfo.update(T);
9916   }
9917 
9918   // We won't need to flush pending loads if this asm doesn't touch
9919   // memory and is nonvolatile.
9920   SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
9921 
9922   bool EmitEHLabels = isa<InvokeInst>(Call);
9923   if (EmitEHLabels) {
9924     assert(EHPadBB && "InvokeInst must have an EHPadBB");
9925   }
9926   bool IsCallBr = isa<CallBrInst>(Call);
9927 
9928   if (IsCallBr || EmitEHLabels) {
9929     // If this is a callbr or invoke we need to flush pending exports since
9930     // inlineasm_br and invoke are terminators.
9931     // We need to do this before nodes are glued to the inlineasm_br node.
9932     Chain = getControlRoot();
9933   }
9934 
9935   MCSymbol *BeginLabel = nullptr;
9936   if (EmitEHLabels) {
9937     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
9938   }
9939 
9940   int OpNo = -1;
9941   SmallVector<StringRef> AsmStrs;
9942   IA->collectAsmStrs(AsmStrs);
9943 
9944   // Second pass over the constraints: compute which constraint option to use.
9945   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9946     if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
9947       OpNo++;
9948 
9949     // If this is an output operand with a matching input operand, look up the
9950     // matching input. If their types mismatch, e.g. one is an integer, the
9951     // other is floating point, or their sizes are different, flag it as an
9952     // error.
9953     if (OpInfo.hasMatchingInput()) {
9954       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
9955       patchMatchingInput(OpInfo, Input, DAG);
9956     }
9957 
9958     // Compute the constraint code and ConstraintType to use.
9959     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
9960 
9961     if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
9962          OpInfo.Type == InlineAsm::isClobber) ||
9963         OpInfo.ConstraintType == TargetLowering::C_Address)
9964       continue;
9965 
9966     // In Linux PIC model, there are 4 cases about value/label addressing:
9967     //
9968     // 1: Function call or Label jmp inside the module.
9969     // 2: Data access (such as global variable, static variable) inside module.
9970     // 3: Function call or Label jmp outside the module.
9971     // 4: Data access (such as global variable) outside the module.
9972     //
9973     // Due to current llvm inline asm architecture designed to not "recognize"
9974     // the asm code, there are quite troubles for us to treat mem addressing
9975     // differently for same value/adress used in different instuctions.
9976     // For example, in pic model, call a func may in plt way or direclty
9977     // pc-related, but lea/mov a function adress may use got.
9978     //
9979     // Here we try to "recognize" function call for the case 1 and case 3 in
9980     // inline asm. And try to adjust the constraint for them.
9981     //
9982     // TODO: Due to current inline asm didn't encourage to jmp to the outsider
9983     // label, so here we don't handle jmp function label now, but we need to
9984     // enhance it (especilly in PIC model) if we meet meaningful requirements.
9985     if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
9986         TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
9987         TM.getCodeModel() != CodeModel::Large) {
9988       OpInfo.isIndirect = false;
9989       OpInfo.ConstraintType = TargetLowering::C_Address;
9990     }
9991 
9992     // If this is a memory input, and if the operand is not indirect, do what we
9993     // need to provide an address for the memory input.
9994     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
9995         !OpInfo.isIndirect) {
9996       assert((OpInfo.isMultipleAlternative ||
9997               (OpInfo.Type == InlineAsm::isInput)) &&
9998              "Can only indirectify direct input operands!");
9999 
10000       // Memory operands really want the address of the value.
10001       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
10002 
10003       // There is no longer a Value* corresponding to this operand.
10004       OpInfo.CallOperandVal = nullptr;
10005 
10006       // It is now an indirect operand.
10007       OpInfo.isIndirect = true;
10008     }
10009 
10010   }
10011 
10012   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
10013   std::vector<SDValue> AsmNodeOperands;
10014   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
10015   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
10016       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
10017 
10018   // If we have a !srcloc metadata node associated with it, we want to attach
10019   // this to the ultimately generated inline asm machineinstr.  To do this, we
10020   // pass in the third operand as this (potentially null) inline asm MDNode.
10021   const MDNode *SrcLoc = Call.getMetadata("srcloc");
10022   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
10023 
10024   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
10025   // bits as operand 3.
10026   AsmNodeOperands.push_back(DAG.getTargetConstant(
10027       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
10028 
10029   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
10030   // this, assign virtual and physical registers for inputs and otput.
10031   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
10032     // Assign Registers.
10033     SDISelAsmOperandInfo &RefOpInfo =
10034         OpInfo.isMatchingInputConstraint()
10035             ? ConstraintOperands[OpInfo.getMatchedOperand()]
10036             : OpInfo;
10037     const auto RegError =
10038         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
10039     if (RegError) {
10040       const MachineFunction &MF = DAG.getMachineFunction();
10041       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
10042       const char *RegName = TRI.getName(*RegError);
10043       emitInlineAsmError(Call, "register '" + Twine(RegName) +
10044                                    "' allocated for constraint '" +
10045                                    Twine(OpInfo.ConstraintCode) +
10046                                    "' does not match required type");
10047       return;
10048     }
10049 
10050     auto DetectWriteToReservedRegister = [&]() {
10051       const MachineFunction &MF = DAG.getMachineFunction();
10052       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
10053       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
10054         if (Register::isPhysicalRegister(Reg) &&
10055             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
10056           const char *RegName = TRI.getName(Reg);
10057           emitInlineAsmError(Call, "write to reserved register '" +
10058                                        Twine(RegName) + "'");
10059           return true;
10060         }
10061       }
10062       return false;
10063     };
10064     assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
10065             (OpInfo.Type == InlineAsm::isInput &&
10066              !OpInfo.isMatchingInputConstraint())) &&
10067            "Only address as input operand is allowed.");
10068 
10069     switch (OpInfo.Type) {
10070     case InlineAsm::isOutput:
10071       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10072         const InlineAsm::ConstraintCode ConstraintID =
10073             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10074         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10075                "Failed to convert memory constraint code to constraint id.");
10076 
10077         // Add information to the INLINEASM node to know about this output.
10078         InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1);
10079         OpFlags.setMemConstraint(ConstraintID);
10080         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
10081                                                         MVT::i32));
10082         AsmNodeOperands.push_back(OpInfo.CallOperand);
10083       } else {
10084         // Otherwise, this outputs to a register (directly for C_Register /
10085         // C_RegisterClass, and a target-defined fashion for
10086         // C_Immediate/C_Other). Find a register that we can use.
10087         if (OpInfo.AssignedRegs.Regs.empty()) {
10088           emitInlineAsmError(
10089               Call, "couldn't allocate output register for constraint '" +
10090                         Twine(OpInfo.ConstraintCode) + "'");
10091           return;
10092         }
10093 
10094         if (DetectWriteToReservedRegister())
10095           return;
10096 
10097         // Add information to the INLINEASM node to know that this register is
10098         // set.
10099         OpInfo.AssignedRegs.AddInlineAsmOperands(
10100             OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber
10101                                   : InlineAsm::Kind::RegDef,
10102             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
10103       }
10104       break;
10105 
10106     case InlineAsm::isInput:
10107     case InlineAsm::isLabel: {
10108       SDValue InOperandVal = OpInfo.CallOperand;
10109 
10110       if (OpInfo.isMatchingInputConstraint()) {
10111         // If this is required to match an output register we have already set,
10112         // just use its register.
10113         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
10114                                                   AsmNodeOperands);
10115         InlineAsm::Flag Flag(AsmNodeOperands[CurOp]->getAsZExtVal());
10116         if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) {
10117           if (OpInfo.isIndirect) {
10118             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
10119             emitInlineAsmError(Call, "inline asm not supported yet: "
10120                                      "don't know how to handle tied "
10121                                      "indirect register inputs");
10122             return;
10123           }
10124 
10125           SmallVector<Register, 4> Regs;
10126           MachineFunction &MF = DAG.getMachineFunction();
10127           MachineRegisterInfo &MRI = MF.getRegInfo();
10128           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
10129           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
10130           Register TiedReg = R->getReg();
10131           MVT RegVT = R->getSimpleValueType(0);
10132           const TargetRegisterClass *RC =
10133               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
10134               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
10135                                       : TRI.getMinimalPhysRegClass(TiedReg);
10136           for (unsigned i = 0, e = Flag.getNumOperandRegisters(); i != e; ++i)
10137             Regs.push_back(MRI.createVirtualRegister(RC));
10138 
10139           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
10140 
10141           SDLoc dl = getCurSDLoc();
10142           // Use the produced MatchedRegs object to
10143           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call);
10144           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, true,
10145                                            OpInfo.getMatchedOperand(), dl, DAG,
10146                                            AsmNodeOperands);
10147           break;
10148         }
10149 
10150         assert(Flag.isMemKind() && "Unknown matching constraint!");
10151         assert(Flag.getNumOperandRegisters() == 1 &&
10152                "Unexpected number of operands");
10153         // Add information to the INLINEASM node to know about this input.
10154         // See InlineAsm.h isUseOperandTiedToDef.
10155         Flag.clearMemConstraint();
10156         Flag.setMatchingOp(OpInfo.getMatchedOperand());
10157         AsmNodeOperands.push_back(DAG.getTargetConstant(
10158             Flag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
10159         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
10160         break;
10161       }
10162 
10163       // Treat indirect 'X' constraint as memory.
10164       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
10165           OpInfo.isIndirect)
10166         OpInfo.ConstraintType = TargetLowering::C_Memory;
10167 
10168       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
10169           OpInfo.ConstraintType == TargetLowering::C_Other) {
10170         std::vector<SDValue> Ops;
10171         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
10172                                           Ops, DAG);
10173         if (Ops.empty()) {
10174           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
10175             if (isa<ConstantSDNode>(InOperandVal)) {
10176               emitInlineAsmError(Call, "value out of range for constraint '" +
10177                                            Twine(OpInfo.ConstraintCode) + "'");
10178               return;
10179             }
10180 
10181           emitInlineAsmError(Call,
10182                              "invalid operand for inline asm constraint '" +
10183                                  Twine(OpInfo.ConstraintCode) + "'");
10184           return;
10185         }
10186 
10187         // Add information to the INLINEASM node to know about this input.
10188         InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size());
10189         AsmNodeOperands.push_back(DAG.getTargetConstant(
10190             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
10191         llvm::append_range(AsmNodeOperands, Ops);
10192         break;
10193       }
10194 
10195       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10196         assert((OpInfo.isIndirect ||
10197                 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
10198                "Operand must be indirect to be a mem!");
10199         assert(InOperandVal.getValueType() ==
10200                    TLI.getPointerTy(DAG.getDataLayout()) &&
10201                "Memory operands expect pointer values");
10202 
10203         const InlineAsm::ConstraintCode ConstraintID =
10204             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10205         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10206                "Failed to convert memory constraint code to constraint id.");
10207 
10208         // Add information to the INLINEASM node to know about this input.
10209         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
10210         ResOpType.setMemConstraint(ConstraintID);
10211         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
10212                                                         getCurSDLoc(),
10213                                                         MVT::i32));
10214         AsmNodeOperands.push_back(InOperandVal);
10215         break;
10216       }
10217 
10218       if (OpInfo.ConstraintType == TargetLowering::C_Address) {
10219         const InlineAsm::ConstraintCode ConstraintID =
10220             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10221         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10222                "Failed to convert memory constraint code to constraint id.");
10223 
10224         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
10225 
10226         SDValue AsmOp = InOperandVal;
10227         if (isFunction(InOperandVal)) {
10228           auto *GA = cast<GlobalAddressSDNode>(InOperandVal);
10229           ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1);
10230           AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(),
10231                                              InOperandVal.getValueType(),
10232                                              GA->getOffset());
10233         }
10234 
10235         // Add information to the INLINEASM node to know about this input.
10236         ResOpType.setMemConstraint(ConstraintID);
10237 
10238         AsmNodeOperands.push_back(
10239             DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32));
10240 
10241         AsmNodeOperands.push_back(AsmOp);
10242         break;
10243       }
10244 
10245       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
10246           OpInfo.ConstraintType != TargetLowering::C_Register) {
10247         emitInlineAsmError(Call, "unknown asm constraint '" +
10248                                      Twine(OpInfo.ConstraintCode) + "'");
10249         return;
10250       }
10251 
10252       // TODO: Support this.
10253       if (OpInfo.isIndirect) {
10254         emitInlineAsmError(
10255             Call, "Don't know how to handle indirect register inputs yet "
10256                   "for constraint '" +
10257                       Twine(OpInfo.ConstraintCode) + "'");
10258         return;
10259       }
10260 
10261       // Copy the input into the appropriate registers.
10262       if (OpInfo.AssignedRegs.Regs.empty()) {
10263         emitInlineAsmError(Call,
10264                            "couldn't allocate input reg for constraint '" +
10265                                Twine(OpInfo.ConstraintCode) + "'");
10266         return;
10267       }
10268 
10269       if (DetectWriteToReservedRegister())
10270         return;
10271 
10272       SDLoc dl = getCurSDLoc();
10273 
10274       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue,
10275                                         &Call);
10276 
10277       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, false,
10278                                                0, dl, DAG, AsmNodeOperands);
10279       break;
10280     }
10281     case InlineAsm::isClobber:
10282       // Add the clobbered value to the operand list, so that the register
10283       // allocator is aware that the physreg got clobbered.
10284       if (!OpInfo.AssignedRegs.Regs.empty())
10285         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::Clobber,
10286                                                  false, 0, getCurSDLoc(), DAG,
10287                                                  AsmNodeOperands);
10288       break;
10289     }
10290   }
10291 
10292   // Finish up input operands.  Set the input chain and add the flag last.
10293   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
10294   if (Glue.getNode()) AsmNodeOperands.push_back(Glue);
10295 
10296   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
10297   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
10298                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
10299   Glue = Chain.getValue(1);
10300 
10301   // Do additional work to generate outputs.
10302 
10303   SmallVector<EVT, 1> ResultVTs;
10304   SmallVector<SDValue, 1> ResultValues;
10305   SmallVector<SDValue, 8> OutChains;
10306 
10307   llvm::Type *CallResultType = Call.getType();
10308   ArrayRef<Type *> ResultTypes;
10309   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
10310     ResultTypes = StructResult->elements();
10311   else if (!CallResultType->isVoidTy())
10312     ResultTypes = ArrayRef(CallResultType);
10313 
10314   auto CurResultType = ResultTypes.begin();
10315   auto handleRegAssign = [&](SDValue V) {
10316     assert(CurResultType != ResultTypes.end() && "Unexpected value");
10317     assert((*CurResultType)->isSized() && "Unexpected unsized type");
10318     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
10319     ++CurResultType;
10320     // If the type of the inline asm call site return value is different but has
10321     // same size as the type of the asm output bitcast it.  One example of this
10322     // is for vectors with different width / number of elements.  This can
10323     // happen for register classes that can contain multiple different value
10324     // types.  The preg or vreg allocated may not have the same VT as was
10325     // expected.
10326     //
10327     // This can also happen for a return value that disagrees with the register
10328     // class it is put in, eg. a double in a general-purpose register on a
10329     // 32-bit machine.
10330     if (ResultVT != V.getValueType() &&
10331         ResultVT.getSizeInBits() == V.getValueSizeInBits())
10332       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
10333     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
10334              V.getValueType().isInteger()) {
10335       // If a result value was tied to an input value, the computed result
10336       // may have a wider width than the expected result.  Extract the
10337       // relevant portion.
10338       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
10339     }
10340     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
10341     ResultVTs.push_back(ResultVT);
10342     ResultValues.push_back(V);
10343   };
10344 
10345   // Deal with output operands.
10346   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
10347     if (OpInfo.Type == InlineAsm::isOutput) {
10348       SDValue Val;
10349       // Skip trivial output operands.
10350       if (OpInfo.AssignedRegs.Regs.empty())
10351         continue;
10352 
10353       switch (OpInfo.ConstraintType) {
10354       case TargetLowering::C_Register:
10355       case TargetLowering::C_RegisterClass:
10356         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
10357                                                   Chain, &Glue, &Call);
10358         break;
10359       case TargetLowering::C_Immediate:
10360       case TargetLowering::C_Other:
10361         Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(),
10362                                               OpInfo, DAG);
10363         break;
10364       case TargetLowering::C_Memory:
10365         break; // Already handled.
10366       case TargetLowering::C_Address:
10367         break; // Silence warning.
10368       case TargetLowering::C_Unknown:
10369         assert(false && "Unexpected unknown constraint");
10370       }
10371 
10372       // Indirect output manifest as stores. Record output chains.
10373       if (OpInfo.isIndirect) {
10374         const Value *Ptr = OpInfo.CallOperandVal;
10375         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
10376         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
10377                                      MachinePointerInfo(Ptr));
10378         OutChains.push_back(Store);
10379       } else {
10380         // generate CopyFromRegs to associated registers.
10381         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
10382         if (Val.getOpcode() == ISD::MERGE_VALUES) {
10383           for (const SDValue &V : Val->op_values())
10384             handleRegAssign(V);
10385         } else
10386           handleRegAssign(Val);
10387       }
10388     }
10389   }
10390 
10391   // Set results.
10392   if (!ResultValues.empty()) {
10393     assert(CurResultType == ResultTypes.end() &&
10394            "Mismatch in number of ResultTypes");
10395     assert(ResultValues.size() == ResultTypes.size() &&
10396            "Mismatch in number of output operands in asm result");
10397 
10398     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
10399                             DAG.getVTList(ResultVTs), ResultValues);
10400     setValue(&Call, V);
10401   }
10402 
10403   // Collect store chains.
10404   if (!OutChains.empty())
10405     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
10406 
10407   if (EmitEHLabels) {
10408     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
10409   }
10410 
10411   // Only Update Root if inline assembly has a memory effect.
10412   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
10413       EmitEHLabels)
10414     DAG.setRoot(Chain);
10415 }
10416 
10417 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
10418                                              const Twine &Message) {
10419   LLVMContext &Ctx = *DAG.getContext();
10420   Ctx.emitError(&Call, Message);
10421 
10422   // Make sure we leave the DAG in a valid state
10423   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10424   SmallVector<EVT, 1> ValueVTs;
10425   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
10426 
10427   if (ValueVTs.empty())
10428     return;
10429 
10430   SmallVector<SDValue, 1> Ops;
10431   for (const EVT &VT : ValueVTs)
10432     Ops.push_back(DAG.getUNDEF(VT));
10433 
10434   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
10435 }
10436 
10437 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
10438   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
10439                           MVT::Other, getRoot(),
10440                           getValue(I.getArgOperand(0)),
10441                           DAG.getSrcValue(I.getArgOperand(0))));
10442 }
10443 
10444 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
10445   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10446   const DataLayout &DL = DAG.getDataLayout();
10447   SDValue V = DAG.getVAArg(
10448       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
10449       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
10450       DL.getABITypeAlign(I.getType()).value());
10451   DAG.setRoot(V.getValue(1));
10452 
10453   if (I.getType()->isPointerTy())
10454     V = DAG.getPtrExtOrTrunc(
10455         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
10456   setValue(&I, V);
10457 }
10458 
10459 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
10460   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
10461                           MVT::Other, getRoot(),
10462                           getValue(I.getArgOperand(0)),
10463                           DAG.getSrcValue(I.getArgOperand(0))));
10464 }
10465 
10466 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
10467   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
10468                           MVT::Other, getRoot(),
10469                           getValue(I.getArgOperand(0)),
10470                           getValue(I.getArgOperand(1)),
10471                           DAG.getSrcValue(I.getArgOperand(0)),
10472                           DAG.getSrcValue(I.getArgOperand(1))));
10473 }
10474 
10475 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
10476                                                     const Instruction &I,
10477                                                     SDValue Op) {
10478   std::optional<ConstantRange> CR = getRange(I);
10479 
10480   if (!CR || CR->isFullSet() || CR->isEmptySet() || CR->isUpperWrapped())
10481     return Op;
10482 
10483   APInt Lo = CR->getUnsignedMin();
10484   if (!Lo.isMinValue())
10485     return Op;
10486 
10487   APInt Hi = CR->getUnsignedMax();
10488   unsigned Bits = std::max(Hi.getActiveBits(),
10489                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
10490 
10491   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
10492 
10493   SDLoc SL = getCurSDLoc();
10494 
10495   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
10496                              DAG.getValueType(SmallVT));
10497   unsigned NumVals = Op.getNode()->getNumValues();
10498   if (NumVals == 1)
10499     return ZExt;
10500 
10501   SmallVector<SDValue, 4> Ops;
10502 
10503   Ops.push_back(ZExt);
10504   for (unsigned I = 1; I != NumVals; ++I)
10505     Ops.push_back(Op.getValue(I));
10506 
10507   return DAG.getMergeValues(Ops, SL);
10508 }
10509 
10510 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
10511 /// the call being lowered.
10512 ///
10513 /// This is a helper for lowering intrinsics that follow a target calling
10514 /// convention or require stack pointer adjustment. Only a subset of the
10515 /// intrinsic's operands need to participate in the calling convention.
10516 void SelectionDAGBuilder::populateCallLoweringInfo(
10517     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
10518     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
10519     AttributeSet RetAttrs, bool IsPatchPoint) {
10520   TargetLowering::ArgListTy Args;
10521   Args.reserve(NumArgs);
10522 
10523   // Populate the argument list.
10524   // Attributes for args start at offset 1, after the return attribute.
10525   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
10526        ArgI != ArgE; ++ArgI) {
10527     const Value *V = Call->getOperand(ArgI);
10528 
10529     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
10530 
10531     TargetLowering::ArgListEntry Entry;
10532     Entry.Node = getValue(V);
10533     Entry.Ty = V->getType();
10534     Entry.setAttributes(Call, ArgI);
10535     Args.push_back(Entry);
10536   }
10537 
10538   CLI.setDebugLoc(getCurSDLoc())
10539       .setChain(getRoot())
10540       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args),
10541                  RetAttrs)
10542       .setDiscardResult(Call->use_empty())
10543       .setIsPatchPoint(IsPatchPoint)
10544       .setIsPreallocated(
10545           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
10546 }
10547 
10548 /// Add a stack map intrinsic call's live variable operands to a stackmap
10549 /// or patchpoint target node's operand list.
10550 ///
10551 /// Constants are converted to TargetConstants purely as an optimization to
10552 /// avoid constant materialization and register allocation.
10553 ///
10554 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
10555 /// generate addess computation nodes, and so FinalizeISel can convert the
10556 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
10557 /// address materialization and register allocation, but may also be required
10558 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
10559 /// alloca in the entry block, then the runtime may assume that the alloca's
10560 /// StackMap location can be read immediately after compilation and that the
10561 /// location is valid at any point during execution (this is similar to the
10562 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
10563 /// only available in a register, then the runtime would need to trap when
10564 /// execution reaches the StackMap in order to read the alloca's location.
10565 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
10566                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
10567                                 SelectionDAGBuilder &Builder) {
10568   SelectionDAG &DAG = Builder.DAG;
10569   for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
10570     SDValue Op = Builder.getValue(Call.getArgOperand(I));
10571 
10572     // Things on the stack are pointer-typed, meaning that they are already
10573     // legal and can be emitted directly to target nodes.
10574     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
10575       Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
10576     } else {
10577       // Otherwise emit a target independent node to be legalised.
10578       Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
10579     }
10580   }
10581 }
10582 
10583 /// Lower llvm.experimental.stackmap.
10584 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
10585   // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
10586   //                                  [live variables...])
10587 
10588   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
10589 
10590   SDValue Chain, InGlue, Callee;
10591   SmallVector<SDValue, 32> Ops;
10592 
10593   SDLoc DL = getCurSDLoc();
10594   Callee = getValue(CI.getCalledOperand());
10595 
10596   // The stackmap intrinsic only records the live variables (the arguments
10597   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
10598   // intrinsic, this won't be lowered to a function call. This means we don't
10599   // have to worry about calling conventions and target specific lowering code.
10600   // Instead we perform the call lowering right here.
10601   //
10602   // chain, flag = CALLSEQ_START(chain, 0, 0)
10603   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
10604   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
10605   //
10606   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
10607   InGlue = Chain.getValue(1);
10608 
10609   // Add the STACKMAP operands, starting with DAG house-keeping.
10610   Ops.push_back(Chain);
10611   Ops.push_back(InGlue);
10612 
10613   // Add the <id>, <numShadowBytes> operands.
10614   //
10615   // These do not require legalisation, and can be emitted directly to target
10616   // constant nodes.
10617   SDValue ID = getValue(CI.getArgOperand(0));
10618   assert(ID.getValueType() == MVT::i64);
10619   SDValue IDConst =
10620       DAG.getTargetConstant(ID->getAsZExtVal(), DL, ID.getValueType());
10621   Ops.push_back(IDConst);
10622 
10623   SDValue Shad = getValue(CI.getArgOperand(1));
10624   assert(Shad.getValueType() == MVT::i32);
10625   SDValue ShadConst =
10626       DAG.getTargetConstant(Shad->getAsZExtVal(), DL, Shad.getValueType());
10627   Ops.push_back(ShadConst);
10628 
10629   // Add the live variables.
10630   addStackMapLiveVars(CI, 2, DL, Ops, *this);
10631 
10632   // Create the STACKMAP node.
10633   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10634   Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
10635   InGlue = Chain.getValue(1);
10636 
10637   Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL);
10638 
10639   // Stackmaps don't generate values, so nothing goes into the NodeMap.
10640 
10641   // Set the root to the target-lowered call chain.
10642   DAG.setRoot(Chain);
10643 
10644   // Inform the Frame Information that we have a stackmap in this function.
10645   FuncInfo.MF->getFrameInfo().setHasStackMap();
10646 }
10647 
10648 /// Lower llvm.experimental.patchpoint directly to its target opcode.
10649 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
10650                                           const BasicBlock *EHPadBB) {
10651   // <ty> @llvm.experimental.patchpoint.<ty>(i64 <id>,
10652   //                                         i32 <numBytes>,
10653   //                                         i8* <target>,
10654   //                                         i32 <numArgs>,
10655   //                                         [Args...],
10656   //                                         [live variables...])
10657 
10658   CallingConv::ID CC = CB.getCallingConv();
10659   bool IsAnyRegCC = CC == CallingConv::AnyReg;
10660   bool HasDef = !CB.getType()->isVoidTy();
10661   SDLoc dl = getCurSDLoc();
10662   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
10663 
10664   // Handle immediate and symbolic callees.
10665   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
10666     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
10667                                    /*isTarget=*/true);
10668   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
10669     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
10670                                          SDLoc(SymbolicCallee),
10671                                          SymbolicCallee->getValueType(0));
10672 
10673   // Get the real number of arguments participating in the call <numArgs>
10674   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
10675   unsigned NumArgs = NArgVal->getAsZExtVal();
10676 
10677   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
10678   // Intrinsics include all meta-operands up to but not including CC.
10679   unsigned NumMetaOpers = PatchPointOpers::CCPos;
10680   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
10681          "Not enough arguments provided to the patchpoint intrinsic");
10682 
10683   // For AnyRegCC the arguments are lowered later on manually.
10684   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
10685   Type *ReturnTy =
10686       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
10687 
10688   TargetLowering::CallLoweringInfo CLI(DAG);
10689   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
10690                            ReturnTy, CB.getAttributes().getRetAttrs(), true);
10691   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
10692 
10693   SDNode *CallEnd = Result.second.getNode();
10694   if (CallEnd->getOpcode() == ISD::EH_LABEL)
10695     CallEnd = CallEnd->getOperand(0).getNode();
10696   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
10697     CallEnd = CallEnd->getOperand(0).getNode();
10698 
10699   /// Get a call instruction from the call sequence chain.
10700   /// Tail calls are not allowed.
10701   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
10702          "Expected a callseq node.");
10703   SDNode *Call = CallEnd->getOperand(0).getNode();
10704   bool HasGlue = Call->getGluedNode();
10705 
10706   // Replace the target specific call node with the patchable intrinsic.
10707   SmallVector<SDValue, 8> Ops;
10708 
10709   // Push the chain.
10710   Ops.push_back(*(Call->op_begin()));
10711 
10712   // Optionally, push the glue (if any).
10713   if (HasGlue)
10714     Ops.push_back(*(Call->op_end() - 1));
10715 
10716   // Push the register mask info.
10717   if (HasGlue)
10718     Ops.push_back(*(Call->op_end() - 2));
10719   else
10720     Ops.push_back(*(Call->op_end() - 1));
10721 
10722   // Add the <id> and <numBytes> constants.
10723   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
10724   Ops.push_back(DAG.getTargetConstant(IDVal->getAsZExtVal(), dl, MVT::i64));
10725   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
10726   Ops.push_back(DAG.getTargetConstant(NBytesVal->getAsZExtVal(), dl, MVT::i32));
10727 
10728   // Add the callee.
10729   Ops.push_back(Callee);
10730 
10731   // Adjust <numArgs> to account for any arguments that have been passed on the
10732   // stack instead.
10733   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
10734   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
10735   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
10736   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
10737 
10738   // Add the calling convention
10739   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
10740 
10741   // Add the arguments we omitted previously. The register allocator should
10742   // place these in any free register.
10743   if (IsAnyRegCC)
10744     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
10745       Ops.push_back(getValue(CB.getArgOperand(i)));
10746 
10747   // Push the arguments from the call instruction.
10748   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
10749   Ops.append(Call->op_begin() + 2, e);
10750 
10751   // Push live variables for the stack map.
10752   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
10753 
10754   SDVTList NodeTys;
10755   if (IsAnyRegCC && HasDef) {
10756     // Create the return types based on the intrinsic definition
10757     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10758     SmallVector<EVT, 3> ValueVTs;
10759     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
10760     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
10761 
10762     // There is always a chain and a glue type at the end
10763     ValueVTs.push_back(MVT::Other);
10764     ValueVTs.push_back(MVT::Glue);
10765     NodeTys = DAG.getVTList(ValueVTs);
10766   } else
10767     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10768 
10769   // Replace the target specific call node with a PATCHPOINT node.
10770   SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
10771 
10772   // Update the NodeMap.
10773   if (HasDef) {
10774     if (IsAnyRegCC)
10775       setValue(&CB, SDValue(PPV.getNode(), 0));
10776     else
10777       setValue(&CB, Result.first);
10778   }
10779 
10780   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
10781   // call sequence. Furthermore the location of the chain and glue can change
10782   // when the AnyReg calling convention is used and the intrinsic returns a
10783   // value.
10784   if (IsAnyRegCC && HasDef) {
10785     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
10786     SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
10787     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10788   } else
10789     DAG.ReplaceAllUsesWith(Call, PPV.getNode());
10790   DAG.DeleteNode(Call);
10791 
10792   // Inform the Frame Information that we have a patchpoint in this function.
10793   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
10794 }
10795 
10796 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
10797                                             unsigned Intrinsic) {
10798   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10799   SDValue Op1 = getValue(I.getArgOperand(0));
10800   SDValue Op2;
10801   if (I.arg_size() > 1)
10802     Op2 = getValue(I.getArgOperand(1));
10803   SDLoc dl = getCurSDLoc();
10804   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
10805   SDValue Res;
10806   SDNodeFlags SDFlags;
10807   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
10808     SDFlags.copyFMF(*FPMO);
10809 
10810   switch (Intrinsic) {
10811   case Intrinsic::vector_reduce_fadd:
10812     if (SDFlags.hasAllowReassociation())
10813       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
10814                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
10815                         SDFlags);
10816     else
10817       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
10818     break;
10819   case Intrinsic::vector_reduce_fmul:
10820     if (SDFlags.hasAllowReassociation())
10821       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
10822                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
10823                         SDFlags);
10824     else
10825       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
10826     break;
10827   case Intrinsic::vector_reduce_add:
10828     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
10829     break;
10830   case Intrinsic::vector_reduce_mul:
10831     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
10832     break;
10833   case Intrinsic::vector_reduce_and:
10834     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
10835     break;
10836   case Intrinsic::vector_reduce_or:
10837     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
10838     break;
10839   case Intrinsic::vector_reduce_xor:
10840     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
10841     break;
10842   case Intrinsic::vector_reduce_smax:
10843     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
10844     break;
10845   case Intrinsic::vector_reduce_smin:
10846     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
10847     break;
10848   case Intrinsic::vector_reduce_umax:
10849     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
10850     break;
10851   case Intrinsic::vector_reduce_umin:
10852     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
10853     break;
10854   case Intrinsic::vector_reduce_fmax:
10855     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
10856     break;
10857   case Intrinsic::vector_reduce_fmin:
10858     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
10859     break;
10860   case Intrinsic::vector_reduce_fmaximum:
10861     Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags);
10862     break;
10863   case Intrinsic::vector_reduce_fminimum:
10864     Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags);
10865     break;
10866   default:
10867     llvm_unreachable("Unhandled vector reduce intrinsic");
10868   }
10869   setValue(&I, Res);
10870 }
10871 
10872 /// Returns an AttributeList representing the attributes applied to the return
10873 /// value of the given call.
10874 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
10875   SmallVector<Attribute::AttrKind, 2> Attrs;
10876   if (CLI.RetSExt)
10877     Attrs.push_back(Attribute::SExt);
10878   if (CLI.RetZExt)
10879     Attrs.push_back(Attribute::ZExt);
10880   if (CLI.IsInReg)
10881     Attrs.push_back(Attribute::InReg);
10882 
10883   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
10884                             Attrs);
10885 }
10886 
10887 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
10888 /// implementation, which just calls LowerCall.
10889 /// FIXME: When all targets are
10890 /// migrated to using LowerCall, this hook should be integrated into SDISel.
10891 std::pair<SDValue, SDValue>
10892 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
10893   // Handle the incoming return values from the call.
10894   CLI.Ins.clear();
10895   Type *OrigRetTy = CLI.RetTy;
10896   SmallVector<EVT, 4> RetTys;
10897   SmallVector<TypeSize, 4> Offsets;
10898   auto &DL = CLI.DAG.getDataLayout();
10899   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
10900 
10901   if (CLI.IsPostTypeLegalization) {
10902     // If we are lowering a libcall after legalization, split the return type.
10903     SmallVector<EVT, 4> OldRetTys;
10904     SmallVector<TypeSize, 4> OldOffsets;
10905     RetTys.swap(OldRetTys);
10906     Offsets.swap(OldOffsets);
10907 
10908     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
10909       EVT RetVT = OldRetTys[i];
10910       uint64_t Offset = OldOffsets[i];
10911       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
10912       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
10913       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
10914       RetTys.append(NumRegs, RegisterVT);
10915       for (unsigned j = 0; j != NumRegs; ++j)
10916         Offsets.push_back(TypeSize::getFixed(Offset + j * RegisterVTByteSZ));
10917     }
10918   }
10919 
10920   SmallVector<ISD::OutputArg, 4> Outs;
10921   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
10922 
10923   bool CanLowerReturn =
10924       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
10925                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
10926 
10927   SDValue DemoteStackSlot;
10928   int DemoteStackIdx = -100;
10929   if (!CanLowerReturn) {
10930     // FIXME: equivalent assert?
10931     // assert(!CS.hasInAllocaArgument() &&
10932     //        "sret demotion is incompatible with inalloca");
10933     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
10934     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
10935     MachineFunction &MF = CLI.DAG.getMachineFunction();
10936     DemoteStackIdx =
10937         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
10938     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
10939                                               DL.getAllocaAddrSpace());
10940 
10941     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
10942     ArgListEntry Entry;
10943     Entry.Node = DemoteStackSlot;
10944     Entry.Ty = StackSlotPtrType;
10945     Entry.IsSExt = false;
10946     Entry.IsZExt = false;
10947     Entry.IsInReg = false;
10948     Entry.IsSRet = true;
10949     Entry.IsNest = false;
10950     Entry.IsByVal = false;
10951     Entry.IsByRef = false;
10952     Entry.IsReturned = false;
10953     Entry.IsSwiftSelf = false;
10954     Entry.IsSwiftAsync = false;
10955     Entry.IsSwiftError = false;
10956     Entry.IsCFGuardTarget = false;
10957     Entry.Alignment = Alignment;
10958     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
10959     CLI.NumFixedArgs += 1;
10960     CLI.getArgs()[0].IndirectType = CLI.RetTy;
10961     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
10962 
10963     // sret demotion isn't compatible with tail-calls, since the sret argument
10964     // points into the callers stack frame.
10965     CLI.IsTailCall = false;
10966   } else {
10967     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10968         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
10969     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
10970       ISD::ArgFlagsTy Flags;
10971       if (NeedsRegBlock) {
10972         Flags.setInConsecutiveRegs();
10973         if (I == RetTys.size() - 1)
10974           Flags.setInConsecutiveRegsLast();
10975       }
10976       EVT VT = RetTys[I];
10977       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10978                                                      CLI.CallConv, VT);
10979       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10980                                                        CLI.CallConv, VT);
10981       for (unsigned i = 0; i != NumRegs; ++i) {
10982         ISD::InputArg MyFlags;
10983         MyFlags.Flags = Flags;
10984         MyFlags.VT = RegisterVT;
10985         MyFlags.ArgVT = VT;
10986         MyFlags.Used = CLI.IsReturnValueUsed;
10987         if (CLI.RetTy->isPointerTy()) {
10988           MyFlags.Flags.setPointer();
10989           MyFlags.Flags.setPointerAddrSpace(
10990               cast<PointerType>(CLI.RetTy)->getAddressSpace());
10991         }
10992         if (CLI.RetSExt)
10993           MyFlags.Flags.setSExt();
10994         if (CLI.RetZExt)
10995           MyFlags.Flags.setZExt();
10996         if (CLI.IsInReg)
10997           MyFlags.Flags.setInReg();
10998         CLI.Ins.push_back(MyFlags);
10999       }
11000     }
11001   }
11002 
11003   // We push in swifterror return as the last element of CLI.Ins.
11004   ArgListTy &Args = CLI.getArgs();
11005   if (supportSwiftError()) {
11006     for (const ArgListEntry &Arg : Args) {
11007       if (Arg.IsSwiftError) {
11008         ISD::InputArg MyFlags;
11009         MyFlags.VT = getPointerTy(DL);
11010         MyFlags.ArgVT = EVT(getPointerTy(DL));
11011         MyFlags.Flags.setSwiftError();
11012         CLI.Ins.push_back(MyFlags);
11013       }
11014     }
11015   }
11016 
11017   // Handle all of the outgoing arguments.
11018   CLI.Outs.clear();
11019   CLI.OutVals.clear();
11020   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
11021     SmallVector<EVT, 4> ValueVTs;
11022     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
11023     // FIXME: Split arguments if CLI.IsPostTypeLegalization
11024     Type *FinalType = Args[i].Ty;
11025     if (Args[i].IsByVal)
11026       FinalType = Args[i].IndirectType;
11027     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
11028         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
11029     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
11030          ++Value) {
11031       EVT VT = ValueVTs[Value];
11032       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
11033       SDValue Op = SDValue(Args[i].Node.getNode(),
11034                            Args[i].Node.getResNo() + Value);
11035       ISD::ArgFlagsTy Flags;
11036 
11037       // Certain targets (such as MIPS), may have a different ABI alignment
11038       // for a type depending on the context. Give the target a chance to
11039       // specify the alignment it wants.
11040       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
11041       Flags.setOrigAlign(OriginalAlignment);
11042 
11043       if (Args[i].Ty->isPointerTy()) {
11044         Flags.setPointer();
11045         Flags.setPointerAddrSpace(
11046             cast<PointerType>(Args[i].Ty)->getAddressSpace());
11047       }
11048       if (Args[i].IsZExt)
11049         Flags.setZExt();
11050       if (Args[i].IsSExt)
11051         Flags.setSExt();
11052       if (Args[i].IsNoExt)
11053         Flags.setNoExt();
11054       if (Args[i].IsInReg) {
11055         // If we are using vectorcall calling convention, a structure that is
11056         // passed InReg - is surely an HVA
11057         if (CLI.CallConv == CallingConv::X86_VectorCall &&
11058             isa<StructType>(FinalType)) {
11059           // The first value of a structure is marked
11060           if (0 == Value)
11061             Flags.setHvaStart();
11062           Flags.setHva();
11063         }
11064         // Set InReg Flag
11065         Flags.setInReg();
11066       }
11067       if (Args[i].IsSRet)
11068         Flags.setSRet();
11069       if (Args[i].IsSwiftSelf)
11070         Flags.setSwiftSelf();
11071       if (Args[i].IsSwiftAsync)
11072         Flags.setSwiftAsync();
11073       if (Args[i].IsSwiftError)
11074         Flags.setSwiftError();
11075       if (Args[i].IsCFGuardTarget)
11076         Flags.setCFGuardTarget();
11077       if (Args[i].IsByVal)
11078         Flags.setByVal();
11079       if (Args[i].IsByRef)
11080         Flags.setByRef();
11081       if (Args[i].IsPreallocated) {
11082         Flags.setPreallocated();
11083         // Set the byval flag for CCAssignFn callbacks that don't know about
11084         // preallocated.  This way we can know how many bytes we should've
11085         // allocated and how many bytes a callee cleanup function will pop.  If
11086         // we port preallocated to more targets, we'll have to add custom
11087         // preallocated handling in the various CC lowering callbacks.
11088         Flags.setByVal();
11089       }
11090       if (Args[i].IsInAlloca) {
11091         Flags.setInAlloca();
11092         // Set the byval flag for CCAssignFn callbacks that don't know about
11093         // inalloca.  This way we can know how many bytes we should've allocated
11094         // and how many bytes a callee cleanup function will pop.  If we port
11095         // inalloca to more targets, we'll have to add custom inalloca handling
11096         // in the various CC lowering callbacks.
11097         Flags.setByVal();
11098       }
11099       Align MemAlign;
11100       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
11101         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
11102         Flags.setByValSize(FrameSize);
11103 
11104         // info is not there but there are cases it cannot get right.
11105         if (auto MA = Args[i].Alignment)
11106           MemAlign = *MA;
11107         else
11108           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
11109       } else if (auto MA = Args[i].Alignment) {
11110         MemAlign = *MA;
11111       } else {
11112         MemAlign = OriginalAlignment;
11113       }
11114       Flags.setMemAlign(MemAlign);
11115       if (Args[i].IsNest)
11116         Flags.setNest();
11117       if (NeedsRegBlock)
11118         Flags.setInConsecutiveRegs();
11119 
11120       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
11121                                                  CLI.CallConv, VT);
11122       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
11123                                                         CLI.CallConv, VT);
11124       SmallVector<SDValue, 4> Parts(NumParts);
11125       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
11126 
11127       if (Args[i].IsSExt)
11128         ExtendKind = ISD::SIGN_EXTEND;
11129       else if (Args[i].IsZExt)
11130         ExtendKind = ISD::ZERO_EXTEND;
11131 
11132       // Conservatively only handle 'returned' on non-vectors that can be lowered,
11133       // for now.
11134       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
11135           CanLowerReturn) {
11136         assert((CLI.RetTy == Args[i].Ty ||
11137                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
11138                  CLI.RetTy->getPointerAddressSpace() ==
11139                      Args[i].Ty->getPointerAddressSpace())) &&
11140                RetTys.size() == NumValues && "unexpected use of 'returned'");
11141         // Before passing 'returned' to the target lowering code, ensure that
11142         // either the register MVT and the actual EVT are the same size or that
11143         // the return value and argument are extended in the same way; in these
11144         // cases it's safe to pass the argument register value unchanged as the
11145         // return register value (although it's at the target's option whether
11146         // to do so)
11147         // TODO: allow code generation to take advantage of partially preserved
11148         // registers rather than clobbering the entire register when the
11149         // parameter extension method is not compatible with the return
11150         // extension method
11151         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
11152             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
11153              CLI.RetZExt == Args[i].IsZExt))
11154           Flags.setReturned();
11155       }
11156 
11157       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
11158                      CLI.CallConv, ExtendKind);
11159 
11160       for (unsigned j = 0; j != NumParts; ++j) {
11161         // if it isn't first piece, alignment must be 1
11162         // For scalable vectors the scalable part is currently handled
11163         // by individual targets, so we just use the known minimum size here.
11164         ISD::OutputArg MyFlags(
11165             Flags, Parts[j].getValueType().getSimpleVT(), VT,
11166             i < CLI.NumFixedArgs, i,
11167             j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
11168         if (NumParts > 1 && j == 0)
11169           MyFlags.Flags.setSplit();
11170         else if (j != 0) {
11171           MyFlags.Flags.setOrigAlign(Align(1));
11172           if (j == NumParts - 1)
11173             MyFlags.Flags.setSplitEnd();
11174         }
11175 
11176         CLI.Outs.push_back(MyFlags);
11177         CLI.OutVals.push_back(Parts[j]);
11178       }
11179 
11180       if (NeedsRegBlock && Value == NumValues - 1)
11181         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
11182     }
11183   }
11184 
11185   SmallVector<SDValue, 4> InVals;
11186   CLI.Chain = LowerCall(CLI, InVals);
11187 
11188   // Update CLI.InVals to use outside of this function.
11189   CLI.InVals = InVals;
11190 
11191   // Verify that the target's LowerCall behaved as expected.
11192   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
11193          "LowerCall didn't return a valid chain!");
11194   assert((!CLI.IsTailCall || InVals.empty()) &&
11195          "LowerCall emitted a return value for a tail call!");
11196   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
11197          "LowerCall didn't emit the correct number of values!");
11198 
11199   // For a tail call, the return value is merely live-out and there aren't
11200   // any nodes in the DAG representing it. Return a special value to
11201   // indicate that a tail call has been emitted and no more Instructions
11202   // should be processed in the current block.
11203   if (CLI.IsTailCall) {
11204     CLI.DAG.setRoot(CLI.Chain);
11205     return std::make_pair(SDValue(), SDValue());
11206   }
11207 
11208 #ifndef NDEBUG
11209   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
11210     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
11211     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
11212            "LowerCall emitted a value with the wrong type!");
11213   }
11214 #endif
11215 
11216   SmallVector<SDValue, 4> ReturnValues;
11217   if (!CanLowerReturn) {
11218     // The instruction result is the result of loading from the
11219     // hidden sret parameter.
11220     SmallVector<EVT, 1> PVTs;
11221     Type *PtrRetTy =
11222         PointerType::get(OrigRetTy->getContext(), DL.getAllocaAddrSpace());
11223 
11224     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
11225     assert(PVTs.size() == 1 && "Pointers should fit in one register");
11226     EVT PtrVT = PVTs[0];
11227 
11228     unsigned NumValues = RetTys.size();
11229     ReturnValues.resize(NumValues);
11230     SmallVector<SDValue, 4> Chains(NumValues);
11231 
11232     // An aggregate return value cannot wrap around the address space, so
11233     // offsets to its parts don't wrap either.
11234     MachineFunction &MF = CLI.DAG.getMachineFunction();
11235     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
11236     for (unsigned i = 0; i < NumValues; ++i) {
11237       SDValue Add =
11238           CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
11239                           CLI.DAG.getConstant(Offsets[i], CLI.DL, PtrVT),
11240                           SDNodeFlags::NoUnsignedWrap);
11241       SDValue L = CLI.DAG.getLoad(
11242           RetTys[i], CLI.DL, CLI.Chain, Add,
11243           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
11244                                             DemoteStackIdx, Offsets[i]),
11245           HiddenSRetAlign);
11246       ReturnValues[i] = L;
11247       Chains[i] = L.getValue(1);
11248     }
11249 
11250     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
11251   } else {
11252     // Collect the legal value parts into potentially illegal values
11253     // that correspond to the original function's return values.
11254     std::optional<ISD::NodeType> AssertOp;
11255     if (CLI.RetSExt)
11256       AssertOp = ISD::AssertSext;
11257     else if (CLI.RetZExt)
11258       AssertOp = ISD::AssertZext;
11259     unsigned CurReg = 0;
11260     for (EVT VT : RetTys) {
11261       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
11262                                                      CLI.CallConv, VT);
11263       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
11264                                                        CLI.CallConv, VT);
11265 
11266       ReturnValues.push_back(getCopyFromParts(
11267           CLI.DAG, CLI.DL, &InVals[CurReg], NumRegs, RegisterVT, VT, nullptr,
11268           CLI.Chain, CLI.CallConv, AssertOp));
11269       CurReg += NumRegs;
11270     }
11271 
11272     // For a function returning void, there is no return value. We can't create
11273     // such a node, so we just return a null return value in that case. In
11274     // that case, nothing will actually look at the value.
11275     if (ReturnValues.empty())
11276       return std::make_pair(SDValue(), CLI.Chain);
11277   }
11278 
11279   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
11280                                 CLI.DAG.getVTList(RetTys), ReturnValues);
11281   return std::make_pair(Res, CLI.Chain);
11282 }
11283 
11284 /// Places new result values for the node in Results (their number
11285 /// and types must exactly match those of the original return values of
11286 /// the node), or leaves Results empty, which indicates that the node is not
11287 /// to be custom lowered after all.
11288 void TargetLowering::LowerOperationWrapper(SDNode *N,
11289                                            SmallVectorImpl<SDValue> &Results,
11290                                            SelectionDAG &DAG) const {
11291   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
11292 
11293   if (!Res.getNode())
11294     return;
11295 
11296   // If the original node has one result, take the return value from
11297   // LowerOperation as is. It might not be result number 0.
11298   if (N->getNumValues() == 1) {
11299     Results.push_back(Res);
11300     return;
11301   }
11302 
11303   // If the original node has multiple results, then the return node should
11304   // have the same number of results.
11305   assert((N->getNumValues() == Res->getNumValues()) &&
11306       "Lowering returned the wrong number of results!");
11307 
11308   // Places new result values base on N result number.
11309   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
11310     Results.push_back(Res.getValue(I));
11311 }
11312 
11313 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11314   llvm_unreachable("LowerOperation not implemented for this target!");
11315 }
11316 
11317 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
11318                                                      unsigned Reg,
11319                                                      ISD::NodeType ExtendType) {
11320   SDValue Op = getNonRegisterValue(V);
11321   assert((Op.getOpcode() != ISD::CopyFromReg ||
11322           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
11323          "Copy from a reg to the same reg!");
11324   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
11325 
11326   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11327   // If this is an InlineAsm we have to match the registers required, not the
11328   // notional registers required by the type.
11329 
11330   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
11331                    std::nullopt); // This is not an ABI copy.
11332   SDValue Chain = DAG.getEntryNode();
11333 
11334   if (ExtendType == ISD::ANY_EXTEND) {
11335     auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
11336     if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
11337       ExtendType = PreferredExtendIt->second;
11338   }
11339   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
11340   PendingExports.push_back(Chain);
11341 }
11342 
11343 #include "llvm/CodeGen/SelectionDAGISel.h"
11344 
11345 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
11346 /// entry block, return true.  This includes arguments used by switches, since
11347 /// the switch may expand into multiple basic blocks.
11348 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
11349   // With FastISel active, we may be splitting blocks, so force creation
11350   // of virtual registers for all non-dead arguments.
11351   if (FastISel)
11352     return A->use_empty();
11353 
11354   const BasicBlock &Entry = A->getParent()->front();
11355   for (const User *U : A->users())
11356     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
11357       return false;  // Use not in entry block.
11358 
11359   return true;
11360 }
11361 
11362 using ArgCopyElisionMapTy =
11363     DenseMap<const Argument *,
11364              std::pair<const AllocaInst *, const StoreInst *>>;
11365 
11366 /// Scan the entry block of the function in FuncInfo for arguments that look
11367 /// like copies into a local alloca. Record any copied arguments in
11368 /// ArgCopyElisionCandidates.
11369 static void
11370 findArgumentCopyElisionCandidates(const DataLayout &DL,
11371                                   FunctionLoweringInfo *FuncInfo,
11372                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
11373   // Record the state of every static alloca used in the entry block. Argument
11374   // allocas are all used in the entry block, so we need approximately as many
11375   // entries as we have arguments.
11376   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
11377   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
11378   unsigned NumArgs = FuncInfo->Fn->arg_size();
11379   StaticAllocas.reserve(NumArgs * 2);
11380 
11381   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
11382     if (!V)
11383       return nullptr;
11384     V = V->stripPointerCasts();
11385     const auto *AI = dyn_cast<AllocaInst>(V);
11386     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
11387       return nullptr;
11388     auto Iter = StaticAllocas.insert({AI, Unknown});
11389     return &Iter.first->second;
11390   };
11391 
11392   // Look for stores of arguments to static allocas. Look through bitcasts and
11393   // GEPs to handle type coercions, as long as the alloca is fully initialized
11394   // by the store. Any non-store use of an alloca escapes it and any subsequent
11395   // unanalyzed store might write it.
11396   // FIXME: Handle structs initialized with multiple stores.
11397   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
11398     // Look for stores, and handle non-store uses conservatively.
11399     const auto *SI = dyn_cast<StoreInst>(&I);
11400     if (!SI) {
11401       // We will look through cast uses, so ignore them completely.
11402       if (I.isCast())
11403         continue;
11404       // Ignore debug info and pseudo op intrinsics, they don't escape or store
11405       // to allocas.
11406       if (I.isDebugOrPseudoInst())
11407         continue;
11408       // This is an unknown instruction. Assume it escapes or writes to all
11409       // static alloca operands.
11410       for (const Use &U : I.operands()) {
11411         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
11412           *Info = StaticAllocaInfo::Clobbered;
11413       }
11414       continue;
11415     }
11416 
11417     // If the stored value is a static alloca, mark it as escaped.
11418     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
11419       *Info = StaticAllocaInfo::Clobbered;
11420 
11421     // Check if the destination is a static alloca.
11422     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
11423     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
11424     if (!Info)
11425       continue;
11426     const AllocaInst *AI = cast<AllocaInst>(Dst);
11427 
11428     // Skip allocas that have been initialized or clobbered.
11429     if (*Info != StaticAllocaInfo::Unknown)
11430       continue;
11431 
11432     // Check if the stored value is an argument, and that this store fully
11433     // initializes the alloca.
11434     // If the argument type has padding bits we can't directly forward a pointer
11435     // as the upper bits may contain garbage.
11436     // Don't elide copies from the same argument twice.
11437     const Value *Val = SI->getValueOperand()->stripPointerCasts();
11438     const auto *Arg = dyn_cast<Argument>(Val);
11439     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
11440         Arg->getType()->isEmptyTy() ||
11441         DL.getTypeStoreSize(Arg->getType()) !=
11442             DL.getTypeAllocSize(AI->getAllocatedType()) ||
11443         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
11444         ArgCopyElisionCandidates.count(Arg)) {
11445       *Info = StaticAllocaInfo::Clobbered;
11446       continue;
11447     }
11448 
11449     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
11450                       << '\n');
11451 
11452     // Mark this alloca and store for argument copy elision.
11453     *Info = StaticAllocaInfo::Elidable;
11454     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
11455 
11456     // Stop scanning if we've seen all arguments. This will happen early in -O0
11457     // builds, which is useful, because -O0 builds have large entry blocks and
11458     // many allocas.
11459     if (ArgCopyElisionCandidates.size() == NumArgs)
11460       break;
11461   }
11462 }
11463 
11464 /// Try to elide argument copies from memory into a local alloca. Succeeds if
11465 /// ArgVal is a load from a suitable fixed stack object.
11466 static void tryToElideArgumentCopy(
11467     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
11468     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
11469     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
11470     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
11471     ArrayRef<SDValue> ArgVals, bool &ArgHasUses) {
11472   // Check if this is a load from a fixed stack object.
11473   auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]);
11474   if (!LNode)
11475     return;
11476   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
11477   if (!FINode)
11478     return;
11479 
11480   // Check that the fixed stack object is the right size and alignment.
11481   // Look at the alignment that the user wrote on the alloca instead of looking
11482   // at the stack object.
11483   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
11484   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
11485   const AllocaInst *AI = ArgCopyIter->second.first;
11486   int FixedIndex = FINode->getIndex();
11487   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
11488   int OldIndex = AllocaIndex;
11489   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
11490   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
11491     LLVM_DEBUG(
11492         dbgs() << "  argument copy elision failed due to bad fixed stack "
11493                   "object size\n");
11494     return;
11495   }
11496   Align RequiredAlignment = AI->getAlign();
11497   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
11498     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
11499                          "greater than stack argument alignment ("
11500                       << DebugStr(RequiredAlignment) << " vs "
11501                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
11502     return;
11503   }
11504 
11505   // Perform the elision. Delete the old stack object and replace its only use
11506   // in the variable info map. Mark the stack object as mutable and aliased.
11507   LLVM_DEBUG({
11508     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
11509            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
11510            << '\n';
11511   });
11512   MFI.RemoveStackObject(OldIndex);
11513   MFI.setIsImmutableObjectIndex(FixedIndex, false);
11514   MFI.setIsAliasedObjectIndex(FixedIndex, true);
11515   AllocaIndex = FixedIndex;
11516   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
11517   for (SDValue ArgVal : ArgVals)
11518     Chains.push_back(ArgVal.getValue(1));
11519 
11520   // Avoid emitting code for the store implementing the copy.
11521   const StoreInst *SI = ArgCopyIter->second.second;
11522   ElidedArgCopyInstrs.insert(SI);
11523 
11524   // Check for uses of the argument again so that we can avoid exporting ArgVal
11525   // if it is't used by anything other than the store.
11526   for (const Value *U : Arg.users()) {
11527     if (U != SI) {
11528       ArgHasUses = true;
11529       break;
11530     }
11531   }
11532 }
11533 
11534 void SelectionDAGISel::LowerArguments(const Function &F) {
11535   SelectionDAG &DAG = SDB->DAG;
11536   SDLoc dl = SDB->getCurSDLoc();
11537   const DataLayout &DL = DAG.getDataLayout();
11538   SmallVector<ISD::InputArg, 16> Ins;
11539 
11540   // In Naked functions we aren't going to save any registers.
11541   if (F.hasFnAttribute(Attribute::Naked))
11542     return;
11543 
11544   if (!FuncInfo->CanLowerReturn) {
11545     // Put in an sret pointer parameter before all the other parameters.
11546     SmallVector<EVT, 1> ValueVTs;
11547     ComputeValueVTs(*TLI, DAG.getDataLayout(),
11548                     PointerType::get(F.getContext(),
11549                                      DAG.getDataLayout().getAllocaAddrSpace()),
11550                     ValueVTs);
11551 
11552     // NOTE: Assuming that a pointer will never break down to more than one VT
11553     // or one register.
11554     ISD::ArgFlagsTy Flags;
11555     Flags.setSRet();
11556     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
11557     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
11558                          ISD::InputArg::NoArgIndex, 0);
11559     Ins.push_back(RetArg);
11560   }
11561 
11562   // Look for stores of arguments to static allocas. Mark such arguments with a
11563   // flag to ask the target to give us the memory location of that argument if
11564   // available.
11565   ArgCopyElisionMapTy ArgCopyElisionCandidates;
11566   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
11567                                     ArgCopyElisionCandidates);
11568 
11569   // Set up the incoming argument description vector.
11570   for (const Argument &Arg : F.args()) {
11571     unsigned ArgNo = Arg.getArgNo();
11572     SmallVector<EVT, 4> ValueVTs;
11573     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
11574     bool isArgValueUsed = !Arg.use_empty();
11575     unsigned PartBase = 0;
11576     Type *FinalType = Arg.getType();
11577     if (Arg.hasAttribute(Attribute::ByVal))
11578       FinalType = Arg.getParamByValType();
11579     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
11580         FinalType, F.getCallingConv(), F.isVarArg(), DL);
11581     for (unsigned Value = 0, NumValues = ValueVTs.size();
11582          Value != NumValues; ++Value) {
11583       EVT VT = ValueVTs[Value];
11584       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
11585       ISD::ArgFlagsTy Flags;
11586 
11587 
11588       if (Arg.getType()->isPointerTy()) {
11589         Flags.setPointer();
11590         Flags.setPointerAddrSpace(
11591             cast<PointerType>(Arg.getType())->getAddressSpace());
11592       }
11593       if (Arg.hasAttribute(Attribute::ZExt))
11594         Flags.setZExt();
11595       if (Arg.hasAttribute(Attribute::SExt))
11596         Flags.setSExt();
11597       if (Arg.hasAttribute(Attribute::InReg)) {
11598         // If we are using vectorcall calling convention, a structure that is
11599         // passed InReg - is surely an HVA
11600         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
11601             isa<StructType>(Arg.getType())) {
11602           // The first value of a structure is marked
11603           if (0 == Value)
11604             Flags.setHvaStart();
11605           Flags.setHva();
11606         }
11607         // Set InReg Flag
11608         Flags.setInReg();
11609       }
11610       if (Arg.hasAttribute(Attribute::StructRet))
11611         Flags.setSRet();
11612       if (Arg.hasAttribute(Attribute::SwiftSelf))
11613         Flags.setSwiftSelf();
11614       if (Arg.hasAttribute(Attribute::SwiftAsync))
11615         Flags.setSwiftAsync();
11616       if (Arg.hasAttribute(Attribute::SwiftError))
11617         Flags.setSwiftError();
11618       if (Arg.hasAttribute(Attribute::ByVal))
11619         Flags.setByVal();
11620       if (Arg.hasAttribute(Attribute::ByRef))
11621         Flags.setByRef();
11622       if (Arg.hasAttribute(Attribute::InAlloca)) {
11623         Flags.setInAlloca();
11624         // Set the byval flag for CCAssignFn callbacks that don't know about
11625         // inalloca.  This way we can know how many bytes we should've allocated
11626         // and how many bytes a callee cleanup function will pop.  If we port
11627         // inalloca to more targets, we'll have to add custom inalloca handling
11628         // in the various CC lowering callbacks.
11629         Flags.setByVal();
11630       }
11631       if (Arg.hasAttribute(Attribute::Preallocated)) {
11632         Flags.setPreallocated();
11633         // Set the byval flag for CCAssignFn callbacks that don't know about
11634         // preallocated.  This way we can know how many bytes we should've
11635         // allocated and how many bytes a callee cleanup function will pop.  If
11636         // we port preallocated to more targets, we'll have to add custom
11637         // preallocated handling in the various CC lowering callbacks.
11638         Flags.setByVal();
11639       }
11640 
11641       // Certain targets (such as MIPS), may have a different ABI alignment
11642       // for a type depending on the context. Give the target a chance to
11643       // specify the alignment it wants.
11644       const Align OriginalAlignment(
11645           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
11646       Flags.setOrigAlign(OriginalAlignment);
11647 
11648       Align MemAlign;
11649       Type *ArgMemTy = nullptr;
11650       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
11651           Flags.isByRef()) {
11652         if (!ArgMemTy)
11653           ArgMemTy = Arg.getPointeeInMemoryValueType();
11654 
11655         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
11656 
11657         // For in-memory arguments, size and alignment should be passed from FE.
11658         // BE will guess if this info is not there but there are cases it cannot
11659         // get right.
11660         if (auto ParamAlign = Arg.getParamStackAlign())
11661           MemAlign = *ParamAlign;
11662         else if ((ParamAlign = Arg.getParamAlign()))
11663           MemAlign = *ParamAlign;
11664         else
11665           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
11666         if (Flags.isByRef())
11667           Flags.setByRefSize(MemSize);
11668         else
11669           Flags.setByValSize(MemSize);
11670       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
11671         MemAlign = *ParamAlign;
11672       } else {
11673         MemAlign = OriginalAlignment;
11674       }
11675       Flags.setMemAlign(MemAlign);
11676 
11677       if (Arg.hasAttribute(Attribute::Nest))
11678         Flags.setNest();
11679       if (NeedsRegBlock)
11680         Flags.setInConsecutiveRegs();
11681       if (ArgCopyElisionCandidates.count(&Arg))
11682         Flags.setCopyElisionCandidate();
11683       if (Arg.hasAttribute(Attribute::Returned))
11684         Flags.setReturned();
11685 
11686       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
11687           *CurDAG->getContext(), F.getCallingConv(), VT);
11688       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
11689           *CurDAG->getContext(), F.getCallingConv(), VT);
11690       for (unsigned i = 0; i != NumRegs; ++i) {
11691         // For scalable vectors, use the minimum size; individual targets
11692         // are responsible for handling scalable vector arguments and
11693         // return values.
11694         ISD::InputArg MyFlags(
11695             Flags, RegisterVT, VT, isArgValueUsed, ArgNo,
11696             PartBase + i * RegisterVT.getStoreSize().getKnownMinValue());
11697         if (NumRegs > 1 && i == 0)
11698           MyFlags.Flags.setSplit();
11699         // if it isn't first piece, alignment must be 1
11700         else if (i > 0) {
11701           MyFlags.Flags.setOrigAlign(Align(1));
11702           if (i == NumRegs - 1)
11703             MyFlags.Flags.setSplitEnd();
11704         }
11705         Ins.push_back(MyFlags);
11706       }
11707       if (NeedsRegBlock && Value == NumValues - 1)
11708         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
11709       PartBase += VT.getStoreSize().getKnownMinValue();
11710     }
11711   }
11712 
11713   // Call the target to set up the argument values.
11714   SmallVector<SDValue, 8> InVals;
11715   SDValue NewRoot = TLI->LowerFormalArguments(
11716       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
11717 
11718   // Verify that the target's LowerFormalArguments behaved as expected.
11719   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
11720          "LowerFormalArguments didn't return a valid chain!");
11721   assert(InVals.size() == Ins.size() &&
11722          "LowerFormalArguments didn't emit the correct number of values!");
11723   LLVM_DEBUG({
11724     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
11725       assert(InVals[i].getNode() &&
11726              "LowerFormalArguments emitted a null value!");
11727       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
11728              "LowerFormalArguments emitted a value with the wrong type!");
11729     }
11730   });
11731 
11732   // Update the DAG with the new chain value resulting from argument lowering.
11733   DAG.setRoot(NewRoot);
11734 
11735   // Set up the argument values.
11736   unsigned i = 0;
11737   if (!FuncInfo->CanLowerReturn) {
11738     // Create a virtual register for the sret pointer, and put in a copy
11739     // from the sret argument into it.
11740     SmallVector<EVT, 1> ValueVTs;
11741     ComputeValueVTs(*TLI, DAG.getDataLayout(),
11742                     PointerType::get(F.getContext(),
11743                                      DAG.getDataLayout().getAllocaAddrSpace()),
11744                     ValueVTs);
11745     MVT VT = ValueVTs[0].getSimpleVT();
11746     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
11747     std::optional<ISD::NodeType> AssertOp;
11748     SDValue ArgValue =
11749         getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, nullptr, NewRoot,
11750                          F.getCallingConv(), AssertOp);
11751 
11752     MachineFunction& MF = SDB->DAG.getMachineFunction();
11753     MachineRegisterInfo& RegInfo = MF.getRegInfo();
11754     Register SRetReg =
11755         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
11756     FuncInfo->DemoteRegister = SRetReg;
11757     NewRoot =
11758         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
11759     DAG.setRoot(NewRoot);
11760 
11761     // i indexes lowered arguments.  Bump it past the hidden sret argument.
11762     ++i;
11763   }
11764 
11765   SmallVector<SDValue, 4> Chains;
11766   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
11767   for (const Argument &Arg : F.args()) {
11768     SmallVector<SDValue, 4> ArgValues;
11769     SmallVector<EVT, 4> ValueVTs;
11770     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
11771     unsigned NumValues = ValueVTs.size();
11772     if (NumValues == 0)
11773       continue;
11774 
11775     bool ArgHasUses = !Arg.use_empty();
11776 
11777     // Elide the copying store if the target loaded this argument from a
11778     // suitable fixed stack object.
11779     if (Ins[i].Flags.isCopyElisionCandidate()) {
11780       unsigned NumParts = 0;
11781       for (EVT VT : ValueVTs)
11782         NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(),
11783                                                        F.getCallingConv(), VT);
11784 
11785       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
11786                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
11787                              ArrayRef(&InVals[i], NumParts), ArgHasUses);
11788     }
11789 
11790     // If this argument is unused then remember its value. It is used to generate
11791     // debugging information.
11792     bool isSwiftErrorArg =
11793         TLI->supportSwiftError() &&
11794         Arg.hasAttribute(Attribute::SwiftError);
11795     if (!ArgHasUses && !isSwiftErrorArg) {
11796       SDB->setUnusedArgValue(&Arg, InVals[i]);
11797 
11798       // Also remember any frame index for use in FastISel.
11799       if (FrameIndexSDNode *FI =
11800           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
11801         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11802     }
11803 
11804     for (unsigned Val = 0; Val != NumValues; ++Val) {
11805       EVT VT = ValueVTs[Val];
11806       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
11807                                                       F.getCallingConv(), VT);
11808       unsigned NumParts = TLI->getNumRegistersForCallingConv(
11809           *CurDAG->getContext(), F.getCallingConv(), VT);
11810 
11811       // Even an apparent 'unused' swifterror argument needs to be returned. So
11812       // we do generate a copy for it that can be used on return from the
11813       // function.
11814       if (ArgHasUses || isSwiftErrorArg) {
11815         std::optional<ISD::NodeType> AssertOp;
11816         if (Arg.hasAttribute(Attribute::SExt))
11817           AssertOp = ISD::AssertSext;
11818         else if (Arg.hasAttribute(Attribute::ZExt))
11819           AssertOp = ISD::AssertZext;
11820 
11821         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
11822                                              PartVT, VT, nullptr, NewRoot,
11823                                              F.getCallingConv(), AssertOp));
11824       }
11825 
11826       i += NumParts;
11827     }
11828 
11829     // We don't need to do anything else for unused arguments.
11830     if (ArgValues.empty())
11831       continue;
11832 
11833     // Note down frame index.
11834     if (FrameIndexSDNode *FI =
11835         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
11836       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11837 
11838     SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues),
11839                                      SDB->getCurSDLoc());
11840 
11841     SDB->setValue(&Arg, Res);
11842     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
11843       // We want to associate the argument with the frame index, among
11844       // involved operands, that correspond to the lowest address. The
11845       // getCopyFromParts function, called earlier, is swapping the order of
11846       // the operands to BUILD_PAIR depending on endianness. The result of
11847       // that swapping is that the least significant bits of the argument will
11848       // be in the first operand of the BUILD_PAIR node, and the most
11849       // significant bits will be in the second operand.
11850       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
11851       if (LoadSDNode *LNode =
11852           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
11853         if (FrameIndexSDNode *FI =
11854             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
11855           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11856     }
11857 
11858     // Analyses past this point are naive and don't expect an assertion.
11859     if (Res.getOpcode() == ISD::AssertZext)
11860       Res = Res.getOperand(0);
11861 
11862     // Update the SwiftErrorVRegDefMap.
11863     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
11864       Register Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11865       if (Reg.isVirtual())
11866         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
11867                                    Reg);
11868     }
11869 
11870     // If this argument is live outside of the entry block, insert a copy from
11871     // wherever we got it to the vreg that other BB's will reference it as.
11872     if (Res.getOpcode() == ISD::CopyFromReg) {
11873       // If we can, though, try to skip creating an unnecessary vreg.
11874       // FIXME: This isn't very clean... it would be nice to make this more
11875       // general.
11876       Register Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11877       if (Reg.isVirtual()) {
11878         FuncInfo->ValueMap[&Arg] = Reg;
11879         continue;
11880       }
11881     }
11882     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
11883       FuncInfo->InitializeRegForValue(&Arg);
11884       SDB->CopyToExportRegsIfNeeded(&Arg);
11885     }
11886   }
11887 
11888   if (!Chains.empty()) {
11889     Chains.push_back(NewRoot);
11890     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
11891   }
11892 
11893   DAG.setRoot(NewRoot);
11894 
11895   assert(i == InVals.size() && "Argument register count mismatch!");
11896 
11897   // If any argument copy elisions occurred and we have debug info, update the
11898   // stale frame indices used in the dbg.declare variable info table.
11899   if (!ArgCopyElisionFrameIndexMap.empty()) {
11900     for (MachineFunction::VariableDbgInfo &VI :
11901          MF->getInStackSlotVariableDbgInfo()) {
11902       auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot());
11903       if (I != ArgCopyElisionFrameIndexMap.end())
11904         VI.updateStackSlot(I->second);
11905     }
11906   }
11907 
11908   // Finally, if the target has anything special to do, allow it to do so.
11909   emitFunctionEntryCode();
11910 }
11911 
11912 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
11913 /// ensure constants are generated when needed.  Remember the virtual registers
11914 /// that need to be added to the Machine PHI nodes as input.  We cannot just
11915 /// directly add them, because expansion might result in multiple MBB's for one
11916 /// BB.  As such, the start of the BB might correspond to a different MBB than
11917 /// the end.
11918 void
11919 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
11920   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11921 
11922   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
11923 
11924   // Check PHI nodes in successors that expect a value to be available from this
11925   // block.
11926   for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
11927     if (!isa<PHINode>(SuccBB->begin())) continue;
11928     MachineBasicBlock *SuccMBB = FuncInfo.getMBB(SuccBB);
11929 
11930     // If this terminator has multiple identical successors (common for
11931     // switches), only handle each succ once.
11932     if (!SuccsHandled.insert(SuccMBB).second)
11933       continue;
11934 
11935     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
11936 
11937     // At this point we know that there is a 1-1 correspondence between LLVM PHI
11938     // nodes and Machine PHI nodes, but the incoming operands have not been
11939     // emitted yet.
11940     for (const PHINode &PN : SuccBB->phis()) {
11941       // Ignore dead phi's.
11942       if (PN.use_empty())
11943         continue;
11944 
11945       // Skip empty types
11946       if (PN.getType()->isEmptyTy())
11947         continue;
11948 
11949       unsigned Reg;
11950       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
11951 
11952       if (const auto *C = dyn_cast<Constant>(PHIOp)) {
11953         unsigned &RegOut = ConstantsOut[C];
11954         if (RegOut == 0) {
11955           RegOut = FuncInfo.CreateRegs(C);
11956           // We need to zero/sign extend ConstantInt phi operands to match
11957           // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
11958           ISD::NodeType ExtendType = ISD::ANY_EXTEND;
11959           if (auto *CI = dyn_cast<ConstantInt>(C))
11960             ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
11961                                                     : ISD::ZERO_EXTEND;
11962           CopyValueToVirtualRegister(C, RegOut, ExtendType);
11963         }
11964         Reg = RegOut;
11965       } else {
11966         DenseMap<const Value *, Register>::iterator I =
11967           FuncInfo.ValueMap.find(PHIOp);
11968         if (I != FuncInfo.ValueMap.end())
11969           Reg = I->second;
11970         else {
11971           assert(isa<AllocaInst>(PHIOp) &&
11972                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
11973                  "Didn't codegen value into a register!??");
11974           Reg = FuncInfo.CreateRegs(PHIOp);
11975           CopyValueToVirtualRegister(PHIOp, Reg);
11976         }
11977       }
11978 
11979       // Remember that this register needs to added to the machine PHI node as
11980       // the input for this MBB.
11981       SmallVector<EVT, 4> ValueVTs;
11982       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
11983       for (EVT VT : ValueVTs) {
11984         const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
11985         for (unsigned i = 0; i != NumRegisters; ++i)
11986           FuncInfo.PHINodesToUpdate.push_back(
11987               std::make_pair(&*MBBI++, Reg + i));
11988         Reg += NumRegisters;
11989       }
11990     }
11991   }
11992 
11993   ConstantsOut.clear();
11994 }
11995 
11996 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
11997   MachineFunction::iterator I(MBB);
11998   if (++I == FuncInfo.MF->end())
11999     return nullptr;
12000   return &*I;
12001 }
12002 
12003 /// During lowering new call nodes can be created (such as memset, etc.).
12004 /// Those will become new roots of the current DAG, but complications arise
12005 /// when they are tail calls. In such cases, the call lowering will update
12006 /// the root, but the builder still needs to know that a tail call has been
12007 /// lowered in order to avoid generating an additional return.
12008 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
12009   // If the node is null, we do have a tail call.
12010   if (MaybeTC.getNode() != nullptr)
12011     DAG.setRoot(MaybeTC);
12012   else
12013     HasTailCall = true;
12014 }
12015 
12016 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
12017                                         MachineBasicBlock *SwitchMBB,
12018                                         MachineBasicBlock *DefaultMBB) {
12019   MachineFunction *CurMF = FuncInfo.MF;
12020   MachineBasicBlock *NextMBB = nullptr;
12021   MachineFunction::iterator BBI(W.MBB);
12022   if (++BBI != FuncInfo.MF->end())
12023     NextMBB = &*BBI;
12024 
12025   unsigned Size = W.LastCluster - W.FirstCluster + 1;
12026 
12027   BranchProbabilityInfo *BPI = FuncInfo.BPI;
12028 
12029   if (Size == 2 && W.MBB == SwitchMBB) {
12030     // If any two of the cases has the same destination, and if one value
12031     // is the same as the other, but has one bit unset that the other has set,
12032     // use bit manipulation to do two compares at once.  For example:
12033     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
12034     // TODO: This could be extended to merge any 2 cases in switches with 3
12035     // cases.
12036     // TODO: Handle cases where W.CaseBB != SwitchBB.
12037     CaseCluster &Small = *W.FirstCluster;
12038     CaseCluster &Big = *W.LastCluster;
12039 
12040     if (Small.Low == Small.High && Big.Low == Big.High &&
12041         Small.MBB == Big.MBB) {
12042       const APInt &SmallValue = Small.Low->getValue();
12043       const APInt &BigValue = Big.Low->getValue();
12044 
12045       // Check that there is only one bit different.
12046       APInt CommonBit = BigValue ^ SmallValue;
12047       if (CommonBit.isPowerOf2()) {
12048         SDValue CondLHS = getValue(Cond);
12049         EVT VT = CondLHS.getValueType();
12050         SDLoc DL = getCurSDLoc();
12051 
12052         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
12053                                  DAG.getConstant(CommonBit, DL, VT));
12054         SDValue Cond = DAG.getSetCC(
12055             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
12056             ISD::SETEQ);
12057 
12058         // Update successor info.
12059         // Both Small and Big will jump to Small.BB, so we sum up the
12060         // probabilities.
12061         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
12062         if (BPI)
12063           addSuccessorWithProb(
12064               SwitchMBB, DefaultMBB,
12065               // The default destination is the first successor in IR.
12066               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
12067         else
12068           addSuccessorWithProb(SwitchMBB, DefaultMBB);
12069 
12070         // Insert the true branch.
12071         SDValue BrCond =
12072             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
12073                         DAG.getBasicBlock(Small.MBB));
12074         // Insert the false branch.
12075         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
12076                              DAG.getBasicBlock(DefaultMBB));
12077 
12078         DAG.setRoot(BrCond);
12079         return;
12080       }
12081     }
12082   }
12083 
12084   if (TM.getOptLevel() != CodeGenOptLevel::None) {
12085     // Here, we order cases by probability so the most likely case will be
12086     // checked first. However, two clusters can have the same probability in
12087     // which case their relative ordering is non-deterministic. So we use Low
12088     // as a tie-breaker as clusters are guaranteed to never overlap.
12089     llvm::sort(W.FirstCluster, W.LastCluster + 1,
12090                [](const CaseCluster &a, const CaseCluster &b) {
12091       return a.Prob != b.Prob ?
12092              a.Prob > b.Prob :
12093              a.Low->getValue().slt(b.Low->getValue());
12094     });
12095 
12096     // Rearrange the case blocks so that the last one falls through if possible
12097     // without changing the order of probabilities.
12098     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
12099       --I;
12100       if (I->Prob > W.LastCluster->Prob)
12101         break;
12102       if (I->Kind == CC_Range && I->MBB == NextMBB) {
12103         std::swap(*I, *W.LastCluster);
12104         break;
12105       }
12106     }
12107   }
12108 
12109   // Compute total probability.
12110   BranchProbability DefaultProb = W.DefaultProb;
12111   BranchProbability UnhandledProbs = DefaultProb;
12112   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
12113     UnhandledProbs += I->Prob;
12114 
12115   MachineBasicBlock *CurMBB = W.MBB;
12116   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
12117     bool FallthroughUnreachable = false;
12118     MachineBasicBlock *Fallthrough;
12119     if (I == W.LastCluster) {
12120       // For the last cluster, fall through to the default destination.
12121       Fallthrough = DefaultMBB;
12122       FallthroughUnreachable = isa<UnreachableInst>(
12123           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
12124     } else {
12125       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
12126       CurMF->insert(BBI, Fallthrough);
12127       // Put Cond in a virtual register to make it available from the new blocks.
12128       ExportFromCurrentBlock(Cond);
12129     }
12130     UnhandledProbs -= I->Prob;
12131 
12132     switch (I->Kind) {
12133       case CC_JumpTable: {
12134         // FIXME: Optimize away range check based on pivot comparisons.
12135         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
12136         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
12137 
12138         // The jump block hasn't been inserted yet; insert it here.
12139         MachineBasicBlock *JumpMBB = JT->MBB;
12140         CurMF->insert(BBI, JumpMBB);
12141 
12142         auto JumpProb = I->Prob;
12143         auto FallthroughProb = UnhandledProbs;
12144 
12145         // If the default statement is a target of the jump table, we evenly
12146         // distribute the default probability to successors of CurMBB. Also
12147         // update the probability on the edge from JumpMBB to Fallthrough.
12148         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
12149                                               SE = JumpMBB->succ_end();
12150              SI != SE; ++SI) {
12151           if (*SI == DefaultMBB) {
12152             JumpProb += DefaultProb / 2;
12153             FallthroughProb -= DefaultProb / 2;
12154             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
12155             JumpMBB->normalizeSuccProbs();
12156             break;
12157           }
12158         }
12159 
12160         // If the default clause is unreachable, propagate that knowledge into
12161         // JTH->FallthroughUnreachable which will use it to suppress the range
12162         // check.
12163         //
12164         // However, don't do this if we're doing branch target enforcement,
12165         // because a table branch _without_ a range check can be a tempting JOP
12166         // gadget - out-of-bounds inputs that are impossible in correct
12167         // execution become possible again if an attacker can influence the
12168         // control flow. So if an attacker doesn't already have a BTI bypass
12169         // available, we don't want them to be able to get one out of this
12170         // table branch.
12171         if (FallthroughUnreachable) {
12172           Function &CurFunc = CurMF->getFunction();
12173           if (!CurFunc.hasFnAttribute("branch-target-enforcement"))
12174             JTH->FallthroughUnreachable = true;
12175         }
12176 
12177         if (!JTH->FallthroughUnreachable)
12178           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
12179         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
12180         CurMBB->normalizeSuccProbs();
12181 
12182         // The jump table header will be inserted in our current block, do the
12183         // range check, and fall through to our fallthrough block.
12184         JTH->HeaderBB = CurMBB;
12185         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
12186 
12187         // If we're in the right place, emit the jump table header right now.
12188         if (CurMBB == SwitchMBB) {
12189           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
12190           JTH->Emitted = true;
12191         }
12192         break;
12193       }
12194       case CC_BitTests: {
12195         // FIXME: Optimize away range check based on pivot comparisons.
12196         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
12197 
12198         // The bit test blocks haven't been inserted yet; insert them here.
12199         for (BitTestCase &BTC : BTB->Cases)
12200           CurMF->insert(BBI, BTC.ThisBB);
12201 
12202         // Fill in fields of the BitTestBlock.
12203         BTB->Parent = CurMBB;
12204         BTB->Default = Fallthrough;
12205 
12206         BTB->DefaultProb = UnhandledProbs;
12207         // If the cases in bit test don't form a contiguous range, we evenly
12208         // distribute the probability on the edge to Fallthrough to two
12209         // successors of CurMBB.
12210         if (!BTB->ContiguousRange) {
12211           BTB->Prob += DefaultProb / 2;
12212           BTB->DefaultProb -= DefaultProb / 2;
12213         }
12214 
12215         if (FallthroughUnreachable)
12216           BTB->FallthroughUnreachable = true;
12217 
12218         // If we're in the right place, emit the bit test header right now.
12219         if (CurMBB == SwitchMBB) {
12220           visitBitTestHeader(*BTB, SwitchMBB);
12221           BTB->Emitted = true;
12222         }
12223         break;
12224       }
12225       case CC_Range: {
12226         const Value *RHS, *LHS, *MHS;
12227         ISD::CondCode CC;
12228         if (I->Low == I->High) {
12229           // Check Cond == I->Low.
12230           CC = ISD::SETEQ;
12231           LHS = Cond;
12232           RHS=I->Low;
12233           MHS = nullptr;
12234         } else {
12235           // Check I->Low <= Cond <= I->High.
12236           CC = ISD::SETLE;
12237           LHS = I->Low;
12238           MHS = Cond;
12239           RHS = I->High;
12240         }
12241 
12242         // If Fallthrough is unreachable, fold away the comparison.
12243         if (FallthroughUnreachable)
12244           CC = ISD::SETTRUE;
12245 
12246         // The false probability is the sum of all unhandled cases.
12247         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
12248                      getCurSDLoc(), I->Prob, UnhandledProbs);
12249 
12250         if (CurMBB == SwitchMBB)
12251           visitSwitchCase(CB, SwitchMBB);
12252         else
12253           SL->SwitchCases.push_back(CB);
12254 
12255         break;
12256       }
12257     }
12258     CurMBB = Fallthrough;
12259   }
12260 }
12261 
12262 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
12263                                         const SwitchWorkListItem &W,
12264                                         Value *Cond,
12265                                         MachineBasicBlock *SwitchMBB) {
12266   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
12267          "Clusters not sorted?");
12268   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
12269 
12270   auto [LastLeft, FirstRight, LeftProb, RightProb] =
12271       SL->computeSplitWorkItemInfo(W);
12272 
12273   // Use the first element on the right as pivot since we will make less-than
12274   // comparisons against it.
12275   CaseClusterIt PivotCluster = FirstRight;
12276   assert(PivotCluster > W.FirstCluster);
12277   assert(PivotCluster <= W.LastCluster);
12278 
12279   CaseClusterIt FirstLeft = W.FirstCluster;
12280   CaseClusterIt LastRight = W.LastCluster;
12281 
12282   const ConstantInt *Pivot = PivotCluster->Low;
12283 
12284   // New blocks will be inserted immediately after the current one.
12285   MachineFunction::iterator BBI(W.MBB);
12286   ++BBI;
12287 
12288   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
12289   // we can branch to its destination directly if it's squeezed exactly in
12290   // between the known lower bound and Pivot - 1.
12291   MachineBasicBlock *LeftMBB;
12292   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
12293       FirstLeft->Low == W.GE &&
12294       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
12295     LeftMBB = FirstLeft->MBB;
12296   } else {
12297     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12298     FuncInfo.MF->insert(BBI, LeftMBB);
12299     WorkList.push_back(
12300         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
12301     // Put Cond in a virtual register to make it available from the new blocks.
12302     ExportFromCurrentBlock(Cond);
12303   }
12304 
12305   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
12306   // single cluster, RHS.Low == Pivot, and we can branch to its destination
12307   // directly if RHS.High equals the current upper bound.
12308   MachineBasicBlock *RightMBB;
12309   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
12310       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
12311     RightMBB = FirstRight->MBB;
12312   } else {
12313     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12314     FuncInfo.MF->insert(BBI, RightMBB);
12315     WorkList.push_back(
12316         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
12317     // Put Cond in a virtual register to make it available from the new blocks.
12318     ExportFromCurrentBlock(Cond);
12319   }
12320 
12321   // Create the CaseBlock record that will be used to lower the branch.
12322   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
12323                getCurSDLoc(), LeftProb, RightProb);
12324 
12325   if (W.MBB == SwitchMBB)
12326     visitSwitchCase(CB, SwitchMBB);
12327   else
12328     SL->SwitchCases.push_back(CB);
12329 }
12330 
12331 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
12332 // from the swith statement.
12333 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
12334                                             BranchProbability PeeledCaseProb) {
12335   if (PeeledCaseProb == BranchProbability::getOne())
12336     return BranchProbability::getZero();
12337   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
12338 
12339   uint32_t Numerator = CaseProb.getNumerator();
12340   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
12341   return BranchProbability(Numerator, std::max(Numerator, Denominator));
12342 }
12343 
12344 // Try to peel the top probability case if it exceeds the threshold.
12345 // Return current MachineBasicBlock for the switch statement if the peeling
12346 // does not occur.
12347 // If the peeling is performed, return the newly created MachineBasicBlock
12348 // for the peeled switch statement. Also update Clusters to remove the peeled
12349 // case. PeeledCaseProb is the BranchProbability for the peeled case.
12350 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
12351     const SwitchInst &SI, CaseClusterVector &Clusters,
12352     BranchProbability &PeeledCaseProb) {
12353   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12354   // Don't perform if there is only one cluster or optimizing for size.
12355   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
12356       TM.getOptLevel() == CodeGenOptLevel::None ||
12357       SwitchMBB->getParent()->getFunction().hasMinSize())
12358     return SwitchMBB;
12359 
12360   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
12361   unsigned PeeledCaseIndex = 0;
12362   bool SwitchPeeled = false;
12363   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
12364     CaseCluster &CC = Clusters[Index];
12365     if (CC.Prob < TopCaseProb)
12366       continue;
12367     TopCaseProb = CC.Prob;
12368     PeeledCaseIndex = Index;
12369     SwitchPeeled = true;
12370   }
12371   if (!SwitchPeeled)
12372     return SwitchMBB;
12373 
12374   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
12375                     << TopCaseProb << "\n");
12376 
12377   // Record the MBB for the peeled switch statement.
12378   MachineFunction::iterator BBI(SwitchMBB);
12379   ++BBI;
12380   MachineBasicBlock *PeeledSwitchMBB =
12381       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
12382   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
12383 
12384   ExportFromCurrentBlock(SI.getCondition());
12385   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
12386   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
12387                           nullptr,   nullptr,      TopCaseProb.getCompl()};
12388   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
12389 
12390   Clusters.erase(PeeledCaseIt);
12391   for (CaseCluster &CC : Clusters) {
12392     LLVM_DEBUG(
12393         dbgs() << "Scale the probablity for one cluster, before scaling: "
12394                << CC.Prob << "\n");
12395     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
12396     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
12397   }
12398   PeeledCaseProb = TopCaseProb;
12399   return PeeledSwitchMBB;
12400 }
12401 
12402 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
12403   // Extract cases from the switch.
12404   BranchProbabilityInfo *BPI = FuncInfo.BPI;
12405   CaseClusterVector Clusters;
12406   Clusters.reserve(SI.getNumCases());
12407   for (auto I : SI.cases()) {
12408     MachineBasicBlock *Succ = FuncInfo.getMBB(I.getCaseSuccessor());
12409     const ConstantInt *CaseVal = I.getCaseValue();
12410     BranchProbability Prob =
12411         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
12412             : BranchProbability(1, SI.getNumCases() + 1);
12413     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
12414   }
12415 
12416   MachineBasicBlock *DefaultMBB = FuncInfo.getMBB(SI.getDefaultDest());
12417 
12418   // Cluster adjacent cases with the same destination. We do this at all
12419   // optimization levels because it's cheap to do and will make codegen faster
12420   // if there are many clusters.
12421   sortAndRangeify(Clusters);
12422 
12423   // The branch probablity of the peeled case.
12424   BranchProbability PeeledCaseProb = BranchProbability::getZero();
12425   MachineBasicBlock *PeeledSwitchMBB =
12426       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
12427 
12428   // If there is only the default destination, jump there directly.
12429   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12430   if (Clusters.empty()) {
12431     assert(PeeledSwitchMBB == SwitchMBB);
12432     SwitchMBB->addSuccessor(DefaultMBB);
12433     if (DefaultMBB != NextBlock(SwitchMBB)) {
12434       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
12435                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
12436     }
12437     return;
12438   }
12439 
12440   SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(),
12441                      DAG.getBFI());
12442   SL->findBitTestClusters(Clusters, &SI);
12443 
12444   LLVM_DEBUG({
12445     dbgs() << "Case clusters: ";
12446     for (const CaseCluster &C : Clusters) {
12447       if (C.Kind == CC_JumpTable)
12448         dbgs() << "JT:";
12449       if (C.Kind == CC_BitTests)
12450         dbgs() << "BT:";
12451 
12452       C.Low->getValue().print(dbgs(), true);
12453       if (C.Low != C.High) {
12454         dbgs() << '-';
12455         C.High->getValue().print(dbgs(), true);
12456       }
12457       dbgs() << ' ';
12458     }
12459     dbgs() << '\n';
12460   });
12461 
12462   assert(!Clusters.empty());
12463   SwitchWorkList WorkList;
12464   CaseClusterIt First = Clusters.begin();
12465   CaseClusterIt Last = Clusters.end() - 1;
12466   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
12467   // Scale the branchprobability for DefaultMBB if the peel occurs and
12468   // DefaultMBB is not replaced.
12469   if (PeeledCaseProb != BranchProbability::getZero() &&
12470       DefaultMBB == FuncInfo.getMBB(SI.getDefaultDest()))
12471     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
12472   WorkList.push_back(
12473       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
12474 
12475   while (!WorkList.empty()) {
12476     SwitchWorkListItem W = WorkList.pop_back_val();
12477     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
12478 
12479     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None &&
12480         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
12481       // For optimized builds, lower large range as a balanced binary tree.
12482       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
12483       continue;
12484     }
12485 
12486     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
12487   }
12488 }
12489 
12490 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
12491   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12492   auto DL = getCurSDLoc();
12493   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12494   setValue(&I, DAG.getStepVector(DL, ResultVT));
12495 }
12496 
12497 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
12498   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12499   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12500 
12501   SDLoc DL = getCurSDLoc();
12502   SDValue V = getValue(I.getOperand(0));
12503   assert(VT == V.getValueType() && "Malformed vector.reverse!");
12504 
12505   if (VT.isScalableVector()) {
12506     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
12507     return;
12508   }
12509 
12510   // Use VECTOR_SHUFFLE for the fixed-length vector
12511   // to maintain existing behavior.
12512   SmallVector<int, 8> Mask;
12513   unsigned NumElts = VT.getVectorMinNumElements();
12514   for (unsigned i = 0; i != NumElts; ++i)
12515     Mask.push_back(NumElts - 1 - i);
12516 
12517   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
12518 }
12519 
12520 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) {
12521   auto DL = getCurSDLoc();
12522   SDValue InVec = getValue(I.getOperand(0));
12523   EVT OutVT =
12524       InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
12525 
12526   unsigned OutNumElts = OutVT.getVectorMinNumElements();
12527 
12528   // ISD Node needs the input vectors split into two equal parts
12529   SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
12530                            DAG.getVectorIdxConstant(0, DL));
12531   SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
12532                            DAG.getVectorIdxConstant(OutNumElts, DL));
12533 
12534   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
12535   // legalisation and combines.
12536   if (OutVT.isFixedLengthVector()) {
12537     SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
12538                                         createStrideMask(0, 2, OutNumElts));
12539     SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
12540                                        createStrideMask(1, 2, OutNumElts));
12541     SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc());
12542     setValue(&I, Res);
12543     return;
12544   }
12545 
12546   SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL,
12547                             DAG.getVTList(OutVT, OutVT), Lo, Hi);
12548   setValue(&I, Res);
12549 }
12550 
12551 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) {
12552   auto DL = getCurSDLoc();
12553   EVT InVT = getValue(I.getOperand(0)).getValueType();
12554   SDValue InVec0 = getValue(I.getOperand(0));
12555   SDValue InVec1 = getValue(I.getOperand(1));
12556   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12557   EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12558 
12559   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
12560   // legalisation and combines.
12561   if (OutVT.isFixedLengthVector()) {
12562     unsigned NumElts = InVT.getVectorMinNumElements();
12563     SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1);
12564     setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT),
12565                                       createInterleaveMask(NumElts, 2)));
12566     return;
12567   }
12568 
12569   SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL,
12570                             DAG.getVTList(InVT, InVT), InVec0, InVec1);
12571   Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0),
12572                     Res.getValue(1));
12573   setValue(&I, Res);
12574 }
12575 
12576 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
12577   SmallVector<EVT, 4> ValueVTs;
12578   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
12579                   ValueVTs);
12580   unsigned NumValues = ValueVTs.size();
12581   if (NumValues == 0) return;
12582 
12583   SmallVector<SDValue, 4> Values(NumValues);
12584   SDValue Op = getValue(I.getOperand(0));
12585 
12586   for (unsigned i = 0; i != NumValues; ++i)
12587     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
12588                             SDValue(Op.getNode(), Op.getResNo() + i));
12589 
12590   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12591                            DAG.getVTList(ValueVTs), Values));
12592 }
12593 
12594 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
12595   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12596   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12597 
12598   SDLoc DL = getCurSDLoc();
12599   SDValue V1 = getValue(I.getOperand(0));
12600   SDValue V2 = getValue(I.getOperand(1));
12601   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
12602 
12603   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
12604   if (VT.isScalableVector()) {
12605     setValue(
12606         &I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
12607                         DAG.getSignedConstant(
12608                             Imm, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))));
12609     return;
12610   }
12611 
12612   unsigned NumElts = VT.getVectorNumElements();
12613 
12614   uint64_t Idx = (NumElts + Imm) % NumElts;
12615 
12616   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
12617   SmallVector<int, 8> Mask;
12618   for (unsigned i = 0; i < NumElts; ++i)
12619     Mask.push_back(Idx + i);
12620   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
12621 }
12622 
12623 // Consider the following MIR after SelectionDAG, which produces output in
12624 // phyregs in the first case or virtregs in the second case.
12625 //
12626 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx
12627 // %5:gr32 = COPY $ebx
12628 // %6:gr32 = COPY $edx
12629 // %1:gr32 = COPY %6:gr32
12630 // %0:gr32 = COPY %5:gr32
12631 //
12632 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32
12633 // %1:gr32 = COPY %6:gr32
12634 // %0:gr32 = COPY %5:gr32
12635 //
12636 // Given %0, we'd like to return $ebx in the first case and %5 in the second.
12637 // Given %1, we'd like to return $edx in the first case and %6 in the second.
12638 //
12639 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap
12640 // to a single virtreg (such as %0). The remaining outputs monotonically
12641 // increase in virtreg number from there. If a callbr has no outputs, then it
12642 // should not have a corresponding callbr landingpad; in fact, the callbr
12643 // landingpad would not even be able to refer to such a callbr.
12644 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) {
12645   MachineInstr *MI = MRI.def_begin(Reg)->getParent();
12646   // There is definitely at least one copy.
12647   assert(MI->getOpcode() == TargetOpcode::COPY &&
12648          "start of copy chain MUST be COPY");
12649   Reg = MI->getOperand(1).getReg();
12650   MI = MRI.def_begin(Reg)->getParent();
12651   // There may be an optional second copy.
12652   if (MI->getOpcode() == TargetOpcode::COPY) {
12653     assert(Reg.isVirtual() && "expected COPY of virtual register");
12654     Reg = MI->getOperand(1).getReg();
12655     assert(Reg.isPhysical() && "expected COPY of physical register");
12656     MI = MRI.def_begin(Reg)->getParent();
12657   }
12658   // The start of the chain must be an INLINEASM_BR.
12659   assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR &&
12660          "end of copy chain MUST be INLINEASM_BR");
12661   return Reg;
12662 }
12663 
12664 // We must do this walk rather than the simpler
12665 //   setValue(&I, getCopyFromRegs(CBR, CBR->getType()));
12666 // otherwise we will end up with copies of virtregs only valid along direct
12667 // edges.
12668 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) {
12669   SmallVector<EVT, 8> ResultVTs;
12670   SmallVector<SDValue, 8> ResultValues;
12671   const auto *CBR =
12672       cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator());
12673 
12674   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12675   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
12676   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
12677 
12678   unsigned InitialDef = FuncInfo.ValueMap[CBR];
12679   SDValue Chain = DAG.getRoot();
12680 
12681   // Re-parse the asm constraints string.
12682   TargetLowering::AsmOperandInfoVector TargetConstraints =
12683       TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR);
12684   for (auto &T : TargetConstraints) {
12685     SDISelAsmOperandInfo OpInfo(T);
12686     if (OpInfo.Type != InlineAsm::isOutput)
12687       continue;
12688 
12689     // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the
12690     // individual constraint.
12691     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
12692 
12693     switch (OpInfo.ConstraintType) {
12694     case TargetLowering::C_Register:
12695     case TargetLowering::C_RegisterClass: {
12696       // Fill in OpInfo.AssignedRegs.Regs.
12697       getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo);
12698 
12699       // getRegistersForValue may produce 1 to many registers based on whether
12700       // the OpInfo.ConstraintVT is legal on the target or not.
12701       for (Register &Reg : OpInfo.AssignedRegs.Regs) {
12702         Register OriginalDef = FollowCopyChain(MRI, InitialDef++);
12703         if (Register::isPhysicalRegister(OriginalDef))
12704           FuncInfo.MBB->addLiveIn(OriginalDef);
12705         // Update the assigned registers to use the original defs.
12706         Reg = OriginalDef;
12707       }
12708 
12709       SDValue V = OpInfo.AssignedRegs.getCopyFromRegs(
12710           DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR);
12711       ResultValues.push_back(V);
12712       ResultVTs.push_back(OpInfo.ConstraintVT);
12713       break;
12714     }
12715     case TargetLowering::C_Other: {
12716       SDValue Flag;
12717       SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
12718                                                   OpInfo, DAG);
12719       ++InitialDef;
12720       ResultValues.push_back(V);
12721       ResultVTs.push_back(OpInfo.ConstraintVT);
12722       break;
12723     }
12724     default:
12725       break;
12726     }
12727   }
12728   SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12729                           DAG.getVTList(ResultVTs), ResultValues);
12730   setValue(&I, V);
12731 }
12732