xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision ed5aaddd7b35850a7c427aec5d2ea9dd0131904b)
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 void SelectionDAGBuilder::visitVectorExtractLastActive(const CallInst &I,
6419                                                        unsigned Intrinsic) {
6420   assert(Intrinsic == Intrinsic::experimental_vector_extract_last_active &&
6421          "Tried lowering invalid vector extract last");
6422   SDLoc sdl = getCurSDLoc();
6423   SDValue Data = getValue(I.getOperand(0));
6424   SDValue Mask = getValue(I.getOperand(1));
6425   SDValue PassThru = getValue(I.getOperand(2));
6426 
6427   EVT DataVT = Data.getValueType();
6428   EVT ScalarVT = PassThru.getValueType();
6429   EVT BoolVT = Mask.getValueType().getScalarType();
6430 
6431   // Find a suitable type for a stepvector.
6432   ConstantRange VScaleRange(1, /*isFullSet=*/true); // Dummy value.
6433   if (DataVT.isScalableVector())
6434     VScaleRange = getVScaleRange(I.getCaller(), 64);
6435   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6436   unsigned EltWidth = TLI.getBitWidthForCttzElements(
6437       I.getType(), DataVT.getVectorElementCount(), /*ZeroIsPoison=*/true,
6438       &VScaleRange);
6439   MVT StepVT = MVT::getIntegerVT(EltWidth);
6440   EVT StepVecVT = DataVT.changeVectorElementType(StepVT);
6441 
6442   // Zero out lanes with inactive elements, then find the highest remaining
6443   // value from the stepvector.
6444   SDValue Zeroes = DAG.getConstant(0, sdl, StepVecVT);
6445   SDValue StepVec = DAG.getStepVector(sdl, StepVecVT);
6446   SDValue ActiveElts = DAG.getSelect(sdl, StepVecVT, Mask, StepVec, Zeroes);
6447   SDValue HighestIdx =
6448       DAG.getNode(ISD::VECREDUCE_UMAX, sdl, StepVT, ActiveElts);
6449 
6450   // Extract the corresponding lane from the data vector
6451   EVT ExtVT = TLI.getVectorIdxTy(DAG.getDataLayout());
6452   SDValue Idx = DAG.getZExtOrTrunc(HighestIdx, sdl, ExtVT);
6453   SDValue Extract =
6454       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, sdl, ScalarVT, Data, Idx);
6455 
6456   // If all mask lanes were inactive, choose the passthru value instead.
6457   SDValue AnyActive = DAG.getNode(ISD::VECREDUCE_OR, sdl, BoolVT, Mask);
6458   SDValue Result = DAG.getSelect(sdl, ScalarVT, AnyActive, Extract, PassThru);
6459   setValue(&I, Result);
6460 }
6461 
6462 /// Lower the call to the specified intrinsic function.
6463 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
6464                                              unsigned Intrinsic) {
6465   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6466   SDLoc sdl = getCurSDLoc();
6467   DebugLoc dl = getCurDebugLoc();
6468   SDValue Res;
6469 
6470   SDNodeFlags Flags;
6471   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
6472     Flags.copyFMF(*FPOp);
6473 
6474   switch (Intrinsic) {
6475   default:
6476     // By default, turn this into a target intrinsic node.
6477     visitTargetIntrinsic(I, Intrinsic);
6478     return;
6479   case Intrinsic::vscale: {
6480     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6481     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
6482     return;
6483   }
6484   case Intrinsic::vastart:  visitVAStart(I); return;
6485   case Intrinsic::vaend:    visitVAEnd(I); return;
6486   case Intrinsic::vacopy:   visitVACopy(I); return;
6487   case Intrinsic::returnaddress:
6488     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
6489                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6490                              getValue(I.getArgOperand(0))));
6491     return;
6492   case Intrinsic::addressofreturnaddress:
6493     setValue(&I,
6494              DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
6495                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6496     return;
6497   case Intrinsic::sponentry:
6498     setValue(&I,
6499              DAG.getNode(ISD::SPONENTRY, sdl,
6500                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6501     return;
6502   case Intrinsic::frameaddress:
6503     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
6504                              TLI.getFrameIndexTy(DAG.getDataLayout()),
6505                              getValue(I.getArgOperand(0))));
6506     return;
6507   case Intrinsic::read_volatile_register:
6508   case Intrinsic::read_register: {
6509     Value *Reg = I.getArgOperand(0);
6510     SDValue Chain = getRoot();
6511     SDValue RegName =
6512         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6513     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6514     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
6515       DAG.getVTList(VT, MVT::Other), Chain, RegName);
6516     setValue(&I, Res);
6517     DAG.setRoot(Res.getValue(1));
6518     return;
6519   }
6520   case Intrinsic::write_register: {
6521     Value *Reg = I.getArgOperand(0);
6522     Value *RegValue = I.getArgOperand(1);
6523     SDValue Chain = getRoot();
6524     SDValue RegName =
6525         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6526     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
6527                             RegName, getValue(RegValue)));
6528     return;
6529   }
6530   case Intrinsic::memcpy: {
6531     const auto &MCI = cast<MemCpyInst>(I);
6532     SDValue Op1 = getValue(I.getArgOperand(0));
6533     SDValue Op2 = getValue(I.getArgOperand(1));
6534     SDValue Op3 = getValue(I.getArgOperand(2));
6535     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
6536     Align DstAlign = MCI.getDestAlign().valueOrOne();
6537     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6538     Align Alignment = std::min(DstAlign, SrcAlign);
6539     bool isVol = MCI.isVolatile();
6540     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6541     // node.
6542     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6543     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6544                                /* AlwaysInline */ false, &I, std::nullopt,
6545                                MachinePointerInfo(I.getArgOperand(0)),
6546                                MachinePointerInfo(I.getArgOperand(1)),
6547                                I.getAAMetadata(), AA);
6548     updateDAGForMaybeTailCall(MC);
6549     return;
6550   }
6551   case Intrinsic::memcpy_inline: {
6552     const auto &MCI = cast<MemCpyInlineInst>(I);
6553     SDValue Dst = getValue(I.getArgOperand(0));
6554     SDValue Src = getValue(I.getArgOperand(1));
6555     SDValue Size = getValue(I.getArgOperand(2));
6556     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
6557     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
6558     Align DstAlign = MCI.getDestAlign().valueOrOne();
6559     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6560     Align Alignment = std::min(DstAlign, SrcAlign);
6561     bool isVol = MCI.isVolatile();
6562     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6563     // node.
6564     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
6565                                /* AlwaysInline */ true, &I, std::nullopt,
6566                                MachinePointerInfo(I.getArgOperand(0)),
6567                                MachinePointerInfo(I.getArgOperand(1)),
6568                                I.getAAMetadata(), AA);
6569     updateDAGForMaybeTailCall(MC);
6570     return;
6571   }
6572   case Intrinsic::memset: {
6573     const auto &MSI = cast<MemSetInst>(I);
6574     SDValue Op1 = getValue(I.getArgOperand(0));
6575     SDValue Op2 = getValue(I.getArgOperand(1));
6576     SDValue Op3 = getValue(I.getArgOperand(2));
6577     // @llvm.memset defines 0 and 1 to both mean no alignment.
6578     Align Alignment = MSI.getDestAlign().valueOrOne();
6579     bool isVol = MSI.isVolatile();
6580     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6581     SDValue MS = DAG.getMemset(
6582         Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false,
6583         &I, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
6584     updateDAGForMaybeTailCall(MS);
6585     return;
6586   }
6587   case Intrinsic::memset_inline: {
6588     const auto &MSII = cast<MemSetInlineInst>(I);
6589     SDValue Dst = getValue(I.getArgOperand(0));
6590     SDValue Value = getValue(I.getArgOperand(1));
6591     SDValue Size = getValue(I.getArgOperand(2));
6592     assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size");
6593     // @llvm.memset defines 0 and 1 to both mean no alignment.
6594     Align DstAlign = MSII.getDestAlign().valueOrOne();
6595     bool isVol = MSII.isVolatile();
6596     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6597     SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol,
6598                                /* AlwaysInline */ true, &I,
6599                                MachinePointerInfo(I.getArgOperand(0)),
6600                                I.getAAMetadata());
6601     updateDAGForMaybeTailCall(MC);
6602     return;
6603   }
6604   case Intrinsic::memmove: {
6605     const auto &MMI = cast<MemMoveInst>(I);
6606     SDValue Op1 = getValue(I.getArgOperand(0));
6607     SDValue Op2 = getValue(I.getArgOperand(1));
6608     SDValue Op3 = getValue(I.getArgOperand(2));
6609     // @llvm.memmove defines 0 and 1 to both mean no alignment.
6610     Align DstAlign = MMI.getDestAlign().valueOrOne();
6611     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
6612     Align Alignment = std::min(DstAlign, SrcAlign);
6613     bool isVol = MMI.isVolatile();
6614     // FIXME: Support passing different dest/src alignments to the memmove DAG
6615     // node.
6616     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6617     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, &I,
6618                                 /* OverrideTailCall */ std::nullopt,
6619                                 MachinePointerInfo(I.getArgOperand(0)),
6620                                 MachinePointerInfo(I.getArgOperand(1)),
6621                                 I.getAAMetadata(), AA);
6622     updateDAGForMaybeTailCall(MM);
6623     return;
6624   }
6625   case Intrinsic::memcpy_element_unordered_atomic: {
6626     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
6627     SDValue Dst = getValue(MI.getRawDest());
6628     SDValue Src = getValue(MI.getRawSource());
6629     SDValue Length = getValue(MI.getLength());
6630 
6631     Type *LengthTy = MI.getLength()->getType();
6632     unsigned ElemSz = MI.getElementSizeInBytes();
6633     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6634     SDValue MC =
6635         DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6636                             isTC, MachinePointerInfo(MI.getRawDest()),
6637                             MachinePointerInfo(MI.getRawSource()));
6638     updateDAGForMaybeTailCall(MC);
6639     return;
6640   }
6641   case Intrinsic::memmove_element_unordered_atomic: {
6642     auto &MI = cast<AtomicMemMoveInst>(I);
6643     SDValue Dst = getValue(MI.getRawDest());
6644     SDValue Src = getValue(MI.getRawSource());
6645     SDValue Length = getValue(MI.getLength());
6646 
6647     Type *LengthTy = MI.getLength()->getType();
6648     unsigned ElemSz = MI.getElementSizeInBytes();
6649     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6650     SDValue MC =
6651         DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6652                              isTC, MachinePointerInfo(MI.getRawDest()),
6653                              MachinePointerInfo(MI.getRawSource()));
6654     updateDAGForMaybeTailCall(MC);
6655     return;
6656   }
6657   case Intrinsic::memset_element_unordered_atomic: {
6658     auto &MI = cast<AtomicMemSetInst>(I);
6659     SDValue Dst = getValue(MI.getRawDest());
6660     SDValue Val = getValue(MI.getValue());
6661     SDValue Length = getValue(MI.getLength());
6662 
6663     Type *LengthTy = MI.getLength()->getType();
6664     unsigned ElemSz = MI.getElementSizeInBytes();
6665     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6666     SDValue MC =
6667         DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
6668                             isTC, MachinePointerInfo(MI.getRawDest()));
6669     updateDAGForMaybeTailCall(MC);
6670     return;
6671   }
6672   case Intrinsic::call_preallocated_setup: {
6673     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
6674     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6675     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
6676                               getRoot(), SrcValue);
6677     setValue(&I, Res);
6678     DAG.setRoot(Res);
6679     return;
6680   }
6681   case Intrinsic::call_preallocated_arg: {
6682     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6683     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6684     SDValue Ops[3];
6685     Ops[0] = getRoot();
6686     Ops[1] = SrcValue;
6687     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6688                                    MVT::i32); // arg index
6689     SDValue Res = DAG.getNode(
6690         ISD::PREALLOCATED_ARG, sdl,
6691         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6692     setValue(&I, Res);
6693     DAG.setRoot(Res.getValue(1));
6694     return;
6695   }
6696   case Intrinsic::dbg_declare: {
6697     const auto &DI = cast<DbgDeclareInst>(I);
6698     // Debug intrinsics are handled separately in assignment tracking mode.
6699     // Some intrinsics are handled right after Argument lowering.
6700     if (AssignmentTrackingEnabled ||
6701         FuncInfo.PreprocessedDbgDeclares.count(&DI))
6702       return;
6703     LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DI << "\n");
6704     DILocalVariable *Variable = DI.getVariable();
6705     DIExpression *Expression = DI.getExpression();
6706     dropDanglingDebugInfo(Variable, Expression);
6707     // Assume dbg.declare can not currently use DIArgList, i.e.
6708     // it is non-variadic.
6709     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6710     handleDebugDeclare(DI.getVariableLocationOp(0), Variable, Expression,
6711                        DI.getDebugLoc());
6712     return;
6713   }
6714   case Intrinsic::dbg_label: {
6715     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6716     DILabel *Label = DI.getLabel();
6717     assert(Label && "Missing label");
6718 
6719     SDDbgLabel *SDV;
6720     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6721     DAG.AddDbgLabel(SDV);
6722     return;
6723   }
6724   case Intrinsic::dbg_assign: {
6725     // Debug intrinsics are handled separately in assignment tracking mode.
6726     if (AssignmentTrackingEnabled)
6727       return;
6728     // If assignment tracking hasn't been enabled then fall through and treat
6729     // the dbg.assign as a dbg.value.
6730     [[fallthrough]];
6731   }
6732   case Intrinsic::dbg_value: {
6733     // Debug intrinsics are handled separately in assignment tracking mode.
6734     if (AssignmentTrackingEnabled)
6735       return;
6736     const DbgValueInst &DI = cast<DbgValueInst>(I);
6737     assert(DI.getVariable() && "Missing variable");
6738 
6739     DILocalVariable *Variable = DI.getVariable();
6740     DIExpression *Expression = DI.getExpression();
6741     dropDanglingDebugInfo(Variable, Expression);
6742 
6743     if (DI.isKillLocation()) {
6744       handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder);
6745       return;
6746     }
6747 
6748     SmallVector<Value *, 4> Values(DI.getValues());
6749     if (Values.empty())
6750       return;
6751 
6752     bool IsVariadic = DI.hasArgList();
6753     if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(),
6754                           SDNodeOrder, IsVariadic))
6755       addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
6756                            DI.getDebugLoc(), SDNodeOrder);
6757     return;
6758   }
6759 
6760   case Intrinsic::eh_typeid_for: {
6761     // Find the type id for the given typeinfo.
6762     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6763     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6764     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6765     setValue(&I, Res);
6766     return;
6767   }
6768 
6769   case Intrinsic::eh_return_i32:
6770   case Intrinsic::eh_return_i64:
6771     DAG.getMachineFunction().setCallsEHReturn(true);
6772     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6773                             MVT::Other,
6774                             getControlRoot(),
6775                             getValue(I.getArgOperand(0)),
6776                             getValue(I.getArgOperand(1))));
6777     return;
6778   case Intrinsic::eh_unwind_init:
6779     DAG.getMachineFunction().setCallsUnwindInit(true);
6780     return;
6781   case Intrinsic::eh_dwarf_cfa:
6782     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6783                              TLI.getPointerTy(DAG.getDataLayout()),
6784                              getValue(I.getArgOperand(0))));
6785     return;
6786   case Intrinsic::eh_sjlj_callsite: {
6787     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
6788     assert(FuncInfo.getCurrentCallSite() == 0 && "Overlapping call sites!");
6789 
6790     FuncInfo.setCurrentCallSite(CI->getZExtValue());
6791     return;
6792   }
6793   case Intrinsic::eh_sjlj_functioncontext: {
6794     // Get and store the index of the function context.
6795     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6796     AllocaInst *FnCtx =
6797       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6798     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6799     MFI.setFunctionContextIndex(FI);
6800     return;
6801   }
6802   case Intrinsic::eh_sjlj_setjmp: {
6803     SDValue Ops[2];
6804     Ops[0] = getRoot();
6805     Ops[1] = getValue(I.getArgOperand(0));
6806     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6807                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6808     setValue(&I, Op.getValue(0));
6809     DAG.setRoot(Op.getValue(1));
6810     return;
6811   }
6812   case Intrinsic::eh_sjlj_longjmp:
6813     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6814                             getRoot(), getValue(I.getArgOperand(0))));
6815     return;
6816   case Intrinsic::eh_sjlj_setup_dispatch:
6817     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6818                             getRoot()));
6819     return;
6820   case Intrinsic::masked_gather:
6821     visitMaskedGather(I);
6822     return;
6823   case Intrinsic::masked_load:
6824     visitMaskedLoad(I);
6825     return;
6826   case Intrinsic::masked_scatter:
6827     visitMaskedScatter(I);
6828     return;
6829   case Intrinsic::masked_store:
6830     visitMaskedStore(I);
6831     return;
6832   case Intrinsic::masked_expandload:
6833     visitMaskedLoad(I, true /* IsExpanding */);
6834     return;
6835   case Intrinsic::masked_compressstore:
6836     visitMaskedStore(I, true /* IsCompressing */);
6837     return;
6838   case Intrinsic::powi:
6839     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6840                             getValue(I.getArgOperand(1)), DAG));
6841     return;
6842   case Intrinsic::log:
6843     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6844     return;
6845   case Intrinsic::log2:
6846     setValue(&I,
6847              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6848     return;
6849   case Intrinsic::log10:
6850     setValue(&I,
6851              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6852     return;
6853   case Intrinsic::exp:
6854     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6855     return;
6856   case Intrinsic::exp2:
6857     setValue(&I,
6858              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6859     return;
6860   case Intrinsic::pow:
6861     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6862                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6863     return;
6864   case Intrinsic::sqrt:
6865   case Intrinsic::fabs:
6866   case Intrinsic::sin:
6867   case Intrinsic::cos:
6868   case Intrinsic::tan:
6869   case Intrinsic::asin:
6870   case Intrinsic::acos:
6871   case Intrinsic::atan:
6872   case Intrinsic::sinh:
6873   case Intrinsic::cosh:
6874   case Intrinsic::tanh:
6875   case Intrinsic::exp10:
6876   case Intrinsic::floor:
6877   case Intrinsic::ceil:
6878   case Intrinsic::trunc:
6879   case Intrinsic::rint:
6880   case Intrinsic::nearbyint:
6881   case Intrinsic::round:
6882   case Intrinsic::roundeven:
6883   case Intrinsic::canonicalize: {
6884     unsigned Opcode;
6885     // clang-format off
6886     switch (Intrinsic) {
6887     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6888     case Intrinsic::sqrt:         Opcode = ISD::FSQRT;         break;
6889     case Intrinsic::fabs:         Opcode = ISD::FABS;          break;
6890     case Intrinsic::sin:          Opcode = ISD::FSIN;          break;
6891     case Intrinsic::cos:          Opcode = ISD::FCOS;          break;
6892     case Intrinsic::tan:          Opcode = ISD::FTAN;          break;
6893     case Intrinsic::asin:         Opcode = ISD::FASIN;         break;
6894     case Intrinsic::acos:         Opcode = ISD::FACOS;         break;
6895     case Intrinsic::atan:         Opcode = ISD::FATAN;         break;
6896     case Intrinsic::sinh:         Opcode = ISD::FSINH;         break;
6897     case Intrinsic::cosh:         Opcode = ISD::FCOSH;         break;
6898     case Intrinsic::tanh:         Opcode = ISD::FTANH;         break;
6899     case Intrinsic::exp10:        Opcode = ISD::FEXP10;        break;
6900     case Intrinsic::floor:        Opcode = ISD::FFLOOR;        break;
6901     case Intrinsic::ceil:         Opcode = ISD::FCEIL;         break;
6902     case Intrinsic::trunc:        Opcode = ISD::FTRUNC;        break;
6903     case Intrinsic::rint:         Opcode = ISD::FRINT;         break;
6904     case Intrinsic::nearbyint:    Opcode = ISD::FNEARBYINT;    break;
6905     case Intrinsic::round:        Opcode = ISD::FROUND;        break;
6906     case Intrinsic::roundeven:    Opcode = ISD::FROUNDEVEN;    break;
6907     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6908     }
6909     // clang-format on
6910 
6911     setValue(&I, DAG.getNode(Opcode, sdl,
6912                              getValue(I.getArgOperand(0)).getValueType(),
6913                              getValue(I.getArgOperand(0)), Flags));
6914     return;
6915   }
6916   case Intrinsic::atan2:
6917     setValue(&I, DAG.getNode(ISD::FATAN2, sdl,
6918                              getValue(I.getArgOperand(0)).getValueType(),
6919                              getValue(I.getArgOperand(0)),
6920                              getValue(I.getArgOperand(1)), Flags));
6921     return;
6922   case Intrinsic::lround:
6923   case Intrinsic::llround:
6924   case Intrinsic::lrint:
6925   case Intrinsic::llrint: {
6926     unsigned Opcode;
6927     // clang-format off
6928     switch (Intrinsic) {
6929     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6930     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6931     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6932     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6933     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6934     }
6935     // clang-format on
6936 
6937     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6938     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6939                              getValue(I.getArgOperand(0))));
6940     return;
6941   }
6942   case Intrinsic::minnum:
6943     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6944                              getValue(I.getArgOperand(0)).getValueType(),
6945                              getValue(I.getArgOperand(0)),
6946                              getValue(I.getArgOperand(1)), Flags));
6947     return;
6948   case Intrinsic::maxnum:
6949     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6950                              getValue(I.getArgOperand(0)).getValueType(),
6951                              getValue(I.getArgOperand(0)),
6952                              getValue(I.getArgOperand(1)), Flags));
6953     return;
6954   case Intrinsic::minimum:
6955     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6956                              getValue(I.getArgOperand(0)).getValueType(),
6957                              getValue(I.getArgOperand(0)),
6958                              getValue(I.getArgOperand(1)), Flags));
6959     return;
6960   case Intrinsic::maximum:
6961     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6962                              getValue(I.getArgOperand(0)).getValueType(),
6963                              getValue(I.getArgOperand(0)),
6964                              getValue(I.getArgOperand(1)), Flags));
6965     return;
6966   case Intrinsic::minimumnum:
6967     setValue(&I, DAG.getNode(ISD::FMINIMUMNUM, sdl,
6968                              getValue(I.getArgOperand(0)).getValueType(),
6969                              getValue(I.getArgOperand(0)),
6970                              getValue(I.getArgOperand(1)), Flags));
6971     return;
6972   case Intrinsic::maximumnum:
6973     setValue(&I, DAG.getNode(ISD::FMAXIMUMNUM, sdl,
6974                              getValue(I.getArgOperand(0)).getValueType(),
6975                              getValue(I.getArgOperand(0)),
6976                              getValue(I.getArgOperand(1)), Flags));
6977     return;
6978   case Intrinsic::copysign:
6979     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6980                              getValue(I.getArgOperand(0)).getValueType(),
6981                              getValue(I.getArgOperand(0)),
6982                              getValue(I.getArgOperand(1)), Flags));
6983     return;
6984   case Intrinsic::ldexp:
6985     setValue(&I, DAG.getNode(ISD::FLDEXP, sdl,
6986                              getValue(I.getArgOperand(0)).getValueType(),
6987                              getValue(I.getArgOperand(0)),
6988                              getValue(I.getArgOperand(1)), Flags));
6989     return;
6990   case Intrinsic::sincos:
6991   case Intrinsic::frexp: {
6992     unsigned Opcode;
6993     switch (Intrinsic) {
6994     default:
6995       llvm_unreachable("unexpected intrinsic");
6996     case Intrinsic::sincos:
6997       Opcode = ISD::FSINCOS;
6998       break;
6999     case Intrinsic::frexp:
7000       Opcode = ISD::FFREXP;
7001       break;
7002     }
7003     SmallVector<EVT, 2> ValueVTs;
7004     ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
7005     SDVTList VTs = DAG.getVTList(ValueVTs);
7006     setValue(
7007         &I, DAG.getNode(Opcode, sdl, VTs, getValue(I.getArgOperand(0)), Flags));
7008     return;
7009   }
7010   case Intrinsic::arithmetic_fence: {
7011     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
7012                              getValue(I.getArgOperand(0)).getValueType(),
7013                              getValue(I.getArgOperand(0)), Flags));
7014     return;
7015   }
7016   case Intrinsic::fma:
7017     setValue(&I, DAG.getNode(
7018                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
7019                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
7020                      getValue(I.getArgOperand(2)), Flags));
7021     return;
7022 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
7023   case Intrinsic::INTRINSIC:
7024 #include "llvm/IR/ConstrainedOps.def"
7025     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
7026     return;
7027 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
7028 #include "llvm/IR/VPIntrinsics.def"
7029     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
7030     return;
7031   case Intrinsic::fptrunc_round: {
7032     // Get the last argument, the metadata and convert it to an integer in the
7033     // call
7034     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
7035     std::optional<RoundingMode> RoundMode =
7036         convertStrToRoundingMode(cast<MDString>(MD)->getString());
7037 
7038     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7039 
7040     // Propagate fast-math-flags from IR to node(s).
7041     SDNodeFlags Flags;
7042     Flags.copyFMF(*cast<FPMathOperator>(&I));
7043     SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
7044 
7045     SDValue Result;
7046     Result = DAG.getNode(
7047         ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
7048         DAG.getTargetConstant((int)*RoundMode, sdl, MVT::i32));
7049     setValue(&I, Result);
7050 
7051     return;
7052   }
7053   case Intrinsic::fmuladd: {
7054     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7055     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
7056         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
7057       setValue(&I, DAG.getNode(ISD::FMA, sdl,
7058                                getValue(I.getArgOperand(0)).getValueType(),
7059                                getValue(I.getArgOperand(0)),
7060                                getValue(I.getArgOperand(1)),
7061                                getValue(I.getArgOperand(2)), Flags));
7062     } else {
7063       // TODO: Intrinsic calls should have fast-math-flags.
7064       SDValue Mul = DAG.getNode(
7065           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
7066           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
7067       SDValue Add = DAG.getNode(ISD::FADD, sdl,
7068                                 getValue(I.getArgOperand(0)).getValueType(),
7069                                 Mul, getValue(I.getArgOperand(2)), Flags);
7070       setValue(&I, Add);
7071     }
7072     return;
7073   }
7074   case Intrinsic::convert_to_fp16:
7075     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
7076                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
7077                                          getValue(I.getArgOperand(0)),
7078                                          DAG.getTargetConstant(0, sdl,
7079                                                                MVT::i32))));
7080     return;
7081   case Intrinsic::convert_from_fp16:
7082     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
7083                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
7084                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
7085                                          getValue(I.getArgOperand(0)))));
7086     return;
7087   case Intrinsic::fptosi_sat: {
7088     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7089     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
7090                              getValue(I.getArgOperand(0)),
7091                              DAG.getValueType(VT.getScalarType())));
7092     return;
7093   }
7094   case Intrinsic::fptoui_sat: {
7095     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7096     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
7097                              getValue(I.getArgOperand(0)),
7098                              DAG.getValueType(VT.getScalarType())));
7099     return;
7100   }
7101   case Intrinsic::set_rounding:
7102     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
7103                       {getRoot(), getValue(I.getArgOperand(0))});
7104     setValue(&I, Res);
7105     DAG.setRoot(Res.getValue(0));
7106     return;
7107   case Intrinsic::is_fpclass: {
7108     const DataLayout DLayout = DAG.getDataLayout();
7109     EVT DestVT = TLI.getValueType(DLayout, I.getType());
7110     EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
7111     FPClassTest Test = static_cast<FPClassTest>(
7112         cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
7113     MachineFunction &MF = DAG.getMachineFunction();
7114     const Function &F = MF.getFunction();
7115     SDValue Op = getValue(I.getArgOperand(0));
7116     SDNodeFlags Flags;
7117     Flags.setNoFPExcept(
7118         !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
7119     // If ISD::IS_FPCLASS should be expanded, do it right now, because the
7120     // expansion can use illegal types. Making expansion early allows
7121     // legalizing these types prior to selection.
7122     if (!TLI.isOperationLegal(ISD::IS_FPCLASS, ArgVT) &&
7123         !TLI.isOperationCustom(ISD::IS_FPCLASS, ArgVT)) {
7124       SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
7125       setValue(&I, Result);
7126       return;
7127     }
7128 
7129     SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
7130     SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
7131     setValue(&I, V);
7132     return;
7133   }
7134   case Intrinsic::get_fpenv: {
7135     const DataLayout DLayout = DAG.getDataLayout();
7136     EVT EnvVT = TLI.getValueType(DLayout, I.getType());
7137     Align TempAlign = DAG.getEVTAlign(EnvVT);
7138     SDValue Chain = getRoot();
7139     // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node
7140     // and temporary storage in stack.
7141     if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) {
7142       Res = DAG.getNode(
7143           ISD::GET_FPENV, sdl,
7144           DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7145                         MVT::Other),
7146           Chain);
7147     } else {
7148       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7149       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7150       auto MPI =
7151           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7152       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7153           MPI, MachineMemOperand::MOStore, LocationSize::beforeOrAfterPointer(),
7154           TempAlign);
7155       Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7156       Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI);
7157     }
7158     setValue(&I, Res);
7159     DAG.setRoot(Res.getValue(1));
7160     return;
7161   }
7162   case Intrinsic::set_fpenv: {
7163     const DataLayout DLayout = DAG.getDataLayout();
7164     SDValue Env = getValue(I.getArgOperand(0));
7165     EVT EnvVT = Env.getValueType();
7166     Align TempAlign = DAG.getEVTAlign(EnvVT);
7167     SDValue Chain = getRoot();
7168     // If SET_FPENV is custom or legal, use it. Otherwise use loading
7169     // environment from memory.
7170     if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) {
7171       Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env);
7172     } else {
7173       // Allocate space in stack, copy environment bits into it and use this
7174       // memory in SET_FPENV_MEM.
7175       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7176       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7177       auto MPI =
7178           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7179       Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign,
7180                            MachineMemOperand::MOStore);
7181       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7182           MPI, MachineMemOperand::MOLoad, LocationSize::beforeOrAfterPointer(),
7183           TempAlign);
7184       Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7185     }
7186     DAG.setRoot(Chain);
7187     return;
7188   }
7189   case Intrinsic::reset_fpenv:
7190     DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot()));
7191     return;
7192   case Intrinsic::get_fpmode:
7193     Res = DAG.getNode(
7194         ISD::GET_FPMODE, sdl,
7195         DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7196                       MVT::Other),
7197         DAG.getRoot());
7198     setValue(&I, Res);
7199     DAG.setRoot(Res.getValue(1));
7200     return;
7201   case Intrinsic::set_fpmode:
7202     Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()},
7203                       getValue(I.getArgOperand(0)));
7204     DAG.setRoot(Res);
7205     return;
7206   case Intrinsic::reset_fpmode: {
7207     Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot());
7208     DAG.setRoot(Res);
7209     return;
7210   }
7211   case Intrinsic::pcmarker: {
7212     SDValue Tmp = getValue(I.getArgOperand(0));
7213     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
7214     return;
7215   }
7216   case Intrinsic::readcyclecounter: {
7217     SDValue Op = getRoot();
7218     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
7219                       DAG.getVTList(MVT::i64, MVT::Other), Op);
7220     setValue(&I, Res);
7221     DAG.setRoot(Res.getValue(1));
7222     return;
7223   }
7224   case Intrinsic::readsteadycounter: {
7225     SDValue Op = getRoot();
7226     Res = DAG.getNode(ISD::READSTEADYCOUNTER, sdl,
7227                       DAG.getVTList(MVT::i64, MVT::Other), Op);
7228     setValue(&I, Res);
7229     DAG.setRoot(Res.getValue(1));
7230     return;
7231   }
7232   case Intrinsic::bitreverse:
7233     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
7234                              getValue(I.getArgOperand(0)).getValueType(),
7235                              getValue(I.getArgOperand(0))));
7236     return;
7237   case Intrinsic::bswap:
7238     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
7239                              getValue(I.getArgOperand(0)).getValueType(),
7240                              getValue(I.getArgOperand(0))));
7241     return;
7242   case Intrinsic::cttz: {
7243     SDValue Arg = getValue(I.getArgOperand(0));
7244     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7245     EVT Ty = Arg.getValueType();
7246     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
7247                              sdl, Ty, Arg));
7248     return;
7249   }
7250   case Intrinsic::ctlz: {
7251     SDValue Arg = getValue(I.getArgOperand(0));
7252     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7253     EVT Ty = Arg.getValueType();
7254     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
7255                              sdl, Ty, Arg));
7256     return;
7257   }
7258   case Intrinsic::ctpop: {
7259     SDValue Arg = getValue(I.getArgOperand(0));
7260     EVT Ty = Arg.getValueType();
7261     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
7262     return;
7263   }
7264   case Intrinsic::fshl:
7265   case Intrinsic::fshr: {
7266     bool IsFSHL = Intrinsic == Intrinsic::fshl;
7267     SDValue X = getValue(I.getArgOperand(0));
7268     SDValue Y = getValue(I.getArgOperand(1));
7269     SDValue Z = getValue(I.getArgOperand(2));
7270     EVT VT = X.getValueType();
7271 
7272     if (X == Y) {
7273       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
7274       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
7275     } else {
7276       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
7277       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
7278     }
7279     return;
7280   }
7281   case Intrinsic::sadd_sat: {
7282     SDValue Op1 = getValue(I.getArgOperand(0));
7283     SDValue Op2 = getValue(I.getArgOperand(1));
7284     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7285     return;
7286   }
7287   case Intrinsic::uadd_sat: {
7288     SDValue Op1 = getValue(I.getArgOperand(0));
7289     SDValue Op2 = getValue(I.getArgOperand(1));
7290     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7291     return;
7292   }
7293   case Intrinsic::ssub_sat: {
7294     SDValue Op1 = getValue(I.getArgOperand(0));
7295     SDValue Op2 = getValue(I.getArgOperand(1));
7296     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7297     return;
7298   }
7299   case Intrinsic::usub_sat: {
7300     SDValue Op1 = getValue(I.getArgOperand(0));
7301     SDValue Op2 = getValue(I.getArgOperand(1));
7302     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7303     return;
7304   }
7305   case Intrinsic::sshl_sat: {
7306     SDValue Op1 = getValue(I.getArgOperand(0));
7307     SDValue Op2 = getValue(I.getArgOperand(1));
7308     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
7309     return;
7310   }
7311   case Intrinsic::ushl_sat: {
7312     SDValue Op1 = getValue(I.getArgOperand(0));
7313     SDValue Op2 = getValue(I.getArgOperand(1));
7314     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
7315     return;
7316   }
7317   case Intrinsic::smul_fix:
7318   case Intrinsic::umul_fix:
7319   case Intrinsic::smul_fix_sat:
7320   case Intrinsic::umul_fix_sat: {
7321     SDValue Op1 = getValue(I.getArgOperand(0));
7322     SDValue Op2 = getValue(I.getArgOperand(1));
7323     SDValue Op3 = getValue(I.getArgOperand(2));
7324     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7325                              Op1.getValueType(), Op1, Op2, Op3));
7326     return;
7327   }
7328   case Intrinsic::sdiv_fix:
7329   case Intrinsic::udiv_fix:
7330   case Intrinsic::sdiv_fix_sat:
7331   case Intrinsic::udiv_fix_sat: {
7332     SDValue Op1 = getValue(I.getArgOperand(0));
7333     SDValue Op2 = getValue(I.getArgOperand(1));
7334     SDValue Op3 = getValue(I.getArgOperand(2));
7335     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7336                               Op1, Op2, Op3, DAG, TLI));
7337     return;
7338   }
7339   case Intrinsic::smax: {
7340     SDValue Op1 = getValue(I.getArgOperand(0));
7341     SDValue Op2 = getValue(I.getArgOperand(1));
7342     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
7343     return;
7344   }
7345   case Intrinsic::smin: {
7346     SDValue Op1 = getValue(I.getArgOperand(0));
7347     SDValue Op2 = getValue(I.getArgOperand(1));
7348     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
7349     return;
7350   }
7351   case Intrinsic::umax: {
7352     SDValue Op1 = getValue(I.getArgOperand(0));
7353     SDValue Op2 = getValue(I.getArgOperand(1));
7354     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
7355     return;
7356   }
7357   case Intrinsic::umin: {
7358     SDValue Op1 = getValue(I.getArgOperand(0));
7359     SDValue Op2 = getValue(I.getArgOperand(1));
7360     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
7361     return;
7362   }
7363   case Intrinsic::abs: {
7364     // TODO: Preserve "int min is poison" arg in SDAG?
7365     SDValue Op1 = getValue(I.getArgOperand(0));
7366     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
7367     return;
7368   }
7369   case Intrinsic::scmp: {
7370     SDValue Op1 = getValue(I.getArgOperand(0));
7371     SDValue Op2 = getValue(I.getArgOperand(1));
7372     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7373     setValue(&I, DAG.getNode(ISD::SCMP, sdl, DestVT, Op1, Op2));
7374     break;
7375   }
7376   case Intrinsic::ucmp: {
7377     SDValue Op1 = getValue(I.getArgOperand(0));
7378     SDValue Op2 = getValue(I.getArgOperand(1));
7379     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7380     setValue(&I, DAG.getNode(ISD::UCMP, sdl, DestVT, Op1, Op2));
7381     break;
7382   }
7383   case Intrinsic::stacksave: {
7384     SDValue Op = getRoot();
7385     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7386     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
7387     setValue(&I, Res);
7388     DAG.setRoot(Res.getValue(1));
7389     return;
7390   }
7391   case Intrinsic::stackrestore:
7392     Res = getValue(I.getArgOperand(0));
7393     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
7394     return;
7395   case Intrinsic::get_dynamic_area_offset: {
7396     SDValue Op = getRoot();
7397     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7398     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7399     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
7400     // target.
7401     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
7402       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
7403                          " intrinsic!");
7404     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
7405                       Op);
7406     DAG.setRoot(Op);
7407     setValue(&I, Res);
7408     return;
7409   }
7410   case Intrinsic::stackguard: {
7411     MachineFunction &MF = DAG.getMachineFunction();
7412     const Module &M = *MF.getFunction().getParent();
7413     EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7414     SDValue Chain = getRoot();
7415     if (TLI.useLoadStackGuardNode(M)) {
7416       Res = getLoadStackGuard(DAG, sdl, Chain);
7417       Res = DAG.getPtrExtOrTrunc(Res, sdl, PtrTy);
7418     } else {
7419       const Value *Global = TLI.getSDagStackGuard(M);
7420       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
7421       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
7422                         MachinePointerInfo(Global, 0), Align,
7423                         MachineMemOperand::MOVolatile);
7424     }
7425     if (TLI.useStackGuardXorFP())
7426       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
7427     DAG.setRoot(Chain);
7428     setValue(&I, Res);
7429     return;
7430   }
7431   case Intrinsic::stackprotector: {
7432     // Emit code into the DAG to store the stack guard onto the stack.
7433     MachineFunction &MF = DAG.getMachineFunction();
7434     MachineFrameInfo &MFI = MF.getFrameInfo();
7435     const Module &M = *MF.getFunction().getParent();
7436     SDValue Src, Chain = getRoot();
7437 
7438     if (TLI.useLoadStackGuardNode(M))
7439       Src = getLoadStackGuard(DAG, sdl, Chain);
7440     else
7441       Src = getValue(I.getArgOperand(0));   // The guard's value.
7442 
7443     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
7444 
7445     int FI = FuncInfo.StaticAllocaMap[Slot];
7446     MFI.setStackProtectorIndex(FI);
7447     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7448 
7449     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
7450 
7451     // Store the stack protector onto the stack.
7452     Res = DAG.getStore(
7453         Chain, sdl, Src, FIN,
7454         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
7455         MaybeAlign(), MachineMemOperand::MOVolatile);
7456     setValue(&I, Res);
7457     DAG.setRoot(Res);
7458     return;
7459   }
7460   case Intrinsic::objectsize:
7461     llvm_unreachable("llvm.objectsize.* should have been lowered already");
7462 
7463   case Intrinsic::is_constant:
7464     llvm_unreachable("llvm.is.constant.* should have been lowered already");
7465 
7466   case Intrinsic::annotation:
7467   case Intrinsic::ptr_annotation:
7468   case Intrinsic::launder_invariant_group:
7469   case Intrinsic::strip_invariant_group:
7470     // Drop the intrinsic, but forward the value
7471     setValue(&I, getValue(I.getOperand(0)));
7472     return;
7473 
7474   case Intrinsic::assume:
7475   case Intrinsic::experimental_noalias_scope_decl:
7476   case Intrinsic::var_annotation:
7477   case Intrinsic::sideeffect:
7478     // Discard annotate attributes, noalias scope declarations, assumptions, and
7479     // artificial side-effects.
7480     return;
7481 
7482   case Intrinsic::codeview_annotation: {
7483     // Emit a label associated with this metadata.
7484     MachineFunction &MF = DAG.getMachineFunction();
7485     MCSymbol *Label = MF.getContext().createTempSymbol("annotation", true);
7486     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
7487     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
7488     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
7489     DAG.setRoot(Res);
7490     return;
7491   }
7492 
7493   case Intrinsic::init_trampoline: {
7494     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
7495 
7496     SDValue Ops[6];
7497     Ops[0] = getRoot();
7498     Ops[1] = getValue(I.getArgOperand(0));
7499     Ops[2] = getValue(I.getArgOperand(1));
7500     Ops[3] = getValue(I.getArgOperand(2));
7501     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
7502     Ops[5] = DAG.getSrcValue(F);
7503 
7504     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
7505 
7506     DAG.setRoot(Res);
7507     return;
7508   }
7509   case Intrinsic::adjust_trampoline:
7510     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
7511                              TLI.getPointerTy(DAG.getDataLayout()),
7512                              getValue(I.getArgOperand(0))));
7513     return;
7514   case Intrinsic::gcroot: {
7515     assert(DAG.getMachineFunction().getFunction().hasGC() &&
7516            "only valid in functions with gc specified, enforced by Verifier");
7517     assert(GFI && "implied by previous");
7518     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
7519     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
7520 
7521     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
7522     GFI->addStackRoot(FI->getIndex(), TypeMap);
7523     return;
7524   }
7525   case Intrinsic::gcread:
7526   case Intrinsic::gcwrite:
7527     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
7528   case Intrinsic::get_rounding:
7529     Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot());
7530     setValue(&I, Res);
7531     DAG.setRoot(Res.getValue(1));
7532     return;
7533 
7534   case Intrinsic::expect:
7535     // Just replace __builtin_expect(exp, c) with EXP.
7536     setValue(&I, getValue(I.getArgOperand(0)));
7537     return;
7538 
7539   case Intrinsic::ubsantrap:
7540   case Intrinsic::debugtrap:
7541   case Intrinsic::trap: {
7542     StringRef TrapFuncName =
7543         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
7544     if (TrapFuncName.empty()) {
7545       switch (Intrinsic) {
7546       case Intrinsic::trap:
7547         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
7548         break;
7549       case Intrinsic::debugtrap:
7550         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
7551         break;
7552       case Intrinsic::ubsantrap:
7553         DAG.setRoot(DAG.getNode(
7554             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
7555             DAG.getTargetConstant(
7556                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
7557                 MVT::i32)));
7558         break;
7559       default: llvm_unreachable("unknown trap intrinsic");
7560       }
7561       DAG.addNoMergeSiteInfo(DAG.getRoot().getNode(),
7562                              I.hasFnAttr(Attribute::NoMerge));
7563       return;
7564     }
7565     TargetLowering::ArgListTy Args;
7566     if (Intrinsic == Intrinsic::ubsantrap) {
7567       Args.push_back(TargetLoweringBase::ArgListEntry());
7568       Args[0].Val = I.getArgOperand(0);
7569       Args[0].Node = getValue(Args[0].Val);
7570       Args[0].Ty = Args[0].Val->getType();
7571     }
7572 
7573     TargetLowering::CallLoweringInfo CLI(DAG);
7574     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
7575         CallingConv::C, I.getType(),
7576         DAG.getExternalSymbol(TrapFuncName.data(),
7577                               TLI.getPointerTy(DAG.getDataLayout())),
7578         std::move(Args));
7579     CLI.NoMerge = I.hasFnAttr(Attribute::NoMerge);
7580     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7581     DAG.setRoot(Result.second);
7582     return;
7583   }
7584 
7585   case Intrinsic::allow_runtime_check:
7586   case Intrinsic::allow_ubsan_check:
7587     setValue(&I, getValue(ConstantInt::getTrue(I.getType())));
7588     return;
7589 
7590   case Intrinsic::uadd_with_overflow:
7591   case Intrinsic::sadd_with_overflow:
7592   case Intrinsic::usub_with_overflow:
7593   case Intrinsic::ssub_with_overflow:
7594   case Intrinsic::umul_with_overflow:
7595   case Intrinsic::smul_with_overflow: {
7596     ISD::NodeType Op;
7597     switch (Intrinsic) {
7598     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7599     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
7600     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
7601     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
7602     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
7603     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
7604     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
7605     }
7606     SDValue Op1 = getValue(I.getArgOperand(0));
7607     SDValue Op2 = getValue(I.getArgOperand(1));
7608 
7609     EVT ResultVT = Op1.getValueType();
7610     EVT OverflowVT = MVT::i1;
7611     if (ResultVT.isVector())
7612       OverflowVT = EVT::getVectorVT(
7613           *Context, OverflowVT, ResultVT.getVectorElementCount());
7614 
7615     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
7616     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
7617     return;
7618   }
7619   case Intrinsic::prefetch: {
7620     SDValue Ops[5];
7621     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7622     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
7623     Ops[0] = DAG.getRoot();
7624     Ops[1] = getValue(I.getArgOperand(0));
7625     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
7626                                    MVT::i32);
7627     Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl,
7628                                    MVT::i32);
7629     Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl,
7630                                    MVT::i32);
7631     SDValue Result = DAG.getMemIntrinsicNode(
7632         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
7633         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
7634         /* align */ std::nullopt, Flags);
7635 
7636     // Chain the prefetch in parallel with any pending loads, to stay out of
7637     // the way of later optimizations.
7638     PendingLoads.push_back(Result);
7639     Result = getRoot();
7640     DAG.setRoot(Result);
7641     return;
7642   }
7643   case Intrinsic::lifetime_start:
7644   case Intrinsic::lifetime_end: {
7645     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
7646     // Stack coloring is not enabled in O0, discard region information.
7647     if (TM.getOptLevel() == CodeGenOptLevel::None)
7648       return;
7649 
7650     const int64_t ObjectSize =
7651         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
7652     Value *const ObjectPtr = I.getArgOperand(1);
7653     SmallVector<const Value *, 4> Allocas;
7654     getUnderlyingObjects(ObjectPtr, Allocas);
7655 
7656     for (const Value *Alloca : Allocas) {
7657       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
7658 
7659       // Could not find an Alloca.
7660       if (!LifetimeObject)
7661         continue;
7662 
7663       // First check that the Alloca is static, otherwise it won't have a
7664       // valid frame index.
7665       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
7666       if (SI == FuncInfo.StaticAllocaMap.end())
7667         return;
7668 
7669       const int FrameIndex = SI->second;
7670       int64_t Offset;
7671       if (GetPointerBaseWithConstantOffset(
7672               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
7673         Offset = -1; // Cannot determine offset from alloca to lifetime object.
7674       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
7675                                 Offset);
7676       DAG.setRoot(Res);
7677     }
7678     return;
7679   }
7680   case Intrinsic::pseudoprobe: {
7681     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
7682     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7683     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
7684     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
7685     DAG.setRoot(Res);
7686     return;
7687   }
7688   case Intrinsic::invariant_start:
7689     // Discard region information.
7690     setValue(&I,
7691              DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
7692     return;
7693   case Intrinsic::invariant_end:
7694     // Discard region information.
7695     return;
7696   case Intrinsic::clear_cache: {
7697     SDValue InputChain = DAG.getRoot();
7698     SDValue StartVal = getValue(I.getArgOperand(0));
7699     SDValue EndVal = getValue(I.getArgOperand(1));
7700     Res = DAG.getNode(ISD::CLEAR_CACHE, sdl, DAG.getVTList(MVT::Other),
7701                       {InputChain, StartVal, EndVal});
7702     setValue(&I, Res);
7703     DAG.setRoot(Res);
7704     return;
7705   }
7706   case Intrinsic::donothing:
7707   case Intrinsic::seh_try_begin:
7708   case Intrinsic::seh_scope_begin:
7709   case Intrinsic::seh_try_end:
7710   case Intrinsic::seh_scope_end:
7711     // ignore
7712     return;
7713   case Intrinsic::experimental_stackmap:
7714     visitStackmap(I);
7715     return;
7716   case Intrinsic::experimental_patchpoint_void:
7717   case Intrinsic::experimental_patchpoint:
7718     visitPatchpoint(I);
7719     return;
7720   case Intrinsic::experimental_gc_statepoint:
7721     LowerStatepoint(cast<GCStatepointInst>(I));
7722     return;
7723   case Intrinsic::experimental_gc_result:
7724     visitGCResult(cast<GCResultInst>(I));
7725     return;
7726   case Intrinsic::experimental_gc_relocate:
7727     visitGCRelocate(cast<GCRelocateInst>(I));
7728     return;
7729   case Intrinsic::instrprof_cover:
7730     llvm_unreachable("instrprof failed to lower a cover");
7731   case Intrinsic::instrprof_increment:
7732     llvm_unreachable("instrprof failed to lower an increment");
7733   case Intrinsic::instrprof_timestamp:
7734     llvm_unreachable("instrprof failed to lower a timestamp");
7735   case Intrinsic::instrprof_value_profile:
7736     llvm_unreachable("instrprof failed to lower a value profiling call");
7737   case Intrinsic::instrprof_mcdc_parameters:
7738     llvm_unreachable("instrprof failed to lower mcdc parameters");
7739   case Intrinsic::instrprof_mcdc_tvbitmap_update:
7740     llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update");
7741   case Intrinsic::localescape: {
7742     MachineFunction &MF = DAG.getMachineFunction();
7743     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
7744 
7745     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
7746     // is the same on all targets.
7747     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
7748       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
7749       if (isa<ConstantPointerNull>(Arg))
7750         continue; // Skip null pointers. They represent a hole in index space.
7751       AllocaInst *Slot = cast<AllocaInst>(Arg);
7752       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
7753              "can only escape static allocas");
7754       int FI = FuncInfo.StaticAllocaMap[Slot];
7755       MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
7756           GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
7757       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
7758               TII->get(TargetOpcode::LOCAL_ESCAPE))
7759           .addSym(FrameAllocSym)
7760           .addFrameIndex(FI);
7761     }
7762 
7763     return;
7764   }
7765 
7766   case Intrinsic::localrecover: {
7767     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
7768     MachineFunction &MF = DAG.getMachineFunction();
7769 
7770     // Get the symbol that defines the frame offset.
7771     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
7772     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
7773     unsigned IdxVal =
7774         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
7775     MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
7776         GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
7777 
7778     Value *FP = I.getArgOperand(1);
7779     SDValue FPVal = getValue(FP);
7780     EVT PtrVT = FPVal.getValueType();
7781 
7782     // Create a MCSymbol for the label to avoid any target lowering
7783     // that would make this PC relative.
7784     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
7785     SDValue OffsetVal =
7786         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
7787 
7788     // Add the offset to the FP.
7789     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
7790     setValue(&I, Add);
7791 
7792     return;
7793   }
7794 
7795   case Intrinsic::fake_use: {
7796     Value *V = I.getArgOperand(0);
7797     SDValue Ops[2];
7798     // For Values not declared or previously used in this basic block, the
7799     // NodeMap will not have an entry, and `getValue` will assert if V has no
7800     // valid register value.
7801     auto FakeUseValue = [&]() -> SDValue {
7802       SDValue &N = NodeMap[V];
7803       if (N.getNode())
7804         return N;
7805 
7806       // If there's a virtual register allocated and initialized for this
7807       // value, use it.
7808       if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
7809         return copyFromReg;
7810       // FIXME: Do we want to preserve constants? It seems pointless.
7811       if (isa<Constant>(V))
7812         return getValue(V);
7813       return SDValue();
7814     }();
7815     if (!FakeUseValue || FakeUseValue.isUndef())
7816       return;
7817     Ops[0] = getRoot();
7818     Ops[1] = FakeUseValue;
7819     // Also, do not translate a fake use with an undef operand, or any other
7820     // empty SDValues.
7821     if (!Ops[1] || Ops[1].isUndef())
7822       return;
7823     DAG.setRoot(DAG.getNode(ISD::FAKE_USE, sdl, MVT::Other, Ops));
7824     return;
7825   }
7826 
7827   case Intrinsic::eh_exceptionpointer:
7828   case Intrinsic::eh_exceptioncode: {
7829     // Get the exception pointer vreg, copy from it, and resize it to fit.
7830     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
7831     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
7832     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
7833     Register VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
7834     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
7835     if (Intrinsic == Intrinsic::eh_exceptioncode)
7836       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
7837     setValue(&I, N);
7838     return;
7839   }
7840   case Intrinsic::xray_customevent: {
7841     // Here we want to make sure that the intrinsic behaves as if it has a
7842     // specific calling convention.
7843     const auto &Triple = DAG.getTarget().getTargetTriple();
7844     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7845       return;
7846 
7847     SmallVector<SDValue, 8> Ops;
7848 
7849     // We want to say that we always want the arguments in registers.
7850     SDValue LogEntryVal = getValue(I.getArgOperand(0));
7851     SDValue StrSizeVal = getValue(I.getArgOperand(1));
7852     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7853     SDValue Chain = getRoot();
7854     Ops.push_back(LogEntryVal);
7855     Ops.push_back(StrSizeVal);
7856     Ops.push_back(Chain);
7857 
7858     // We need to enforce the calling convention for the callsite, so that
7859     // argument ordering is enforced correctly, and that register allocation can
7860     // see that some registers may be assumed clobbered and have to preserve
7861     // them across calls to the intrinsic.
7862     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
7863                                            sdl, NodeTys, Ops);
7864     SDValue patchableNode = SDValue(MN, 0);
7865     DAG.setRoot(patchableNode);
7866     setValue(&I, patchableNode);
7867     return;
7868   }
7869   case Intrinsic::xray_typedevent: {
7870     // Here we want to make sure that the intrinsic behaves as if it has a
7871     // specific calling convention.
7872     const auto &Triple = DAG.getTarget().getTargetTriple();
7873     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7874       return;
7875 
7876     SmallVector<SDValue, 8> Ops;
7877 
7878     // We want to say that we always want the arguments in registers.
7879     // It's unclear to me how manipulating the selection DAG here forces callers
7880     // to provide arguments in registers instead of on the stack.
7881     SDValue LogTypeId = getValue(I.getArgOperand(0));
7882     SDValue LogEntryVal = getValue(I.getArgOperand(1));
7883     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7884     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7885     SDValue Chain = getRoot();
7886     Ops.push_back(LogTypeId);
7887     Ops.push_back(LogEntryVal);
7888     Ops.push_back(StrSizeVal);
7889     Ops.push_back(Chain);
7890 
7891     // We need to enforce the calling convention for the callsite, so that
7892     // argument ordering is enforced correctly, and that register allocation can
7893     // see that some registers may be assumed clobbered and have to preserve
7894     // them across calls to the intrinsic.
7895     MachineSDNode *MN = DAG.getMachineNode(
7896         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7897     SDValue patchableNode = SDValue(MN, 0);
7898     DAG.setRoot(patchableNode);
7899     setValue(&I, patchableNode);
7900     return;
7901   }
7902   case Intrinsic::experimental_deoptimize:
7903     LowerDeoptimizeCall(&I);
7904     return;
7905   case Intrinsic::stepvector:
7906     visitStepVector(I);
7907     return;
7908   case Intrinsic::vector_reduce_fadd:
7909   case Intrinsic::vector_reduce_fmul:
7910   case Intrinsic::vector_reduce_add:
7911   case Intrinsic::vector_reduce_mul:
7912   case Intrinsic::vector_reduce_and:
7913   case Intrinsic::vector_reduce_or:
7914   case Intrinsic::vector_reduce_xor:
7915   case Intrinsic::vector_reduce_smax:
7916   case Intrinsic::vector_reduce_smin:
7917   case Intrinsic::vector_reduce_umax:
7918   case Intrinsic::vector_reduce_umin:
7919   case Intrinsic::vector_reduce_fmax:
7920   case Intrinsic::vector_reduce_fmin:
7921   case Intrinsic::vector_reduce_fmaximum:
7922   case Intrinsic::vector_reduce_fminimum:
7923     visitVectorReduce(I, Intrinsic);
7924     return;
7925 
7926   case Intrinsic::icall_branch_funnel: {
7927     SmallVector<SDValue, 16> Ops;
7928     Ops.push_back(getValue(I.getArgOperand(0)));
7929 
7930     int64_t Offset;
7931     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7932         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7933     if (!Base)
7934       report_fatal_error(
7935           "llvm.icall.branch.funnel operand must be a GlobalValue");
7936     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7937 
7938     struct BranchFunnelTarget {
7939       int64_t Offset;
7940       SDValue Target;
7941     };
7942     SmallVector<BranchFunnelTarget, 8> Targets;
7943 
7944     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7945       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7946           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7947       if (ElemBase != Base)
7948         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7949                            "to the same GlobalValue");
7950 
7951       SDValue Val = getValue(I.getArgOperand(Op + 1));
7952       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7953       if (!GA)
7954         report_fatal_error(
7955             "llvm.icall.branch.funnel operand must be a GlobalValue");
7956       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7957                                      GA->getGlobal(), sdl, Val.getValueType(),
7958                                      GA->getOffset())});
7959     }
7960     llvm::sort(Targets,
7961                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7962                  return T1.Offset < T2.Offset;
7963                });
7964 
7965     for (auto &T : Targets) {
7966       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7967       Ops.push_back(T.Target);
7968     }
7969 
7970     Ops.push_back(DAG.getRoot()); // Chain
7971     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7972                                  MVT::Other, Ops),
7973               0);
7974     DAG.setRoot(N);
7975     setValue(&I, N);
7976     HasTailCall = true;
7977     return;
7978   }
7979 
7980   case Intrinsic::wasm_landingpad_index:
7981     // Information this intrinsic contained has been transferred to
7982     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7983     // delete it now.
7984     return;
7985 
7986   case Intrinsic::aarch64_settag:
7987   case Intrinsic::aarch64_settag_zero: {
7988     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7989     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7990     SDValue Val = TSI.EmitTargetCodeForSetTag(
7991         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7992         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7993         ZeroMemory);
7994     DAG.setRoot(Val);
7995     setValue(&I, Val);
7996     return;
7997   }
7998   case Intrinsic::amdgcn_cs_chain: {
7999     assert(I.arg_size() == 5 && "Additional args not supported yet");
8000     assert(cast<ConstantInt>(I.getOperand(4))->isZero() &&
8001            "Non-zero flags not supported yet");
8002 
8003     // At this point we don't care if it's amdgpu_cs_chain or
8004     // amdgpu_cs_chain_preserve.
8005     CallingConv::ID CC = CallingConv::AMDGPU_CS_Chain;
8006 
8007     Type *RetTy = I.getType();
8008     assert(RetTy->isVoidTy() && "Should not return");
8009 
8010     SDValue Callee = getValue(I.getOperand(0));
8011 
8012     // We only have 2 actual args: one for the SGPRs and one for the VGPRs.
8013     // We'll also tack the value of the EXEC mask at the end.
8014     TargetLowering::ArgListTy Args;
8015     Args.reserve(3);
8016 
8017     for (unsigned Idx : {2, 3, 1}) {
8018       TargetLowering::ArgListEntry Arg;
8019       Arg.Node = getValue(I.getOperand(Idx));
8020       Arg.Ty = I.getOperand(Idx)->getType();
8021       Arg.setAttributes(&I, Idx);
8022       Args.push_back(Arg);
8023     }
8024 
8025     assert(Args[0].IsInReg && "SGPR args should be marked inreg");
8026     assert(!Args[1].IsInReg && "VGPR args should not be marked inreg");
8027     Args[2].IsInReg = true; // EXEC should be inreg
8028 
8029     TargetLowering::CallLoweringInfo CLI(DAG);
8030     CLI.setDebugLoc(getCurSDLoc())
8031         .setChain(getRoot())
8032         .setCallee(CC, RetTy, Callee, std::move(Args))
8033         .setNoReturn(true)
8034         .setTailCall(true)
8035         .setConvergent(I.isConvergent());
8036     CLI.CB = &I;
8037     std::pair<SDValue, SDValue> Result =
8038         lowerInvokable(CLI, /*EHPadBB*/ nullptr);
8039     (void)Result;
8040     assert(!Result.first.getNode() && !Result.second.getNode() &&
8041            "Should've lowered as tail call");
8042 
8043     HasTailCall = true;
8044     return;
8045   }
8046   case Intrinsic::ptrmask: {
8047     SDValue Ptr = getValue(I.getOperand(0));
8048     SDValue Mask = getValue(I.getOperand(1));
8049 
8050     // On arm64_32, pointers are 32 bits when stored in memory, but
8051     // zero-extended to 64 bits when in registers.  Thus the mask is 32 bits to
8052     // match the index type, but the pointer is 64 bits, so the the mask must be
8053     // zero-extended up to 64 bits to match the pointer.
8054     EVT PtrVT =
8055         TLI.getValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
8056     EVT MemVT =
8057         TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
8058     assert(PtrVT == Ptr.getValueType());
8059     assert(MemVT == Mask.getValueType());
8060     if (MemVT != PtrVT)
8061       Mask = DAG.getPtrExtOrTrunc(Mask, sdl, PtrVT);
8062 
8063     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask));
8064     return;
8065   }
8066   case Intrinsic::threadlocal_address: {
8067     setValue(&I, getValue(I.getOperand(0)));
8068     return;
8069   }
8070   case Intrinsic::get_active_lane_mask: {
8071     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8072     SDValue Index = getValue(I.getOperand(0));
8073     EVT ElementVT = Index.getValueType();
8074 
8075     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
8076       visitTargetIntrinsic(I, Intrinsic);
8077       return;
8078     }
8079 
8080     SDValue TripCount = getValue(I.getOperand(1));
8081     EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT,
8082                                  CCVT.getVectorElementCount());
8083 
8084     SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
8085     SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
8086     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
8087     SDValue VectorInduction = DAG.getNode(
8088         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
8089     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
8090                                  VectorTripCount, ISD::CondCode::SETULT);
8091     setValue(&I, SetCC);
8092     return;
8093   }
8094   case Intrinsic::experimental_get_vector_length: {
8095     assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 &&
8096            "Expected positive VF");
8097     unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue();
8098     bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne();
8099 
8100     SDValue Count = getValue(I.getOperand(0));
8101     EVT CountVT = Count.getValueType();
8102 
8103     if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) {
8104       visitTargetIntrinsic(I, Intrinsic);
8105       return;
8106     }
8107 
8108     // Expand to a umin between the trip count and the maximum elements the type
8109     // can hold.
8110     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8111 
8112     // Extend the trip count to at least the result VT.
8113     if (CountVT.bitsLT(VT)) {
8114       Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count);
8115       CountVT = VT;
8116     }
8117 
8118     SDValue MaxEVL = DAG.getElementCount(sdl, CountVT,
8119                                          ElementCount::get(VF, IsScalable));
8120 
8121     SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL);
8122     // Clip to the result type if needed.
8123     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin);
8124 
8125     setValue(&I, Trunc);
8126     return;
8127   }
8128   case Intrinsic::experimental_vector_partial_reduce_add: {
8129 
8130     if (!TLI.shouldExpandPartialReductionIntrinsic(cast<IntrinsicInst>(&I))) {
8131       visitTargetIntrinsic(I, Intrinsic);
8132       return;
8133     }
8134 
8135     setValue(&I, DAG.getPartialReduceAdd(sdl, EVT::getEVT(I.getType()),
8136                                          getValue(I.getOperand(0)),
8137                                          getValue(I.getOperand(1))));
8138     return;
8139   }
8140   case Intrinsic::experimental_cttz_elts: {
8141     auto DL = getCurSDLoc();
8142     SDValue Op = getValue(I.getOperand(0));
8143     EVT OpVT = Op.getValueType();
8144 
8145     if (!TLI.shouldExpandCttzElements(OpVT)) {
8146       visitTargetIntrinsic(I, Intrinsic);
8147       return;
8148     }
8149 
8150     if (OpVT.getScalarType() != MVT::i1) {
8151       // Compare the input vector elements to zero & use to count trailing zeros
8152       SDValue AllZero = DAG.getConstant(0, DL, OpVT);
8153       OpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
8154                               OpVT.getVectorElementCount());
8155       Op = DAG.getSetCC(DL, OpVT, Op, AllZero, ISD::SETNE);
8156     }
8157 
8158     // If the zero-is-poison flag is set, we can assume the upper limit
8159     // of the result is VF-1.
8160     bool ZeroIsPoison =
8161         !cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero();
8162     ConstantRange VScaleRange(1, true); // Dummy value.
8163     if (isa<ScalableVectorType>(I.getOperand(0)->getType()))
8164       VScaleRange = getVScaleRange(I.getCaller(), 64);
8165     unsigned EltWidth = TLI.getBitWidthForCttzElements(
8166         I.getType(), OpVT.getVectorElementCount(), ZeroIsPoison, &VScaleRange);
8167 
8168     MVT NewEltTy = MVT::getIntegerVT(EltWidth);
8169 
8170     // Create the new vector type & get the vector length
8171     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), NewEltTy,
8172                                  OpVT.getVectorElementCount());
8173 
8174     SDValue VL =
8175         DAG.getElementCount(DL, NewEltTy, OpVT.getVectorElementCount());
8176 
8177     SDValue StepVec = DAG.getStepVector(DL, NewVT);
8178     SDValue SplatVL = DAG.getSplat(NewVT, DL, VL);
8179     SDValue StepVL = DAG.getNode(ISD::SUB, DL, NewVT, SplatVL, StepVec);
8180     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, Op);
8181     SDValue And = DAG.getNode(ISD::AND, DL, NewVT, StepVL, Ext);
8182     SDValue Max = DAG.getNode(ISD::VECREDUCE_UMAX, DL, NewEltTy, And);
8183     SDValue Sub = DAG.getNode(ISD::SUB, DL, NewEltTy, VL, Max);
8184 
8185     EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
8186     SDValue Ret = DAG.getZExtOrTrunc(Sub, DL, RetTy);
8187 
8188     setValue(&I, Ret);
8189     return;
8190   }
8191   case Intrinsic::vector_insert: {
8192     SDValue Vec = getValue(I.getOperand(0));
8193     SDValue SubVec = getValue(I.getOperand(1));
8194     SDValue Index = getValue(I.getOperand(2));
8195 
8196     // The intrinsic's index type is i64, but the SDNode requires an index type
8197     // suitable for the target. Convert the index as required.
8198     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8199     if (Index.getValueType() != VectorIdxTy)
8200       Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8201 
8202     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8203     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
8204                              Index));
8205     return;
8206   }
8207   case Intrinsic::vector_extract: {
8208     SDValue Vec = getValue(I.getOperand(0));
8209     SDValue Index = getValue(I.getOperand(1));
8210     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8211 
8212     // The intrinsic's index type is i64, but the SDNode requires an index type
8213     // suitable for the target. Convert the index as required.
8214     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8215     if (Index.getValueType() != VectorIdxTy)
8216       Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8217 
8218     setValue(&I,
8219              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
8220     return;
8221   }
8222   case Intrinsic::experimental_vector_match: {
8223     SDValue Op1 = getValue(I.getOperand(0));
8224     SDValue Op2 = getValue(I.getOperand(1));
8225     SDValue Mask = getValue(I.getOperand(2));
8226     EVT Op1VT = Op1.getValueType();
8227     EVT Op2VT = Op2.getValueType();
8228     EVT ResVT = Mask.getValueType();
8229     unsigned SearchSize = Op2VT.getVectorNumElements();
8230 
8231     // If the target has native support for this vector match operation, lower
8232     // the intrinsic untouched; otherwise, expand it below.
8233     if (!TLI.shouldExpandVectorMatch(Op1VT, SearchSize)) {
8234       visitTargetIntrinsic(I, Intrinsic);
8235       return;
8236     }
8237 
8238     SDValue Ret = DAG.getConstant(0, sdl, ResVT);
8239 
8240     for (unsigned i = 0; i < SearchSize; ++i) {
8241       SDValue Op2Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, sdl,
8242                                     Op2VT.getVectorElementType(), Op2,
8243                                     DAG.getVectorIdxConstant(i, sdl));
8244       SDValue Splat = DAG.getNode(ISD::SPLAT_VECTOR, sdl, Op1VT, Op2Elem);
8245       SDValue Cmp = DAG.getSetCC(sdl, ResVT, Op1, Splat, ISD::SETEQ);
8246       Ret = DAG.getNode(ISD::OR, sdl, ResVT, Ret, Cmp);
8247     }
8248 
8249     setValue(&I, DAG.getNode(ISD::AND, sdl, ResVT, Ret, Mask));
8250     return;
8251   }
8252   case Intrinsic::vector_reverse:
8253     visitVectorReverse(I);
8254     return;
8255   case Intrinsic::vector_splice:
8256     visitVectorSplice(I);
8257     return;
8258   case Intrinsic::callbr_landingpad:
8259     visitCallBrLandingPad(I);
8260     return;
8261   case Intrinsic::vector_interleave2:
8262     visitVectorInterleave(I);
8263     return;
8264   case Intrinsic::vector_deinterleave2:
8265     visitVectorDeinterleave(I);
8266     return;
8267   case Intrinsic::experimental_vector_compress:
8268     setValue(&I, DAG.getNode(ISD::VECTOR_COMPRESS, sdl,
8269                              getValue(I.getArgOperand(0)).getValueType(),
8270                              getValue(I.getArgOperand(0)),
8271                              getValue(I.getArgOperand(1)),
8272                              getValue(I.getArgOperand(2)), Flags));
8273     return;
8274   case Intrinsic::experimental_convergence_anchor:
8275   case Intrinsic::experimental_convergence_entry:
8276   case Intrinsic::experimental_convergence_loop:
8277     visitConvergenceControl(I, Intrinsic);
8278     return;
8279   case Intrinsic::experimental_vector_histogram_add: {
8280     visitVectorHistogram(I, Intrinsic);
8281     return;
8282   }
8283   case Intrinsic::experimental_vector_extract_last_active: {
8284     visitVectorExtractLastActive(I, Intrinsic);
8285     return;
8286   }
8287   }
8288 }
8289 
8290 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
8291     const ConstrainedFPIntrinsic &FPI) {
8292   SDLoc sdl = getCurSDLoc();
8293 
8294   // We do not need to serialize constrained FP intrinsics against
8295   // each other or against (nonvolatile) loads, so they can be
8296   // chained like loads.
8297   SDValue Chain = DAG.getRoot();
8298   SmallVector<SDValue, 4> Opers;
8299   Opers.push_back(Chain);
8300   for (unsigned I = 0, E = FPI.getNonMetadataArgCount(); I != E; ++I)
8301     Opers.push_back(getValue(FPI.getArgOperand(I)));
8302 
8303   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
8304     assert(Result.getNode()->getNumValues() == 2);
8305 
8306     // Push node to the appropriate list so that future instructions can be
8307     // chained up correctly.
8308     SDValue OutChain = Result.getValue(1);
8309     switch (EB) {
8310     case fp::ExceptionBehavior::ebIgnore:
8311       // The only reason why ebIgnore nodes still need to be chained is that
8312       // they might depend on the current rounding mode, and therefore must
8313       // not be moved across instruction that may change that mode.
8314       [[fallthrough]];
8315     case fp::ExceptionBehavior::ebMayTrap:
8316       // These must not be moved across calls or instructions that may change
8317       // floating-point exception masks.
8318       PendingConstrainedFP.push_back(OutChain);
8319       break;
8320     case fp::ExceptionBehavior::ebStrict:
8321       // These must not be moved across calls or instructions that may change
8322       // floating-point exception masks or read floating-point exception flags.
8323       // In addition, they cannot be optimized out even if unused.
8324       PendingConstrainedFPStrict.push_back(OutChain);
8325       break;
8326     }
8327   };
8328 
8329   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8330   EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
8331   SDVTList VTs = DAG.getVTList(VT, MVT::Other);
8332   fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
8333 
8334   SDNodeFlags Flags;
8335   if (EB == fp::ExceptionBehavior::ebIgnore)
8336     Flags.setNoFPExcept(true);
8337 
8338   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
8339     Flags.copyFMF(*FPOp);
8340 
8341   unsigned Opcode;
8342   switch (FPI.getIntrinsicID()) {
8343   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
8344 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8345   case Intrinsic::INTRINSIC:                                                   \
8346     Opcode = ISD::STRICT_##DAGN;                                               \
8347     break;
8348 #include "llvm/IR/ConstrainedOps.def"
8349   case Intrinsic::experimental_constrained_fmuladd: {
8350     Opcode = ISD::STRICT_FMA;
8351     // Break fmuladd into fmul and fadd.
8352     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
8353         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
8354       Opers.pop_back();
8355       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
8356       pushOutChain(Mul, EB);
8357       Opcode = ISD::STRICT_FADD;
8358       Opers.clear();
8359       Opers.push_back(Mul.getValue(1));
8360       Opers.push_back(Mul.getValue(0));
8361       Opers.push_back(getValue(FPI.getArgOperand(2)));
8362     }
8363     break;
8364   }
8365   }
8366 
8367   // A few strict DAG nodes carry additional operands that are not
8368   // set up by the default code above.
8369   switch (Opcode) {
8370   default: break;
8371   case ISD::STRICT_FP_ROUND:
8372     Opers.push_back(
8373         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
8374     break;
8375   case ISD::STRICT_FSETCC:
8376   case ISD::STRICT_FSETCCS: {
8377     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
8378     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
8379     if (TM.Options.NoNaNsFPMath)
8380       Condition = getFCmpCodeWithoutNaN(Condition);
8381     Opers.push_back(DAG.getCondCode(Condition));
8382     break;
8383   }
8384   }
8385 
8386   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
8387   pushOutChain(Result, EB);
8388 
8389   SDValue FPResult = Result.getValue(0);
8390   setValue(&FPI, FPResult);
8391 }
8392 
8393 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
8394   std::optional<unsigned> ResOPC;
8395   switch (VPIntrin.getIntrinsicID()) {
8396   case Intrinsic::vp_ctlz: {
8397     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8398     ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ;
8399     break;
8400   }
8401   case Intrinsic::vp_cttz: {
8402     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8403     ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ;
8404     break;
8405   }
8406   case Intrinsic::vp_cttz_elts: {
8407     bool IsZeroPoison = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8408     ResOPC = IsZeroPoison ? ISD::VP_CTTZ_ELTS_ZERO_UNDEF : ISD::VP_CTTZ_ELTS;
8409     break;
8410   }
8411 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD)                                    \
8412   case Intrinsic::VPID:                                                        \
8413     ResOPC = ISD::VPSD;                                                        \
8414     break;
8415 #include "llvm/IR/VPIntrinsics.def"
8416   }
8417 
8418   if (!ResOPC)
8419     llvm_unreachable(
8420         "Inconsistency: no SDNode available for this VPIntrinsic!");
8421 
8422   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
8423       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
8424     if (VPIntrin.getFastMathFlags().allowReassoc())
8425       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
8426                                                 : ISD::VP_REDUCE_FMUL;
8427   }
8428 
8429   return *ResOPC;
8430 }
8431 
8432 void SelectionDAGBuilder::visitVPLoad(
8433     const VPIntrinsic &VPIntrin, EVT VT,
8434     const SmallVectorImpl<SDValue> &OpValues) {
8435   SDLoc DL = getCurSDLoc();
8436   Value *PtrOperand = VPIntrin.getArgOperand(0);
8437   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8438   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8439   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8440   SDValue LD;
8441   // Do not serialize variable-length loads of constant memory with
8442   // anything.
8443   if (!Alignment)
8444     Alignment = DAG.getEVTAlign(VT);
8445   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
8446   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
8447   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8448   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8449       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
8450       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8451   LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
8452                      MMO, false /*IsExpanding */);
8453   if (AddToChain)
8454     PendingLoads.push_back(LD.getValue(1));
8455   setValue(&VPIntrin, LD);
8456 }
8457 
8458 void SelectionDAGBuilder::visitVPGather(
8459     const VPIntrinsic &VPIntrin, EVT VT,
8460     const SmallVectorImpl<SDValue> &OpValues) {
8461   SDLoc DL = getCurSDLoc();
8462   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8463   Value *PtrOperand = VPIntrin.getArgOperand(0);
8464   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8465   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8466   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8467   SDValue LD;
8468   if (!Alignment)
8469     Alignment = DAG.getEVTAlign(VT.getScalarType());
8470   unsigned AS =
8471     PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8472   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8473       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
8474       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8475   SDValue Base, Index, Scale;
8476   ISD::MemIndexType IndexType;
8477   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
8478                                     this, VPIntrin.getParent(),
8479                                     VT.getScalarStoreSize());
8480   if (!UniformBase) {
8481     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
8482     Index = getValue(PtrOperand);
8483     IndexType = ISD::SIGNED_SCALED;
8484     Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
8485   }
8486   EVT IdxVT = Index.getValueType();
8487   EVT EltTy = IdxVT.getVectorElementType();
8488   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
8489     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
8490     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
8491   }
8492   LD = DAG.getGatherVP(
8493       DAG.getVTList(VT, MVT::Other), VT, DL,
8494       {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
8495       IndexType);
8496   PendingLoads.push_back(LD.getValue(1));
8497   setValue(&VPIntrin, LD);
8498 }
8499 
8500 void SelectionDAGBuilder::visitVPStore(
8501     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8502   SDLoc DL = getCurSDLoc();
8503   Value *PtrOperand = VPIntrin.getArgOperand(1);
8504   EVT VT = OpValues[0].getValueType();
8505   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8506   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8507   SDValue ST;
8508   if (!Alignment)
8509     Alignment = DAG.getEVTAlign(VT);
8510   SDValue Ptr = OpValues[1];
8511   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
8512   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8513       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
8514       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8515   ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
8516                       OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
8517                       /* IsTruncating */ false, /*IsCompressing*/ false);
8518   DAG.setRoot(ST);
8519   setValue(&VPIntrin, ST);
8520 }
8521 
8522 void SelectionDAGBuilder::visitVPScatter(
8523     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8524   SDLoc DL = getCurSDLoc();
8525   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8526   Value *PtrOperand = VPIntrin.getArgOperand(1);
8527   EVT VT = OpValues[0].getValueType();
8528   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8529   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8530   SDValue ST;
8531   if (!Alignment)
8532     Alignment = DAG.getEVTAlign(VT.getScalarType());
8533   unsigned AS =
8534       PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8535   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8536       MachinePointerInfo(AS), MachineMemOperand::MOStore,
8537       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8538   SDValue Base, Index, Scale;
8539   ISD::MemIndexType IndexType;
8540   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
8541                                     this, VPIntrin.getParent(),
8542                                     VT.getScalarStoreSize());
8543   if (!UniformBase) {
8544     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
8545     Index = getValue(PtrOperand);
8546     IndexType = ISD::SIGNED_SCALED;
8547     Scale =
8548       DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
8549   }
8550   EVT IdxVT = Index.getValueType();
8551   EVT EltTy = IdxVT.getVectorElementType();
8552   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
8553     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
8554     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
8555   }
8556   ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
8557                         {getMemoryRoot(), OpValues[0], Base, Index, Scale,
8558                          OpValues[2], OpValues[3]},
8559                         MMO, IndexType);
8560   DAG.setRoot(ST);
8561   setValue(&VPIntrin, ST);
8562 }
8563 
8564 void SelectionDAGBuilder::visitVPStridedLoad(
8565     const VPIntrinsic &VPIntrin, EVT VT,
8566     const SmallVectorImpl<SDValue> &OpValues) {
8567   SDLoc DL = getCurSDLoc();
8568   Value *PtrOperand = VPIntrin.getArgOperand(0);
8569   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8570   if (!Alignment)
8571     Alignment = DAG.getEVTAlign(VT.getScalarType());
8572   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8573   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8574   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
8575   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
8576   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8577   unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8578   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8579       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
8580       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8581 
8582   SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
8583                                     OpValues[2], OpValues[3], MMO,
8584                                     false /*IsExpanding*/);
8585 
8586   if (AddToChain)
8587     PendingLoads.push_back(LD.getValue(1));
8588   setValue(&VPIntrin, LD);
8589 }
8590 
8591 void SelectionDAGBuilder::visitVPStridedStore(
8592     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8593   SDLoc DL = getCurSDLoc();
8594   Value *PtrOperand = VPIntrin.getArgOperand(1);
8595   EVT VT = OpValues[0].getValueType();
8596   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8597   if (!Alignment)
8598     Alignment = DAG.getEVTAlign(VT.getScalarType());
8599   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8600   unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8601   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8602       MachinePointerInfo(AS), MachineMemOperand::MOStore,
8603       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8604 
8605   SDValue ST = DAG.getStridedStoreVP(
8606       getMemoryRoot(), DL, OpValues[0], OpValues[1],
8607       DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3],
8608       OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
8609       /*IsCompressing*/ false);
8610 
8611   DAG.setRoot(ST);
8612   setValue(&VPIntrin, ST);
8613 }
8614 
8615 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) {
8616   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8617   SDLoc DL = getCurSDLoc();
8618 
8619   ISD::CondCode Condition;
8620   CmpInst::Predicate CondCode = VPIntrin.getPredicate();
8621   bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy();
8622   if (IsFP) {
8623     // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan)
8624     // flags, but calls that don't return floating-point types can't be
8625     // FPMathOperators, like vp.fcmp. This affects constrained fcmp too.
8626     Condition = getFCmpCondCode(CondCode);
8627     if (TM.Options.NoNaNsFPMath)
8628       Condition = getFCmpCodeWithoutNaN(Condition);
8629   } else {
8630     Condition = getICmpCondCode(CondCode);
8631   }
8632 
8633   SDValue Op1 = getValue(VPIntrin.getOperand(0));
8634   SDValue Op2 = getValue(VPIntrin.getOperand(1));
8635   // #2 is the condition code
8636   SDValue MaskOp = getValue(VPIntrin.getOperand(3));
8637   SDValue EVL = getValue(VPIntrin.getOperand(4));
8638   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8639   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8640          "Unexpected target EVL type");
8641   EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL);
8642 
8643   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8644                                                         VPIntrin.getType());
8645   setValue(&VPIntrin,
8646            DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL));
8647 }
8648 
8649 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
8650     const VPIntrinsic &VPIntrin) {
8651   SDLoc DL = getCurSDLoc();
8652   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
8653 
8654   auto IID = VPIntrin.getIntrinsicID();
8655 
8656   if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin))
8657     return visitVPCmp(*CmpI);
8658 
8659   SmallVector<EVT, 4> ValueVTs;
8660   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8661   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
8662   SDVTList VTs = DAG.getVTList(ValueVTs);
8663 
8664   auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
8665 
8666   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8667   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8668          "Unexpected target EVL type");
8669 
8670   // Request operands.
8671   SmallVector<SDValue, 7> OpValues;
8672   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
8673     auto Op = getValue(VPIntrin.getArgOperand(I));
8674     if (I == EVLParamPos)
8675       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
8676     OpValues.push_back(Op);
8677   }
8678 
8679   switch (Opcode) {
8680   default: {
8681     SDNodeFlags SDFlags;
8682     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8683       SDFlags.copyFMF(*FPMO);
8684     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
8685     setValue(&VPIntrin, Result);
8686     break;
8687   }
8688   case ISD::VP_LOAD:
8689     visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
8690     break;
8691   case ISD::VP_GATHER:
8692     visitVPGather(VPIntrin, ValueVTs[0], OpValues);
8693     break;
8694   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
8695     visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
8696     break;
8697   case ISD::VP_STORE:
8698     visitVPStore(VPIntrin, OpValues);
8699     break;
8700   case ISD::VP_SCATTER:
8701     visitVPScatter(VPIntrin, OpValues);
8702     break;
8703   case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
8704     visitVPStridedStore(VPIntrin, OpValues);
8705     break;
8706   case ISD::VP_FMULADD: {
8707     assert(OpValues.size() == 5 && "Unexpected number of operands");
8708     SDNodeFlags SDFlags;
8709     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8710       SDFlags.copyFMF(*FPMO);
8711     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
8712         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) {
8713       setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags));
8714     } else {
8715       SDValue Mul = DAG.getNode(
8716           ISD::VP_FMUL, DL, VTs,
8717           {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags);
8718       SDValue Add =
8719           DAG.getNode(ISD::VP_FADD, DL, VTs,
8720                       {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags);
8721       setValue(&VPIntrin, Add);
8722     }
8723     break;
8724   }
8725   case ISD::VP_IS_FPCLASS: {
8726     const DataLayout DLayout = DAG.getDataLayout();
8727     EVT DestVT = TLI.getValueType(DLayout, VPIntrin.getType());
8728     auto Constant = OpValues[1]->getAsZExtVal();
8729     SDValue Check = DAG.getTargetConstant(Constant, DL, MVT::i32);
8730     SDValue V = DAG.getNode(ISD::VP_IS_FPCLASS, DL, DestVT,
8731                             {OpValues[0], Check, OpValues[2], OpValues[3]});
8732     setValue(&VPIntrin, V);
8733     return;
8734   }
8735   case ISD::VP_INTTOPTR: {
8736     SDValue N = OpValues[0];
8737     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType());
8738     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType());
8739     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8740                                OpValues[2]);
8741     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8742                              OpValues[2]);
8743     setValue(&VPIntrin, N);
8744     break;
8745   }
8746   case ISD::VP_PTRTOINT: {
8747     SDValue N = OpValues[0];
8748     EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8749                                                           VPIntrin.getType());
8750     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(),
8751                                        VPIntrin.getOperand(0)->getType());
8752     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8753                                OpValues[2]);
8754     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8755                              OpValues[2]);
8756     setValue(&VPIntrin, N);
8757     break;
8758   }
8759   case ISD::VP_ABS:
8760   case ISD::VP_CTLZ:
8761   case ISD::VP_CTLZ_ZERO_UNDEF:
8762   case ISD::VP_CTTZ:
8763   case ISD::VP_CTTZ_ZERO_UNDEF:
8764   case ISD::VP_CTTZ_ELTS_ZERO_UNDEF:
8765   case ISD::VP_CTTZ_ELTS: {
8766     SDValue Result =
8767         DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]});
8768     setValue(&VPIntrin, Result);
8769     break;
8770   }
8771   }
8772 }
8773 
8774 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
8775                                           const BasicBlock *EHPadBB,
8776                                           MCSymbol *&BeginLabel) {
8777   MachineFunction &MF = DAG.getMachineFunction();
8778 
8779   // Insert a label before the invoke call to mark the try range.  This can be
8780   // used to detect deletion of the invoke via the MachineModuleInfo.
8781   BeginLabel = MF.getContext().createTempSymbol();
8782 
8783   // For SjLj, keep track of which landing pads go with which invokes
8784   // so as to maintain the ordering of pads in the LSDA.
8785   unsigned CallSiteIndex = FuncInfo.getCurrentCallSite();
8786   if (CallSiteIndex) {
8787     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
8788     LPadToCallSiteMap[FuncInfo.getMBB(EHPadBB)].push_back(CallSiteIndex);
8789 
8790     // Now that the call site is handled, stop tracking it.
8791     FuncInfo.setCurrentCallSite(0);
8792   }
8793 
8794   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
8795 }
8796 
8797 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
8798                                         const BasicBlock *EHPadBB,
8799                                         MCSymbol *BeginLabel) {
8800   assert(BeginLabel && "BeginLabel should've been set");
8801 
8802   MachineFunction &MF = DAG.getMachineFunction();
8803 
8804   // Insert a label at the end of the invoke call to mark the try range.  This
8805   // can be used to detect deletion of the invoke via the MachineModuleInfo.
8806   MCSymbol *EndLabel = MF.getContext().createTempSymbol();
8807   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
8808 
8809   // Inform MachineModuleInfo of range.
8810   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
8811   // There is a platform (e.g. wasm) that uses funclet style IR but does not
8812   // actually use outlined funclets and their LSDA info style.
8813   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
8814     assert(II && "II should've been set");
8815     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
8816     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
8817   } else if (!isScopedEHPersonality(Pers)) {
8818     assert(EHPadBB);
8819     MF.addInvoke(FuncInfo.getMBB(EHPadBB), BeginLabel, EndLabel);
8820   }
8821 
8822   return Chain;
8823 }
8824 
8825 std::pair<SDValue, SDValue>
8826 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
8827                                     const BasicBlock *EHPadBB) {
8828   MCSymbol *BeginLabel = nullptr;
8829 
8830   if (EHPadBB) {
8831     // Both PendingLoads and PendingExports must be flushed here;
8832     // this call might not return.
8833     (void)getRoot();
8834     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
8835     CLI.setChain(getRoot());
8836   }
8837 
8838   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8839   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
8840 
8841   assert((CLI.IsTailCall || Result.second.getNode()) &&
8842          "Non-null chain expected with non-tail call!");
8843   assert((Result.second.getNode() || !Result.first.getNode()) &&
8844          "Null value expected with tail call!");
8845 
8846   if (!Result.second.getNode()) {
8847     // As a special case, a null chain means that a tail call has been emitted
8848     // and the DAG root is already updated.
8849     HasTailCall = true;
8850 
8851     // Since there's no actual continuation from this block, nothing can be
8852     // relying on us setting vregs for them.
8853     PendingExports.clear();
8854   } else {
8855     DAG.setRoot(Result.second);
8856   }
8857 
8858   if (EHPadBB) {
8859     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
8860                            BeginLabel));
8861     Result.second = getRoot();
8862   }
8863 
8864   return Result;
8865 }
8866 
8867 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
8868                                       bool isTailCall, bool isMustTailCall,
8869                                       const BasicBlock *EHPadBB,
8870                                       const TargetLowering::PtrAuthInfo *PAI) {
8871   auto &DL = DAG.getDataLayout();
8872   FunctionType *FTy = CB.getFunctionType();
8873   Type *RetTy = CB.getType();
8874 
8875   TargetLowering::ArgListTy Args;
8876   Args.reserve(CB.arg_size());
8877 
8878   const Value *SwiftErrorVal = nullptr;
8879   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8880 
8881   if (isTailCall) {
8882     // Avoid emitting tail calls in functions with the disable-tail-calls
8883     // attribute.
8884     auto *Caller = CB.getParent()->getParent();
8885     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
8886         "true" && !isMustTailCall)
8887       isTailCall = false;
8888 
8889     // We can't tail call inside a function with a swifterror argument. Lowering
8890     // does not support this yet. It would have to move into the swifterror
8891     // register before the call.
8892     if (TLI.supportSwiftError() &&
8893         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
8894       isTailCall = false;
8895   }
8896 
8897   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
8898     TargetLowering::ArgListEntry Entry;
8899     const Value *V = *I;
8900 
8901     // Skip empty types
8902     if (V->getType()->isEmptyTy())
8903       continue;
8904 
8905     SDValue ArgNode = getValue(V);
8906     Entry.Node = ArgNode; Entry.Ty = V->getType();
8907 
8908     Entry.setAttributes(&CB, I - CB.arg_begin());
8909 
8910     // Use swifterror virtual register as input to the call.
8911     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
8912       SwiftErrorVal = V;
8913       // We find the virtual register for the actual swifterror argument.
8914       // Instead of using the Value, we use the virtual register instead.
8915       Entry.Node =
8916           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
8917                           EVT(TLI.getPointerTy(DL)));
8918     }
8919 
8920     Args.push_back(Entry);
8921 
8922     // If we have an explicit sret argument that is an Instruction, (i.e., it
8923     // might point to function-local memory), we can't meaningfully tail-call.
8924     if (Entry.IsSRet && isa<Instruction>(V))
8925       isTailCall = false;
8926   }
8927 
8928   // If call site has a cfguardtarget operand bundle, create and add an
8929   // additional ArgListEntry.
8930   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
8931     TargetLowering::ArgListEntry Entry;
8932     Value *V = Bundle->Inputs[0];
8933     SDValue ArgNode = getValue(V);
8934     Entry.Node = ArgNode;
8935     Entry.Ty = V->getType();
8936     Entry.IsCFGuardTarget = true;
8937     Args.push_back(Entry);
8938   }
8939 
8940   // Check if target-independent constraints permit a tail call here.
8941   // Target-dependent constraints are checked within TLI->LowerCallTo.
8942   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
8943     isTailCall = false;
8944 
8945   // Disable tail calls if there is an swifterror argument. Targets have not
8946   // been updated to support tail calls.
8947   if (TLI.supportSwiftError() && SwiftErrorVal)
8948     isTailCall = false;
8949 
8950   ConstantInt *CFIType = nullptr;
8951   if (CB.isIndirectCall()) {
8952     if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
8953       if (!TLI.supportKCFIBundles())
8954         report_fatal_error(
8955             "Target doesn't support calls with kcfi operand bundles.");
8956       CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
8957       assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
8958     }
8959   }
8960 
8961   SDValue ConvControlToken;
8962   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_convergencectrl)) {
8963     auto *Token = Bundle->Inputs[0].get();
8964     ConvControlToken = getValue(Token);
8965   }
8966 
8967   TargetLowering::CallLoweringInfo CLI(DAG);
8968   CLI.setDebugLoc(getCurSDLoc())
8969       .setChain(getRoot())
8970       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
8971       .setTailCall(isTailCall)
8972       .setConvergent(CB.isConvergent())
8973       .setIsPreallocated(
8974           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
8975       .setCFIType(CFIType)
8976       .setConvergenceControlToken(ConvControlToken);
8977 
8978   // Set the pointer authentication info if we have it.
8979   if (PAI) {
8980     if (!TLI.supportPtrAuthBundles())
8981       report_fatal_error(
8982           "This target doesn't support calls with ptrauth operand bundles.");
8983     CLI.setPtrAuth(*PAI);
8984   }
8985 
8986   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8987 
8988   if (Result.first.getNode()) {
8989     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
8990     setValue(&CB, Result.first);
8991   }
8992 
8993   // The last element of CLI.InVals has the SDValue for swifterror return.
8994   // Here we copy it to a virtual register and update SwiftErrorMap for
8995   // book-keeping.
8996   if (SwiftErrorVal && TLI.supportSwiftError()) {
8997     // Get the last element of InVals.
8998     SDValue Src = CLI.InVals.back();
8999     Register VReg =
9000         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
9001     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
9002     DAG.setRoot(CopyNode);
9003   }
9004 }
9005 
9006 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
9007                              SelectionDAGBuilder &Builder) {
9008   // Check to see if this load can be trivially constant folded, e.g. if the
9009   // input is from a string literal.
9010   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
9011     // Cast pointer to the type we really want to load.
9012     Type *LoadTy =
9013         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
9014     if (LoadVT.isVector())
9015       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
9016 
9017     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
9018                                          PointerType::getUnqual(LoadTy));
9019 
9020     if (const Constant *LoadCst =
9021             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
9022                                          LoadTy, Builder.DAG.getDataLayout()))
9023       return Builder.getValue(LoadCst);
9024   }
9025 
9026   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
9027   // still constant memory, the input chain can be the entry node.
9028   SDValue Root;
9029   bool ConstantMemory = false;
9030 
9031   // Do not serialize (non-volatile) loads of constant memory with anything.
9032   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
9033     Root = Builder.DAG.getEntryNode();
9034     ConstantMemory = true;
9035   } else {
9036     // Do not serialize non-volatile loads against each other.
9037     Root = Builder.DAG.getRoot();
9038   }
9039 
9040   SDValue Ptr = Builder.getValue(PtrVal);
9041   SDValue LoadVal =
9042       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
9043                           MachinePointerInfo(PtrVal), Align(1));
9044 
9045   if (!ConstantMemory)
9046     Builder.PendingLoads.push_back(LoadVal.getValue(1));
9047   return LoadVal;
9048 }
9049 
9050 /// Record the value for an instruction that produces an integer result,
9051 /// converting the type where necessary.
9052 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
9053                                                   SDValue Value,
9054                                                   bool IsSigned) {
9055   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
9056                                                     I.getType(), true);
9057   Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT);
9058   setValue(&I, Value);
9059 }
9060 
9061 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
9062 /// true and lower it. Otherwise return false, and it will be lowered like a
9063 /// normal call.
9064 /// The caller already checked that \p I calls the appropriate LibFunc with a
9065 /// correct prototype.
9066 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
9067   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
9068   const Value *Size = I.getArgOperand(2);
9069   const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
9070   if (CSize && CSize->getZExtValue() == 0) {
9071     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
9072                                                           I.getType(), true);
9073     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
9074     return true;
9075   }
9076 
9077   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9078   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
9079       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
9080       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
9081   if (Res.first.getNode()) {
9082     processIntegerCallValue(I, Res.first, true);
9083     PendingLoads.push_back(Res.second);
9084     return true;
9085   }
9086 
9087   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
9088   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
9089   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
9090     return false;
9091 
9092   // If the target has a fast compare for the given size, it will return a
9093   // preferred load type for that size. Require that the load VT is legal and
9094   // that the target supports unaligned loads of that type. Otherwise, return
9095   // INVALID.
9096   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
9097     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9098     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
9099     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
9100       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
9101       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
9102       // TODO: Check alignment of src and dest ptrs.
9103       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
9104       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
9105       if (!TLI.isTypeLegal(LVT) ||
9106           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
9107           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
9108         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
9109     }
9110 
9111     return LVT;
9112   };
9113 
9114   // This turns into unaligned loads. We only do this if the target natively
9115   // supports the MVT we'll be loading or if it is small enough (<= 4) that
9116   // we'll only produce a small number of byte loads.
9117   MVT LoadVT;
9118   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
9119   switch (NumBitsToCompare) {
9120   default:
9121     return false;
9122   case 16:
9123     LoadVT = MVT::i16;
9124     break;
9125   case 32:
9126     LoadVT = MVT::i32;
9127     break;
9128   case 64:
9129   case 128:
9130   case 256:
9131     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
9132     break;
9133   }
9134 
9135   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
9136     return false;
9137 
9138   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
9139   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
9140 
9141   // Bitcast to a wide integer type if the loads are vectors.
9142   if (LoadVT.isVector()) {
9143     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
9144     LoadL = DAG.getBitcast(CmpVT, LoadL);
9145     LoadR = DAG.getBitcast(CmpVT, LoadR);
9146   }
9147 
9148   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
9149   processIntegerCallValue(I, Cmp, false);
9150   return true;
9151 }
9152 
9153 /// See if we can lower a memchr call into an optimized form. If so, return
9154 /// true and lower it. Otherwise return false, and it will be lowered like a
9155 /// normal call.
9156 /// The caller already checked that \p I calls the appropriate LibFunc with a
9157 /// correct prototype.
9158 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
9159   const Value *Src = I.getArgOperand(0);
9160   const Value *Char = I.getArgOperand(1);
9161   const Value *Length = I.getArgOperand(2);
9162 
9163   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9164   std::pair<SDValue, SDValue> Res =
9165     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
9166                                 getValue(Src), getValue(Char), getValue(Length),
9167                                 MachinePointerInfo(Src));
9168   if (Res.first.getNode()) {
9169     setValue(&I, Res.first);
9170     PendingLoads.push_back(Res.second);
9171     return true;
9172   }
9173 
9174   return false;
9175 }
9176 
9177 /// See if we can lower a mempcpy call into an optimized form. If so, return
9178 /// true and lower it. Otherwise return false, and it will be lowered like a
9179 /// normal call.
9180 /// The caller already checked that \p I calls the appropriate LibFunc with a
9181 /// correct prototype.
9182 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
9183   SDValue Dst = getValue(I.getArgOperand(0));
9184   SDValue Src = getValue(I.getArgOperand(1));
9185   SDValue Size = getValue(I.getArgOperand(2));
9186 
9187   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
9188   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
9189   // DAG::getMemcpy needs Alignment to be defined.
9190   Align Alignment = std::min(DstAlign, SrcAlign);
9191 
9192   SDLoc sdl = getCurSDLoc();
9193 
9194   // In the mempcpy context we need to pass in a false value for isTailCall
9195   // because the return pointer needs to be adjusted by the size of
9196   // the copied memory.
9197   SDValue Root = getMemoryRoot();
9198   SDValue MC = DAG.getMemcpy(
9199       Root, sdl, Dst, Src, Size, Alignment, false, false, /*CI=*/nullptr,
9200       std::nullopt, MachinePointerInfo(I.getArgOperand(0)),
9201       MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata());
9202   assert(MC.getNode() != nullptr &&
9203          "** memcpy should not be lowered as TailCall in mempcpy context **");
9204   DAG.setRoot(MC);
9205 
9206   // Check if Size needs to be truncated or extended.
9207   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
9208 
9209   // Adjust return pointer to point just past the last dst byte.
9210   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
9211                                     Dst, Size);
9212   setValue(&I, DstPlusSize);
9213   return true;
9214 }
9215 
9216 /// See if we can lower a strcpy call into an optimized form.  If so, return
9217 /// true and lower it, otherwise return false and it will be lowered like a
9218 /// normal call.
9219 /// The caller already checked that \p I calls the appropriate LibFunc with a
9220 /// correct prototype.
9221 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
9222   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9223 
9224   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9225   std::pair<SDValue, SDValue> Res =
9226     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
9227                                 getValue(Arg0), getValue(Arg1),
9228                                 MachinePointerInfo(Arg0),
9229                                 MachinePointerInfo(Arg1), isStpcpy);
9230   if (Res.first.getNode()) {
9231     setValue(&I, Res.first);
9232     DAG.setRoot(Res.second);
9233     return true;
9234   }
9235 
9236   return false;
9237 }
9238 
9239 /// See if we can lower a strcmp call into an optimized form.  If so, return
9240 /// true and lower it, otherwise return false and it will be lowered like a
9241 /// normal call.
9242 /// The caller already checked that \p I calls the appropriate LibFunc with a
9243 /// correct prototype.
9244 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
9245   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9246 
9247   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9248   std::pair<SDValue, SDValue> Res =
9249     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
9250                                 getValue(Arg0), getValue(Arg1),
9251                                 MachinePointerInfo(Arg0),
9252                                 MachinePointerInfo(Arg1));
9253   if (Res.first.getNode()) {
9254     processIntegerCallValue(I, Res.first, true);
9255     PendingLoads.push_back(Res.second);
9256     return true;
9257   }
9258 
9259   return false;
9260 }
9261 
9262 /// See if we can lower a strlen call into an optimized form.  If so, return
9263 /// true and lower it, otherwise return false and it will be lowered like a
9264 /// normal call.
9265 /// The caller already checked that \p I calls the appropriate LibFunc with a
9266 /// correct prototype.
9267 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
9268   const Value *Arg0 = I.getArgOperand(0);
9269 
9270   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9271   std::pair<SDValue, SDValue> Res =
9272     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
9273                                 getValue(Arg0), MachinePointerInfo(Arg0));
9274   if (Res.first.getNode()) {
9275     processIntegerCallValue(I, Res.first, false);
9276     PendingLoads.push_back(Res.second);
9277     return true;
9278   }
9279 
9280   return false;
9281 }
9282 
9283 /// See if we can lower a strnlen call into an optimized form.  If so, return
9284 /// true and lower it, otherwise return false and it will be lowered like a
9285 /// normal call.
9286 /// The caller already checked that \p I calls the appropriate LibFunc with a
9287 /// correct prototype.
9288 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
9289   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9290 
9291   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9292   std::pair<SDValue, SDValue> Res =
9293     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
9294                                  getValue(Arg0), getValue(Arg1),
9295                                  MachinePointerInfo(Arg0));
9296   if (Res.first.getNode()) {
9297     processIntegerCallValue(I, Res.first, false);
9298     PendingLoads.push_back(Res.second);
9299     return true;
9300   }
9301 
9302   return false;
9303 }
9304 
9305 /// See if we can lower a unary floating-point operation into an SDNode with
9306 /// the specified Opcode.  If so, return true and lower it, otherwise return
9307 /// false and it will be lowered like a normal call.
9308 /// The caller already checked that \p I calls the appropriate LibFunc with a
9309 /// correct prototype.
9310 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
9311                                               unsigned Opcode) {
9312   // We already checked this call's prototype; verify it doesn't modify errno.
9313   if (!I.onlyReadsMemory())
9314     return false;
9315 
9316   SDNodeFlags Flags;
9317   Flags.copyFMF(cast<FPMathOperator>(I));
9318 
9319   SDValue Tmp = getValue(I.getArgOperand(0));
9320   setValue(&I,
9321            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
9322   return true;
9323 }
9324 
9325 /// See if we can lower a binary floating-point operation into an SDNode with
9326 /// the specified Opcode. If so, return true and lower it. Otherwise return
9327 /// false, and it will be lowered like a normal call.
9328 /// The caller already checked that \p I calls the appropriate LibFunc with a
9329 /// correct prototype.
9330 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
9331                                                unsigned Opcode) {
9332   // We already checked this call's prototype; verify it doesn't modify errno.
9333   if (!I.onlyReadsMemory())
9334     return false;
9335 
9336   SDNodeFlags Flags;
9337   Flags.copyFMF(cast<FPMathOperator>(I));
9338 
9339   SDValue Tmp0 = getValue(I.getArgOperand(0));
9340   SDValue Tmp1 = getValue(I.getArgOperand(1));
9341   EVT VT = Tmp0.getValueType();
9342   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
9343   return true;
9344 }
9345 
9346 void SelectionDAGBuilder::visitCall(const CallInst &I) {
9347   // Handle inline assembly differently.
9348   if (I.isInlineAsm()) {
9349     visitInlineAsm(I);
9350     return;
9351   }
9352 
9353   diagnoseDontCall(I);
9354 
9355   if (Function *F = I.getCalledFunction()) {
9356     if (F->isDeclaration()) {
9357       // Is this an LLVM intrinsic or a target-specific intrinsic?
9358       unsigned IID = F->getIntrinsicID();
9359       if (!IID)
9360         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
9361           IID = II->getIntrinsicID(F);
9362 
9363       if (IID) {
9364         visitIntrinsicCall(I, IID);
9365         return;
9366       }
9367     }
9368 
9369     // Check for well-known libc/libm calls.  If the function is internal, it
9370     // can't be a library call.  Don't do the check if marked as nobuiltin for
9371     // some reason or the call site requires strict floating point semantics.
9372     LibFunc Func;
9373     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
9374         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
9375         LibInfo->hasOptimizedCodeGen(Func)) {
9376       switch (Func) {
9377       default: break;
9378       case LibFunc_bcmp:
9379         if (visitMemCmpBCmpCall(I))
9380           return;
9381         break;
9382       case LibFunc_copysign:
9383       case LibFunc_copysignf:
9384       case LibFunc_copysignl:
9385         // We already checked this call's prototype; verify it doesn't modify
9386         // errno.
9387         if (I.onlyReadsMemory()) {
9388           SDValue LHS = getValue(I.getArgOperand(0));
9389           SDValue RHS = getValue(I.getArgOperand(1));
9390           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
9391                                    LHS.getValueType(), LHS, RHS));
9392           return;
9393         }
9394         break;
9395       case LibFunc_fabs:
9396       case LibFunc_fabsf:
9397       case LibFunc_fabsl:
9398         if (visitUnaryFloatCall(I, ISD::FABS))
9399           return;
9400         break;
9401       case LibFunc_fmin:
9402       case LibFunc_fminf:
9403       case LibFunc_fminl:
9404         if (visitBinaryFloatCall(I, ISD::FMINNUM))
9405           return;
9406         break;
9407       case LibFunc_fmax:
9408       case LibFunc_fmaxf:
9409       case LibFunc_fmaxl:
9410         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
9411           return;
9412         break;
9413       case LibFunc_fminimum_num:
9414       case LibFunc_fminimum_numf:
9415       case LibFunc_fminimum_numl:
9416         if (visitBinaryFloatCall(I, ISD::FMINIMUMNUM))
9417           return;
9418         break;
9419       case LibFunc_fmaximum_num:
9420       case LibFunc_fmaximum_numf:
9421       case LibFunc_fmaximum_numl:
9422         if (visitBinaryFloatCall(I, ISD::FMAXIMUMNUM))
9423           return;
9424         break;
9425       case LibFunc_sin:
9426       case LibFunc_sinf:
9427       case LibFunc_sinl:
9428         if (visitUnaryFloatCall(I, ISD::FSIN))
9429           return;
9430         break;
9431       case LibFunc_cos:
9432       case LibFunc_cosf:
9433       case LibFunc_cosl:
9434         if (visitUnaryFloatCall(I, ISD::FCOS))
9435           return;
9436         break;
9437       case LibFunc_tan:
9438       case LibFunc_tanf:
9439       case LibFunc_tanl:
9440         if (visitUnaryFloatCall(I, ISD::FTAN))
9441           return;
9442         break;
9443       case LibFunc_asin:
9444       case LibFunc_asinf:
9445       case LibFunc_asinl:
9446         if (visitUnaryFloatCall(I, ISD::FASIN))
9447           return;
9448         break;
9449       case LibFunc_acos:
9450       case LibFunc_acosf:
9451       case LibFunc_acosl:
9452         if (visitUnaryFloatCall(I, ISD::FACOS))
9453           return;
9454         break;
9455       case LibFunc_atan:
9456       case LibFunc_atanf:
9457       case LibFunc_atanl:
9458         if (visitUnaryFloatCall(I, ISD::FATAN))
9459           return;
9460         break;
9461       case LibFunc_atan2:
9462       case LibFunc_atan2f:
9463       case LibFunc_atan2l:
9464         if (visitBinaryFloatCall(I, ISD::FATAN2))
9465           return;
9466         break;
9467       case LibFunc_sinh:
9468       case LibFunc_sinhf:
9469       case LibFunc_sinhl:
9470         if (visitUnaryFloatCall(I, ISD::FSINH))
9471           return;
9472         break;
9473       case LibFunc_cosh:
9474       case LibFunc_coshf:
9475       case LibFunc_coshl:
9476         if (visitUnaryFloatCall(I, ISD::FCOSH))
9477           return;
9478         break;
9479       case LibFunc_tanh:
9480       case LibFunc_tanhf:
9481       case LibFunc_tanhl:
9482         if (visitUnaryFloatCall(I, ISD::FTANH))
9483           return;
9484         break;
9485       case LibFunc_sqrt:
9486       case LibFunc_sqrtf:
9487       case LibFunc_sqrtl:
9488       case LibFunc_sqrt_finite:
9489       case LibFunc_sqrtf_finite:
9490       case LibFunc_sqrtl_finite:
9491         if (visitUnaryFloatCall(I, ISD::FSQRT))
9492           return;
9493         break;
9494       case LibFunc_floor:
9495       case LibFunc_floorf:
9496       case LibFunc_floorl:
9497         if (visitUnaryFloatCall(I, ISD::FFLOOR))
9498           return;
9499         break;
9500       case LibFunc_nearbyint:
9501       case LibFunc_nearbyintf:
9502       case LibFunc_nearbyintl:
9503         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
9504           return;
9505         break;
9506       case LibFunc_ceil:
9507       case LibFunc_ceilf:
9508       case LibFunc_ceill:
9509         if (visitUnaryFloatCall(I, ISD::FCEIL))
9510           return;
9511         break;
9512       case LibFunc_rint:
9513       case LibFunc_rintf:
9514       case LibFunc_rintl:
9515         if (visitUnaryFloatCall(I, ISD::FRINT))
9516           return;
9517         break;
9518       case LibFunc_round:
9519       case LibFunc_roundf:
9520       case LibFunc_roundl:
9521         if (visitUnaryFloatCall(I, ISD::FROUND))
9522           return;
9523         break;
9524       case LibFunc_trunc:
9525       case LibFunc_truncf:
9526       case LibFunc_truncl:
9527         if (visitUnaryFloatCall(I, ISD::FTRUNC))
9528           return;
9529         break;
9530       case LibFunc_log2:
9531       case LibFunc_log2f:
9532       case LibFunc_log2l:
9533         if (visitUnaryFloatCall(I, ISD::FLOG2))
9534           return;
9535         break;
9536       case LibFunc_exp2:
9537       case LibFunc_exp2f:
9538       case LibFunc_exp2l:
9539         if (visitUnaryFloatCall(I, ISD::FEXP2))
9540           return;
9541         break;
9542       case LibFunc_exp10:
9543       case LibFunc_exp10f:
9544       case LibFunc_exp10l:
9545         if (visitUnaryFloatCall(I, ISD::FEXP10))
9546           return;
9547         break;
9548       case LibFunc_ldexp:
9549       case LibFunc_ldexpf:
9550       case LibFunc_ldexpl:
9551         if (visitBinaryFloatCall(I, ISD::FLDEXP))
9552           return;
9553         break;
9554       case LibFunc_memcmp:
9555         if (visitMemCmpBCmpCall(I))
9556           return;
9557         break;
9558       case LibFunc_mempcpy:
9559         if (visitMemPCpyCall(I))
9560           return;
9561         break;
9562       case LibFunc_memchr:
9563         if (visitMemChrCall(I))
9564           return;
9565         break;
9566       case LibFunc_strcpy:
9567         if (visitStrCpyCall(I, false))
9568           return;
9569         break;
9570       case LibFunc_stpcpy:
9571         if (visitStrCpyCall(I, true))
9572           return;
9573         break;
9574       case LibFunc_strcmp:
9575         if (visitStrCmpCall(I))
9576           return;
9577         break;
9578       case LibFunc_strlen:
9579         if (visitStrLenCall(I))
9580           return;
9581         break;
9582       case LibFunc_strnlen:
9583         if (visitStrNLenCall(I))
9584           return;
9585         break;
9586       }
9587     }
9588   }
9589 
9590   if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
9591     LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), /*EHPadBB=*/nullptr);
9592     return;
9593   }
9594 
9595   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
9596   // have to do anything here to lower funclet bundles.
9597   // CFGuardTarget bundles are lowered in LowerCallTo.
9598   assert(!I.hasOperandBundlesOtherThan(
9599              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
9600               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
9601               LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi,
9602               LLVMContext::OB_convergencectrl}) &&
9603          "Cannot lower calls with arbitrary operand bundles!");
9604 
9605   SDValue Callee = getValue(I.getCalledOperand());
9606 
9607   if (I.hasDeoptState())
9608     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
9609   else
9610     // Check if we can potentially perform a tail call. More detailed checking
9611     // is be done within LowerCallTo, after more information about the call is
9612     // known.
9613     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
9614 }
9615 
9616 void SelectionDAGBuilder::LowerCallSiteWithPtrAuthBundle(
9617     const CallBase &CB, const BasicBlock *EHPadBB) {
9618   auto PAB = CB.getOperandBundle("ptrauth");
9619   const Value *CalleeV = CB.getCalledOperand();
9620 
9621   // Gather the call ptrauth data from the operand bundle:
9622   //   [ i32 <key>, i64 <discriminator> ]
9623   const auto *Key = cast<ConstantInt>(PAB->Inputs[0]);
9624   const Value *Discriminator = PAB->Inputs[1];
9625 
9626   assert(Key->getType()->isIntegerTy(32) && "Invalid ptrauth key");
9627   assert(Discriminator->getType()->isIntegerTy(64) &&
9628          "Invalid ptrauth discriminator");
9629 
9630   // Look through ptrauth constants to find the raw callee.
9631   // Do a direct unauthenticated call if we found it and everything matches.
9632   if (const auto *CalleeCPA = dyn_cast<ConstantPtrAuth>(CalleeV))
9633     if (CalleeCPA->isKnownCompatibleWith(Key, Discriminator,
9634                                          DAG.getDataLayout()))
9635       return LowerCallTo(CB, getValue(CalleeCPA->getPointer()), CB.isTailCall(),
9636                          CB.isMustTailCall(), EHPadBB);
9637 
9638   // Functions should never be ptrauth-called directly.
9639   assert(!isa<Function>(CalleeV) && "invalid direct ptrauth call");
9640 
9641   // Otherwise, do an authenticated indirect call.
9642   TargetLowering::PtrAuthInfo PAI = {Key->getZExtValue(),
9643                                      getValue(Discriminator)};
9644 
9645   LowerCallTo(CB, getValue(CalleeV), CB.isTailCall(), CB.isMustTailCall(),
9646               EHPadBB, &PAI);
9647 }
9648 
9649 namespace {
9650 
9651 /// AsmOperandInfo - This contains information for each constraint that we are
9652 /// lowering.
9653 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
9654 public:
9655   /// CallOperand - If this is the result output operand or a clobber
9656   /// this is null, otherwise it is the incoming operand to the CallInst.
9657   /// This gets modified as the asm is processed.
9658   SDValue CallOperand;
9659 
9660   /// AssignedRegs - If this is a register or register class operand, this
9661   /// contains the set of register corresponding to the operand.
9662   RegsForValue AssignedRegs;
9663 
9664   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
9665     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
9666   }
9667 
9668   /// Whether or not this operand accesses memory
9669   bool hasMemory(const TargetLowering &TLI) const {
9670     // Indirect operand accesses access memory.
9671     if (isIndirect)
9672       return true;
9673 
9674     for (const auto &Code : Codes)
9675       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
9676         return true;
9677 
9678     return false;
9679   }
9680 };
9681 
9682 
9683 } // end anonymous namespace
9684 
9685 /// Make sure that the output operand \p OpInfo and its corresponding input
9686 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
9687 /// out).
9688 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
9689                                SDISelAsmOperandInfo &MatchingOpInfo,
9690                                SelectionDAG &DAG) {
9691   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
9692     return;
9693 
9694   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
9695   const auto &TLI = DAG.getTargetLoweringInfo();
9696 
9697   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
9698       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
9699                                        OpInfo.ConstraintVT);
9700   std::pair<unsigned, const TargetRegisterClass *> InputRC =
9701       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
9702                                        MatchingOpInfo.ConstraintVT);
9703   const bool OutOpIsIntOrFP =
9704       OpInfo.ConstraintVT.isInteger() || OpInfo.ConstraintVT.isFloatingPoint();
9705   const bool InOpIsIntOrFP = MatchingOpInfo.ConstraintVT.isInteger() ||
9706                              MatchingOpInfo.ConstraintVT.isFloatingPoint();
9707   if ((OutOpIsIntOrFP != InOpIsIntOrFP) || (MatchRC.second != InputRC.second)) {
9708     // FIXME: error out in a more elegant fashion
9709     report_fatal_error("Unsupported asm: input constraint"
9710                        " with a matching output constraint of"
9711                        " incompatible type!");
9712   }
9713   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
9714 }
9715 
9716 /// Get a direct memory input to behave well as an indirect operand.
9717 /// This may introduce stores, hence the need for a \p Chain.
9718 /// \return The (possibly updated) chain.
9719 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
9720                                         SDISelAsmOperandInfo &OpInfo,
9721                                         SelectionDAG &DAG) {
9722   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9723 
9724   // If we don't have an indirect input, put it in the constpool if we can,
9725   // otherwise spill it to a stack slot.
9726   // TODO: This isn't quite right. We need to handle these according to
9727   // the addressing mode that the constraint wants. Also, this may take
9728   // an additional register for the computation and we don't want that
9729   // either.
9730 
9731   // If the operand is a float, integer, or vector constant, spill to a
9732   // constant pool entry to get its address.
9733   const Value *OpVal = OpInfo.CallOperandVal;
9734   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
9735       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
9736     OpInfo.CallOperand = DAG.getConstantPool(
9737         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
9738     return Chain;
9739   }
9740 
9741   // Otherwise, create a stack slot and emit a store to it before the asm.
9742   Type *Ty = OpVal->getType();
9743   auto &DL = DAG.getDataLayout();
9744   TypeSize TySize = DL.getTypeAllocSize(Ty);
9745   MachineFunction &MF = DAG.getMachineFunction();
9746   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
9747   int StackID = 0;
9748   if (TySize.isScalable())
9749     StackID = TFI->getStackIDForScalableVectors();
9750   int SSFI = MF.getFrameInfo().CreateStackObject(TySize.getKnownMinValue(),
9751                                                  DL.getPrefTypeAlign(Ty), false,
9752                                                  nullptr, StackID);
9753   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
9754   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
9755                             MachinePointerInfo::getFixedStack(MF, SSFI),
9756                             TLI.getMemValueType(DL, Ty));
9757   OpInfo.CallOperand = StackSlot;
9758 
9759   return Chain;
9760 }
9761 
9762 /// GetRegistersForValue - Assign registers (virtual or physical) for the
9763 /// specified operand.  We prefer to assign virtual registers, to allow the
9764 /// register allocator to handle the assignment process.  However, if the asm
9765 /// uses features that we can't model on machineinstrs, we have SDISel do the
9766 /// allocation.  This produces generally horrible, but correct, code.
9767 ///
9768 ///   OpInfo describes the operand
9769 ///   RefOpInfo describes the matching operand if any, the operand otherwise
9770 static std::optional<unsigned>
9771 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
9772                      SDISelAsmOperandInfo &OpInfo,
9773                      SDISelAsmOperandInfo &RefOpInfo) {
9774   LLVMContext &Context = *DAG.getContext();
9775   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9776 
9777   MachineFunction &MF = DAG.getMachineFunction();
9778   SmallVector<Register, 4> Regs;
9779   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9780 
9781   // No work to do for memory/address operands.
9782   if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9783       OpInfo.ConstraintType == TargetLowering::C_Address)
9784     return std::nullopt;
9785 
9786   // If this is a constraint for a single physreg, or a constraint for a
9787   // register class, find it.
9788   unsigned AssignedReg;
9789   const TargetRegisterClass *RC;
9790   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
9791       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
9792   // RC is unset only on failure. Return immediately.
9793   if (!RC)
9794     return std::nullopt;
9795 
9796   // Get the actual register value type.  This is important, because the user
9797   // may have asked for (e.g.) the AX register in i32 type.  We need to
9798   // remember that AX is actually i16 to get the right extension.
9799   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
9800 
9801   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
9802     // If this is an FP operand in an integer register (or visa versa), or more
9803     // generally if the operand value disagrees with the register class we plan
9804     // to stick it in, fix the operand type.
9805     //
9806     // If this is an input value, the bitcast to the new type is done now.
9807     // Bitcast for output value is done at the end of visitInlineAsm().
9808     if ((OpInfo.Type == InlineAsm::isOutput ||
9809          OpInfo.Type == InlineAsm::isInput) &&
9810         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
9811       // Try to convert to the first EVT that the reg class contains.  If the
9812       // types are identical size, use a bitcast to convert (e.g. two differing
9813       // vector types).  Note: output bitcast is done at the end of
9814       // visitInlineAsm().
9815       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
9816         // Exclude indirect inputs while they are unsupported because the code
9817         // to perform the load is missing and thus OpInfo.CallOperand still
9818         // refers to the input address rather than the pointed-to value.
9819         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
9820           OpInfo.CallOperand =
9821               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
9822         OpInfo.ConstraintVT = RegVT;
9823         // If the operand is an FP value and we want it in integer registers,
9824         // use the corresponding integer type. This turns an f64 value into
9825         // i64, which can be passed with two i32 values on a 32-bit machine.
9826       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
9827         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
9828         if (OpInfo.Type == InlineAsm::isInput)
9829           OpInfo.CallOperand =
9830               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
9831         OpInfo.ConstraintVT = VT;
9832       }
9833     }
9834   }
9835 
9836   // No need to allocate a matching input constraint since the constraint it's
9837   // matching to has already been allocated.
9838   if (OpInfo.isMatchingInputConstraint())
9839     return std::nullopt;
9840 
9841   EVT ValueVT = OpInfo.ConstraintVT;
9842   if (OpInfo.ConstraintVT == MVT::Other)
9843     ValueVT = RegVT;
9844 
9845   // Initialize NumRegs.
9846   unsigned NumRegs = 1;
9847   if (OpInfo.ConstraintVT != MVT::Other)
9848     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
9849 
9850   // If this is a constraint for a specific physical register, like {r17},
9851   // assign it now.
9852 
9853   // If this associated to a specific register, initialize iterator to correct
9854   // place. If virtual, make sure we have enough registers
9855 
9856   // Initialize iterator if necessary
9857   TargetRegisterClass::iterator I = RC->begin();
9858   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9859 
9860   // Do not check for single registers.
9861   if (AssignedReg) {
9862     I = std::find(I, RC->end(), AssignedReg);
9863     if (I == RC->end()) {
9864       // RC does not contain the selected register, which indicates a
9865       // mismatch between the register and the required type/bitwidth.
9866       return {AssignedReg};
9867     }
9868   }
9869 
9870   for (; NumRegs; --NumRegs, ++I) {
9871     assert(I != RC->end() && "Ran out of registers to allocate!");
9872     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
9873     Regs.push_back(R);
9874   }
9875 
9876   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
9877   return std::nullopt;
9878 }
9879 
9880 static unsigned
9881 findMatchingInlineAsmOperand(unsigned OperandNo,
9882                              const std::vector<SDValue> &AsmNodeOperands) {
9883   // Scan until we find the definition we already emitted of this operand.
9884   unsigned CurOp = InlineAsm::Op_FirstOperand;
9885   for (; OperandNo; --OperandNo) {
9886     // Advance to the next operand.
9887     unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal();
9888     const InlineAsm::Flag F(OpFlag);
9889     assert(
9890         (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) &&
9891         "Skipped past definitions?");
9892     CurOp += F.getNumOperandRegisters() + 1;
9893   }
9894   return CurOp;
9895 }
9896 
9897 namespace {
9898 
9899 class ExtraFlags {
9900   unsigned Flags = 0;
9901 
9902 public:
9903   explicit ExtraFlags(const CallBase &Call) {
9904     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9905     if (IA->hasSideEffects())
9906       Flags |= InlineAsm::Extra_HasSideEffects;
9907     if (IA->isAlignStack())
9908       Flags |= InlineAsm::Extra_IsAlignStack;
9909     if (Call.isConvergent())
9910       Flags |= InlineAsm::Extra_IsConvergent;
9911     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
9912   }
9913 
9914   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
9915     // Ideally, we would only check against memory constraints.  However, the
9916     // meaning of an Other constraint can be target-specific and we can't easily
9917     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
9918     // for Other constraints as well.
9919     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9920         OpInfo.ConstraintType == TargetLowering::C_Other) {
9921       if (OpInfo.Type == InlineAsm::isInput)
9922         Flags |= InlineAsm::Extra_MayLoad;
9923       else if (OpInfo.Type == InlineAsm::isOutput)
9924         Flags |= InlineAsm::Extra_MayStore;
9925       else if (OpInfo.Type == InlineAsm::isClobber)
9926         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
9927     }
9928   }
9929 
9930   unsigned get() const { return Flags; }
9931 };
9932 
9933 } // end anonymous namespace
9934 
9935 static bool isFunction(SDValue Op) {
9936   if (Op && Op.getOpcode() == ISD::GlobalAddress) {
9937     if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
9938       auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
9939 
9940       // In normal "call dllimport func" instruction (non-inlineasm) it force
9941       // indirect access by specifing call opcode. And usually specially print
9942       // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
9943       // not do in this way now. (In fact, this is similar with "Data Access"
9944       // action). So here we ignore dllimport function.
9945       if (Fn && !Fn->hasDLLImportStorageClass())
9946         return true;
9947     }
9948   }
9949   return false;
9950 }
9951 
9952 /// visitInlineAsm - Handle a call to an InlineAsm object.
9953 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
9954                                          const BasicBlock *EHPadBB) {
9955   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9956 
9957   /// ConstraintOperands - Information about all of the constraints.
9958   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
9959 
9960   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9961   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
9962       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
9963 
9964   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
9965   // AsmDialect, MayLoad, MayStore).
9966   bool HasSideEffect = IA->hasSideEffects();
9967   ExtraFlags ExtraInfo(Call);
9968 
9969   for (auto &T : TargetConstraints) {
9970     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
9971     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
9972 
9973     if (OpInfo.CallOperandVal)
9974       OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
9975 
9976     if (!HasSideEffect)
9977       HasSideEffect = OpInfo.hasMemory(TLI);
9978 
9979     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
9980     // FIXME: Could we compute this on OpInfo rather than T?
9981 
9982     // Compute the constraint code and ConstraintType to use.
9983     TLI.ComputeConstraintToUse(T, SDValue());
9984 
9985     if (T.ConstraintType == TargetLowering::C_Immediate &&
9986         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
9987       // We've delayed emitting a diagnostic like the "n" constraint because
9988       // inlining could cause an integer showing up.
9989       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
9990                                           "' expects an integer constant "
9991                                           "expression");
9992 
9993     ExtraInfo.update(T);
9994   }
9995 
9996   // We won't need to flush pending loads if this asm doesn't touch
9997   // memory and is nonvolatile.
9998   SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
9999 
10000   bool EmitEHLabels = isa<InvokeInst>(Call);
10001   if (EmitEHLabels) {
10002     assert(EHPadBB && "InvokeInst must have an EHPadBB");
10003   }
10004   bool IsCallBr = isa<CallBrInst>(Call);
10005 
10006   if (IsCallBr || EmitEHLabels) {
10007     // If this is a callbr or invoke we need to flush pending exports since
10008     // inlineasm_br and invoke are terminators.
10009     // We need to do this before nodes are glued to the inlineasm_br node.
10010     Chain = getControlRoot();
10011   }
10012 
10013   MCSymbol *BeginLabel = nullptr;
10014   if (EmitEHLabels) {
10015     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
10016   }
10017 
10018   int OpNo = -1;
10019   SmallVector<StringRef> AsmStrs;
10020   IA->collectAsmStrs(AsmStrs);
10021 
10022   // Second pass over the constraints: compute which constraint option to use.
10023   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
10024     if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
10025       OpNo++;
10026 
10027     // If this is an output operand with a matching input operand, look up the
10028     // matching input. If their types mismatch, e.g. one is an integer, the
10029     // other is floating point, or their sizes are different, flag it as an
10030     // error.
10031     if (OpInfo.hasMatchingInput()) {
10032       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
10033       patchMatchingInput(OpInfo, Input, DAG);
10034     }
10035 
10036     // Compute the constraint code and ConstraintType to use.
10037     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
10038 
10039     if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
10040          OpInfo.Type == InlineAsm::isClobber) ||
10041         OpInfo.ConstraintType == TargetLowering::C_Address)
10042       continue;
10043 
10044     // In Linux PIC model, there are 4 cases about value/label addressing:
10045     //
10046     // 1: Function call or Label jmp inside the module.
10047     // 2: Data access (such as global variable, static variable) inside module.
10048     // 3: Function call or Label jmp outside the module.
10049     // 4: Data access (such as global variable) outside the module.
10050     //
10051     // Due to current llvm inline asm architecture designed to not "recognize"
10052     // the asm code, there are quite troubles for us to treat mem addressing
10053     // differently for same value/adress used in different instuctions.
10054     // For example, in pic model, call a func may in plt way or direclty
10055     // pc-related, but lea/mov a function adress may use got.
10056     //
10057     // Here we try to "recognize" function call for the case 1 and case 3 in
10058     // inline asm. And try to adjust the constraint for them.
10059     //
10060     // TODO: Due to current inline asm didn't encourage to jmp to the outsider
10061     // label, so here we don't handle jmp function label now, but we need to
10062     // enhance it (especilly in PIC model) if we meet meaningful requirements.
10063     if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
10064         TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
10065         TM.getCodeModel() != CodeModel::Large) {
10066       OpInfo.isIndirect = false;
10067       OpInfo.ConstraintType = TargetLowering::C_Address;
10068     }
10069 
10070     // If this is a memory input, and if the operand is not indirect, do what we
10071     // need to provide an address for the memory input.
10072     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
10073         !OpInfo.isIndirect) {
10074       assert((OpInfo.isMultipleAlternative ||
10075               (OpInfo.Type == InlineAsm::isInput)) &&
10076              "Can only indirectify direct input operands!");
10077 
10078       // Memory operands really want the address of the value.
10079       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
10080 
10081       // There is no longer a Value* corresponding to this operand.
10082       OpInfo.CallOperandVal = nullptr;
10083 
10084       // It is now an indirect operand.
10085       OpInfo.isIndirect = true;
10086     }
10087 
10088   }
10089 
10090   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
10091   std::vector<SDValue> AsmNodeOperands;
10092   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
10093   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
10094       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
10095 
10096   // If we have a !srcloc metadata node associated with it, we want to attach
10097   // this to the ultimately generated inline asm machineinstr.  To do this, we
10098   // pass in the third operand as this (potentially null) inline asm MDNode.
10099   const MDNode *SrcLoc = Call.getMetadata("srcloc");
10100   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
10101 
10102   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
10103   // bits as operand 3.
10104   AsmNodeOperands.push_back(DAG.getTargetConstant(
10105       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
10106 
10107   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
10108   // this, assign virtual and physical registers for inputs and otput.
10109   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
10110     // Assign Registers.
10111     SDISelAsmOperandInfo &RefOpInfo =
10112         OpInfo.isMatchingInputConstraint()
10113             ? ConstraintOperands[OpInfo.getMatchedOperand()]
10114             : OpInfo;
10115     const auto RegError =
10116         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
10117     if (RegError) {
10118       const MachineFunction &MF = DAG.getMachineFunction();
10119       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
10120       const char *RegName = TRI.getName(*RegError);
10121       emitInlineAsmError(Call, "register '" + Twine(RegName) +
10122                                    "' allocated for constraint '" +
10123                                    Twine(OpInfo.ConstraintCode) +
10124                                    "' does not match required type");
10125       return;
10126     }
10127 
10128     auto DetectWriteToReservedRegister = [&]() {
10129       const MachineFunction &MF = DAG.getMachineFunction();
10130       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
10131       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
10132         if (Register::isPhysicalRegister(Reg) &&
10133             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
10134           const char *RegName = TRI.getName(Reg);
10135           emitInlineAsmError(Call, "write to reserved register '" +
10136                                        Twine(RegName) + "'");
10137           return true;
10138         }
10139       }
10140       return false;
10141     };
10142     assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
10143             (OpInfo.Type == InlineAsm::isInput &&
10144              !OpInfo.isMatchingInputConstraint())) &&
10145            "Only address as input operand is allowed.");
10146 
10147     switch (OpInfo.Type) {
10148     case InlineAsm::isOutput:
10149       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10150         const InlineAsm::ConstraintCode ConstraintID =
10151             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10152         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10153                "Failed to convert memory constraint code to constraint id.");
10154 
10155         // Add information to the INLINEASM node to know about this output.
10156         InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1);
10157         OpFlags.setMemConstraint(ConstraintID);
10158         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
10159                                                         MVT::i32));
10160         AsmNodeOperands.push_back(OpInfo.CallOperand);
10161       } else {
10162         // Otherwise, this outputs to a register (directly for C_Register /
10163         // C_RegisterClass, and a target-defined fashion for
10164         // C_Immediate/C_Other). Find a register that we can use.
10165         if (OpInfo.AssignedRegs.Regs.empty()) {
10166           emitInlineAsmError(
10167               Call, "couldn't allocate output register for constraint '" +
10168                         Twine(OpInfo.ConstraintCode) + "'");
10169           return;
10170         }
10171 
10172         if (DetectWriteToReservedRegister())
10173           return;
10174 
10175         // Add information to the INLINEASM node to know that this register is
10176         // set.
10177         OpInfo.AssignedRegs.AddInlineAsmOperands(
10178             OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber
10179                                   : InlineAsm::Kind::RegDef,
10180             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
10181       }
10182       break;
10183 
10184     case InlineAsm::isInput:
10185     case InlineAsm::isLabel: {
10186       SDValue InOperandVal = OpInfo.CallOperand;
10187 
10188       if (OpInfo.isMatchingInputConstraint()) {
10189         // If this is required to match an output register we have already set,
10190         // just use its register.
10191         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
10192                                                   AsmNodeOperands);
10193         InlineAsm::Flag Flag(AsmNodeOperands[CurOp]->getAsZExtVal());
10194         if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) {
10195           if (OpInfo.isIndirect) {
10196             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
10197             emitInlineAsmError(Call, "inline asm not supported yet: "
10198                                      "don't know how to handle tied "
10199                                      "indirect register inputs");
10200             return;
10201           }
10202 
10203           SmallVector<Register, 4> Regs;
10204           MachineFunction &MF = DAG.getMachineFunction();
10205           MachineRegisterInfo &MRI = MF.getRegInfo();
10206           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
10207           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
10208           Register TiedReg = R->getReg();
10209           MVT RegVT = R->getSimpleValueType(0);
10210           const TargetRegisterClass *RC =
10211               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
10212               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
10213                                       : TRI.getMinimalPhysRegClass(TiedReg);
10214           for (unsigned i = 0, e = Flag.getNumOperandRegisters(); i != e; ++i)
10215             Regs.push_back(MRI.createVirtualRegister(RC));
10216 
10217           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
10218 
10219           SDLoc dl = getCurSDLoc();
10220           // Use the produced MatchedRegs object to
10221           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call);
10222           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, true,
10223                                            OpInfo.getMatchedOperand(), dl, DAG,
10224                                            AsmNodeOperands);
10225           break;
10226         }
10227 
10228         assert(Flag.isMemKind() && "Unknown matching constraint!");
10229         assert(Flag.getNumOperandRegisters() == 1 &&
10230                "Unexpected number of operands");
10231         // Add information to the INLINEASM node to know about this input.
10232         // See InlineAsm.h isUseOperandTiedToDef.
10233         Flag.clearMemConstraint();
10234         Flag.setMatchingOp(OpInfo.getMatchedOperand());
10235         AsmNodeOperands.push_back(DAG.getTargetConstant(
10236             Flag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
10237         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
10238         break;
10239       }
10240 
10241       // Treat indirect 'X' constraint as memory.
10242       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
10243           OpInfo.isIndirect)
10244         OpInfo.ConstraintType = TargetLowering::C_Memory;
10245 
10246       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
10247           OpInfo.ConstraintType == TargetLowering::C_Other) {
10248         std::vector<SDValue> Ops;
10249         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
10250                                           Ops, DAG);
10251         if (Ops.empty()) {
10252           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
10253             if (isa<ConstantSDNode>(InOperandVal)) {
10254               emitInlineAsmError(Call, "value out of range for constraint '" +
10255                                            Twine(OpInfo.ConstraintCode) + "'");
10256               return;
10257             }
10258 
10259           emitInlineAsmError(Call,
10260                              "invalid operand for inline asm constraint '" +
10261                                  Twine(OpInfo.ConstraintCode) + "'");
10262           return;
10263         }
10264 
10265         // Add information to the INLINEASM node to know about this input.
10266         InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size());
10267         AsmNodeOperands.push_back(DAG.getTargetConstant(
10268             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
10269         llvm::append_range(AsmNodeOperands, Ops);
10270         break;
10271       }
10272 
10273       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10274         assert((OpInfo.isIndirect ||
10275                 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
10276                "Operand must be indirect to be a mem!");
10277         assert(InOperandVal.getValueType() ==
10278                    TLI.getPointerTy(DAG.getDataLayout()) &&
10279                "Memory operands expect pointer values");
10280 
10281         const InlineAsm::ConstraintCode ConstraintID =
10282             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10283         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10284                "Failed to convert memory constraint code to constraint id.");
10285 
10286         // Add information to the INLINEASM node to know about this input.
10287         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
10288         ResOpType.setMemConstraint(ConstraintID);
10289         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
10290                                                         getCurSDLoc(),
10291                                                         MVT::i32));
10292         AsmNodeOperands.push_back(InOperandVal);
10293         break;
10294       }
10295 
10296       if (OpInfo.ConstraintType == TargetLowering::C_Address) {
10297         const InlineAsm::ConstraintCode ConstraintID =
10298             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10299         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10300                "Failed to convert memory constraint code to constraint id.");
10301 
10302         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
10303 
10304         SDValue AsmOp = InOperandVal;
10305         if (isFunction(InOperandVal)) {
10306           auto *GA = cast<GlobalAddressSDNode>(InOperandVal);
10307           ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1);
10308           AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(),
10309                                              InOperandVal.getValueType(),
10310                                              GA->getOffset());
10311         }
10312 
10313         // Add information to the INLINEASM node to know about this input.
10314         ResOpType.setMemConstraint(ConstraintID);
10315 
10316         AsmNodeOperands.push_back(
10317             DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32));
10318 
10319         AsmNodeOperands.push_back(AsmOp);
10320         break;
10321       }
10322 
10323       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
10324           OpInfo.ConstraintType != TargetLowering::C_Register) {
10325         emitInlineAsmError(Call, "unknown asm constraint '" +
10326                                      Twine(OpInfo.ConstraintCode) + "'");
10327         return;
10328       }
10329 
10330       // TODO: Support this.
10331       if (OpInfo.isIndirect) {
10332         emitInlineAsmError(
10333             Call, "Don't know how to handle indirect register inputs yet "
10334                   "for constraint '" +
10335                       Twine(OpInfo.ConstraintCode) + "'");
10336         return;
10337       }
10338 
10339       // Copy the input into the appropriate registers.
10340       if (OpInfo.AssignedRegs.Regs.empty()) {
10341         emitInlineAsmError(Call,
10342                            "couldn't allocate input reg for constraint '" +
10343                                Twine(OpInfo.ConstraintCode) + "'");
10344         return;
10345       }
10346 
10347       if (DetectWriteToReservedRegister())
10348         return;
10349 
10350       SDLoc dl = getCurSDLoc();
10351 
10352       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue,
10353                                         &Call);
10354 
10355       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, false,
10356                                                0, dl, DAG, AsmNodeOperands);
10357       break;
10358     }
10359     case InlineAsm::isClobber:
10360       // Add the clobbered value to the operand list, so that the register
10361       // allocator is aware that the physreg got clobbered.
10362       if (!OpInfo.AssignedRegs.Regs.empty())
10363         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::Clobber,
10364                                                  false, 0, getCurSDLoc(), DAG,
10365                                                  AsmNodeOperands);
10366       break;
10367     }
10368   }
10369 
10370   // Finish up input operands.  Set the input chain and add the flag last.
10371   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
10372   if (Glue.getNode()) AsmNodeOperands.push_back(Glue);
10373 
10374   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
10375   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
10376                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
10377   Glue = Chain.getValue(1);
10378 
10379   // Do additional work to generate outputs.
10380 
10381   SmallVector<EVT, 1> ResultVTs;
10382   SmallVector<SDValue, 1> ResultValues;
10383   SmallVector<SDValue, 8> OutChains;
10384 
10385   llvm::Type *CallResultType = Call.getType();
10386   ArrayRef<Type *> ResultTypes;
10387   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
10388     ResultTypes = StructResult->elements();
10389   else if (!CallResultType->isVoidTy())
10390     ResultTypes = ArrayRef(CallResultType);
10391 
10392   auto CurResultType = ResultTypes.begin();
10393   auto handleRegAssign = [&](SDValue V) {
10394     assert(CurResultType != ResultTypes.end() && "Unexpected value");
10395     assert((*CurResultType)->isSized() && "Unexpected unsized type");
10396     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
10397     ++CurResultType;
10398     // If the type of the inline asm call site return value is different but has
10399     // same size as the type of the asm output bitcast it.  One example of this
10400     // is for vectors with different width / number of elements.  This can
10401     // happen for register classes that can contain multiple different value
10402     // types.  The preg or vreg allocated may not have the same VT as was
10403     // expected.
10404     //
10405     // This can also happen for a return value that disagrees with the register
10406     // class it is put in, eg. a double in a general-purpose register on a
10407     // 32-bit machine.
10408     if (ResultVT != V.getValueType() &&
10409         ResultVT.getSizeInBits() == V.getValueSizeInBits())
10410       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
10411     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
10412              V.getValueType().isInteger()) {
10413       // If a result value was tied to an input value, the computed result
10414       // may have a wider width than the expected result.  Extract the
10415       // relevant portion.
10416       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
10417     }
10418     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
10419     ResultVTs.push_back(ResultVT);
10420     ResultValues.push_back(V);
10421   };
10422 
10423   // Deal with output operands.
10424   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
10425     if (OpInfo.Type == InlineAsm::isOutput) {
10426       SDValue Val;
10427       // Skip trivial output operands.
10428       if (OpInfo.AssignedRegs.Regs.empty())
10429         continue;
10430 
10431       switch (OpInfo.ConstraintType) {
10432       case TargetLowering::C_Register:
10433       case TargetLowering::C_RegisterClass:
10434         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
10435                                                   Chain, &Glue, &Call);
10436         break;
10437       case TargetLowering::C_Immediate:
10438       case TargetLowering::C_Other:
10439         Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(),
10440                                               OpInfo, DAG);
10441         break;
10442       case TargetLowering::C_Memory:
10443         break; // Already handled.
10444       case TargetLowering::C_Address:
10445         break; // Silence warning.
10446       case TargetLowering::C_Unknown:
10447         assert(false && "Unexpected unknown constraint");
10448       }
10449 
10450       // Indirect output manifest as stores. Record output chains.
10451       if (OpInfo.isIndirect) {
10452         const Value *Ptr = OpInfo.CallOperandVal;
10453         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
10454         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
10455                                      MachinePointerInfo(Ptr));
10456         OutChains.push_back(Store);
10457       } else {
10458         // generate CopyFromRegs to associated registers.
10459         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
10460         if (Val.getOpcode() == ISD::MERGE_VALUES) {
10461           for (const SDValue &V : Val->op_values())
10462             handleRegAssign(V);
10463         } else
10464           handleRegAssign(Val);
10465       }
10466     }
10467   }
10468 
10469   // Set results.
10470   if (!ResultValues.empty()) {
10471     assert(CurResultType == ResultTypes.end() &&
10472            "Mismatch in number of ResultTypes");
10473     assert(ResultValues.size() == ResultTypes.size() &&
10474            "Mismatch in number of output operands in asm result");
10475 
10476     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
10477                             DAG.getVTList(ResultVTs), ResultValues);
10478     setValue(&Call, V);
10479   }
10480 
10481   // Collect store chains.
10482   if (!OutChains.empty())
10483     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
10484 
10485   if (EmitEHLabels) {
10486     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
10487   }
10488 
10489   // Only Update Root if inline assembly has a memory effect.
10490   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
10491       EmitEHLabels)
10492     DAG.setRoot(Chain);
10493 }
10494 
10495 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
10496                                              const Twine &Message) {
10497   LLVMContext &Ctx = *DAG.getContext();
10498   Ctx.emitError(&Call, Message);
10499 
10500   // Make sure we leave the DAG in a valid state
10501   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10502   SmallVector<EVT, 1> ValueVTs;
10503   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
10504 
10505   if (ValueVTs.empty())
10506     return;
10507 
10508   SmallVector<SDValue, 1> Ops;
10509   for (const EVT &VT : ValueVTs)
10510     Ops.push_back(DAG.getUNDEF(VT));
10511 
10512   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
10513 }
10514 
10515 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
10516   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
10517                           MVT::Other, getRoot(),
10518                           getValue(I.getArgOperand(0)),
10519                           DAG.getSrcValue(I.getArgOperand(0))));
10520 }
10521 
10522 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
10523   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10524   const DataLayout &DL = DAG.getDataLayout();
10525   SDValue V = DAG.getVAArg(
10526       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
10527       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
10528       DL.getABITypeAlign(I.getType()).value());
10529   DAG.setRoot(V.getValue(1));
10530 
10531   if (I.getType()->isPointerTy())
10532     V = DAG.getPtrExtOrTrunc(
10533         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
10534   setValue(&I, V);
10535 }
10536 
10537 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
10538   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
10539                           MVT::Other, getRoot(),
10540                           getValue(I.getArgOperand(0)),
10541                           DAG.getSrcValue(I.getArgOperand(0))));
10542 }
10543 
10544 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
10545   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
10546                           MVT::Other, getRoot(),
10547                           getValue(I.getArgOperand(0)),
10548                           getValue(I.getArgOperand(1)),
10549                           DAG.getSrcValue(I.getArgOperand(0)),
10550                           DAG.getSrcValue(I.getArgOperand(1))));
10551 }
10552 
10553 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
10554                                                     const Instruction &I,
10555                                                     SDValue Op) {
10556   std::optional<ConstantRange> CR = getRange(I);
10557 
10558   if (!CR || CR->isFullSet() || CR->isEmptySet() || CR->isUpperWrapped())
10559     return Op;
10560 
10561   APInt Lo = CR->getUnsignedMin();
10562   if (!Lo.isMinValue())
10563     return Op;
10564 
10565   APInt Hi = CR->getUnsignedMax();
10566   unsigned Bits = std::max(Hi.getActiveBits(),
10567                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
10568 
10569   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
10570 
10571   SDLoc SL = getCurSDLoc();
10572 
10573   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
10574                              DAG.getValueType(SmallVT));
10575   unsigned NumVals = Op.getNode()->getNumValues();
10576   if (NumVals == 1)
10577     return ZExt;
10578 
10579   SmallVector<SDValue, 4> Ops;
10580 
10581   Ops.push_back(ZExt);
10582   for (unsigned I = 1; I != NumVals; ++I)
10583     Ops.push_back(Op.getValue(I));
10584 
10585   return DAG.getMergeValues(Ops, SL);
10586 }
10587 
10588 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
10589 /// the call being lowered.
10590 ///
10591 /// This is a helper for lowering intrinsics that follow a target calling
10592 /// convention or require stack pointer adjustment. Only a subset of the
10593 /// intrinsic's operands need to participate in the calling convention.
10594 void SelectionDAGBuilder::populateCallLoweringInfo(
10595     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
10596     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
10597     AttributeSet RetAttrs, bool IsPatchPoint) {
10598   TargetLowering::ArgListTy Args;
10599   Args.reserve(NumArgs);
10600 
10601   // Populate the argument list.
10602   // Attributes for args start at offset 1, after the return attribute.
10603   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
10604        ArgI != ArgE; ++ArgI) {
10605     const Value *V = Call->getOperand(ArgI);
10606 
10607     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
10608 
10609     TargetLowering::ArgListEntry Entry;
10610     Entry.Node = getValue(V);
10611     Entry.Ty = V->getType();
10612     Entry.setAttributes(Call, ArgI);
10613     Args.push_back(Entry);
10614   }
10615 
10616   CLI.setDebugLoc(getCurSDLoc())
10617       .setChain(getRoot())
10618       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args),
10619                  RetAttrs)
10620       .setDiscardResult(Call->use_empty())
10621       .setIsPatchPoint(IsPatchPoint)
10622       .setIsPreallocated(
10623           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
10624 }
10625 
10626 /// Add a stack map intrinsic call's live variable operands to a stackmap
10627 /// or patchpoint target node's operand list.
10628 ///
10629 /// Constants are converted to TargetConstants purely as an optimization to
10630 /// avoid constant materialization and register allocation.
10631 ///
10632 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
10633 /// generate addess computation nodes, and so FinalizeISel can convert the
10634 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
10635 /// address materialization and register allocation, but may also be required
10636 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
10637 /// alloca in the entry block, then the runtime may assume that the alloca's
10638 /// StackMap location can be read immediately after compilation and that the
10639 /// location is valid at any point during execution (this is similar to the
10640 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
10641 /// only available in a register, then the runtime would need to trap when
10642 /// execution reaches the StackMap in order to read the alloca's location.
10643 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
10644                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
10645                                 SelectionDAGBuilder &Builder) {
10646   SelectionDAG &DAG = Builder.DAG;
10647   for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
10648     SDValue Op = Builder.getValue(Call.getArgOperand(I));
10649 
10650     // Things on the stack are pointer-typed, meaning that they are already
10651     // legal and can be emitted directly to target nodes.
10652     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
10653       Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
10654     } else {
10655       // Otherwise emit a target independent node to be legalised.
10656       Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
10657     }
10658   }
10659 }
10660 
10661 /// Lower llvm.experimental.stackmap.
10662 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
10663   // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
10664   //                                  [live variables...])
10665 
10666   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
10667 
10668   SDValue Chain, InGlue, Callee;
10669   SmallVector<SDValue, 32> Ops;
10670 
10671   SDLoc DL = getCurSDLoc();
10672   Callee = getValue(CI.getCalledOperand());
10673 
10674   // The stackmap intrinsic only records the live variables (the arguments
10675   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
10676   // intrinsic, this won't be lowered to a function call. This means we don't
10677   // have to worry about calling conventions and target specific lowering code.
10678   // Instead we perform the call lowering right here.
10679   //
10680   // chain, flag = CALLSEQ_START(chain, 0, 0)
10681   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
10682   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
10683   //
10684   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
10685   InGlue = Chain.getValue(1);
10686 
10687   // Add the STACKMAP operands, starting with DAG house-keeping.
10688   Ops.push_back(Chain);
10689   Ops.push_back(InGlue);
10690 
10691   // Add the <id>, <numShadowBytes> operands.
10692   //
10693   // These do not require legalisation, and can be emitted directly to target
10694   // constant nodes.
10695   SDValue ID = getValue(CI.getArgOperand(0));
10696   assert(ID.getValueType() == MVT::i64);
10697   SDValue IDConst =
10698       DAG.getTargetConstant(ID->getAsZExtVal(), DL, ID.getValueType());
10699   Ops.push_back(IDConst);
10700 
10701   SDValue Shad = getValue(CI.getArgOperand(1));
10702   assert(Shad.getValueType() == MVT::i32);
10703   SDValue ShadConst =
10704       DAG.getTargetConstant(Shad->getAsZExtVal(), DL, Shad.getValueType());
10705   Ops.push_back(ShadConst);
10706 
10707   // Add the live variables.
10708   addStackMapLiveVars(CI, 2, DL, Ops, *this);
10709 
10710   // Create the STACKMAP node.
10711   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10712   Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
10713   InGlue = Chain.getValue(1);
10714 
10715   Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL);
10716 
10717   // Stackmaps don't generate values, so nothing goes into the NodeMap.
10718 
10719   // Set the root to the target-lowered call chain.
10720   DAG.setRoot(Chain);
10721 
10722   // Inform the Frame Information that we have a stackmap in this function.
10723   FuncInfo.MF->getFrameInfo().setHasStackMap();
10724 }
10725 
10726 /// Lower llvm.experimental.patchpoint directly to its target opcode.
10727 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
10728                                           const BasicBlock *EHPadBB) {
10729   // <ty> @llvm.experimental.patchpoint.<ty>(i64 <id>,
10730   //                                         i32 <numBytes>,
10731   //                                         i8* <target>,
10732   //                                         i32 <numArgs>,
10733   //                                         [Args...],
10734   //                                         [live variables...])
10735 
10736   CallingConv::ID CC = CB.getCallingConv();
10737   bool IsAnyRegCC = CC == CallingConv::AnyReg;
10738   bool HasDef = !CB.getType()->isVoidTy();
10739   SDLoc dl = getCurSDLoc();
10740   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
10741 
10742   // Handle immediate and symbolic callees.
10743   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
10744     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
10745                                    /*isTarget=*/true);
10746   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
10747     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
10748                                          SDLoc(SymbolicCallee),
10749                                          SymbolicCallee->getValueType(0));
10750 
10751   // Get the real number of arguments participating in the call <numArgs>
10752   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
10753   unsigned NumArgs = NArgVal->getAsZExtVal();
10754 
10755   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
10756   // Intrinsics include all meta-operands up to but not including CC.
10757   unsigned NumMetaOpers = PatchPointOpers::CCPos;
10758   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
10759          "Not enough arguments provided to the patchpoint intrinsic");
10760 
10761   // For AnyRegCC the arguments are lowered later on manually.
10762   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
10763   Type *ReturnTy =
10764       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
10765 
10766   TargetLowering::CallLoweringInfo CLI(DAG);
10767   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
10768                            ReturnTy, CB.getAttributes().getRetAttrs(), true);
10769   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
10770 
10771   SDNode *CallEnd = Result.second.getNode();
10772   if (CallEnd->getOpcode() == ISD::EH_LABEL)
10773     CallEnd = CallEnd->getOperand(0).getNode();
10774   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
10775     CallEnd = CallEnd->getOperand(0).getNode();
10776 
10777   /// Get a call instruction from the call sequence chain.
10778   /// Tail calls are not allowed.
10779   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
10780          "Expected a callseq node.");
10781   SDNode *Call = CallEnd->getOperand(0).getNode();
10782   bool HasGlue = Call->getGluedNode();
10783 
10784   // Replace the target specific call node with the patchable intrinsic.
10785   SmallVector<SDValue, 8> Ops;
10786 
10787   // Push the chain.
10788   Ops.push_back(*(Call->op_begin()));
10789 
10790   // Optionally, push the glue (if any).
10791   if (HasGlue)
10792     Ops.push_back(*(Call->op_end() - 1));
10793 
10794   // Push the register mask info.
10795   if (HasGlue)
10796     Ops.push_back(*(Call->op_end() - 2));
10797   else
10798     Ops.push_back(*(Call->op_end() - 1));
10799 
10800   // Add the <id> and <numBytes> constants.
10801   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
10802   Ops.push_back(DAG.getTargetConstant(IDVal->getAsZExtVal(), dl, MVT::i64));
10803   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
10804   Ops.push_back(DAG.getTargetConstant(NBytesVal->getAsZExtVal(), dl, MVT::i32));
10805 
10806   // Add the callee.
10807   Ops.push_back(Callee);
10808 
10809   // Adjust <numArgs> to account for any arguments that have been passed on the
10810   // stack instead.
10811   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
10812   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
10813   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
10814   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
10815 
10816   // Add the calling convention
10817   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
10818 
10819   // Add the arguments we omitted previously. The register allocator should
10820   // place these in any free register.
10821   if (IsAnyRegCC)
10822     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
10823       Ops.push_back(getValue(CB.getArgOperand(i)));
10824 
10825   // Push the arguments from the call instruction.
10826   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
10827   Ops.append(Call->op_begin() + 2, e);
10828 
10829   // Push live variables for the stack map.
10830   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
10831 
10832   SDVTList NodeTys;
10833   if (IsAnyRegCC && HasDef) {
10834     // Create the return types based on the intrinsic definition
10835     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10836     SmallVector<EVT, 3> ValueVTs;
10837     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
10838     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
10839 
10840     // There is always a chain and a glue type at the end
10841     ValueVTs.push_back(MVT::Other);
10842     ValueVTs.push_back(MVT::Glue);
10843     NodeTys = DAG.getVTList(ValueVTs);
10844   } else
10845     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10846 
10847   // Replace the target specific call node with a PATCHPOINT node.
10848   SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
10849 
10850   // Update the NodeMap.
10851   if (HasDef) {
10852     if (IsAnyRegCC)
10853       setValue(&CB, SDValue(PPV.getNode(), 0));
10854     else
10855       setValue(&CB, Result.first);
10856   }
10857 
10858   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
10859   // call sequence. Furthermore the location of the chain and glue can change
10860   // when the AnyReg calling convention is used and the intrinsic returns a
10861   // value.
10862   if (IsAnyRegCC && HasDef) {
10863     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
10864     SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
10865     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10866   } else
10867     DAG.ReplaceAllUsesWith(Call, PPV.getNode());
10868   DAG.DeleteNode(Call);
10869 
10870   // Inform the Frame Information that we have a patchpoint in this function.
10871   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
10872 }
10873 
10874 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
10875                                             unsigned Intrinsic) {
10876   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10877   SDValue Op1 = getValue(I.getArgOperand(0));
10878   SDValue Op2;
10879   if (I.arg_size() > 1)
10880     Op2 = getValue(I.getArgOperand(1));
10881   SDLoc dl = getCurSDLoc();
10882   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
10883   SDValue Res;
10884   SDNodeFlags SDFlags;
10885   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
10886     SDFlags.copyFMF(*FPMO);
10887 
10888   switch (Intrinsic) {
10889   case Intrinsic::vector_reduce_fadd:
10890     if (SDFlags.hasAllowReassociation())
10891       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
10892                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
10893                         SDFlags);
10894     else
10895       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
10896     break;
10897   case Intrinsic::vector_reduce_fmul:
10898     if (SDFlags.hasAllowReassociation())
10899       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
10900                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
10901                         SDFlags);
10902     else
10903       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
10904     break;
10905   case Intrinsic::vector_reduce_add:
10906     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
10907     break;
10908   case Intrinsic::vector_reduce_mul:
10909     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
10910     break;
10911   case Intrinsic::vector_reduce_and:
10912     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
10913     break;
10914   case Intrinsic::vector_reduce_or:
10915     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
10916     break;
10917   case Intrinsic::vector_reduce_xor:
10918     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
10919     break;
10920   case Intrinsic::vector_reduce_smax:
10921     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
10922     break;
10923   case Intrinsic::vector_reduce_smin:
10924     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
10925     break;
10926   case Intrinsic::vector_reduce_umax:
10927     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
10928     break;
10929   case Intrinsic::vector_reduce_umin:
10930     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
10931     break;
10932   case Intrinsic::vector_reduce_fmax:
10933     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
10934     break;
10935   case Intrinsic::vector_reduce_fmin:
10936     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
10937     break;
10938   case Intrinsic::vector_reduce_fmaximum:
10939     Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags);
10940     break;
10941   case Intrinsic::vector_reduce_fminimum:
10942     Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags);
10943     break;
10944   default:
10945     llvm_unreachable("Unhandled vector reduce intrinsic");
10946   }
10947   setValue(&I, Res);
10948 }
10949 
10950 /// Returns an AttributeList representing the attributes applied to the return
10951 /// value of the given call.
10952 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
10953   SmallVector<Attribute::AttrKind, 2> Attrs;
10954   if (CLI.RetSExt)
10955     Attrs.push_back(Attribute::SExt);
10956   if (CLI.RetZExt)
10957     Attrs.push_back(Attribute::ZExt);
10958   if (CLI.IsInReg)
10959     Attrs.push_back(Attribute::InReg);
10960 
10961   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
10962                             Attrs);
10963 }
10964 
10965 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
10966 /// implementation, which just calls LowerCall.
10967 /// FIXME: When all targets are
10968 /// migrated to using LowerCall, this hook should be integrated into SDISel.
10969 std::pair<SDValue, SDValue>
10970 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
10971   // Handle the incoming return values from the call.
10972   CLI.Ins.clear();
10973   Type *OrigRetTy = CLI.RetTy;
10974   SmallVector<EVT, 4> RetTys;
10975   SmallVector<TypeSize, 4> Offsets;
10976   auto &DL = CLI.DAG.getDataLayout();
10977   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
10978 
10979   if (CLI.IsPostTypeLegalization) {
10980     // If we are lowering a libcall after legalization, split the return type.
10981     SmallVector<EVT, 4> OldRetTys;
10982     SmallVector<TypeSize, 4> OldOffsets;
10983     RetTys.swap(OldRetTys);
10984     Offsets.swap(OldOffsets);
10985 
10986     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
10987       EVT RetVT = OldRetTys[i];
10988       uint64_t Offset = OldOffsets[i];
10989       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
10990       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
10991       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
10992       RetTys.append(NumRegs, RegisterVT);
10993       for (unsigned j = 0; j != NumRegs; ++j)
10994         Offsets.push_back(TypeSize::getFixed(Offset + j * RegisterVTByteSZ));
10995     }
10996   }
10997 
10998   SmallVector<ISD::OutputArg, 4> Outs;
10999   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
11000 
11001   bool CanLowerReturn =
11002       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
11003                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
11004 
11005   SDValue DemoteStackSlot;
11006   int DemoteStackIdx = -100;
11007   if (!CanLowerReturn) {
11008     // FIXME: equivalent assert?
11009     // assert(!CS.hasInAllocaArgument() &&
11010     //        "sret demotion is incompatible with inalloca");
11011     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
11012     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
11013     MachineFunction &MF = CLI.DAG.getMachineFunction();
11014     DemoteStackIdx =
11015         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
11016     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
11017                                               DL.getAllocaAddrSpace());
11018 
11019     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
11020     ArgListEntry Entry;
11021     Entry.Node = DemoteStackSlot;
11022     Entry.Ty = StackSlotPtrType;
11023     Entry.IsSExt = false;
11024     Entry.IsZExt = false;
11025     Entry.IsInReg = false;
11026     Entry.IsSRet = true;
11027     Entry.IsNest = false;
11028     Entry.IsByVal = false;
11029     Entry.IsByRef = false;
11030     Entry.IsReturned = false;
11031     Entry.IsSwiftSelf = false;
11032     Entry.IsSwiftAsync = false;
11033     Entry.IsSwiftError = false;
11034     Entry.IsCFGuardTarget = false;
11035     Entry.Alignment = Alignment;
11036     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
11037     CLI.NumFixedArgs += 1;
11038     CLI.getArgs()[0].IndirectType = CLI.RetTy;
11039     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
11040 
11041     // sret demotion isn't compatible with tail-calls, since the sret argument
11042     // points into the callers stack frame.
11043     CLI.IsTailCall = false;
11044   } else {
11045     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
11046         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
11047     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
11048       ISD::ArgFlagsTy Flags;
11049       if (NeedsRegBlock) {
11050         Flags.setInConsecutiveRegs();
11051         if (I == RetTys.size() - 1)
11052           Flags.setInConsecutiveRegsLast();
11053       }
11054       EVT VT = RetTys[I];
11055       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
11056                                                      CLI.CallConv, VT);
11057       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
11058                                                        CLI.CallConv, VT);
11059       for (unsigned i = 0; i != NumRegs; ++i) {
11060         ISD::InputArg MyFlags;
11061         MyFlags.Flags = Flags;
11062         MyFlags.VT = RegisterVT;
11063         MyFlags.ArgVT = VT;
11064         MyFlags.Used = CLI.IsReturnValueUsed;
11065         if (CLI.RetTy->isPointerTy()) {
11066           MyFlags.Flags.setPointer();
11067           MyFlags.Flags.setPointerAddrSpace(
11068               cast<PointerType>(CLI.RetTy)->getAddressSpace());
11069         }
11070         if (CLI.RetSExt)
11071           MyFlags.Flags.setSExt();
11072         if (CLI.RetZExt)
11073           MyFlags.Flags.setZExt();
11074         if (CLI.IsInReg)
11075           MyFlags.Flags.setInReg();
11076         CLI.Ins.push_back(MyFlags);
11077       }
11078     }
11079   }
11080 
11081   // We push in swifterror return as the last element of CLI.Ins.
11082   ArgListTy &Args = CLI.getArgs();
11083   if (supportSwiftError()) {
11084     for (const ArgListEntry &Arg : Args) {
11085       if (Arg.IsSwiftError) {
11086         ISD::InputArg MyFlags;
11087         MyFlags.VT = getPointerTy(DL);
11088         MyFlags.ArgVT = EVT(getPointerTy(DL));
11089         MyFlags.Flags.setSwiftError();
11090         CLI.Ins.push_back(MyFlags);
11091       }
11092     }
11093   }
11094 
11095   // Handle all of the outgoing arguments.
11096   CLI.Outs.clear();
11097   CLI.OutVals.clear();
11098   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
11099     SmallVector<EVT, 4> ValueVTs;
11100     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
11101     // FIXME: Split arguments if CLI.IsPostTypeLegalization
11102     Type *FinalType = Args[i].Ty;
11103     if (Args[i].IsByVal)
11104       FinalType = Args[i].IndirectType;
11105     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
11106         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
11107     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
11108          ++Value) {
11109       EVT VT = ValueVTs[Value];
11110       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
11111       SDValue Op = SDValue(Args[i].Node.getNode(),
11112                            Args[i].Node.getResNo() + Value);
11113       ISD::ArgFlagsTy Flags;
11114 
11115       // Certain targets (such as MIPS), may have a different ABI alignment
11116       // for a type depending on the context. Give the target a chance to
11117       // specify the alignment it wants.
11118       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
11119       Flags.setOrigAlign(OriginalAlignment);
11120 
11121       if (Args[i].Ty->isPointerTy()) {
11122         Flags.setPointer();
11123         Flags.setPointerAddrSpace(
11124             cast<PointerType>(Args[i].Ty)->getAddressSpace());
11125       }
11126       if (Args[i].IsZExt)
11127         Flags.setZExt();
11128       if (Args[i].IsSExt)
11129         Flags.setSExt();
11130       if (Args[i].IsNoExt)
11131         Flags.setNoExt();
11132       if (Args[i].IsInReg) {
11133         // If we are using vectorcall calling convention, a structure that is
11134         // passed InReg - is surely an HVA
11135         if (CLI.CallConv == CallingConv::X86_VectorCall &&
11136             isa<StructType>(FinalType)) {
11137           // The first value of a structure is marked
11138           if (0 == Value)
11139             Flags.setHvaStart();
11140           Flags.setHva();
11141         }
11142         // Set InReg Flag
11143         Flags.setInReg();
11144       }
11145       if (Args[i].IsSRet)
11146         Flags.setSRet();
11147       if (Args[i].IsSwiftSelf)
11148         Flags.setSwiftSelf();
11149       if (Args[i].IsSwiftAsync)
11150         Flags.setSwiftAsync();
11151       if (Args[i].IsSwiftError)
11152         Flags.setSwiftError();
11153       if (Args[i].IsCFGuardTarget)
11154         Flags.setCFGuardTarget();
11155       if (Args[i].IsByVal)
11156         Flags.setByVal();
11157       if (Args[i].IsByRef)
11158         Flags.setByRef();
11159       if (Args[i].IsPreallocated) {
11160         Flags.setPreallocated();
11161         // Set the byval flag for CCAssignFn callbacks that don't know about
11162         // preallocated.  This way we can know how many bytes we should've
11163         // allocated and how many bytes a callee cleanup function will pop.  If
11164         // we port preallocated to more targets, we'll have to add custom
11165         // preallocated handling in the various CC lowering callbacks.
11166         Flags.setByVal();
11167       }
11168       if (Args[i].IsInAlloca) {
11169         Flags.setInAlloca();
11170         // Set the byval flag for CCAssignFn callbacks that don't know about
11171         // inalloca.  This way we can know how many bytes we should've allocated
11172         // and how many bytes a callee cleanup function will pop.  If we port
11173         // inalloca to more targets, we'll have to add custom inalloca handling
11174         // in the various CC lowering callbacks.
11175         Flags.setByVal();
11176       }
11177       Align MemAlign;
11178       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
11179         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
11180         Flags.setByValSize(FrameSize);
11181 
11182         // info is not there but there are cases it cannot get right.
11183         if (auto MA = Args[i].Alignment)
11184           MemAlign = *MA;
11185         else
11186           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
11187       } else if (auto MA = Args[i].Alignment) {
11188         MemAlign = *MA;
11189       } else {
11190         MemAlign = OriginalAlignment;
11191       }
11192       Flags.setMemAlign(MemAlign);
11193       if (Args[i].IsNest)
11194         Flags.setNest();
11195       if (NeedsRegBlock)
11196         Flags.setInConsecutiveRegs();
11197 
11198       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
11199                                                  CLI.CallConv, VT);
11200       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
11201                                                         CLI.CallConv, VT);
11202       SmallVector<SDValue, 4> Parts(NumParts);
11203       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
11204 
11205       if (Args[i].IsSExt)
11206         ExtendKind = ISD::SIGN_EXTEND;
11207       else if (Args[i].IsZExt)
11208         ExtendKind = ISD::ZERO_EXTEND;
11209 
11210       // Conservatively only handle 'returned' on non-vectors that can be lowered,
11211       // for now.
11212       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
11213           CanLowerReturn) {
11214         assert((CLI.RetTy == Args[i].Ty ||
11215                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
11216                  CLI.RetTy->getPointerAddressSpace() ==
11217                      Args[i].Ty->getPointerAddressSpace())) &&
11218                RetTys.size() == NumValues && "unexpected use of 'returned'");
11219         // Before passing 'returned' to the target lowering code, ensure that
11220         // either the register MVT and the actual EVT are the same size or that
11221         // the return value and argument are extended in the same way; in these
11222         // cases it's safe to pass the argument register value unchanged as the
11223         // return register value (although it's at the target's option whether
11224         // to do so)
11225         // TODO: allow code generation to take advantage of partially preserved
11226         // registers rather than clobbering the entire register when the
11227         // parameter extension method is not compatible with the return
11228         // extension method
11229         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
11230             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
11231              CLI.RetZExt == Args[i].IsZExt))
11232           Flags.setReturned();
11233       }
11234 
11235       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
11236                      CLI.CallConv, ExtendKind);
11237 
11238       for (unsigned j = 0; j != NumParts; ++j) {
11239         // if it isn't first piece, alignment must be 1
11240         // For scalable vectors the scalable part is currently handled
11241         // by individual targets, so we just use the known minimum size here.
11242         ISD::OutputArg MyFlags(
11243             Flags, Parts[j].getValueType().getSimpleVT(), VT,
11244             i < CLI.NumFixedArgs, i,
11245             j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
11246         if (NumParts > 1 && j == 0)
11247           MyFlags.Flags.setSplit();
11248         else if (j != 0) {
11249           MyFlags.Flags.setOrigAlign(Align(1));
11250           if (j == NumParts - 1)
11251             MyFlags.Flags.setSplitEnd();
11252         }
11253 
11254         CLI.Outs.push_back(MyFlags);
11255         CLI.OutVals.push_back(Parts[j]);
11256       }
11257 
11258       if (NeedsRegBlock && Value == NumValues - 1)
11259         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
11260     }
11261   }
11262 
11263   SmallVector<SDValue, 4> InVals;
11264   CLI.Chain = LowerCall(CLI, InVals);
11265 
11266   // Update CLI.InVals to use outside of this function.
11267   CLI.InVals = InVals;
11268 
11269   // Verify that the target's LowerCall behaved as expected.
11270   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
11271          "LowerCall didn't return a valid chain!");
11272   assert((!CLI.IsTailCall || InVals.empty()) &&
11273          "LowerCall emitted a return value for a tail call!");
11274   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
11275          "LowerCall didn't emit the correct number of values!");
11276 
11277   // For a tail call, the return value is merely live-out and there aren't
11278   // any nodes in the DAG representing it. Return a special value to
11279   // indicate that a tail call has been emitted and no more Instructions
11280   // should be processed in the current block.
11281   if (CLI.IsTailCall) {
11282     CLI.DAG.setRoot(CLI.Chain);
11283     return std::make_pair(SDValue(), SDValue());
11284   }
11285 
11286 #ifndef NDEBUG
11287   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
11288     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
11289     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
11290            "LowerCall emitted a value with the wrong type!");
11291   }
11292 #endif
11293 
11294   SmallVector<SDValue, 4> ReturnValues;
11295   if (!CanLowerReturn) {
11296     // The instruction result is the result of loading from the
11297     // hidden sret parameter.
11298     SmallVector<EVT, 1> PVTs;
11299     Type *PtrRetTy =
11300         PointerType::get(OrigRetTy->getContext(), DL.getAllocaAddrSpace());
11301 
11302     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
11303     assert(PVTs.size() == 1 && "Pointers should fit in one register");
11304     EVT PtrVT = PVTs[0];
11305 
11306     unsigned NumValues = RetTys.size();
11307     ReturnValues.resize(NumValues);
11308     SmallVector<SDValue, 4> Chains(NumValues);
11309 
11310     // An aggregate return value cannot wrap around the address space, so
11311     // offsets to its parts don't wrap either.
11312     MachineFunction &MF = CLI.DAG.getMachineFunction();
11313     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
11314     for (unsigned i = 0; i < NumValues; ++i) {
11315       SDValue Add =
11316           CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
11317                           CLI.DAG.getConstant(Offsets[i], CLI.DL, PtrVT),
11318                           SDNodeFlags::NoUnsignedWrap);
11319       SDValue L = CLI.DAG.getLoad(
11320           RetTys[i], CLI.DL, CLI.Chain, Add,
11321           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
11322                                             DemoteStackIdx, Offsets[i]),
11323           HiddenSRetAlign);
11324       ReturnValues[i] = L;
11325       Chains[i] = L.getValue(1);
11326     }
11327 
11328     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
11329   } else {
11330     // Collect the legal value parts into potentially illegal values
11331     // that correspond to the original function's return values.
11332     std::optional<ISD::NodeType> AssertOp;
11333     if (CLI.RetSExt)
11334       AssertOp = ISD::AssertSext;
11335     else if (CLI.RetZExt)
11336       AssertOp = ISD::AssertZext;
11337     unsigned CurReg = 0;
11338     for (EVT VT : RetTys) {
11339       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
11340                                                      CLI.CallConv, VT);
11341       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
11342                                                        CLI.CallConv, VT);
11343 
11344       ReturnValues.push_back(getCopyFromParts(
11345           CLI.DAG, CLI.DL, &InVals[CurReg], NumRegs, RegisterVT, VT, nullptr,
11346           CLI.Chain, CLI.CallConv, AssertOp));
11347       CurReg += NumRegs;
11348     }
11349 
11350     // For a function returning void, there is no return value. We can't create
11351     // such a node, so we just return a null return value in that case. In
11352     // that case, nothing will actually look at the value.
11353     if (ReturnValues.empty())
11354       return std::make_pair(SDValue(), CLI.Chain);
11355   }
11356 
11357   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
11358                                 CLI.DAG.getVTList(RetTys), ReturnValues);
11359   return std::make_pair(Res, CLI.Chain);
11360 }
11361 
11362 /// Places new result values for the node in Results (their number
11363 /// and types must exactly match those of the original return values of
11364 /// the node), or leaves Results empty, which indicates that the node is not
11365 /// to be custom lowered after all.
11366 void TargetLowering::LowerOperationWrapper(SDNode *N,
11367                                            SmallVectorImpl<SDValue> &Results,
11368                                            SelectionDAG &DAG) const {
11369   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
11370 
11371   if (!Res.getNode())
11372     return;
11373 
11374   // If the original node has one result, take the return value from
11375   // LowerOperation as is. It might not be result number 0.
11376   if (N->getNumValues() == 1) {
11377     Results.push_back(Res);
11378     return;
11379   }
11380 
11381   // If the original node has multiple results, then the return node should
11382   // have the same number of results.
11383   assert((N->getNumValues() == Res->getNumValues()) &&
11384       "Lowering returned the wrong number of results!");
11385 
11386   // Places new result values base on N result number.
11387   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
11388     Results.push_back(Res.getValue(I));
11389 }
11390 
11391 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11392   llvm_unreachable("LowerOperation not implemented for this target!");
11393 }
11394 
11395 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
11396                                                      unsigned Reg,
11397                                                      ISD::NodeType ExtendType) {
11398   SDValue Op = getNonRegisterValue(V);
11399   assert((Op.getOpcode() != ISD::CopyFromReg ||
11400           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
11401          "Copy from a reg to the same reg!");
11402   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
11403 
11404   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11405   // If this is an InlineAsm we have to match the registers required, not the
11406   // notional registers required by the type.
11407 
11408   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
11409                    std::nullopt); // This is not an ABI copy.
11410   SDValue Chain = DAG.getEntryNode();
11411 
11412   if (ExtendType == ISD::ANY_EXTEND) {
11413     auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
11414     if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
11415       ExtendType = PreferredExtendIt->second;
11416   }
11417   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
11418   PendingExports.push_back(Chain);
11419 }
11420 
11421 #include "llvm/CodeGen/SelectionDAGISel.h"
11422 
11423 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
11424 /// entry block, return true.  This includes arguments used by switches, since
11425 /// the switch may expand into multiple basic blocks.
11426 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
11427   // With FastISel active, we may be splitting blocks, so force creation
11428   // of virtual registers for all non-dead arguments.
11429   if (FastISel)
11430     return A->use_empty();
11431 
11432   const BasicBlock &Entry = A->getParent()->front();
11433   for (const User *U : A->users())
11434     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
11435       return false;  // Use not in entry block.
11436 
11437   return true;
11438 }
11439 
11440 using ArgCopyElisionMapTy =
11441     DenseMap<const Argument *,
11442              std::pair<const AllocaInst *, const StoreInst *>>;
11443 
11444 /// Scan the entry block of the function in FuncInfo for arguments that look
11445 /// like copies into a local alloca. Record any copied arguments in
11446 /// ArgCopyElisionCandidates.
11447 static void
11448 findArgumentCopyElisionCandidates(const DataLayout &DL,
11449                                   FunctionLoweringInfo *FuncInfo,
11450                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
11451   // Record the state of every static alloca used in the entry block. Argument
11452   // allocas are all used in the entry block, so we need approximately as many
11453   // entries as we have arguments.
11454   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
11455   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
11456   unsigned NumArgs = FuncInfo->Fn->arg_size();
11457   StaticAllocas.reserve(NumArgs * 2);
11458 
11459   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
11460     if (!V)
11461       return nullptr;
11462     V = V->stripPointerCasts();
11463     const auto *AI = dyn_cast<AllocaInst>(V);
11464     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
11465       return nullptr;
11466     auto Iter = StaticAllocas.insert({AI, Unknown});
11467     return &Iter.first->second;
11468   };
11469 
11470   // Look for stores of arguments to static allocas. Look through bitcasts and
11471   // GEPs to handle type coercions, as long as the alloca is fully initialized
11472   // by the store. Any non-store use of an alloca escapes it and any subsequent
11473   // unanalyzed store might write it.
11474   // FIXME: Handle structs initialized with multiple stores.
11475   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
11476     // Look for stores, and handle non-store uses conservatively.
11477     const auto *SI = dyn_cast<StoreInst>(&I);
11478     if (!SI) {
11479       // We will look through cast uses, so ignore them completely.
11480       if (I.isCast())
11481         continue;
11482       // Ignore debug info and pseudo op intrinsics, they don't escape or store
11483       // to allocas.
11484       if (I.isDebugOrPseudoInst())
11485         continue;
11486       // This is an unknown instruction. Assume it escapes or writes to all
11487       // static alloca operands.
11488       for (const Use &U : I.operands()) {
11489         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
11490           *Info = StaticAllocaInfo::Clobbered;
11491       }
11492       continue;
11493     }
11494 
11495     // If the stored value is a static alloca, mark it as escaped.
11496     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
11497       *Info = StaticAllocaInfo::Clobbered;
11498 
11499     // Check if the destination is a static alloca.
11500     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
11501     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
11502     if (!Info)
11503       continue;
11504     const AllocaInst *AI = cast<AllocaInst>(Dst);
11505 
11506     // Skip allocas that have been initialized or clobbered.
11507     if (*Info != StaticAllocaInfo::Unknown)
11508       continue;
11509 
11510     // Check if the stored value is an argument, and that this store fully
11511     // initializes the alloca.
11512     // If the argument type has padding bits we can't directly forward a pointer
11513     // as the upper bits may contain garbage.
11514     // Don't elide copies from the same argument twice.
11515     const Value *Val = SI->getValueOperand()->stripPointerCasts();
11516     const auto *Arg = dyn_cast<Argument>(Val);
11517     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
11518         Arg->getType()->isEmptyTy() ||
11519         DL.getTypeStoreSize(Arg->getType()) !=
11520             DL.getTypeAllocSize(AI->getAllocatedType()) ||
11521         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
11522         ArgCopyElisionCandidates.count(Arg)) {
11523       *Info = StaticAllocaInfo::Clobbered;
11524       continue;
11525     }
11526 
11527     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
11528                       << '\n');
11529 
11530     // Mark this alloca and store for argument copy elision.
11531     *Info = StaticAllocaInfo::Elidable;
11532     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
11533 
11534     // Stop scanning if we've seen all arguments. This will happen early in -O0
11535     // builds, which is useful, because -O0 builds have large entry blocks and
11536     // many allocas.
11537     if (ArgCopyElisionCandidates.size() == NumArgs)
11538       break;
11539   }
11540 }
11541 
11542 /// Try to elide argument copies from memory into a local alloca. Succeeds if
11543 /// ArgVal is a load from a suitable fixed stack object.
11544 static void tryToElideArgumentCopy(
11545     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
11546     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
11547     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
11548     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
11549     ArrayRef<SDValue> ArgVals, bool &ArgHasUses) {
11550   // Check if this is a load from a fixed stack object.
11551   auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]);
11552   if (!LNode)
11553     return;
11554   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
11555   if (!FINode)
11556     return;
11557 
11558   // Check that the fixed stack object is the right size and alignment.
11559   // Look at the alignment that the user wrote on the alloca instead of looking
11560   // at the stack object.
11561   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
11562   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
11563   const AllocaInst *AI = ArgCopyIter->second.first;
11564   int FixedIndex = FINode->getIndex();
11565   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
11566   int OldIndex = AllocaIndex;
11567   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
11568   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
11569     LLVM_DEBUG(
11570         dbgs() << "  argument copy elision failed due to bad fixed stack "
11571                   "object size\n");
11572     return;
11573   }
11574   Align RequiredAlignment = AI->getAlign();
11575   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
11576     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
11577                          "greater than stack argument alignment ("
11578                       << DebugStr(RequiredAlignment) << " vs "
11579                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
11580     return;
11581   }
11582 
11583   // Perform the elision. Delete the old stack object and replace its only use
11584   // in the variable info map. Mark the stack object as mutable and aliased.
11585   LLVM_DEBUG({
11586     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
11587            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
11588            << '\n';
11589   });
11590   MFI.RemoveStackObject(OldIndex);
11591   MFI.setIsImmutableObjectIndex(FixedIndex, false);
11592   MFI.setIsAliasedObjectIndex(FixedIndex, true);
11593   AllocaIndex = FixedIndex;
11594   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
11595   for (SDValue ArgVal : ArgVals)
11596     Chains.push_back(ArgVal.getValue(1));
11597 
11598   // Avoid emitting code for the store implementing the copy.
11599   const StoreInst *SI = ArgCopyIter->second.second;
11600   ElidedArgCopyInstrs.insert(SI);
11601 
11602   // Check for uses of the argument again so that we can avoid exporting ArgVal
11603   // if it is't used by anything other than the store.
11604   for (const Value *U : Arg.users()) {
11605     if (U != SI) {
11606       ArgHasUses = true;
11607       break;
11608     }
11609   }
11610 }
11611 
11612 void SelectionDAGISel::LowerArguments(const Function &F) {
11613   SelectionDAG &DAG = SDB->DAG;
11614   SDLoc dl = SDB->getCurSDLoc();
11615   const DataLayout &DL = DAG.getDataLayout();
11616   SmallVector<ISD::InputArg, 16> Ins;
11617 
11618   // In Naked functions we aren't going to save any registers.
11619   if (F.hasFnAttribute(Attribute::Naked))
11620     return;
11621 
11622   if (!FuncInfo->CanLowerReturn) {
11623     // Put in an sret pointer parameter before all the other parameters.
11624     SmallVector<EVT, 1> ValueVTs;
11625     ComputeValueVTs(*TLI, DAG.getDataLayout(),
11626                     PointerType::get(F.getContext(),
11627                                      DAG.getDataLayout().getAllocaAddrSpace()),
11628                     ValueVTs);
11629 
11630     // NOTE: Assuming that a pointer will never break down to more than one VT
11631     // or one register.
11632     ISD::ArgFlagsTy Flags;
11633     Flags.setSRet();
11634     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
11635     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
11636                          ISD::InputArg::NoArgIndex, 0);
11637     Ins.push_back(RetArg);
11638   }
11639 
11640   // Look for stores of arguments to static allocas. Mark such arguments with a
11641   // flag to ask the target to give us the memory location of that argument if
11642   // available.
11643   ArgCopyElisionMapTy ArgCopyElisionCandidates;
11644   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
11645                                     ArgCopyElisionCandidates);
11646 
11647   // Set up the incoming argument description vector.
11648   for (const Argument &Arg : F.args()) {
11649     unsigned ArgNo = Arg.getArgNo();
11650     SmallVector<EVT, 4> ValueVTs;
11651     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
11652     bool isArgValueUsed = !Arg.use_empty();
11653     unsigned PartBase = 0;
11654     Type *FinalType = Arg.getType();
11655     if (Arg.hasAttribute(Attribute::ByVal))
11656       FinalType = Arg.getParamByValType();
11657     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
11658         FinalType, F.getCallingConv(), F.isVarArg(), DL);
11659     for (unsigned Value = 0, NumValues = ValueVTs.size();
11660          Value != NumValues; ++Value) {
11661       EVT VT = ValueVTs[Value];
11662       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
11663       ISD::ArgFlagsTy Flags;
11664 
11665 
11666       if (Arg.getType()->isPointerTy()) {
11667         Flags.setPointer();
11668         Flags.setPointerAddrSpace(
11669             cast<PointerType>(Arg.getType())->getAddressSpace());
11670       }
11671       if (Arg.hasAttribute(Attribute::ZExt))
11672         Flags.setZExt();
11673       if (Arg.hasAttribute(Attribute::SExt))
11674         Flags.setSExt();
11675       if (Arg.hasAttribute(Attribute::InReg)) {
11676         // If we are using vectorcall calling convention, a structure that is
11677         // passed InReg - is surely an HVA
11678         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
11679             isa<StructType>(Arg.getType())) {
11680           // The first value of a structure is marked
11681           if (0 == Value)
11682             Flags.setHvaStart();
11683           Flags.setHva();
11684         }
11685         // Set InReg Flag
11686         Flags.setInReg();
11687       }
11688       if (Arg.hasAttribute(Attribute::StructRet))
11689         Flags.setSRet();
11690       if (Arg.hasAttribute(Attribute::SwiftSelf))
11691         Flags.setSwiftSelf();
11692       if (Arg.hasAttribute(Attribute::SwiftAsync))
11693         Flags.setSwiftAsync();
11694       if (Arg.hasAttribute(Attribute::SwiftError))
11695         Flags.setSwiftError();
11696       if (Arg.hasAttribute(Attribute::ByVal))
11697         Flags.setByVal();
11698       if (Arg.hasAttribute(Attribute::ByRef))
11699         Flags.setByRef();
11700       if (Arg.hasAttribute(Attribute::InAlloca)) {
11701         Flags.setInAlloca();
11702         // Set the byval flag for CCAssignFn callbacks that don't know about
11703         // inalloca.  This way we can know how many bytes we should've allocated
11704         // and how many bytes a callee cleanup function will pop.  If we port
11705         // inalloca to more targets, we'll have to add custom inalloca handling
11706         // in the various CC lowering callbacks.
11707         Flags.setByVal();
11708       }
11709       if (Arg.hasAttribute(Attribute::Preallocated)) {
11710         Flags.setPreallocated();
11711         // Set the byval flag for CCAssignFn callbacks that don't know about
11712         // preallocated.  This way we can know how many bytes we should've
11713         // allocated and how many bytes a callee cleanup function will pop.  If
11714         // we port preallocated to more targets, we'll have to add custom
11715         // preallocated handling in the various CC lowering callbacks.
11716         Flags.setByVal();
11717       }
11718 
11719       // Certain targets (such as MIPS), may have a different ABI alignment
11720       // for a type depending on the context. Give the target a chance to
11721       // specify the alignment it wants.
11722       const Align OriginalAlignment(
11723           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
11724       Flags.setOrigAlign(OriginalAlignment);
11725 
11726       Align MemAlign;
11727       Type *ArgMemTy = nullptr;
11728       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
11729           Flags.isByRef()) {
11730         if (!ArgMemTy)
11731           ArgMemTy = Arg.getPointeeInMemoryValueType();
11732 
11733         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
11734 
11735         // For in-memory arguments, size and alignment should be passed from FE.
11736         // BE will guess if this info is not there but there are cases it cannot
11737         // get right.
11738         if (auto ParamAlign = Arg.getParamStackAlign())
11739           MemAlign = *ParamAlign;
11740         else if ((ParamAlign = Arg.getParamAlign()))
11741           MemAlign = *ParamAlign;
11742         else
11743           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
11744         if (Flags.isByRef())
11745           Flags.setByRefSize(MemSize);
11746         else
11747           Flags.setByValSize(MemSize);
11748       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
11749         MemAlign = *ParamAlign;
11750       } else {
11751         MemAlign = OriginalAlignment;
11752       }
11753       Flags.setMemAlign(MemAlign);
11754 
11755       if (Arg.hasAttribute(Attribute::Nest))
11756         Flags.setNest();
11757       if (NeedsRegBlock)
11758         Flags.setInConsecutiveRegs();
11759       if (ArgCopyElisionCandidates.count(&Arg))
11760         Flags.setCopyElisionCandidate();
11761       if (Arg.hasAttribute(Attribute::Returned))
11762         Flags.setReturned();
11763 
11764       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
11765           *CurDAG->getContext(), F.getCallingConv(), VT);
11766       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
11767           *CurDAG->getContext(), F.getCallingConv(), VT);
11768       for (unsigned i = 0; i != NumRegs; ++i) {
11769         // For scalable vectors, use the minimum size; individual targets
11770         // are responsible for handling scalable vector arguments and
11771         // return values.
11772         ISD::InputArg MyFlags(
11773             Flags, RegisterVT, VT, isArgValueUsed, ArgNo,
11774             PartBase + i * RegisterVT.getStoreSize().getKnownMinValue());
11775         if (NumRegs > 1 && i == 0)
11776           MyFlags.Flags.setSplit();
11777         // if it isn't first piece, alignment must be 1
11778         else if (i > 0) {
11779           MyFlags.Flags.setOrigAlign(Align(1));
11780           if (i == NumRegs - 1)
11781             MyFlags.Flags.setSplitEnd();
11782         }
11783         Ins.push_back(MyFlags);
11784       }
11785       if (NeedsRegBlock && Value == NumValues - 1)
11786         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
11787       PartBase += VT.getStoreSize().getKnownMinValue();
11788     }
11789   }
11790 
11791   // Call the target to set up the argument values.
11792   SmallVector<SDValue, 8> InVals;
11793   SDValue NewRoot = TLI->LowerFormalArguments(
11794       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
11795 
11796   // Verify that the target's LowerFormalArguments behaved as expected.
11797   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
11798          "LowerFormalArguments didn't return a valid chain!");
11799   assert(InVals.size() == Ins.size() &&
11800          "LowerFormalArguments didn't emit the correct number of values!");
11801   LLVM_DEBUG({
11802     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
11803       assert(InVals[i].getNode() &&
11804              "LowerFormalArguments emitted a null value!");
11805       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
11806              "LowerFormalArguments emitted a value with the wrong type!");
11807     }
11808   });
11809 
11810   // Update the DAG with the new chain value resulting from argument lowering.
11811   DAG.setRoot(NewRoot);
11812 
11813   // Set up the argument values.
11814   unsigned i = 0;
11815   if (!FuncInfo->CanLowerReturn) {
11816     // Create a virtual register for the sret pointer, and put in a copy
11817     // from the sret argument into it.
11818     SmallVector<EVT, 1> ValueVTs;
11819     ComputeValueVTs(*TLI, DAG.getDataLayout(),
11820                     PointerType::get(F.getContext(),
11821                                      DAG.getDataLayout().getAllocaAddrSpace()),
11822                     ValueVTs);
11823     MVT VT = ValueVTs[0].getSimpleVT();
11824     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
11825     std::optional<ISD::NodeType> AssertOp;
11826     SDValue ArgValue =
11827         getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, nullptr, NewRoot,
11828                          F.getCallingConv(), AssertOp);
11829 
11830     MachineFunction& MF = SDB->DAG.getMachineFunction();
11831     MachineRegisterInfo& RegInfo = MF.getRegInfo();
11832     Register SRetReg =
11833         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
11834     FuncInfo->DemoteRegister = SRetReg;
11835     NewRoot =
11836         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
11837     DAG.setRoot(NewRoot);
11838 
11839     // i indexes lowered arguments.  Bump it past the hidden sret argument.
11840     ++i;
11841   }
11842 
11843   SmallVector<SDValue, 4> Chains;
11844   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
11845   for (const Argument &Arg : F.args()) {
11846     SmallVector<SDValue, 4> ArgValues;
11847     SmallVector<EVT, 4> ValueVTs;
11848     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
11849     unsigned NumValues = ValueVTs.size();
11850     if (NumValues == 0)
11851       continue;
11852 
11853     bool ArgHasUses = !Arg.use_empty();
11854 
11855     // Elide the copying store if the target loaded this argument from a
11856     // suitable fixed stack object.
11857     if (Ins[i].Flags.isCopyElisionCandidate()) {
11858       unsigned NumParts = 0;
11859       for (EVT VT : ValueVTs)
11860         NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(),
11861                                                        F.getCallingConv(), VT);
11862 
11863       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
11864                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
11865                              ArrayRef(&InVals[i], NumParts), ArgHasUses);
11866     }
11867 
11868     // If this argument is unused then remember its value. It is used to generate
11869     // debugging information.
11870     bool isSwiftErrorArg =
11871         TLI->supportSwiftError() &&
11872         Arg.hasAttribute(Attribute::SwiftError);
11873     if (!ArgHasUses && !isSwiftErrorArg) {
11874       SDB->setUnusedArgValue(&Arg, InVals[i]);
11875 
11876       // Also remember any frame index for use in FastISel.
11877       if (FrameIndexSDNode *FI =
11878           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
11879         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11880     }
11881 
11882     for (unsigned Val = 0; Val != NumValues; ++Val) {
11883       EVT VT = ValueVTs[Val];
11884       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
11885                                                       F.getCallingConv(), VT);
11886       unsigned NumParts = TLI->getNumRegistersForCallingConv(
11887           *CurDAG->getContext(), F.getCallingConv(), VT);
11888 
11889       // Even an apparent 'unused' swifterror argument needs to be returned. So
11890       // we do generate a copy for it that can be used on return from the
11891       // function.
11892       if (ArgHasUses || isSwiftErrorArg) {
11893         std::optional<ISD::NodeType> AssertOp;
11894         if (Arg.hasAttribute(Attribute::SExt))
11895           AssertOp = ISD::AssertSext;
11896         else if (Arg.hasAttribute(Attribute::ZExt))
11897           AssertOp = ISD::AssertZext;
11898 
11899         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
11900                                              PartVT, VT, nullptr, NewRoot,
11901                                              F.getCallingConv(), AssertOp));
11902       }
11903 
11904       i += NumParts;
11905     }
11906 
11907     // We don't need to do anything else for unused arguments.
11908     if (ArgValues.empty())
11909       continue;
11910 
11911     // Note down frame index.
11912     if (FrameIndexSDNode *FI =
11913         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
11914       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11915 
11916     SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues),
11917                                      SDB->getCurSDLoc());
11918 
11919     SDB->setValue(&Arg, Res);
11920     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
11921       // We want to associate the argument with the frame index, among
11922       // involved operands, that correspond to the lowest address. The
11923       // getCopyFromParts function, called earlier, is swapping the order of
11924       // the operands to BUILD_PAIR depending on endianness. The result of
11925       // that swapping is that the least significant bits of the argument will
11926       // be in the first operand of the BUILD_PAIR node, and the most
11927       // significant bits will be in the second operand.
11928       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
11929       if (LoadSDNode *LNode =
11930           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
11931         if (FrameIndexSDNode *FI =
11932             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
11933           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11934     }
11935 
11936     // Analyses past this point are naive and don't expect an assertion.
11937     if (Res.getOpcode() == ISD::AssertZext)
11938       Res = Res.getOperand(0);
11939 
11940     // Update the SwiftErrorVRegDefMap.
11941     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
11942       Register Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11943       if (Reg.isVirtual())
11944         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
11945                                    Reg);
11946     }
11947 
11948     // If this argument is live outside of the entry block, insert a copy from
11949     // wherever we got it to the vreg that other BB's will reference it as.
11950     if (Res.getOpcode() == ISD::CopyFromReg) {
11951       // If we can, though, try to skip creating an unnecessary vreg.
11952       // FIXME: This isn't very clean... it would be nice to make this more
11953       // general.
11954       Register Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11955       if (Reg.isVirtual()) {
11956         FuncInfo->ValueMap[&Arg] = Reg;
11957         continue;
11958       }
11959     }
11960     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
11961       FuncInfo->InitializeRegForValue(&Arg);
11962       SDB->CopyToExportRegsIfNeeded(&Arg);
11963     }
11964   }
11965 
11966   if (!Chains.empty()) {
11967     Chains.push_back(NewRoot);
11968     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
11969   }
11970 
11971   DAG.setRoot(NewRoot);
11972 
11973   assert(i == InVals.size() && "Argument register count mismatch!");
11974 
11975   // If any argument copy elisions occurred and we have debug info, update the
11976   // stale frame indices used in the dbg.declare variable info table.
11977   if (!ArgCopyElisionFrameIndexMap.empty()) {
11978     for (MachineFunction::VariableDbgInfo &VI :
11979          MF->getInStackSlotVariableDbgInfo()) {
11980       auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot());
11981       if (I != ArgCopyElisionFrameIndexMap.end())
11982         VI.updateStackSlot(I->second);
11983     }
11984   }
11985 
11986   // Finally, if the target has anything special to do, allow it to do so.
11987   emitFunctionEntryCode();
11988 }
11989 
11990 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
11991 /// ensure constants are generated when needed.  Remember the virtual registers
11992 /// that need to be added to the Machine PHI nodes as input.  We cannot just
11993 /// directly add them, because expansion might result in multiple MBB's for one
11994 /// BB.  As such, the start of the BB might correspond to a different MBB than
11995 /// the end.
11996 void
11997 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
11998   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11999 
12000   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
12001 
12002   // Check PHI nodes in successors that expect a value to be available from this
12003   // block.
12004   for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
12005     if (!isa<PHINode>(SuccBB->begin())) continue;
12006     MachineBasicBlock *SuccMBB = FuncInfo.getMBB(SuccBB);
12007 
12008     // If this terminator has multiple identical successors (common for
12009     // switches), only handle each succ once.
12010     if (!SuccsHandled.insert(SuccMBB).second)
12011       continue;
12012 
12013     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
12014 
12015     // At this point we know that there is a 1-1 correspondence between LLVM PHI
12016     // nodes and Machine PHI nodes, but the incoming operands have not been
12017     // emitted yet.
12018     for (const PHINode &PN : SuccBB->phis()) {
12019       // Ignore dead phi's.
12020       if (PN.use_empty())
12021         continue;
12022 
12023       // Skip empty types
12024       if (PN.getType()->isEmptyTy())
12025         continue;
12026 
12027       unsigned Reg;
12028       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
12029 
12030       if (const auto *C = dyn_cast<Constant>(PHIOp)) {
12031         unsigned &RegOut = ConstantsOut[C];
12032         if (RegOut == 0) {
12033           RegOut = FuncInfo.CreateRegs(C);
12034           // We need to zero/sign extend ConstantInt phi operands to match
12035           // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
12036           ISD::NodeType ExtendType = ISD::ANY_EXTEND;
12037           if (auto *CI = dyn_cast<ConstantInt>(C))
12038             ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
12039                                                     : ISD::ZERO_EXTEND;
12040           CopyValueToVirtualRegister(C, RegOut, ExtendType);
12041         }
12042         Reg = RegOut;
12043       } else {
12044         DenseMap<const Value *, Register>::iterator I =
12045           FuncInfo.ValueMap.find(PHIOp);
12046         if (I != FuncInfo.ValueMap.end())
12047           Reg = I->second;
12048         else {
12049           assert(isa<AllocaInst>(PHIOp) &&
12050                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
12051                  "Didn't codegen value into a register!??");
12052           Reg = FuncInfo.CreateRegs(PHIOp);
12053           CopyValueToVirtualRegister(PHIOp, Reg);
12054         }
12055       }
12056 
12057       // Remember that this register needs to added to the machine PHI node as
12058       // the input for this MBB.
12059       SmallVector<EVT, 4> ValueVTs;
12060       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
12061       for (EVT VT : ValueVTs) {
12062         const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
12063         for (unsigned i = 0; i != NumRegisters; ++i)
12064           FuncInfo.PHINodesToUpdate.push_back(
12065               std::make_pair(&*MBBI++, Reg + i));
12066         Reg += NumRegisters;
12067       }
12068     }
12069   }
12070 
12071   ConstantsOut.clear();
12072 }
12073 
12074 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
12075   MachineFunction::iterator I(MBB);
12076   if (++I == FuncInfo.MF->end())
12077     return nullptr;
12078   return &*I;
12079 }
12080 
12081 /// During lowering new call nodes can be created (such as memset, etc.).
12082 /// Those will become new roots of the current DAG, but complications arise
12083 /// when they are tail calls. In such cases, the call lowering will update
12084 /// the root, but the builder still needs to know that a tail call has been
12085 /// lowered in order to avoid generating an additional return.
12086 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
12087   // If the node is null, we do have a tail call.
12088   if (MaybeTC.getNode() != nullptr)
12089     DAG.setRoot(MaybeTC);
12090   else
12091     HasTailCall = true;
12092 }
12093 
12094 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
12095                                         MachineBasicBlock *SwitchMBB,
12096                                         MachineBasicBlock *DefaultMBB) {
12097   MachineFunction *CurMF = FuncInfo.MF;
12098   MachineBasicBlock *NextMBB = nullptr;
12099   MachineFunction::iterator BBI(W.MBB);
12100   if (++BBI != FuncInfo.MF->end())
12101     NextMBB = &*BBI;
12102 
12103   unsigned Size = W.LastCluster - W.FirstCluster + 1;
12104 
12105   BranchProbabilityInfo *BPI = FuncInfo.BPI;
12106 
12107   if (Size == 2 && W.MBB == SwitchMBB) {
12108     // If any two of the cases has the same destination, and if one value
12109     // is the same as the other, but has one bit unset that the other has set,
12110     // use bit manipulation to do two compares at once.  For example:
12111     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
12112     // TODO: This could be extended to merge any 2 cases in switches with 3
12113     // cases.
12114     // TODO: Handle cases where W.CaseBB != SwitchBB.
12115     CaseCluster &Small = *W.FirstCluster;
12116     CaseCluster &Big = *W.LastCluster;
12117 
12118     if (Small.Low == Small.High && Big.Low == Big.High &&
12119         Small.MBB == Big.MBB) {
12120       const APInt &SmallValue = Small.Low->getValue();
12121       const APInt &BigValue = Big.Low->getValue();
12122 
12123       // Check that there is only one bit different.
12124       APInt CommonBit = BigValue ^ SmallValue;
12125       if (CommonBit.isPowerOf2()) {
12126         SDValue CondLHS = getValue(Cond);
12127         EVT VT = CondLHS.getValueType();
12128         SDLoc DL = getCurSDLoc();
12129 
12130         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
12131                                  DAG.getConstant(CommonBit, DL, VT));
12132         SDValue Cond = DAG.getSetCC(
12133             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
12134             ISD::SETEQ);
12135 
12136         // Update successor info.
12137         // Both Small and Big will jump to Small.BB, so we sum up the
12138         // probabilities.
12139         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
12140         if (BPI)
12141           addSuccessorWithProb(
12142               SwitchMBB, DefaultMBB,
12143               // The default destination is the first successor in IR.
12144               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
12145         else
12146           addSuccessorWithProb(SwitchMBB, DefaultMBB);
12147 
12148         // Insert the true branch.
12149         SDValue BrCond =
12150             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
12151                         DAG.getBasicBlock(Small.MBB));
12152         // Insert the false branch.
12153         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
12154                              DAG.getBasicBlock(DefaultMBB));
12155 
12156         DAG.setRoot(BrCond);
12157         return;
12158       }
12159     }
12160   }
12161 
12162   if (TM.getOptLevel() != CodeGenOptLevel::None) {
12163     // Here, we order cases by probability so the most likely case will be
12164     // checked first. However, two clusters can have the same probability in
12165     // which case their relative ordering is non-deterministic. So we use Low
12166     // as a tie-breaker as clusters are guaranteed to never overlap.
12167     llvm::sort(W.FirstCluster, W.LastCluster + 1,
12168                [](const CaseCluster &a, const CaseCluster &b) {
12169       return a.Prob != b.Prob ?
12170              a.Prob > b.Prob :
12171              a.Low->getValue().slt(b.Low->getValue());
12172     });
12173 
12174     // Rearrange the case blocks so that the last one falls through if possible
12175     // without changing the order of probabilities.
12176     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
12177       --I;
12178       if (I->Prob > W.LastCluster->Prob)
12179         break;
12180       if (I->Kind == CC_Range && I->MBB == NextMBB) {
12181         std::swap(*I, *W.LastCluster);
12182         break;
12183       }
12184     }
12185   }
12186 
12187   // Compute total probability.
12188   BranchProbability DefaultProb = W.DefaultProb;
12189   BranchProbability UnhandledProbs = DefaultProb;
12190   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
12191     UnhandledProbs += I->Prob;
12192 
12193   MachineBasicBlock *CurMBB = W.MBB;
12194   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
12195     bool FallthroughUnreachable = false;
12196     MachineBasicBlock *Fallthrough;
12197     if (I == W.LastCluster) {
12198       // For the last cluster, fall through to the default destination.
12199       Fallthrough = DefaultMBB;
12200       FallthroughUnreachable = isa<UnreachableInst>(
12201           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
12202     } else {
12203       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
12204       CurMF->insert(BBI, Fallthrough);
12205       // Put Cond in a virtual register to make it available from the new blocks.
12206       ExportFromCurrentBlock(Cond);
12207     }
12208     UnhandledProbs -= I->Prob;
12209 
12210     switch (I->Kind) {
12211       case CC_JumpTable: {
12212         // FIXME: Optimize away range check based on pivot comparisons.
12213         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
12214         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
12215 
12216         // The jump block hasn't been inserted yet; insert it here.
12217         MachineBasicBlock *JumpMBB = JT->MBB;
12218         CurMF->insert(BBI, JumpMBB);
12219 
12220         auto JumpProb = I->Prob;
12221         auto FallthroughProb = UnhandledProbs;
12222 
12223         // If the default statement is a target of the jump table, we evenly
12224         // distribute the default probability to successors of CurMBB. Also
12225         // update the probability on the edge from JumpMBB to Fallthrough.
12226         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
12227                                               SE = JumpMBB->succ_end();
12228              SI != SE; ++SI) {
12229           if (*SI == DefaultMBB) {
12230             JumpProb += DefaultProb / 2;
12231             FallthroughProb -= DefaultProb / 2;
12232             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
12233             JumpMBB->normalizeSuccProbs();
12234             break;
12235           }
12236         }
12237 
12238         // If the default clause is unreachable, propagate that knowledge into
12239         // JTH->FallthroughUnreachable which will use it to suppress the range
12240         // check.
12241         //
12242         // However, don't do this if we're doing branch target enforcement,
12243         // because a table branch _without_ a range check can be a tempting JOP
12244         // gadget - out-of-bounds inputs that are impossible in correct
12245         // execution become possible again if an attacker can influence the
12246         // control flow. So if an attacker doesn't already have a BTI bypass
12247         // available, we don't want them to be able to get one out of this
12248         // table branch.
12249         if (FallthroughUnreachable) {
12250           Function &CurFunc = CurMF->getFunction();
12251           if (!CurFunc.hasFnAttribute("branch-target-enforcement"))
12252             JTH->FallthroughUnreachable = true;
12253         }
12254 
12255         if (!JTH->FallthroughUnreachable)
12256           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
12257         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
12258         CurMBB->normalizeSuccProbs();
12259 
12260         // The jump table header will be inserted in our current block, do the
12261         // range check, and fall through to our fallthrough block.
12262         JTH->HeaderBB = CurMBB;
12263         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
12264 
12265         // If we're in the right place, emit the jump table header right now.
12266         if (CurMBB == SwitchMBB) {
12267           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
12268           JTH->Emitted = true;
12269         }
12270         break;
12271       }
12272       case CC_BitTests: {
12273         // FIXME: Optimize away range check based on pivot comparisons.
12274         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
12275 
12276         // The bit test blocks haven't been inserted yet; insert them here.
12277         for (BitTestCase &BTC : BTB->Cases)
12278           CurMF->insert(BBI, BTC.ThisBB);
12279 
12280         // Fill in fields of the BitTestBlock.
12281         BTB->Parent = CurMBB;
12282         BTB->Default = Fallthrough;
12283 
12284         BTB->DefaultProb = UnhandledProbs;
12285         // If the cases in bit test don't form a contiguous range, we evenly
12286         // distribute the probability on the edge to Fallthrough to two
12287         // successors of CurMBB.
12288         if (!BTB->ContiguousRange) {
12289           BTB->Prob += DefaultProb / 2;
12290           BTB->DefaultProb -= DefaultProb / 2;
12291         }
12292 
12293         if (FallthroughUnreachable)
12294           BTB->FallthroughUnreachable = true;
12295 
12296         // If we're in the right place, emit the bit test header right now.
12297         if (CurMBB == SwitchMBB) {
12298           visitBitTestHeader(*BTB, SwitchMBB);
12299           BTB->Emitted = true;
12300         }
12301         break;
12302       }
12303       case CC_Range: {
12304         const Value *RHS, *LHS, *MHS;
12305         ISD::CondCode CC;
12306         if (I->Low == I->High) {
12307           // Check Cond == I->Low.
12308           CC = ISD::SETEQ;
12309           LHS = Cond;
12310           RHS=I->Low;
12311           MHS = nullptr;
12312         } else {
12313           // Check I->Low <= Cond <= I->High.
12314           CC = ISD::SETLE;
12315           LHS = I->Low;
12316           MHS = Cond;
12317           RHS = I->High;
12318         }
12319 
12320         // If Fallthrough is unreachable, fold away the comparison.
12321         if (FallthroughUnreachable)
12322           CC = ISD::SETTRUE;
12323 
12324         // The false probability is the sum of all unhandled cases.
12325         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
12326                      getCurSDLoc(), I->Prob, UnhandledProbs);
12327 
12328         if (CurMBB == SwitchMBB)
12329           visitSwitchCase(CB, SwitchMBB);
12330         else
12331           SL->SwitchCases.push_back(CB);
12332 
12333         break;
12334       }
12335     }
12336     CurMBB = Fallthrough;
12337   }
12338 }
12339 
12340 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
12341                                         const SwitchWorkListItem &W,
12342                                         Value *Cond,
12343                                         MachineBasicBlock *SwitchMBB) {
12344   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
12345          "Clusters not sorted?");
12346   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
12347 
12348   auto [LastLeft, FirstRight, LeftProb, RightProb] =
12349       SL->computeSplitWorkItemInfo(W);
12350 
12351   // Use the first element on the right as pivot since we will make less-than
12352   // comparisons against it.
12353   CaseClusterIt PivotCluster = FirstRight;
12354   assert(PivotCluster > W.FirstCluster);
12355   assert(PivotCluster <= W.LastCluster);
12356 
12357   CaseClusterIt FirstLeft = W.FirstCluster;
12358   CaseClusterIt LastRight = W.LastCluster;
12359 
12360   const ConstantInt *Pivot = PivotCluster->Low;
12361 
12362   // New blocks will be inserted immediately after the current one.
12363   MachineFunction::iterator BBI(W.MBB);
12364   ++BBI;
12365 
12366   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
12367   // we can branch to its destination directly if it's squeezed exactly in
12368   // between the known lower bound and Pivot - 1.
12369   MachineBasicBlock *LeftMBB;
12370   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
12371       FirstLeft->Low == W.GE &&
12372       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
12373     LeftMBB = FirstLeft->MBB;
12374   } else {
12375     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12376     FuncInfo.MF->insert(BBI, LeftMBB);
12377     WorkList.push_back(
12378         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
12379     // Put Cond in a virtual register to make it available from the new blocks.
12380     ExportFromCurrentBlock(Cond);
12381   }
12382 
12383   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
12384   // single cluster, RHS.Low == Pivot, and we can branch to its destination
12385   // directly if RHS.High equals the current upper bound.
12386   MachineBasicBlock *RightMBB;
12387   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
12388       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
12389     RightMBB = FirstRight->MBB;
12390   } else {
12391     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12392     FuncInfo.MF->insert(BBI, RightMBB);
12393     WorkList.push_back(
12394         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
12395     // Put Cond in a virtual register to make it available from the new blocks.
12396     ExportFromCurrentBlock(Cond);
12397   }
12398 
12399   // Create the CaseBlock record that will be used to lower the branch.
12400   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
12401                getCurSDLoc(), LeftProb, RightProb);
12402 
12403   if (W.MBB == SwitchMBB)
12404     visitSwitchCase(CB, SwitchMBB);
12405   else
12406     SL->SwitchCases.push_back(CB);
12407 }
12408 
12409 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
12410 // from the swith statement.
12411 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
12412                                             BranchProbability PeeledCaseProb) {
12413   if (PeeledCaseProb == BranchProbability::getOne())
12414     return BranchProbability::getZero();
12415   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
12416 
12417   uint32_t Numerator = CaseProb.getNumerator();
12418   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
12419   return BranchProbability(Numerator, std::max(Numerator, Denominator));
12420 }
12421 
12422 // Try to peel the top probability case if it exceeds the threshold.
12423 // Return current MachineBasicBlock for the switch statement if the peeling
12424 // does not occur.
12425 // If the peeling is performed, return the newly created MachineBasicBlock
12426 // for the peeled switch statement. Also update Clusters to remove the peeled
12427 // case. PeeledCaseProb is the BranchProbability for the peeled case.
12428 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
12429     const SwitchInst &SI, CaseClusterVector &Clusters,
12430     BranchProbability &PeeledCaseProb) {
12431   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12432   // Don't perform if there is only one cluster or optimizing for size.
12433   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
12434       TM.getOptLevel() == CodeGenOptLevel::None ||
12435       SwitchMBB->getParent()->getFunction().hasMinSize())
12436     return SwitchMBB;
12437 
12438   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
12439   unsigned PeeledCaseIndex = 0;
12440   bool SwitchPeeled = false;
12441   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
12442     CaseCluster &CC = Clusters[Index];
12443     if (CC.Prob < TopCaseProb)
12444       continue;
12445     TopCaseProb = CC.Prob;
12446     PeeledCaseIndex = Index;
12447     SwitchPeeled = true;
12448   }
12449   if (!SwitchPeeled)
12450     return SwitchMBB;
12451 
12452   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
12453                     << TopCaseProb << "\n");
12454 
12455   // Record the MBB for the peeled switch statement.
12456   MachineFunction::iterator BBI(SwitchMBB);
12457   ++BBI;
12458   MachineBasicBlock *PeeledSwitchMBB =
12459       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
12460   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
12461 
12462   ExportFromCurrentBlock(SI.getCondition());
12463   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
12464   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
12465                           nullptr,   nullptr,      TopCaseProb.getCompl()};
12466   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
12467 
12468   Clusters.erase(PeeledCaseIt);
12469   for (CaseCluster &CC : Clusters) {
12470     LLVM_DEBUG(
12471         dbgs() << "Scale the probablity for one cluster, before scaling: "
12472                << CC.Prob << "\n");
12473     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
12474     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
12475   }
12476   PeeledCaseProb = TopCaseProb;
12477   return PeeledSwitchMBB;
12478 }
12479 
12480 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
12481   // Extract cases from the switch.
12482   BranchProbabilityInfo *BPI = FuncInfo.BPI;
12483   CaseClusterVector Clusters;
12484   Clusters.reserve(SI.getNumCases());
12485   for (auto I : SI.cases()) {
12486     MachineBasicBlock *Succ = FuncInfo.getMBB(I.getCaseSuccessor());
12487     const ConstantInt *CaseVal = I.getCaseValue();
12488     BranchProbability Prob =
12489         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
12490             : BranchProbability(1, SI.getNumCases() + 1);
12491     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
12492   }
12493 
12494   MachineBasicBlock *DefaultMBB = FuncInfo.getMBB(SI.getDefaultDest());
12495 
12496   // Cluster adjacent cases with the same destination. We do this at all
12497   // optimization levels because it's cheap to do and will make codegen faster
12498   // if there are many clusters.
12499   sortAndRangeify(Clusters);
12500 
12501   // The branch probablity of the peeled case.
12502   BranchProbability PeeledCaseProb = BranchProbability::getZero();
12503   MachineBasicBlock *PeeledSwitchMBB =
12504       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
12505 
12506   // If there is only the default destination, jump there directly.
12507   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12508   if (Clusters.empty()) {
12509     assert(PeeledSwitchMBB == SwitchMBB);
12510     SwitchMBB->addSuccessor(DefaultMBB);
12511     if (DefaultMBB != NextBlock(SwitchMBB)) {
12512       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
12513                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
12514     }
12515     return;
12516   }
12517 
12518   SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(),
12519                      DAG.getBFI());
12520   SL->findBitTestClusters(Clusters, &SI);
12521 
12522   LLVM_DEBUG({
12523     dbgs() << "Case clusters: ";
12524     for (const CaseCluster &C : Clusters) {
12525       if (C.Kind == CC_JumpTable)
12526         dbgs() << "JT:";
12527       if (C.Kind == CC_BitTests)
12528         dbgs() << "BT:";
12529 
12530       C.Low->getValue().print(dbgs(), true);
12531       if (C.Low != C.High) {
12532         dbgs() << '-';
12533         C.High->getValue().print(dbgs(), true);
12534       }
12535       dbgs() << ' ';
12536     }
12537     dbgs() << '\n';
12538   });
12539 
12540   assert(!Clusters.empty());
12541   SwitchWorkList WorkList;
12542   CaseClusterIt First = Clusters.begin();
12543   CaseClusterIt Last = Clusters.end() - 1;
12544   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
12545   // Scale the branchprobability for DefaultMBB if the peel occurs and
12546   // DefaultMBB is not replaced.
12547   if (PeeledCaseProb != BranchProbability::getZero() &&
12548       DefaultMBB == FuncInfo.getMBB(SI.getDefaultDest()))
12549     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
12550   WorkList.push_back(
12551       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
12552 
12553   while (!WorkList.empty()) {
12554     SwitchWorkListItem W = WorkList.pop_back_val();
12555     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
12556 
12557     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None &&
12558         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
12559       // For optimized builds, lower large range as a balanced binary tree.
12560       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
12561       continue;
12562     }
12563 
12564     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
12565   }
12566 }
12567 
12568 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
12569   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12570   auto DL = getCurSDLoc();
12571   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12572   setValue(&I, DAG.getStepVector(DL, ResultVT));
12573 }
12574 
12575 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
12576   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12577   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12578 
12579   SDLoc DL = getCurSDLoc();
12580   SDValue V = getValue(I.getOperand(0));
12581   assert(VT == V.getValueType() && "Malformed vector.reverse!");
12582 
12583   if (VT.isScalableVector()) {
12584     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
12585     return;
12586   }
12587 
12588   // Use VECTOR_SHUFFLE for the fixed-length vector
12589   // to maintain existing behavior.
12590   SmallVector<int, 8> Mask;
12591   unsigned NumElts = VT.getVectorMinNumElements();
12592   for (unsigned i = 0; i != NumElts; ++i)
12593     Mask.push_back(NumElts - 1 - i);
12594 
12595   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
12596 }
12597 
12598 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) {
12599   auto DL = getCurSDLoc();
12600   SDValue InVec = getValue(I.getOperand(0));
12601   EVT OutVT =
12602       InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
12603 
12604   unsigned OutNumElts = OutVT.getVectorMinNumElements();
12605 
12606   // ISD Node needs the input vectors split into two equal parts
12607   SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
12608                            DAG.getVectorIdxConstant(0, DL));
12609   SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
12610                            DAG.getVectorIdxConstant(OutNumElts, DL));
12611 
12612   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
12613   // legalisation and combines.
12614   if (OutVT.isFixedLengthVector()) {
12615     SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
12616                                         createStrideMask(0, 2, OutNumElts));
12617     SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
12618                                        createStrideMask(1, 2, OutNumElts));
12619     SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc());
12620     setValue(&I, Res);
12621     return;
12622   }
12623 
12624   SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL,
12625                             DAG.getVTList(OutVT, OutVT), Lo, Hi);
12626   setValue(&I, Res);
12627 }
12628 
12629 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) {
12630   auto DL = getCurSDLoc();
12631   EVT InVT = getValue(I.getOperand(0)).getValueType();
12632   SDValue InVec0 = getValue(I.getOperand(0));
12633   SDValue InVec1 = getValue(I.getOperand(1));
12634   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12635   EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12636 
12637   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
12638   // legalisation and combines.
12639   if (OutVT.isFixedLengthVector()) {
12640     unsigned NumElts = InVT.getVectorMinNumElements();
12641     SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1);
12642     setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT),
12643                                       createInterleaveMask(NumElts, 2)));
12644     return;
12645   }
12646 
12647   SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL,
12648                             DAG.getVTList(InVT, InVT), InVec0, InVec1);
12649   Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0),
12650                     Res.getValue(1));
12651   setValue(&I, Res);
12652 }
12653 
12654 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
12655   SmallVector<EVT, 4> ValueVTs;
12656   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
12657                   ValueVTs);
12658   unsigned NumValues = ValueVTs.size();
12659   if (NumValues == 0) return;
12660 
12661   SmallVector<SDValue, 4> Values(NumValues);
12662   SDValue Op = getValue(I.getOperand(0));
12663 
12664   for (unsigned i = 0; i != NumValues; ++i)
12665     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
12666                             SDValue(Op.getNode(), Op.getResNo() + i));
12667 
12668   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12669                            DAG.getVTList(ValueVTs), Values));
12670 }
12671 
12672 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
12673   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12674   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12675 
12676   SDLoc DL = getCurSDLoc();
12677   SDValue V1 = getValue(I.getOperand(0));
12678   SDValue V2 = getValue(I.getOperand(1));
12679   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
12680 
12681   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
12682   if (VT.isScalableVector()) {
12683     setValue(
12684         &I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
12685                         DAG.getSignedConstant(
12686                             Imm, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))));
12687     return;
12688   }
12689 
12690   unsigned NumElts = VT.getVectorNumElements();
12691 
12692   uint64_t Idx = (NumElts + Imm) % NumElts;
12693 
12694   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
12695   SmallVector<int, 8> Mask;
12696   for (unsigned i = 0; i < NumElts; ++i)
12697     Mask.push_back(Idx + i);
12698   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
12699 }
12700 
12701 // Consider the following MIR after SelectionDAG, which produces output in
12702 // phyregs in the first case or virtregs in the second case.
12703 //
12704 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx
12705 // %5:gr32 = COPY $ebx
12706 // %6:gr32 = COPY $edx
12707 // %1:gr32 = COPY %6:gr32
12708 // %0:gr32 = COPY %5:gr32
12709 //
12710 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32
12711 // %1:gr32 = COPY %6:gr32
12712 // %0:gr32 = COPY %5:gr32
12713 //
12714 // Given %0, we'd like to return $ebx in the first case and %5 in the second.
12715 // Given %1, we'd like to return $edx in the first case and %6 in the second.
12716 //
12717 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap
12718 // to a single virtreg (such as %0). The remaining outputs monotonically
12719 // increase in virtreg number from there. If a callbr has no outputs, then it
12720 // should not have a corresponding callbr landingpad; in fact, the callbr
12721 // landingpad would not even be able to refer to such a callbr.
12722 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) {
12723   MachineInstr *MI = MRI.def_begin(Reg)->getParent();
12724   // There is definitely at least one copy.
12725   assert(MI->getOpcode() == TargetOpcode::COPY &&
12726          "start of copy chain MUST be COPY");
12727   Reg = MI->getOperand(1).getReg();
12728   MI = MRI.def_begin(Reg)->getParent();
12729   // There may be an optional second copy.
12730   if (MI->getOpcode() == TargetOpcode::COPY) {
12731     assert(Reg.isVirtual() && "expected COPY of virtual register");
12732     Reg = MI->getOperand(1).getReg();
12733     assert(Reg.isPhysical() && "expected COPY of physical register");
12734     MI = MRI.def_begin(Reg)->getParent();
12735   }
12736   // The start of the chain must be an INLINEASM_BR.
12737   assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR &&
12738          "end of copy chain MUST be INLINEASM_BR");
12739   return Reg;
12740 }
12741 
12742 // We must do this walk rather than the simpler
12743 //   setValue(&I, getCopyFromRegs(CBR, CBR->getType()));
12744 // otherwise we will end up with copies of virtregs only valid along direct
12745 // edges.
12746 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) {
12747   SmallVector<EVT, 8> ResultVTs;
12748   SmallVector<SDValue, 8> ResultValues;
12749   const auto *CBR =
12750       cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator());
12751 
12752   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12753   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
12754   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
12755 
12756   unsigned InitialDef = FuncInfo.ValueMap[CBR];
12757   SDValue Chain = DAG.getRoot();
12758 
12759   // Re-parse the asm constraints string.
12760   TargetLowering::AsmOperandInfoVector TargetConstraints =
12761       TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR);
12762   for (auto &T : TargetConstraints) {
12763     SDISelAsmOperandInfo OpInfo(T);
12764     if (OpInfo.Type != InlineAsm::isOutput)
12765       continue;
12766 
12767     // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the
12768     // individual constraint.
12769     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
12770 
12771     switch (OpInfo.ConstraintType) {
12772     case TargetLowering::C_Register:
12773     case TargetLowering::C_RegisterClass: {
12774       // Fill in OpInfo.AssignedRegs.Regs.
12775       getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo);
12776 
12777       // getRegistersForValue may produce 1 to many registers based on whether
12778       // the OpInfo.ConstraintVT is legal on the target or not.
12779       for (Register &Reg : OpInfo.AssignedRegs.Regs) {
12780         Register OriginalDef = FollowCopyChain(MRI, InitialDef++);
12781         if (Register::isPhysicalRegister(OriginalDef))
12782           FuncInfo.MBB->addLiveIn(OriginalDef);
12783         // Update the assigned registers to use the original defs.
12784         Reg = OriginalDef;
12785       }
12786 
12787       SDValue V = OpInfo.AssignedRegs.getCopyFromRegs(
12788           DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR);
12789       ResultValues.push_back(V);
12790       ResultVTs.push_back(OpInfo.ConstraintVT);
12791       break;
12792     }
12793     case TargetLowering::C_Other: {
12794       SDValue Flag;
12795       SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
12796                                                   OpInfo, DAG);
12797       ++InitialDef;
12798       ResultValues.push_back(V);
12799       ResultVTs.push_back(OpInfo.ConstraintVT);
12800       break;
12801     }
12802     default:
12803       break;
12804     }
12805   }
12806   SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12807                           DAG.getVTList(ResultVTs), ResultValues);
12808   setValue(&I, V);
12809 }
12810