xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 8c1b7fba1fbe9729d6258127b633bd05339e766b)
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/ValueTracking.h"
30 #include "llvm/Analysis/VectorUtils.h"
31 #include "llvm/CodeGen/Analysis.h"
32 #include "llvm/CodeGen/AssignmentTrackingAnalysis.h"
33 #include "llvm/CodeGen/CodeGenCommonISel.h"
34 #include "llvm/CodeGen/FunctionLoweringInfo.h"
35 #include "llvm/CodeGen/GCMetadata.h"
36 #include "llvm/CodeGen/ISDOpcodes.h"
37 #include "llvm/CodeGen/MachineBasicBlock.h"
38 #include "llvm/CodeGen/MachineFrameInfo.h"
39 #include "llvm/CodeGen/MachineFunction.h"
40 #include "llvm/CodeGen/MachineInstrBuilder.h"
41 #include "llvm/CodeGen/MachineInstrBundleIterator.h"
42 #include "llvm/CodeGen/MachineMemOperand.h"
43 #include "llvm/CodeGen/MachineModuleInfo.h"
44 #include "llvm/CodeGen/MachineOperand.h"
45 #include "llvm/CodeGen/MachineRegisterInfo.h"
46 #include "llvm/CodeGen/RuntimeLibcalls.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/Metadata.h"
83 #include "llvm/IR/Module.h"
84 #include "llvm/IR/Operator.h"
85 #include "llvm/IR/PatternMatch.h"
86 #include "llvm/IR/Statepoint.h"
87 #include "llvm/IR/Type.h"
88 #include "llvm/IR/User.h"
89 #include "llvm/IR/Value.h"
90 #include "llvm/MC/MCContext.h"
91 #include "llvm/Support/AtomicOrdering.h"
92 #include "llvm/Support/Casting.h"
93 #include "llvm/Support/CommandLine.h"
94 #include "llvm/Support/Compiler.h"
95 #include "llvm/Support/Debug.h"
96 #include "llvm/Support/MathExtras.h"
97 #include "llvm/Support/raw_ostream.h"
98 #include "llvm/Target/TargetIntrinsicInfo.h"
99 #include "llvm/Target/TargetMachine.h"
100 #include "llvm/Target/TargetOptions.h"
101 #include "llvm/TargetParser/Triple.h"
102 #include "llvm/Transforms/Utils/Local.h"
103 #include <cstddef>
104 #include <iterator>
105 #include <limits>
106 #include <optional>
107 #include <tuple>
108 
109 using namespace llvm;
110 using namespace PatternMatch;
111 using namespace SwitchCG;
112 
113 #define DEBUG_TYPE "isel"
114 
115 /// LimitFloatPrecision - Generate low-precision inline sequences for
116 /// some float libcalls (6, 8 or 12 bits).
117 static unsigned LimitFloatPrecision;
118 
119 static cl::opt<bool>
120     InsertAssertAlign("insert-assert-align", cl::init(true),
121                       cl::desc("Insert the experimental `assertalign` node."),
122                       cl::ReallyHidden);
123 
124 static cl::opt<unsigned, true>
125     LimitFPPrecision("limit-float-precision",
126                      cl::desc("Generate low-precision inline sequences "
127                               "for some float libcalls"),
128                      cl::location(LimitFloatPrecision), cl::Hidden,
129                      cl::init(0));
130 
131 static cl::opt<unsigned> SwitchPeelThreshold(
132     "switch-peel-threshold", cl::Hidden, cl::init(66),
133     cl::desc("Set the case probability threshold for peeling the case from a "
134              "switch statement. A value greater than 100 will void this "
135              "optimization"));
136 
137 // Limit the width of DAG chains. This is important in general to prevent
138 // DAG-based analysis from blowing up. For example, alias analysis and
139 // load clustering may not complete in reasonable time. It is difficult to
140 // recognize and avoid this situation within each individual analysis, and
141 // future analyses are likely to have the same behavior. Limiting DAG width is
142 // the safe approach and will be especially important with global DAGs.
143 //
144 // MaxParallelChains default is arbitrarily high to avoid affecting
145 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
146 // sequence over this should have been converted to llvm.memcpy by the
147 // frontend. It is easy to induce this behavior with .ll code such as:
148 // %buffer = alloca [4096 x i8]
149 // %data = load [4096 x i8]* %argPtr
150 // store [4096 x i8] %data, [4096 x i8]* %buffer
151 static const unsigned MaxParallelChains = 64;
152 
153 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
154                                       const SDValue *Parts, unsigned NumParts,
155                                       MVT PartVT, EVT ValueVT, const Value *V,
156                                       SDValue InChain,
157                                       std::optional<CallingConv::ID> CC);
158 
159 /// getCopyFromParts - Create a value that contains the specified legal parts
160 /// combined into the value they represent.  If the parts combine to a type
161 /// larger than ValueVT then AssertOp can be used to specify whether the extra
162 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
163 /// (ISD::AssertSext).
164 static SDValue
165 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts,
166                  unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V,
167                  SDValue InChain,
168                  std::optional<CallingConv::ID> CC = std::nullopt,
169                  std::optional<ISD::NodeType> AssertOp = std::nullopt) {
170   // Let the target assemble the parts if it wants to
171   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
172   if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
173                                                    PartVT, ValueVT, CC))
174     return Val;
175 
176   if (ValueVT.isVector())
177     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
178                                   InChain, CC);
179 
180   assert(NumParts > 0 && "No parts to assemble!");
181   SDValue Val = Parts[0];
182 
183   if (NumParts > 1) {
184     // Assemble the value from multiple parts.
185     if (ValueVT.isInteger()) {
186       unsigned PartBits = PartVT.getSizeInBits();
187       unsigned ValueBits = ValueVT.getSizeInBits();
188 
189       // Assemble the power of 2 part.
190       unsigned RoundParts = llvm::bit_floor(NumParts);
191       unsigned RoundBits = PartBits * RoundParts;
192       EVT RoundVT = RoundBits == ValueBits ?
193         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
194       SDValue Lo, Hi;
195 
196       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
197 
198       if (RoundParts > 2) {
199         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, PartVT, HalfVT, V,
200                               InChain);
201         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, RoundParts / 2,
202                               PartVT, HalfVT, V, InChain);
203       } else {
204         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
205         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
206       }
207 
208       if (DAG.getDataLayout().isBigEndian())
209         std::swap(Lo, Hi);
210 
211       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
212 
213       if (RoundParts < NumParts) {
214         // Assemble the trailing non-power-of-2 part.
215         unsigned OddParts = NumParts - RoundParts;
216         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
217         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
218                               OddVT, V, InChain, CC);
219 
220         // Combine the round and odd parts.
221         Lo = Val;
222         if (DAG.getDataLayout().isBigEndian())
223           std::swap(Lo, Hi);
224         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
225         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
226         Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
227                          DAG.getConstant(Lo.getValueSizeInBits(), DL,
228                                          TLI.getShiftAmountTy(
229                                              TotalVT, DAG.getDataLayout())));
230         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
231         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
232       }
233     } else if (PartVT.isFloatingPoint()) {
234       // FP split into multiple FP parts (for ppcf128)
235       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
236              "Unexpected split");
237       SDValue Lo, Hi;
238       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
239       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
240       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
241         std::swap(Lo, Hi);
242       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
243     } else {
244       // FP split into integer parts (soft fp)
245       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
246              !PartVT.isVector() && "Unexpected split");
247       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
248       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V,
249                              InChain, CC);
250     }
251   }
252 
253   // There is now one part, held in Val.  Correct it to match ValueVT.
254   // PartEVT is the type of the register class that holds the value.
255   // ValueVT is the type of the inline asm operation.
256   EVT PartEVT = Val.getValueType();
257 
258   if (PartEVT == ValueVT)
259     return Val;
260 
261   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
262       ValueVT.bitsLT(PartEVT)) {
263     // For an FP value in an integer part, we need to truncate to the right
264     // width first.
265     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
266     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
267   }
268 
269   // Handle types that have the same size.
270   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
271     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
272 
273   // Handle types with different sizes.
274   if (PartEVT.isInteger() && ValueVT.isInteger()) {
275     if (ValueVT.bitsLT(PartEVT)) {
276       // For a truncate, see if we have any information to
277       // indicate whether the truncated bits will always be
278       // zero or sign-extension.
279       if (AssertOp)
280         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
281                           DAG.getValueType(ValueVT));
282       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
283     }
284     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
285   }
286 
287   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
288     // FP_ROUND's are always exact here.
289     if (ValueVT.bitsLT(Val.getValueType())) {
290 
291       SDValue NoChange =
292           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
293 
294       if (DAG.getMachineFunction().getFunction().getAttributes().hasFnAttr(
295               llvm::Attribute::StrictFP)) {
296         return DAG.getNode(ISD::STRICT_FP_ROUND, DL,
297                            DAG.getVTList(ValueVT, MVT::Other), InChain, Val,
298                            NoChange);
299       }
300 
301       return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val, NoChange);
302     }
303 
304     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
305   }
306 
307   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
308   // then truncating.
309   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
310       ValueVT.bitsLT(PartEVT)) {
311     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
312     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
313   }
314 
315   report_fatal_error("Unknown mismatch in getCopyFromParts!");
316 }
317 
318 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
319                                               const Twine &ErrMsg) {
320   const Instruction *I = dyn_cast_or_null<Instruction>(V);
321   if (!V)
322     return Ctx.emitError(ErrMsg);
323 
324   const char *AsmError = ", possible invalid constraint for vector type";
325   if (const CallInst *CI = dyn_cast<CallInst>(I))
326     if (CI->isInlineAsm())
327       return Ctx.emitError(I, ErrMsg + AsmError);
328 
329   return Ctx.emitError(I, ErrMsg);
330 }
331 
332 /// getCopyFromPartsVector - Create a value that contains the specified legal
333 /// parts combined into the value they represent.  If the parts combine to a
334 /// type larger than ValueVT then AssertOp can be used to specify whether the
335 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
336 /// ValueVT (ISD::AssertSext).
337 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
338                                       const SDValue *Parts, unsigned NumParts,
339                                       MVT PartVT, EVT ValueVT, const Value *V,
340                                       SDValue InChain,
341                                       std::optional<CallingConv::ID> CallConv) {
342   assert(ValueVT.isVector() && "Not a vector value");
343   assert(NumParts > 0 && "No parts to assemble!");
344   const bool IsABIRegCopy = CallConv.has_value();
345 
346   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
347   SDValue Val = Parts[0];
348 
349   // Handle a multi-element vector.
350   if (NumParts > 1) {
351     EVT IntermediateVT;
352     MVT RegisterVT;
353     unsigned NumIntermediates;
354     unsigned NumRegs;
355 
356     if (IsABIRegCopy) {
357       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
358           *DAG.getContext(), *CallConv, ValueVT, IntermediateVT,
359           NumIntermediates, RegisterVT);
360     } else {
361       NumRegs =
362           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
363                                      NumIntermediates, RegisterVT);
364     }
365 
366     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
367     NumParts = NumRegs; // Silence a compiler warning.
368     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
369     assert(RegisterVT.getSizeInBits() ==
370            Parts[0].getSimpleValueType().getSizeInBits() &&
371            "Part type sizes don't match!");
372 
373     // Assemble the parts into intermediate operands.
374     SmallVector<SDValue, 8> Ops(NumIntermediates);
375     if (NumIntermediates == NumParts) {
376       // If the register was not expanded, truncate or copy the value,
377       // as appropriate.
378       for (unsigned i = 0; i != NumParts; ++i)
379         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, PartVT, IntermediateVT,
380                                   V, InChain, CallConv);
381     } else if (NumParts > 0) {
382       // If the intermediate type was expanded, build the intermediate
383       // operands from the parts.
384       assert(NumParts % NumIntermediates == 0 &&
385              "Must expand into a divisible number of parts!");
386       unsigned Factor = NumParts / NumIntermediates;
387       for (unsigned i = 0; i != NumIntermediates; ++i)
388         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, PartVT,
389                                   IntermediateVT, V, InChain, CallConv);
390     }
391 
392     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
393     // intermediate operands.
394     EVT BuiltVectorTy =
395         IntermediateVT.isVector()
396             ? EVT::getVectorVT(
397                   *DAG.getContext(), IntermediateVT.getScalarType(),
398                   IntermediateVT.getVectorElementCount() * NumParts)
399             : EVT::getVectorVT(*DAG.getContext(),
400                                IntermediateVT.getScalarType(),
401                                NumIntermediates);
402     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
403                                                 : ISD::BUILD_VECTOR,
404                       DL, BuiltVectorTy, Ops);
405   }
406 
407   // There is now one part, held in Val.  Correct it to match ValueVT.
408   EVT PartEVT = Val.getValueType();
409 
410   if (PartEVT == ValueVT)
411     return Val;
412 
413   if (PartEVT.isVector()) {
414     // Vector/Vector bitcast.
415     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
416       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
417 
418     // If the parts vector has more elements than the value vector, then we
419     // have a vector widening case (e.g. <2 x float> -> <4 x float>).
420     // Extract the elements we want.
421     if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
422       assert((PartEVT.getVectorElementCount().getKnownMinValue() >
423               ValueVT.getVectorElementCount().getKnownMinValue()) &&
424              (PartEVT.getVectorElementCount().isScalable() ==
425               ValueVT.getVectorElementCount().isScalable()) &&
426              "Cannot narrow, it would be a lossy transformation");
427       PartEVT =
428           EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(),
429                            ValueVT.getVectorElementCount());
430       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val,
431                         DAG.getVectorIdxConstant(0, DL));
432       if (PartEVT == ValueVT)
433         return Val;
434       if (PartEVT.isInteger() && ValueVT.isFloatingPoint())
435         return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
436 
437       // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>).
438       if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
439         return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
440     }
441 
442     // Promoted vector extract
443     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
444   }
445 
446   // Trivial bitcast if the types are the same size and the destination
447   // vector type is legal.
448   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
449       TLI.isTypeLegal(ValueVT))
450     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
451 
452   if (ValueVT.getVectorNumElements() != 1) {
453      // Certain ABIs require that vectors are passed as integers. For vectors
454      // are the same size, this is an obvious bitcast.
455      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
456        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
457      } else if (ValueVT.bitsLT(PartEVT)) {
458        const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
459        EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
460        // Drop the extra bits.
461        Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
462        return DAG.getBitcast(ValueVT, Val);
463      }
464 
465      diagnosePossiblyInvalidConstraint(
466          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
467      return DAG.getUNDEF(ValueVT);
468   }
469 
470   // Handle cases such as i8 -> <1 x i1>
471   EVT ValueSVT = ValueVT.getVectorElementType();
472   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
473     unsigned ValueSize = ValueSVT.getSizeInBits();
474     if (ValueSize == PartEVT.getSizeInBits()) {
475       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
476     } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) {
477       // It's possible a scalar floating point type gets softened to integer and
478       // then promoted to a larger integer. If PartEVT is the larger integer
479       // we need to truncate it and then bitcast to the FP type.
480       assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types");
481       EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
482       Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
483       Val = DAG.getBitcast(ValueSVT, Val);
484     } else {
485       Val = ValueVT.isFloatingPoint()
486                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
487                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
488     }
489   }
490 
491   return DAG.getBuildVector(ValueVT, DL, Val);
492 }
493 
494 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
495                                  SDValue Val, SDValue *Parts, unsigned NumParts,
496                                  MVT PartVT, const Value *V,
497                                  std::optional<CallingConv::ID> CallConv);
498 
499 /// getCopyToParts - Create a series of nodes that contain the specified value
500 /// split into legal parts.  If the parts contain more bits than Val, then, for
501 /// integers, ExtendKind can be used to specify how to generate the extra bits.
502 static void
503 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
504                unsigned NumParts, MVT PartVT, const Value *V,
505                std::optional<CallingConv::ID> CallConv = std::nullopt,
506                ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
507   // Let the target split the parts if it wants to
508   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
509   if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
510                                       CallConv))
511     return;
512   EVT ValueVT = Val.getValueType();
513 
514   // Handle the vector case separately.
515   if (ValueVT.isVector())
516     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
517                                 CallConv);
518 
519   unsigned OrigNumParts = NumParts;
520   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
521          "Copying to an illegal type!");
522 
523   if (NumParts == 0)
524     return;
525 
526   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
527   EVT PartEVT = PartVT;
528   if (PartEVT == ValueVT) {
529     assert(NumParts == 1 && "No-op copy with multiple parts!");
530     Parts[0] = Val;
531     return;
532   }
533 
534   unsigned PartBits = PartVT.getSizeInBits();
535   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
536     // If the parts cover more bits than the value has, promote the value.
537     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
538       assert(NumParts == 1 && "Do not know what to promote to!");
539       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
540     } else {
541       if (ValueVT.isFloatingPoint()) {
542         // FP values need to be bitcast, then extended if they are being put
543         // into a larger container.
544         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
545         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
546       }
547       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
548              ValueVT.isInteger() &&
549              "Unknown mismatch!");
550       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
551       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
552       if (PartVT == MVT::x86mmx)
553         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
554     }
555   } else if (PartBits == ValueVT.getSizeInBits()) {
556     // Different types of the same size.
557     assert(NumParts == 1 && PartEVT != ValueVT);
558     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
559   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
560     // If the parts cover less bits than value has, truncate the value.
561     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
562            ValueVT.isInteger() &&
563            "Unknown mismatch!");
564     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
565     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
566     if (PartVT == MVT::x86mmx)
567       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
568   }
569 
570   // The value may have changed - recompute ValueVT.
571   ValueVT = Val.getValueType();
572   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
573          "Failed to tile the value with PartVT!");
574 
575   if (NumParts == 1) {
576     if (PartEVT != ValueVT) {
577       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
578                                         "scalar-to-vector conversion failed");
579       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
580     }
581 
582     Parts[0] = Val;
583     return;
584   }
585 
586   // Expand the value into multiple parts.
587   if (NumParts & (NumParts - 1)) {
588     // The number of parts is not a power of 2.  Split off and copy the tail.
589     assert(PartVT.isInteger() && ValueVT.isInteger() &&
590            "Do not know what to expand to!");
591     unsigned RoundParts = llvm::bit_floor(NumParts);
592     unsigned RoundBits = RoundParts * PartBits;
593     unsigned OddParts = NumParts - RoundParts;
594     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
595       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL));
596 
597     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
598                    CallConv);
599 
600     if (DAG.getDataLayout().isBigEndian())
601       // The odd parts were reversed by getCopyToParts - unreverse them.
602       std::reverse(Parts + RoundParts, Parts + NumParts);
603 
604     NumParts = RoundParts;
605     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
606     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
607   }
608 
609   // The number of parts is a power of 2.  Repeatedly bisect the value using
610   // EXTRACT_ELEMENT.
611   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
612                          EVT::getIntegerVT(*DAG.getContext(),
613                                            ValueVT.getSizeInBits()),
614                          Val);
615 
616   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
617     for (unsigned i = 0; i < NumParts; i += StepSize) {
618       unsigned ThisBits = StepSize * PartBits / 2;
619       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
620       SDValue &Part0 = Parts[i];
621       SDValue &Part1 = Parts[i+StepSize/2];
622 
623       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
624                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
625       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
626                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
627 
628       if (ThisBits == PartBits && ThisVT != PartVT) {
629         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
630         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
631       }
632     }
633   }
634 
635   if (DAG.getDataLayout().isBigEndian())
636     std::reverse(Parts, Parts + OrigNumParts);
637 }
638 
639 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val,
640                                      const SDLoc &DL, EVT PartVT) {
641   if (!PartVT.isVector())
642     return SDValue();
643 
644   EVT ValueVT = Val.getValueType();
645   EVT PartEVT = PartVT.getVectorElementType();
646   EVT ValueEVT = ValueVT.getVectorElementType();
647   ElementCount PartNumElts = PartVT.getVectorElementCount();
648   ElementCount ValueNumElts = ValueVT.getVectorElementCount();
649 
650   // We only support widening vectors with equivalent element types and
651   // fixed/scalable properties. If a target needs to widen a fixed-length type
652   // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
653   if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
654       PartNumElts.isScalable() != ValueNumElts.isScalable())
655     return SDValue();
656 
657   // Have a try for bf16 because some targets share its ABI with fp16.
658   if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) {
659     assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
660            "Cannot widen to illegal type");
661     Val = DAG.getNode(ISD::BITCAST, DL,
662                       ValueVT.changeVectorElementType(MVT::f16), Val);
663   } else if (PartEVT != ValueEVT) {
664     return SDValue();
665   }
666 
667   // Widening a scalable vector to another scalable vector is done by inserting
668   // the vector into a larger undef one.
669   if (PartNumElts.isScalable())
670     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
671                        Val, DAG.getVectorIdxConstant(0, DL));
672 
673   // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
674   // undef elements.
675   SmallVector<SDValue, 16> Ops;
676   DAG.ExtractVectorElements(Val, Ops);
677   SDValue EltUndef = DAG.getUNDEF(PartEVT);
678   Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
679 
680   // FIXME: Use CONCAT for 2x -> 4x.
681   return DAG.getBuildVector(PartVT, DL, Ops);
682 }
683 
684 /// getCopyToPartsVector - Create a series of nodes that contain the specified
685 /// value split into legal parts.
686 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
687                                  SDValue Val, SDValue *Parts, unsigned NumParts,
688                                  MVT PartVT, const Value *V,
689                                  std::optional<CallingConv::ID> CallConv) {
690   EVT ValueVT = Val.getValueType();
691   assert(ValueVT.isVector() && "Not a vector");
692   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
693   const bool IsABIRegCopy = CallConv.has_value();
694 
695   if (NumParts == 1) {
696     EVT PartEVT = PartVT;
697     if (PartEVT == ValueVT) {
698       // Nothing to do.
699     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
700       // Bitconvert vector->vector case.
701       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
702     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
703       Val = Widened;
704     } else if (PartVT.isVector() &&
705                PartEVT.getVectorElementType().bitsGE(
706                    ValueVT.getVectorElementType()) &&
707                PartEVT.getVectorElementCount() ==
708                    ValueVT.getVectorElementCount()) {
709 
710       // Promoted vector extract
711       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
712     } else if (PartEVT.isVector() &&
713                PartEVT.getVectorElementType() !=
714                    ValueVT.getVectorElementType() &&
715                TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
716                    TargetLowering::TypeWidenVector) {
717       // Combination of widening and promotion.
718       EVT WidenVT =
719           EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(),
720                            PartVT.getVectorElementCount());
721       SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
722       Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
723     } else {
724       // Don't extract an integer from a float vector. This can happen if the
725       // FP type gets softened to integer and then promoted. The promotion
726       // prevents it from being picked up by the earlier bitcast case.
727       if (ValueVT.getVectorElementCount().isScalar() &&
728           (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) {
729         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
730                           DAG.getVectorIdxConstant(0, DL));
731       } else {
732         uint64_t ValueSize = ValueVT.getFixedSizeInBits();
733         assert(PartVT.getFixedSizeInBits() > ValueSize &&
734                "lossy conversion of vector to scalar type");
735         EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
736         Val = DAG.getBitcast(IntermediateType, Val);
737         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
738       }
739     }
740 
741     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
742     Parts[0] = Val;
743     return;
744   }
745 
746   // Handle a multi-element vector.
747   EVT IntermediateVT;
748   MVT RegisterVT;
749   unsigned NumIntermediates;
750   unsigned NumRegs;
751   if (IsABIRegCopy) {
752     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
753         *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates,
754         RegisterVT);
755   } else {
756     NumRegs =
757         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
758                                    NumIntermediates, RegisterVT);
759   }
760 
761   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
762   NumParts = NumRegs; // Silence a compiler warning.
763   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
764 
765   assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
766          "Mixing scalable and fixed vectors when copying in parts");
767 
768   std::optional<ElementCount> DestEltCnt;
769 
770   if (IntermediateVT.isVector())
771     DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
772   else
773     DestEltCnt = ElementCount::getFixed(NumIntermediates);
774 
775   EVT BuiltVectorTy = EVT::getVectorVT(
776       *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt);
777 
778   if (ValueVT == BuiltVectorTy) {
779     // Nothing to do.
780   } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
781     // Bitconvert vector->vector case.
782     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
783   } else {
784     if (BuiltVectorTy.getVectorElementType().bitsGT(
785             ValueVT.getVectorElementType())) {
786       // Integer promotion.
787       ValueVT = EVT::getVectorVT(*DAG.getContext(),
788                                  BuiltVectorTy.getVectorElementType(),
789                                  ValueVT.getVectorElementCount());
790       Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
791     }
792 
793     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
794       Val = Widened;
795     }
796   }
797 
798   assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
799 
800   // Split the vector into intermediate operands.
801   SmallVector<SDValue, 8> Ops(NumIntermediates);
802   for (unsigned i = 0; i != NumIntermediates; ++i) {
803     if (IntermediateVT.isVector()) {
804       // This does something sensible for scalable vectors - see the
805       // definition of EXTRACT_SUBVECTOR for further details.
806       unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
807       Ops[i] =
808           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
809                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
810     } else {
811       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
812                            DAG.getVectorIdxConstant(i, DL));
813     }
814   }
815 
816   // Split the intermediate operands into legal parts.
817   if (NumParts == NumIntermediates) {
818     // If the register was not expanded, promote or copy the value,
819     // as appropriate.
820     for (unsigned i = 0; i != NumParts; ++i)
821       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
822   } else if (NumParts > 0) {
823     // If the intermediate type was expanded, split each the value into
824     // legal parts.
825     assert(NumIntermediates != 0 && "division by zero");
826     assert(NumParts % NumIntermediates == 0 &&
827            "Must expand into a divisible number of parts!");
828     unsigned Factor = NumParts / NumIntermediates;
829     for (unsigned i = 0; i != NumIntermediates; ++i)
830       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
831                      CallConv);
832   }
833 }
834 
835 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
836                            EVT valuevt, std::optional<CallingConv::ID> CC)
837     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
838       RegCount(1, regs.size()), CallConv(CC) {}
839 
840 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
841                            const DataLayout &DL, unsigned Reg, Type *Ty,
842                            std::optional<CallingConv::ID> CC) {
843   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
844 
845   CallConv = CC;
846 
847   for (EVT ValueVT : ValueVTs) {
848     unsigned NumRegs =
849         isABIMangled()
850             ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT)
851             : TLI.getNumRegisters(Context, ValueVT);
852     MVT RegisterVT =
853         isABIMangled()
854             ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT)
855             : TLI.getRegisterType(Context, ValueVT);
856     for (unsigned i = 0; i != NumRegs; ++i)
857       Regs.push_back(Reg + i);
858     RegVTs.push_back(RegisterVT);
859     RegCount.push_back(NumRegs);
860     Reg += NumRegs;
861   }
862 }
863 
864 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
865                                       FunctionLoweringInfo &FuncInfo,
866                                       const SDLoc &dl, SDValue &Chain,
867                                       SDValue *Glue, const Value *V) const {
868   // A Value with type {} or [0 x %t] needs no registers.
869   if (ValueVTs.empty())
870     return SDValue();
871 
872   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
873 
874   // Assemble the legal parts into the final values.
875   SmallVector<SDValue, 4> Values(ValueVTs.size());
876   SmallVector<SDValue, 8> Parts;
877   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
878     // Copy the legal parts from the registers.
879     EVT ValueVT = ValueVTs[Value];
880     unsigned NumRegs = RegCount[Value];
881     MVT RegisterVT = isABIMangled()
882                          ? TLI.getRegisterTypeForCallingConv(
883                                *DAG.getContext(), *CallConv, RegVTs[Value])
884                          : RegVTs[Value];
885 
886     Parts.resize(NumRegs);
887     for (unsigned i = 0; i != NumRegs; ++i) {
888       SDValue P;
889       if (!Glue) {
890         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
891       } else {
892         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue);
893         *Glue = P.getValue(2);
894       }
895 
896       Chain = P.getValue(1);
897       Parts[i] = P;
898 
899       // If the source register was virtual and if we know something about it,
900       // add an assert node.
901       if (!Register::isVirtualRegister(Regs[Part + i]) ||
902           !RegisterVT.isInteger())
903         continue;
904 
905       const FunctionLoweringInfo::LiveOutInfo *LOI =
906         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
907       if (!LOI)
908         continue;
909 
910       unsigned RegSize = RegisterVT.getScalarSizeInBits();
911       unsigned NumSignBits = LOI->NumSignBits;
912       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
913 
914       if (NumZeroBits == RegSize) {
915         // The current value is a zero.
916         // Explicitly express that as it would be easier for
917         // optimizations to kick in.
918         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
919         continue;
920       }
921 
922       // FIXME: We capture more information than the dag can represent.  For
923       // now, just use the tightest assertzext/assertsext possible.
924       bool isSExt;
925       EVT FromVT(MVT::Other);
926       if (NumZeroBits) {
927         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
928         isSExt = false;
929       } else if (NumSignBits > 1) {
930         FromVT =
931             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
932         isSExt = true;
933       } else {
934         continue;
935       }
936       // Add an assertion node.
937       assert(FromVT != MVT::Other);
938       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
939                              RegisterVT, P, DAG.getValueType(FromVT));
940     }
941 
942     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
943                                      RegisterVT, ValueVT, V, Chain, CallConv);
944     Part += NumRegs;
945     Parts.clear();
946   }
947 
948   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
949 }
950 
951 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
952                                  const SDLoc &dl, SDValue &Chain, SDValue *Glue,
953                                  const Value *V,
954                                  ISD::NodeType PreferredExtendType) const {
955   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
956   ISD::NodeType ExtendKind = PreferredExtendType;
957 
958   // Get the list of the values's legal parts.
959   unsigned NumRegs = Regs.size();
960   SmallVector<SDValue, 8> Parts(NumRegs);
961   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
962     unsigned NumParts = RegCount[Value];
963 
964     MVT RegisterVT = isABIMangled()
965                          ? TLI.getRegisterTypeForCallingConv(
966                                *DAG.getContext(), *CallConv, RegVTs[Value])
967                          : RegVTs[Value];
968 
969     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
970       ExtendKind = ISD::ZERO_EXTEND;
971 
972     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
973                    NumParts, RegisterVT, V, CallConv, ExtendKind);
974     Part += NumParts;
975   }
976 
977   // Copy the parts into the registers.
978   SmallVector<SDValue, 8> Chains(NumRegs);
979   for (unsigned i = 0; i != NumRegs; ++i) {
980     SDValue Part;
981     if (!Glue) {
982       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
983     } else {
984       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue);
985       *Glue = Part.getValue(1);
986     }
987 
988     Chains[i] = Part.getValue(0);
989   }
990 
991   if (NumRegs == 1 || Glue)
992     // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is
993     // flagged to it. That is the CopyToReg nodes and the user are considered
994     // a single scheduling unit. If we create a TokenFactor and return it as
995     // chain, then the TokenFactor is both a predecessor (operand) of the
996     // user as well as a successor (the TF operands are flagged to the user).
997     // c1, f1 = CopyToReg
998     // c2, f2 = CopyToReg
999     // c3     = TokenFactor c1, c2
1000     // ...
1001     //        = op c3, ..., f2
1002     Chain = Chains[NumRegs-1];
1003   else
1004     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
1005 }
1006 
1007 void RegsForValue::AddInlineAsmOperands(InlineAsm::Kind Code, bool HasMatching,
1008                                         unsigned MatchingIdx, const SDLoc &dl,
1009                                         SelectionDAG &DAG,
1010                                         std::vector<SDValue> &Ops) const {
1011   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1012 
1013   InlineAsm::Flag Flag(Code, Regs.size());
1014   if (HasMatching)
1015     Flag.setMatchingOp(MatchingIdx);
1016   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
1017     // Put the register class of the virtual registers in the flag word.  That
1018     // way, later passes can recompute register class constraints for inline
1019     // assembly as well as normal instructions.
1020     // Don't do this for tied operands that can use the regclass information
1021     // from the def.
1022     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1023     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
1024     Flag.setRegClass(RC->getID());
1025   }
1026 
1027   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
1028   Ops.push_back(Res);
1029 
1030   if (Code == InlineAsm::Kind::Clobber) {
1031     // Clobbers should always have a 1:1 mapping with registers, and may
1032     // reference registers that have illegal (e.g. vector) types. Hence, we
1033     // shouldn't try to apply any sort of splitting logic to them.
1034     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
1035            "No 1:1 mapping from clobbers to regs?");
1036     Register SP = TLI.getStackPointerRegisterToSaveRestore();
1037     (void)SP;
1038     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
1039       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
1040       assert(
1041           (Regs[I] != SP ||
1042            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
1043           "If we clobbered the stack pointer, MFI should know about it.");
1044     }
1045     return;
1046   }
1047 
1048   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1049     MVT RegisterVT = RegVTs[Value];
1050     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
1051                                            RegisterVT);
1052     for (unsigned i = 0; i != NumRegs; ++i) {
1053       assert(Reg < Regs.size() && "Mismatch in # registers expected");
1054       unsigned TheReg = Regs[Reg++];
1055       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1056     }
1057   }
1058 }
1059 
1060 SmallVector<std::pair<unsigned, TypeSize>, 4>
1061 RegsForValue::getRegsAndSizes() const {
1062   SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec;
1063   unsigned I = 0;
1064   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1065     unsigned RegCount = std::get<0>(CountAndVT);
1066     MVT RegisterVT = std::get<1>(CountAndVT);
1067     TypeSize RegisterSize = RegisterVT.getSizeInBits();
1068     for (unsigned E = I + RegCount; I != E; ++I)
1069       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1070   }
1071   return OutVec;
1072 }
1073 
1074 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1075                                AssumptionCache *ac,
1076                                const TargetLibraryInfo *li) {
1077   AA = aa;
1078   AC = ac;
1079   GFI = gfi;
1080   LibInfo = li;
1081   Context = DAG.getContext();
1082   LPadToCallSiteMap.clear();
1083   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1084   AssignmentTrackingEnabled = isAssignmentTrackingEnabled(
1085       *DAG.getMachineFunction().getFunction().getParent());
1086 }
1087 
1088 void SelectionDAGBuilder::clear() {
1089   NodeMap.clear();
1090   UnusedArgNodeMap.clear();
1091   PendingLoads.clear();
1092   PendingExports.clear();
1093   PendingConstrainedFP.clear();
1094   PendingConstrainedFPStrict.clear();
1095   CurInst = nullptr;
1096   HasTailCall = false;
1097   SDNodeOrder = LowestSDNodeOrder;
1098   StatepointLowering.clear();
1099 }
1100 
1101 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1102   DanglingDebugInfoMap.clear();
1103 }
1104 
1105 // Update DAG root to include dependencies on Pending chains.
1106 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1107   SDValue Root = DAG.getRoot();
1108 
1109   if (Pending.empty())
1110     return Root;
1111 
1112   // Add current root to PendingChains, unless we already indirectly
1113   // depend on it.
1114   if (Root.getOpcode() != ISD::EntryToken) {
1115     unsigned i = 0, e = Pending.size();
1116     for (; i != e; ++i) {
1117       assert(Pending[i].getNode()->getNumOperands() > 1);
1118       if (Pending[i].getNode()->getOperand(0) == Root)
1119         break;  // Don't add the root if we already indirectly depend on it.
1120     }
1121 
1122     if (i == e)
1123       Pending.push_back(Root);
1124   }
1125 
1126   if (Pending.size() == 1)
1127     Root = Pending[0];
1128   else
1129     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1130 
1131   DAG.setRoot(Root);
1132   Pending.clear();
1133   return Root;
1134 }
1135 
1136 SDValue SelectionDAGBuilder::getMemoryRoot() {
1137   return updateRoot(PendingLoads);
1138 }
1139 
1140 SDValue SelectionDAGBuilder::getRoot() {
1141   // Chain up all pending constrained intrinsics together with all
1142   // pending loads, by simply appending them to PendingLoads and
1143   // then calling getMemoryRoot().
1144   PendingLoads.reserve(PendingLoads.size() +
1145                        PendingConstrainedFP.size() +
1146                        PendingConstrainedFPStrict.size());
1147   PendingLoads.append(PendingConstrainedFP.begin(),
1148                       PendingConstrainedFP.end());
1149   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1150                       PendingConstrainedFPStrict.end());
1151   PendingConstrainedFP.clear();
1152   PendingConstrainedFPStrict.clear();
1153   return getMemoryRoot();
1154 }
1155 
1156 SDValue SelectionDAGBuilder::getControlRoot() {
1157   // We need to emit pending fpexcept.strict constrained intrinsics,
1158   // so append them to the PendingExports list.
1159   PendingExports.append(PendingConstrainedFPStrict.begin(),
1160                         PendingConstrainedFPStrict.end());
1161   PendingConstrainedFPStrict.clear();
1162   return updateRoot(PendingExports);
1163 }
1164 
1165 void SelectionDAGBuilder::handleDebugDeclare(Value *Address,
1166                                              DILocalVariable *Variable,
1167                                              DIExpression *Expression,
1168                                              DebugLoc DL) {
1169   assert(Variable && "Missing variable");
1170 
1171   // Check if address has undef value.
1172   if (!Address || isa<UndefValue>(Address) ||
1173       (Address->use_empty() && !isa<Argument>(Address))) {
1174     LLVM_DEBUG(
1175         dbgs()
1176         << "dbg_declare: Dropping debug info (bad/undef/unused-arg address)\n");
1177     return;
1178   }
1179 
1180   bool IsParameter = Variable->isParameter() || isa<Argument>(Address);
1181 
1182   SDValue &N = NodeMap[Address];
1183   if (!N.getNode() && isa<Argument>(Address))
1184     // Check unused arguments map.
1185     N = UnusedArgNodeMap[Address];
1186   SDDbgValue *SDV;
1187   if (N.getNode()) {
1188     if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
1189       Address = BCI->getOperand(0);
1190     // Parameters are handled specially.
1191     auto *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
1192     if (IsParameter && FINode) {
1193       // Byval parameter. We have a frame index at this point.
1194       SDV = DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
1195                                       /*IsIndirect*/ true, DL, SDNodeOrder);
1196     } else if (isa<Argument>(Address)) {
1197       // Address is an argument, so try to emit its dbg value using
1198       // virtual register info from the FuncInfo.ValueMap.
1199       EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1200                                FuncArgumentDbgValueKind::Declare, N);
1201       return;
1202     } else {
1203       SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
1204                             true, DL, SDNodeOrder);
1205     }
1206     DAG.AddDbgValue(SDV, IsParameter);
1207   } else {
1208     // If Address is an argument then try to emit its dbg value using
1209     // virtual register info from the FuncInfo.ValueMap.
1210     if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1211                                   FuncArgumentDbgValueKind::Declare, N)) {
1212       LLVM_DEBUG(dbgs() << "dbg_declare: Dropping debug info"
1213                         << " (could not emit func-arg dbg_value)\n");
1214     }
1215   }
1216   return;
1217 }
1218 
1219 void SelectionDAGBuilder::visitDbgInfo(const Instruction &I) {
1220   // Add SDDbgValue nodes for any var locs here. Do so before updating
1221   // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1222   if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) {
1223     // Add SDDbgValue nodes for any var locs here. Do so before updating
1224     // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1225     for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I);
1226          It != End; ++It) {
1227       auto *Var = FnVarLocs->getDILocalVariable(It->VariableID);
1228       dropDanglingDebugInfo(Var, It->Expr);
1229       if (It->Values.isKillLocation(It->Expr)) {
1230         handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder);
1231         continue;
1232       }
1233       SmallVector<Value *> Values(It->Values.location_ops());
1234       if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder,
1235                             It->Values.hasArgList())) {
1236         SmallVector<Value *, 4> Vals;
1237         for (Value *V : It->Values.location_ops())
1238           Vals.push_back(V);
1239         addDanglingDebugInfo(Vals,
1240                              FnVarLocs->getDILocalVariable(It->VariableID),
1241                              It->Expr, Vals.size() > 1, It->DL, SDNodeOrder);
1242       }
1243     }
1244   }
1245 
1246   // Is there is any debug-info attached to this instruction, in the form of
1247   // DPValue non-instruction debug-info records.
1248   for (DPValue &DPV : I.getDbgValueRange()) {
1249     DILocalVariable *Variable = DPV.getVariable();
1250     DIExpression *Expression = DPV.getExpression();
1251     dropDanglingDebugInfo(Variable, Expression);
1252 
1253     if (DPV.getType() == DPValue::LocationType::Declare) {
1254       if (FuncInfo.PreprocessedDPVDeclares.contains(&DPV))
1255         continue;
1256       LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DPV
1257                         << "\n");
1258       handleDebugDeclare(DPV.getVariableLocationOp(0), Variable, Expression,
1259                          DPV.getDebugLoc());
1260       continue;
1261     }
1262 
1263     // A DPValue with no locations is a kill location.
1264     SmallVector<Value *, 4> Values(DPV.location_ops());
1265     if (Values.empty()) {
1266       handleKillDebugValue(Variable, Expression, DPV.getDebugLoc(),
1267                            SDNodeOrder);
1268       continue;
1269     }
1270 
1271     // A DPValue with an undef or absent location is also a kill location.
1272     if (llvm::any_of(Values,
1273                      [](Value *V) { return !V || isa<UndefValue>(V); })) {
1274       handleKillDebugValue(Variable, Expression, DPV.getDebugLoc(),
1275                            SDNodeOrder);
1276       continue;
1277     }
1278 
1279     bool IsVariadic = DPV.hasArgList();
1280     if (!handleDebugValue(Values, Variable, Expression, DPV.getDebugLoc(),
1281                           SDNodeOrder, IsVariadic)) {
1282       addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
1283                            DPV.getDebugLoc(), SDNodeOrder);
1284     }
1285   }
1286 }
1287 
1288 void SelectionDAGBuilder::visit(const Instruction &I) {
1289   visitDbgInfo(I);
1290 
1291   // Set up outgoing PHI node register values before emitting the terminator.
1292   if (I.isTerminator()) {
1293     HandlePHINodesInSuccessorBlocks(I.getParent());
1294   }
1295 
1296   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1297   if (!isa<DbgInfoIntrinsic>(I))
1298     ++SDNodeOrder;
1299 
1300   CurInst = &I;
1301 
1302   // Set inserted listener only if required.
1303   bool NodeInserted = false;
1304   std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener;
1305   MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections);
1306   if (PCSectionsMD) {
1307     InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>(
1308         DAG, [&](SDNode *) { NodeInserted = true; });
1309   }
1310 
1311   visit(I.getOpcode(), I);
1312 
1313   if (!I.isTerminator() && !HasTailCall &&
1314       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1315     CopyToExportRegsIfNeeded(&I);
1316 
1317   // Handle metadata.
1318   if (PCSectionsMD) {
1319     auto It = NodeMap.find(&I);
1320     if (It != NodeMap.end()) {
1321       DAG.addPCSections(It->second.getNode(), PCSectionsMD);
1322     } else if (NodeInserted) {
1323       // This should not happen; if it does, don't let it go unnoticed so we can
1324       // fix it. Relevant visit*() function is probably missing a setValue().
1325       errs() << "warning: loosing !pcsections metadata ["
1326              << I.getModule()->getName() << "]\n";
1327       LLVM_DEBUG(I.dump());
1328       assert(false);
1329     }
1330   }
1331 
1332   CurInst = nullptr;
1333 }
1334 
1335 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1336   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1337 }
1338 
1339 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1340   // Note: this doesn't use InstVisitor, because it has to work with
1341   // ConstantExpr's in addition to instructions.
1342   switch (Opcode) {
1343   default: llvm_unreachable("Unknown instruction type encountered!");
1344     // Build the switch statement using the Instruction.def file.
1345 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1346     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1347 #include "llvm/IR/Instruction.def"
1348   }
1349 }
1350 
1351 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG,
1352                                             DILocalVariable *Variable,
1353                                             DebugLoc DL, unsigned Order,
1354                                             SmallVectorImpl<Value *> &Values,
1355                                             DIExpression *Expression) {
1356   // For variadic dbg_values we will now insert an undef.
1357   // FIXME: We can potentially recover these!
1358   SmallVector<SDDbgOperand, 2> Locs;
1359   for (const Value *V : Values) {
1360     auto *Undef = UndefValue::get(V->getType());
1361     Locs.push_back(SDDbgOperand::fromConst(Undef));
1362   }
1363   SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {},
1364                                         /*IsIndirect=*/false, DL, Order,
1365                                         /*IsVariadic=*/true);
1366   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1367   return true;
1368 }
1369 
1370 void SelectionDAGBuilder::addDanglingDebugInfo(SmallVectorImpl<Value *> &Values,
1371                                                DILocalVariable *Var,
1372                                                DIExpression *Expr,
1373                                                bool IsVariadic, DebugLoc DL,
1374                                                unsigned Order) {
1375   if (IsVariadic) {
1376     handleDanglingVariadicDebugInfo(DAG, Var, DL, Order, Values, Expr);
1377     return;
1378   }
1379   // TODO: Dangling debug info will eventually either be resolved or produce
1380   // an Undef DBG_VALUE. However in the resolution case, a gap may appear
1381   // between the original dbg.value location and its resolved DBG_VALUE,
1382   // which we should ideally fill with an extra Undef DBG_VALUE.
1383   assert(Values.size() == 1);
1384   DanglingDebugInfoMap[Values[0]].emplace_back(Var, Expr, DL, Order);
1385 }
1386 
1387 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1388                                                 const DIExpression *Expr) {
1389   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1390     DIVariable *DanglingVariable = DDI.getVariable();
1391     DIExpression *DanglingExpr = DDI.getExpression();
1392     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1393       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for "
1394                         << printDDI(nullptr, DDI) << "\n");
1395       return true;
1396     }
1397     return false;
1398   };
1399 
1400   for (auto &DDIMI : DanglingDebugInfoMap) {
1401     DanglingDebugInfoVector &DDIV = DDIMI.second;
1402 
1403     // If debug info is to be dropped, run it through final checks to see
1404     // whether it can be salvaged.
1405     for (auto &DDI : DDIV)
1406       if (isMatchingDbgValue(DDI))
1407         salvageUnresolvedDbgValue(DDIMI.first, DDI);
1408 
1409     erase_if(DDIV, isMatchingDbgValue);
1410   }
1411 }
1412 
1413 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1414 // generate the debug data structures now that we've seen its definition.
1415 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1416                                                    SDValue Val) {
1417   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1418   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1419     return;
1420 
1421   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1422   for (auto &DDI : DDIV) {
1423     DebugLoc DL = DDI.getDebugLoc();
1424     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1425     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1426     DILocalVariable *Variable = DDI.getVariable();
1427     DIExpression *Expr = DDI.getExpression();
1428     assert(Variable->isValidLocationForIntrinsic(DL) &&
1429            "Expected inlined-at fields to agree");
1430     SDDbgValue *SDV;
1431     if (Val.getNode()) {
1432       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1433       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1434       // we couldn't resolve it directly when examining the DbgValue intrinsic
1435       // in the first place we should not be more successful here). Unless we
1436       // have some test case that prove this to be correct we should avoid
1437       // calling EmitFuncArgumentDbgValue here.
1438       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL,
1439                                     FuncArgumentDbgValueKind::Value, Val)) {
1440         LLVM_DEBUG(dbgs() << "Resolve dangling debug info for "
1441                           << printDDI(V, DDI) << "\n");
1442         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1443         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1444         // inserted after the definition of Val when emitting the instructions
1445         // after ISel. An alternative could be to teach
1446         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1447         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1448                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1449                    << ValSDNodeOrder << "\n");
1450         SDV = getDbgValue(Val, Variable, Expr, DL,
1451                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1452         DAG.AddDbgValue(SDV, false);
1453       } else
1454         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for "
1455                           << printDDI(V, DDI)
1456                           << " in EmitFuncArgumentDbgValue\n");
1457     } else {
1458       LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(V, DDI)
1459                         << "\n");
1460       auto Undef = UndefValue::get(V->getType());
1461       auto SDV =
1462           DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder);
1463       DAG.AddDbgValue(SDV, false);
1464     }
1465   }
1466   DDIV.clear();
1467 }
1468 
1469 void SelectionDAGBuilder::salvageUnresolvedDbgValue(const Value *V,
1470                                                     DanglingDebugInfo &DDI) {
1471   // TODO: For the variadic implementation, instead of only checking the fail
1472   // state of `handleDebugValue`, we need know specifically which values were
1473   // invalid, so that we attempt to salvage only those values when processing
1474   // a DIArgList.
1475   const Value *OrigV = V;
1476   DILocalVariable *Var = DDI.getVariable();
1477   DIExpression *Expr = DDI.getExpression();
1478   DebugLoc DL = DDI.getDebugLoc();
1479   unsigned SDOrder = DDI.getSDNodeOrder();
1480 
1481   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1482   // that DW_OP_stack_value is desired.
1483   bool StackValue = true;
1484 
1485   // Can this Value can be encoded without any further work?
1486   if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false))
1487     return;
1488 
1489   // Attempt to salvage back through as many instructions as possible. Bail if
1490   // a non-instruction is seen, such as a constant expression or global
1491   // variable. FIXME: Further work could recover those too.
1492   while (isa<Instruction>(V)) {
1493     const Instruction &VAsInst = *cast<const Instruction>(V);
1494     // Temporary "0", awaiting real implementation.
1495     SmallVector<uint64_t, 16> Ops;
1496     SmallVector<Value *, 4> AdditionalValues;
1497     V = salvageDebugInfoImpl(const_cast<Instruction &>(VAsInst),
1498                              Expr->getNumLocationOperands(), Ops,
1499                              AdditionalValues);
1500     // If we cannot salvage any further, and haven't yet found a suitable debug
1501     // expression, bail out.
1502     if (!V)
1503       break;
1504 
1505     // TODO: If AdditionalValues isn't empty, then the salvage can only be
1506     // represented with a DBG_VALUE_LIST, so we give up. When we have support
1507     // here for variadic dbg_values, remove that condition.
1508     if (!AdditionalValues.empty())
1509       break;
1510 
1511     // New value and expr now represent this debuginfo.
1512     Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue);
1513 
1514     // Some kind of simplification occurred: check whether the operand of the
1515     // salvaged debug expression can be encoded in this DAG.
1516     if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) {
1517       LLVM_DEBUG(
1518           dbgs() << "Salvaged debug location info for:\n  " << *Var << "\n"
1519                  << *OrigV << "\nBy stripping back to:\n  " << *V << "\n");
1520       return;
1521     }
1522   }
1523 
1524   // This was the final opportunity to salvage this debug information, and it
1525   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1526   // any earlier variable location.
1527   assert(OrigV && "V shouldn't be null");
1528   auto *Undef = UndefValue::get(OrigV->getType());
1529   auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1530   DAG.AddDbgValue(SDV, false);
1531   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  "
1532                     << printDDI(OrigV, DDI) << "\n");
1533 }
1534 
1535 void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var,
1536                                                DIExpression *Expr,
1537                                                DebugLoc DbgLoc,
1538                                                unsigned Order) {
1539   Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context));
1540   DIExpression *NewExpr =
1541       const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr));
1542   handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order,
1543                    /*IsVariadic*/ false);
1544 }
1545 
1546 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1547                                            DILocalVariable *Var,
1548                                            DIExpression *Expr, DebugLoc DbgLoc,
1549                                            unsigned Order, bool IsVariadic) {
1550   if (Values.empty())
1551     return true;
1552 
1553   // Filter EntryValue locations out early.
1554   if (visitEntryValueDbgValue(Values, Var, Expr, DbgLoc))
1555     return true;
1556 
1557   SmallVector<SDDbgOperand> LocationOps;
1558   SmallVector<SDNode *> Dependencies;
1559   for (const Value *V : Values) {
1560     // Constant value.
1561     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1562         isa<ConstantPointerNull>(V)) {
1563       LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1564       continue;
1565     }
1566 
1567     // Look through IntToPtr constants.
1568     if (auto *CE = dyn_cast<ConstantExpr>(V))
1569       if (CE->getOpcode() == Instruction::IntToPtr) {
1570         LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0)));
1571         continue;
1572       }
1573 
1574     // If the Value is a frame index, we can create a FrameIndex debug value
1575     // without relying on the DAG at all.
1576     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1577       auto SI = FuncInfo.StaticAllocaMap.find(AI);
1578       if (SI != FuncInfo.StaticAllocaMap.end()) {
1579         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1580         continue;
1581       }
1582     }
1583 
1584     // Do not use getValue() in here; we don't want to generate code at
1585     // this point if it hasn't been done yet.
1586     SDValue N = NodeMap[V];
1587     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1588       N = UnusedArgNodeMap[V];
1589     if (N.getNode()) {
1590       // Only emit func arg dbg value for non-variadic dbg.values for now.
1591       if (!IsVariadic &&
1592           EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc,
1593                                    FuncArgumentDbgValueKind::Value, N))
1594         return true;
1595       if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1596         // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1597         // describe stack slot locations.
1598         //
1599         // Consider "int x = 0; int *px = &x;". There are two kinds of
1600         // interesting debug values here after optimization:
1601         //
1602         //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
1603         //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1604         //
1605         // Both describe the direct values of their associated variables.
1606         Dependencies.push_back(N.getNode());
1607         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1608         continue;
1609       }
1610       LocationOps.emplace_back(
1611           SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1612       continue;
1613     }
1614 
1615     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1616     // Special rules apply for the first dbg.values of parameter variables in a
1617     // function. Identify them by the fact they reference Argument Values, that
1618     // they're parameters, and they are parameters of the current function. We
1619     // need to let them dangle until they get an SDNode.
1620     bool IsParamOfFunc =
1621         isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt();
1622     if (IsParamOfFunc)
1623       return false;
1624 
1625     // The value is not used in this block yet (or it would have an SDNode).
1626     // We still want the value to appear for the user if possible -- if it has
1627     // an associated VReg, we can refer to that instead.
1628     auto VMI = FuncInfo.ValueMap.find(V);
1629     if (VMI != FuncInfo.ValueMap.end()) {
1630       unsigned Reg = VMI->second;
1631       // If this is a PHI node, it may be split up into several MI PHI nodes
1632       // (in FunctionLoweringInfo::set).
1633       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1634                        V->getType(), std::nullopt);
1635       if (RFV.occupiesMultipleRegs()) {
1636         // FIXME: We could potentially support variadic dbg_values here.
1637         if (IsVariadic)
1638           return false;
1639         unsigned Offset = 0;
1640         unsigned BitsToDescribe = 0;
1641         if (auto VarSize = Var->getSizeInBits())
1642           BitsToDescribe = *VarSize;
1643         if (auto Fragment = Expr->getFragmentInfo())
1644           BitsToDescribe = Fragment->SizeInBits;
1645         for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1646           // Bail out if all bits are described already.
1647           if (Offset >= BitsToDescribe)
1648             break;
1649           // TODO: handle scalable vectors.
1650           unsigned RegisterSize = RegAndSize.second;
1651           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1652                                       ? BitsToDescribe - Offset
1653                                       : RegisterSize;
1654           auto FragmentExpr = DIExpression::createFragmentExpression(
1655               Expr, Offset, FragmentSize);
1656           if (!FragmentExpr)
1657             continue;
1658           SDDbgValue *SDV = DAG.getVRegDbgValue(
1659               Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, SDNodeOrder);
1660           DAG.AddDbgValue(SDV, false);
1661           Offset += RegisterSize;
1662         }
1663         return true;
1664       }
1665       // We can use simple vreg locations for variadic dbg_values as well.
1666       LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1667       continue;
1668     }
1669     // We failed to create a SDDbgOperand for V.
1670     return false;
1671   }
1672 
1673   // We have created a SDDbgOperand for each Value in Values.
1674   // Should use Order instead of SDNodeOrder?
1675   assert(!LocationOps.empty());
1676   SDDbgValue *SDV = DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1677                                         /*IsIndirect=*/false, DbgLoc,
1678                                         SDNodeOrder, IsVariadic);
1679   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1680   return true;
1681 }
1682 
1683 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1684   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1685   for (auto &Pair : DanglingDebugInfoMap)
1686     for (auto &DDI : Pair.second)
1687       salvageUnresolvedDbgValue(const_cast<Value *>(Pair.first), DDI);
1688   clearDanglingDebugInfo();
1689 }
1690 
1691 /// getCopyFromRegs - If there was virtual register allocated for the value V
1692 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1693 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1694   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1695   SDValue Result;
1696 
1697   if (It != FuncInfo.ValueMap.end()) {
1698     Register InReg = It->second;
1699 
1700     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1701                      DAG.getDataLayout(), InReg, Ty,
1702                      std::nullopt); // This is not an ABI copy.
1703     SDValue Chain = DAG.getEntryNode();
1704     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1705                                  V);
1706     resolveDanglingDebugInfo(V, Result);
1707   }
1708 
1709   return Result;
1710 }
1711 
1712 /// getValue - Return an SDValue for the given Value.
1713 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1714   // If we already have an SDValue for this value, use it. It's important
1715   // to do this first, so that we don't create a CopyFromReg if we already
1716   // have a regular SDValue.
1717   SDValue &N = NodeMap[V];
1718   if (N.getNode()) return N;
1719 
1720   // If there's a virtual register allocated and initialized for this
1721   // value, use it.
1722   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1723     return copyFromReg;
1724 
1725   // Otherwise create a new SDValue and remember it.
1726   SDValue Val = getValueImpl(V);
1727   NodeMap[V] = Val;
1728   resolveDanglingDebugInfo(V, Val);
1729   return Val;
1730 }
1731 
1732 /// getNonRegisterValue - Return an SDValue for the given Value, but
1733 /// don't look in FuncInfo.ValueMap for a virtual register.
1734 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1735   // If we already have an SDValue for this value, use it.
1736   SDValue &N = NodeMap[V];
1737   if (N.getNode()) {
1738     if (isIntOrFPConstant(N)) {
1739       // Remove the debug location from the node as the node is about to be used
1740       // in a location which may differ from the original debug location.  This
1741       // is relevant to Constant and ConstantFP nodes because they can appear
1742       // as constant expressions inside PHI nodes.
1743       N->setDebugLoc(DebugLoc());
1744     }
1745     return N;
1746   }
1747 
1748   // Otherwise create a new SDValue and remember it.
1749   SDValue Val = getValueImpl(V);
1750   NodeMap[V] = Val;
1751   resolveDanglingDebugInfo(V, Val);
1752   return Val;
1753 }
1754 
1755 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1756 /// Create an SDValue for the given value.
1757 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1758   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1759 
1760   if (const Constant *C = dyn_cast<Constant>(V)) {
1761     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1762 
1763     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1764       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1765 
1766     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1767       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1768 
1769     if (isa<ConstantPointerNull>(C)) {
1770       unsigned AS = V->getType()->getPointerAddressSpace();
1771       return DAG.getConstant(0, getCurSDLoc(),
1772                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1773     }
1774 
1775     if (match(C, m_VScale()))
1776       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1777 
1778     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1779       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1780 
1781     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1782       return DAG.getUNDEF(VT);
1783 
1784     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1785       visit(CE->getOpcode(), *CE);
1786       SDValue N1 = NodeMap[V];
1787       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1788       return N1;
1789     }
1790 
1791     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1792       SmallVector<SDValue, 4> Constants;
1793       for (const Use &U : C->operands()) {
1794         SDNode *Val = getValue(U).getNode();
1795         // If the operand is an empty aggregate, there are no values.
1796         if (!Val) continue;
1797         // Add each leaf value from the operand to the Constants list
1798         // to form a flattened list of all the values.
1799         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1800           Constants.push_back(SDValue(Val, i));
1801       }
1802 
1803       return DAG.getMergeValues(Constants, getCurSDLoc());
1804     }
1805 
1806     if (const ConstantDataSequential *CDS =
1807           dyn_cast<ConstantDataSequential>(C)) {
1808       SmallVector<SDValue, 4> Ops;
1809       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1810         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1811         // Add each leaf value from the operand to the Constants list
1812         // to form a flattened list of all the values.
1813         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1814           Ops.push_back(SDValue(Val, i));
1815       }
1816 
1817       if (isa<ArrayType>(CDS->getType()))
1818         return DAG.getMergeValues(Ops, getCurSDLoc());
1819       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1820     }
1821 
1822     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1823       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1824              "Unknown struct or array constant!");
1825 
1826       SmallVector<EVT, 4> ValueVTs;
1827       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1828       unsigned NumElts = ValueVTs.size();
1829       if (NumElts == 0)
1830         return SDValue(); // empty struct
1831       SmallVector<SDValue, 4> Constants(NumElts);
1832       for (unsigned i = 0; i != NumElts; ++i) {
1833         EVT EltVT = ValueVTs[i];
1834         if (isa<UndefValue>(C))
1835           Constants[i] = DAG.getUNDEF(EltVT);
1836         else if (EltVT.isFloatingPoint())
1837           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1838         else
1839           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1840       }
1841 
1842       return DAG.getMergeValues(Constants, getCurSDLoc());
1843     }
1844 
1845     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1846       return DAG.getBlockAddress(BA, VT);
1847 
1848     if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1849       return getValue(Equiv->getGlobalValue());
1850 
1851     if (const auto *NC = dyn_cast<NoCFIValue>(C))
1852       return getValue(NC->getGlobalValue());
1853 
1854     if (VT == MVT::aarch64svcount) {
1855       assert(C->isNullValue() && "Can only zero this target type!");
1856       return DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT,
1857                          DAG.getConstant(0, getCurSDLoc(), MVT::nxv16i1));
1858     }
1859 
1860     VectorType *VecTy = cast<VectorType>(V->getType());
1861 
1862     // Now that we know the number and type of the elements, get that number of
1863     // elements into the Ops array based on what kind of constant it is.
1864     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1865       SmallVector<SDValue, 16> Ops;
1866       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1867       for (unsigned i = 0; i != NumElements; ++i)
1868         Ops.push_back(getValue(CV->getOperand(i)));
1869 
1870       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1871     }
1872 
1873     if (isa<ConstantAggregateZero>(C)) {
1874       EVT EltVT =
1875           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1876 
1877       SDValue Op;
1878       if (EltVT.isFloatingPoint())
1879         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1880       else
1881         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1882 
1883       return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op);
1884     }
1885 
1886     llvm_unreachable("Unknown vector constant");
1887   }
1888 
1889   // If this is a static alloca, generate it as the frameindex instead of
1890   // computation.
1891   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1892     DenseMap<const AllocaInst*, int>::iterator SI =
1893       FuncInfo.StaticAllocaMap.find(AI);
1894     if (SI != FuncInfo.StaticAllocaMap.end())
1895       return DAG.getFrameIndex(
1896           SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType()));
1897   }
1898 
1899   // If this is an instruction which fast-isel has deferred, select it now.
1900   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1901     Register InReg = FuncInfo.InitializeRegForValue(Inst);
1902 
1903     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1904                      Inst->getType(), std::nullopt);
1905     SDValue Chain = DAG.getEntryNode();
1906     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1907   }
1908 
1909   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V))
1910     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1911 
1912   if (const auto *BB = dyn_cast<BasicBlock>(V))
1913     return DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
1914 
1915   llvm_unreachable("Can't get register for value!");
1916 }
1917 
1918 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1919   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1920   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1921   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1922   bool IsSEH = isAsynchronousEHPersonality(Pers);
1923   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1924   if (!IsSEH)
1925     CatchPadMBB->setIsEHScopeEntry();
1926   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1927   if (IsMSVCCXX || IsCoreCLR)
1928     CatchPadMBB->setIsEHFuncletEntry();
1929 }
1930 
1931 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1932   // Update machine-CFG edge.
1933   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1934   FuncInfo.MBB->addSuccessor(TargetMBB);
1935   TargetMBB->setIsEHCatchretTarget(true);
1936   DAG.getMachineFunction().setHasEHCatchret(true);
1937 
1938   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1939   bool IsSEH = isAsynchronousEHPersonality(Pers);
1940   if (IsSEH) {
1941     // If this is not a fall-through branch or optimizations are switched off,
1942     // emit the branch.
1943     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1944         TM.getOptLevel() == CodeGenOptLevel::None)
1945       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1946                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1947     return;
1948   }
1949 
1950   // Figure out the funclet membership for the catchret's successor.
1951   // This will be used by the FuncletLayout pass to determine how to order the
1952   // BB's.
1953   // A 'catchret' returns to the outer scope's color.
1954   Value *ParentPad = I.getCatchSwitchParentPad();
1955   const BasicBlock *SuccessorColor;
1956   if (isa<ConstantTokenNone>(ParentPad))
1957     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1958   else
1959     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1960   assert(SuccessorColor && "No parent funclet for catchret!");
1961   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1962   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1963 
1964   // Create the terminator node.
1965   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1966                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1967                             DAG.getBasicBlock(SuccessorColorMBB));
1968   DAG.setRoot(Ret);
1969 }
1970 
1971 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1972   // Don't emit any special code for the cleanuppad instruction. It just marks
1973   // the start of an EH scope/funclet.
1974   FuncInfo.MBB->setIsEHScopeEntry();
1975   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1976   if (Pers != EHPersonality::Wasm_CXX) {
1977     FuncInfo.MBB->setIsEHFuncletEntry();
1978     FuncInfo.MBB->setIsCleanupFuncletEntry();
1979   }
1980 }
1981 
1982 // In wasm EH, even though a catchpad may not catch an exception if a tag does
1983 // not match, it is OK to add only the first unwind destination catchpad to the
1984 // successors, because there will be at least one invoke instruction within the
1985 // catch scope that points to the next unwind destination, if one exists, so
1986 // CFGSort cannot mess up with BB sorting order.
1987 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
1988 // call within them, and catchpads only consisting of 'catch (...)' have a
1989 // '__cxa_end_catch' call within them, both of which generate invokes in case
1990 // the next unwind destination exists, i.e., the next unwind destination is not
1991 // the caller.)
1992 //
1993 // Having at most one EH pad successor is also simpler and helps later
1994 // transformations.
1995 //
1996 // For example,
1997 // current:
1998 //   invoke void @foo to ... unwind label %catch.dispatch
1999 // catch.dispatch:
2000 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
2001 // catch.start:
2002 //   ...
2003 //   ... in this BB or some other child BB dominated by this BB there will be an
2004 //   invoke that points to 'next' BB as an unwind destination
2005 //
2006 // next: ; We don't need to add this to 'current' BB's successor
2007 //   ...
2008 static void findWasmUnwindDestinations(
2009     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2010     BranchProbability Prob,
2011     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2012         &UnwindDests) {
2013   while (EHPadBB) {
2014     const Instruction *Pad = EHPadBB->getFirstNonPHI();
2015     if (isa<CleanupPadInst>(Pad)) {
2016       // Stop on cleanup pads.
2017       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
2018       UnwindDests.back().first->setIsEHScopeEntry();
2019       break;
2020     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
2021       // Add the catchpad handlers to the possible destinations. We don't
2022       // continue to the unwind destination of the catchswitch for wasm.
2023       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2024         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
2025         UnwindDests.back().first->setIsEHScopeEntry();
2026       }
2027       break;
2028     } else {
2029       continue;
2030     }
2031   }
2032 }
2033 
2034 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
2035 /// many places it could ultimately go. In the IR, we have a single unwind
2036 /// destination, but in the machine CFG, we enumerate all the possible blocks.
2037 /// This function skips over imaginary basic blocks that hold catchswitch
2038 /// instructions, and finds all the "real" machine
2039 /// basic block destinations. As those destinations may not be successors of
2040 /// EHPadBB, here we also calculate the edge probability to those destinations.
2041 /// The passed-in Prob is the edge probability to EHPadBB.
2042 static void findUnwindDestinations(
2043     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2044     BranchProbability Prob,
2045     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2046         &UnwindDests) {
2047   EHPersonality Personality =
2048     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
2049   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
2050   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
2051   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
2052   bool IsSEH = isAsynchronousEHPersonality(Personality);
2053 
2054   if (IsWasmCXX) {
2055     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
2056     assert(UnwindDests.size() <= 1 &&
2057            "There should be at most one unwind destination for wasm");
2058     return;
2059   }
2060 
2061   while (EHPadBB) {
2062     const Instruction *Pad = EHPadBB->getFirstNonPHI();
2063     BasicBlock *NewEHPadBB = nullptr;
2064     if (isa<LandingPadInst>(Pad)) {
2065       // Stop on landingpads. They are not funclets.
2066       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
2067       break;
2068     } else if (isa<CleanupPadInst>(Pad)) {
2069       // Stop on cleanup pads. Cleanups are always funclet entries for all known
2070       // personalities.
2071       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
2072       UnwindDests.back().first->setIsEHScopeEntry();
2073       UnwindDests.back().first->setIsEHFuncletEntry();
2074       break;
2075     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
2076       // Add the catchpad handlers to the possible destinations.
2077       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2078         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
2079         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
2080         if (IsMSVCCXX || IsCoreCLR)
2081           UnwindDests.back().first->setIsEHFuncletEntry();
2082         if (!IsSEH)
2083           UnwindDests.back().first->setIsEHScopeEntry();
2084       }
2085       NewEHPadBB = CatchSwitch->getUnwindDest();
2086     } else {
2087       continue;
2088     }
2089 
2090     BranchProbabilityInfo *BPI = FuncInfo.BPI;
2091     if (BPI && NewEHPadBB)
2092       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
2093     EHPadBB = NewEHPadBB;
2094   }
2095 }
2096 
2097 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
2098   // Update successor info.
2099   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2100   auto UnwindDest = I.getUnwindDest();
2101   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2102   BranchProbability UnwindDestProb =
2103       (BPI && UnwindDest)
2104           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
2105           : BranchProbability::getZero();
2106   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
2107   for (auto &UnwindDest : UnwindDests) {
2108     UnwindDest.first->setIsEHPad();
2109     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
2110   }
2111   FuncInfo.MBB->normalizeSuccProbs();
2112 
2113   // Create the terminator node.
2114   SDValue Ret =
2115       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
2116   DAG.setRoot(Ret);
2117 }
2118 
2119 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
2120   report_fatal_error("visitCatchSwitch not yet implemented!");
2121 }
2122 
2123 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
2124   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2125   auto &DL = DAG.getDataLayout();
2126   SDValue Chain = getControlRoot();
2127   SmallVector<ISD::OutputArg, 8> Outs;
2128   SmallVector<SDValue, 8> OutVals;
2129 
2130   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
2131   // lower
2132   //
2133   //   %val = call <ty> @llvm.experimental.deoptimize()
2134   //   ret <ty> %val
2135   //
2136   // differently.
2137   if (I.getParent()->getTerminatingDeoptimizeCall()) {
2138     LowerDeoptimizingReturn();
2139     return;
2140   }
2141 
2142   if (!FuncInfo.CanLowerReturn) {
2143     unsigned DemoteReg = FuncInfo.DemoteRegister;
2144     const Function *F = I.getParent()->getParent();
2145 
2146     // Emit a store of the return value through the virtual register.
2147     // Leave Outs empty so that LowerReturn won't try to load return
2148     // registers the usual way.
2149     SmallVector<EVT, 1> PtrValueVTs;
2150     ComputeValueVTs(TLI, DL,
2151                     PointerType::get(F->getContext(),
2152                                      DAG.getDataLayout().getAllocaAddrSpace()),
2153                     PtrValueVTs);
2154 
2155     SDValue RetPtr =
2156         DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]);
2157     SDValue RetOp = getValue(I.getOperand(0));
2158 
2159     SmallVector<EVT, 4> ValueVTs, MemVTs;
2160     SmallVector<uint64_t, 4> Offsets;
2161     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
2162                     &Offsets, 0);
2163     unsigned NumValues = ValueVTs.size();
2164 
2165     SmallVector<SDValue, 4> Chains(NumValues);
2166     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
2167     for (unsigned i = 0; i != NumValues; ++i) {
2168       // An aggregate return value cannot wrap around the address space, so
2169       // offsets to its parts don't wrap either.
2170       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
2171                                            TypeSize::getFixed(Offsets[i]));
2172 
2173       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
2174       if (MemVTs[i] != ValueVTs[i])
2175         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
2176       Chains[i] = DAG.getStore(
2177           Chain, getCurSDLoc(), Val,
2178           // FIXME: better loc info would be nice.
2179           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
2180           commonAlignment(BaseAlign, Offsets[i]));
2181     }
2182 
2183     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
2184                         MVT::Other, Chains);
2185   } else if (I.getNumOperands() != 0) {
2186     SmallVector<EVT, 4> ValueVTs;
2187     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
2188     unsigned NumValues = ValueVTs.size();
2189     if (NumValues) {
2190       SDValue RetOp = getValue(I.getOperand(0));
2191 
2192       const Function *F = I.getParent()->getParent();
2193 
2194       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
2195           I.getOperand(0)->getType(), F->getCallingConv(),
2196           /*IsVarArg*/ false, DL);
2197 
2198       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
2199       if (F->getAttributes().hasRetAttr(Attribute::SExt))
2200         ExtendKind = ISD::SIGN_EXTEND;
2201       else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
2202         ExtendKind = ISD::ZERO_EXTEND;
2203 
2204       LLVMContext &Context = F->getContext();
2205       bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
2206 
2207       for (unsigned j = 0; j != NumValues; ++j) {
2208         EVT VT = ValueVTs[j];
2209 
2210         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2211           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
2212 
2213         CallingConv::ID CC = F->getCallingConv();
2214 
2215         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
2216         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2217         SmallVector<SDValue, 4> Parts(NumParts);
2218         getCopyToParts(DAG, getCurSDLoc(),
2219                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2220                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
2221 
2222         // 'inreg' on function refers to return value
2223         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2224         if (RetInReg)
2225           Flags.setInReg();
2226 
2227         if (I.getOperand(0)->getType()->isPointerTy()) {
2228           Flags.setPointer();
2229           Flags.setPointerAddrSpace(
2230               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2231         }
2232 
2233         if (NeedsRegBlock) {
2234           Flags.setInConsecutiveRegs();
2235           if (j == NumValues - 1)
2236             Flags.setInConsecutiveRegsLast();
2237         }
2238 
2239         // Propagate extension type if any
2240         if (ExtendKind == ISD::SIGN_EXTEND)
2241           Flags.setSExt();
2242         else if (ExtendKind == ISD::ZERO_EXTEND)
2243           Flags.setZExt();
2244 
2245         for (unsigned i = 0; i < NumParts; ++i) {
2246           Outs.push_back(ISD::OutputArg(Flags,
2247                                         Parts[i].getValueType().getSimpleVT(),
2248                                         VT, /*isfixed=*/true, 0, 0));
2249           OutVals.push_back(Parts[i]);
2250         }
2251       }
2252     }
2253   }
2254 
2255   // Push in swifterror virtual register as the last element of Outs. This makes
2256   // sure swifterror virtual register will be returned in the swifterror
2257   // physical register.
2258   const Function *F = I.getParent()->getParent();
2259   if (TLI.supportSwiftError() &&
2260       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2261     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2262     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2263     Flags.setSwiftError();
2264     Outs.push_back(ISD::OutputArg(
2265         Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
2266         /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
2267     // Create SDNode for the swifterror virtual register.
2268     OutVals.push_back(
2269         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2270                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2271                         EVT(TLI.getPointerTy(DL))));
2272   }
2273 
2274   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2275   CallingConv::ID CallConv =
2276     DAG.getMachineFunction().getFunction().getCallingConv();
2277   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2278       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2279 
2280   // Verify that the target's LowerReturn behaved as expected.
2281   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2282          "LowerReturn didn't return a valid chain!");
2283 
2284   // Update the DAG with the new chain value resulting from return lowering.
2285   DAG.setRoot(Chain);
2286 }
2287 
2288 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2289 /// created for it, emit nodes to copy the value into the virtual
2290 /// registers.
2291 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2292   // Skip empty types
2293   if (V->getType()->isEmptyTy())
2294     return;
2295 
2296   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2297   if (VMI != FuncInfo.ValueMap.end()) {
2298     assert((!V->use_empty() || isa<CallBrInst>(V)) &&
2299            "Unused value assigned virtual registers!");
2300     CopyValueToVirtualRegister(V, VMI->second);
2301   }
2302 }
2303 
2304 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2305 /// the current basic block, add it to ValueMap now so that we'll get a
2306 /// CopyTo/FromReg.
2307 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2308   // No need to export constants.
2309   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2310 
2311   // Already exported?
2312   if (FuncInfo.isExportedInst(V)) return;
2313 
2314   Register Reg = FuncInfo.InitializeRegForValue(V);
2315   CopyValueToVirtualRegister(V, Reg);
2316 }
2317 
2318 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2319                                                      const BasicBlock *FromBB) {
2320   // The operands of the setcc have to be in this block.  We don't know
2321   // how to export them from some other block.
2322   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2323     // Can export from current BB.
2324     if (VI->getParent() == FromBB)
2325       return true;
2326 
2327     // Is already exported, noop.
2328     return FuncInfo.isExportedInst(V);
2329   }
2330 
2331   // If this is an argument, we can export it if the BB is the entry block or
2332   // if it is already exported.
2333   if (isa<Argument>(V)) {
2334     if (FromBB->isEntryBlock())
2335       return true;
2336 
2337     // Otherwise, can only export this if it is already exported.
2338     return FuncInfo.isExportedInst(V);
2339   }
2340 
2341   // Otherwise, constants can always be exported.
2342   return true;
2343 }
2344 
2345 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2346 BranchProbability
2347 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2348                                         const MachineBasicBlock *Dst) const {
2349   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2350   const BasicBlock *SrcBB = Src->getBasicBlock();
2351   const BasicBlock *DstBB = Dst->getBasicBlock();
2352   if (!BPI) {
2353     // If BPI is not available, set the default probability as 1 / N, where N is
2354     // the number of successors.
2355     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2356     return BranchProbability(1, SuccSize);
2357   }
2358   return BPI->getEdgeProbability(SrcBB, DstBB);
2359 }
2360 
2361 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2362                                                MachineBasicBlock *Dst,
2363                                                BranchProbability Prob) {
2364   if (!FuncInfo.BPI)
2365     Src->addSuccessorWithoutProb(Dst);
2366   else {
2367     if (Prob.isUnknown())
2368       Prob = getEdgeProbability(Src, Dst);
2369     Src->addSuccessor(Dst, Prob);
2370   }
2371 }
2372 
2373 static bool InBlock(const Value *V, const BasicBlock *BB) {
2374   if (const Instruction *I = dyn_cast<Instruction>(V))
2375     return I->getParent() == BB;
2376   return true;
2377 }
2378 
2379 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2380 /// This function emits a branch and is used at the leaves of an OR or an
2381 /// AND operator tree.
2382 void
2383 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2384                                                   MachineBasicBlock *TBB,
2385                                                   MachineBasicBlock *FBB,
2386                                                   MachineBasicBlock *CurBB,
2387                                                   MachineBasicBlock *SwitchBB,
2388                                                   BranchProbability TProb,
2389                                                   BranchProbability FProb,
2390                                                   bool InvertCond) {
2391   const BasicBlock *BB = CurBB->getBasicBlock();
2392 
2393   // If the leaf of the tree is a comparison, merge the condition into
2394   // the caseblock.
2395   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2396     // The operands of the cmp have to be in this block.  We don't know
2397     // how to export them from some other block.  If this is the first block
2398     // of the sequence, no exporting is needed.
2399     if (CurBB == SwitchBB ||
2400         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2401          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2402       ISD::CondCode Condition;
2403       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2404         ICmpInst::Predicate Pred =
2405             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2406         Condition = getICmpCondCode(Pred);
2407       } else {
2408         const FCmpInst *FC = cast<FCmpInst>(Cond);
2409         FCmpInst::Predicate Pred =
2410             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2411         Condition = getFCmpCondCode(Pred);
2412         if (TM.Options.NoNaNsFPMath)
2413           Condition = getFCmpCodeWithoutNaN(Condition);
2414       }
2415 
2416       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2417                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2418       SL->SwitchCases.push_back(CB);
2419       return;
2420     }
2421   }
2422 
2423   // Create a CaseBlock record representing this branch.
2424   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2425   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2426                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2427   SL->SwitchCases.push_back(CB);
2428 }
2429 
2430 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2431                                                MachineBasicBlock *TBB,
2432                                                MachineBasicBlock *FBB,
2433                                                MachineBasicBlock *CurBB,
2434                                                MachineBasicBlock *SwitchBB,
2435                                                Instruction::BinaryOps Opc,
2436                                                BranchProbability TProb,
2437                                                BranchProbability FProb,
2438                                                bool InvertCond) {
2439   // Skip over not part of the tree and remember to invert op and operands at
2440   // next level.
2441   Value *NotCond;
2442   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2443       InBlock(NotCond, CurBB->getBasicBlock())) {
2444     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2445                          !InvertCond);
2446     return;
2447   }
2448 
2449   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2450   const Value *BOpOp0, *BOpOp1;
2451   // Compute the effective opcode for Cond, taking into account whether it needs
2452   // to be inverted, e.g.
2453   //   and (not (or A, B)), C
2454   // gets lowered as
2455   //   and (and (not A, not B), C)
2456   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2457   if (BOp) {
2458     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2459                ? Instruction::And
2460                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2461                       ? Instruction::Or
2462                       : (Instruction::BinaryOps)0);
2463     if (InvertCond) {
2464       if (BOpc == Instruction::And)
2465         BOpc = Instruction::Or;
2466       else if (BOpc == Instruction::Or)
2467         BOpc = Instruction::And;
2468     }
2469   }
2470 
2471   // If this node is not part of the or/and tree, emit it as a branch.
2472   // Note that all nodes in the tree should have same opcode.
2473   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2474   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2475       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2476       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2477     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2478                                  TProb, FProb, InvertCond);
2479     return;
2480   }
2481 
2482   //  Create TmpBB after CurBB.
2483   MachineFunction::iterator BBI(CurBB);
2484   MachineFunction &MF = DAG.getMachineFunction();
2485   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2486   CurBB->getParent()->insert(++BBI, TmpBB);
2487 
2488   if (Opc == Instruction::Or) {
2489     // Codegen X | Y as:
2490     // BB1:
2491     //   jmp_if_X TBB
2492     //   jmp TmpBB
2493     // TmpBB:
2494     //   jmp_if_Y TBB
2495     //   jmp FBB
2496     //
2497 
2498     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2499     // The requirement is that
2500     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2501     //     = TrueProb for original BB.
2502     // Assuming the original probabilities are A and B, one choice is to set
2503     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2504     // A/(1+B) and 2B/(1+B). This choice assumes that
2505     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2506     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2507     // TmpBB, but the math is more complicated.
2508 
2509     auto NewTrueProb = TProb / 2;
2510     auto NewFalseProb = TProb / 2 + FProb;
2511     // Emit the LHS condition.
2512     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2513                          NewFalseProb, InvertCond);
2514 
2515     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2516     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2517     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2518     // Emit the RHS condition into TmpBB.
2519     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2520                          Probs[1], InvertCond);
2521   } else {
2522     assert(Opc == Instruction::And && "Unknown merge op!");
2523     // Codegen X & Y as:
2524     // BB1:
2525     //   jmp_if_X TmpBB
2526     //   jmp FBB
2527     // TmpBB:
2528     //   jmp_if_Y TBB
2529     //   jmp FBB
2530     //
2531     //  This requires creation of TmpBB after CurBB.
2532 
2533     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2534     // The requirement is that
2535     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2536     //     = FalseProb for original BB.
2537     // Assuming the original probabilities are A and B, one choice is to set
2538     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2539     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2540     // TrueProb for BB1 * FalseProb for TmpBB.
2541 
2542     auto NewTrueProb = TProb + FProb / 2;
2543     auto NewFalseProb = FProb / 2;
2544     // Emit the LHS condition.
2545     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2546                          NewFalseProb, InvertCond);
2547 
2548     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2549     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2550     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2551     // Emit the RHS condition into TmpBB.
2552     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2553                          Probs[1], InvertCond);
2554   }
2555 }
2556 
2557 /// If the set of cases should be emitted as a series of branches, return true.
2558 /// If we should emit this as a bunch of and/or'd together conditions, return
2559 /// false.
2560 bool
2561 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2562   if (Cases.size() != 2) return true;
2563 
2564   // If this is two comparisons of the same values or'd or and'd together, they
2565   // will get folded into a single comparison, so don't emit two blocks.
2566   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2567        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2568       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2569        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2570     return false;
2571   }
2572 
2573   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2574   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2575   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2576       Cases[0].CC == Cases[1].CC &&
2577       isa<Constant>(Cases[0].CmpRHS) &&
2578       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2579     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2580       return false;
2581     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2582       return false;
2583   }
2584 
2585   return true;
2586 }
2587 
2588 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2589   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2590 
2591   // Update machine-CFG edges.
2592   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2593 
2594   if (I.isUnconditional()) {
2595     // Update machine-CFG edges.
2596     BrMBB->addSuccessor(Succ0MBB);
2597 
2598     // If this is not a fall-through branch or optimizations are switched off,
2599     // emit the branch.
2600     if (Succ0MBB != NextBlock(BrMBB) ||
2601         TM.getOptLevel() == CodeGenOptLevel::None) {
2602       auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
2603                             getControlRoot(), DAG.getBasicBlock(Succ0MBB));
2604       setValue(&I, Br);
2605       DAG.setRoot(Br);
2606     }
2607 
2608     return;
2609   }
2610 
2611   // If this condition is one of the special cases we handle, do special stuff
2612   // now.
2613   const Value *CondVal = I.getCondition();
2614   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2615 
2616   // If this is a series of conditions that are or'd or and'd together, emit
2617   // this as a sequence of branches instead of setcc's with and/or operations.
2618   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2619   // unpredictable branches, and vector extracts because those jumps are likely
2620   // expensive for any target), this should improve performance.
2621   // For example, instead of something like:
2622   //     cmp A, B
2623   //     C = seteq
2624   //     cmp D, E
2625   //     F = setle
2626   //     or C, F
2627   //     jnz foo
2628   // Emit:
2629   //     cmp A, B
2630   //     je foo
2631   //     cmp D, E
2632   //     jle foo
2633   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2634   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2635       BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2636     Value *Vec;
2637     const Value *BOp0, *BOp1;
2638     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2639     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2640       Opcode = Instruction::And;
2641     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2642       Opcode = Instruction::Or;
2643 
2644     if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2645                     match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
2646       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2647                            getEdgeProbability(BrMBB, Succ0MBB),
2648                            getEdgeProbability(BrMBB, Succ1MBB),
2649                            /*InvertCond=*/false);
2650       // If the compares in later blocks need to use values not currently
2651       // exported from this block, export them now.  This block should always
2652       // be the first entry.
2653       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2654 
2655       // Allow some cases to be rejected.
2656       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2657         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2658           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2659           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2660         }
2661 
2662         // Emit the branch for this block.
2663         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2664         SL->SwitchCases.erase(SL->SwitchCases.begin());
2665         return;
2666       }
2667 
2668       // Okay, we decided not to do this, remove any inserted MBB's and clear
2669       // SwitchCases.
2670       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2671         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2672 
2673       SL->SwitchCases.clear();
2674     }
2675   }
2676 
2677   // Create a CaseBlock record representing this branch.
2678   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2679                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2680 
2681   // Use visitSwitchCase to actually insert the fast branch sequence for this
2682   // cond branch.
2683   visitSwitchCase(CB, BrMBB);
2684 }
2685 
2686 /// visitSwitchCase - Emits the necessary code to represent a single node in
2687 /// the binary search tree resulting from lowering a switch instruction.
2688 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2689                                           MachineBasicBlock *SwitchBB) {
2690   SDValue Cond;
2691   SDValue CondLHS = getValue(CB.CmpLHS);
2692   SDLoc dl = CB.DL;
2693 
2694   if (CB.CC == ISD::SETTRUE) {
2695     // Branch or fall through to TrueBB.
2696     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2697     SwitchBB->normalizeSuccProbs();
2698     if (CB.TrueBB != NextBlock(SwitchBB)) {
2699       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2700                               DAG.getBasicBlock(CB.TrueBB)));
2701     }
2702     return;
2703   }
2704 
2705   auto &TLI = DAG.getTargetLoweringInfo();
2706   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2707 
2708   // Build the setcc now.
2709   if (!CB.CmpMHS) {
2710     // Fold "(X == true)" to X and "(X == false)" to !X to
2711     // handle common cases produced by branch lowering.
2712     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2713         CB.CC == ISD::SETEQ)
2714       Cond = CondLHS;
2715     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2716              CB.CC == ISD::SETEQ) {
2717       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2718       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2719     } else {
2720       SDValue CondRHS = getValue(CB.CmpRHS);
2721 
2722       // If a pointer's DAG type is larger than its memory type then the DAG
2723       // values are zero-extended. This breaks signed comparisons so truncate
2724       // back to the underlying type before doing the compare.
2725       if (CondLHS.getValueType() != MemVT) {
2726         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2727         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2728       }
2729       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2730     }
2731   } else {
2732     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2733 
2734     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2735     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2736 
2737     SDValue CmpOp = getValue(CB.CmpMHS);
2738     EVT VT = CmpOp.getValueType();
2739 
2740     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2741       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2742                           ISD::SETLE);
2743     } else {
2744       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2745                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2746       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2747                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2748     }
2749   }
2750 
2751   // Update successor info
2752   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2753   // TrueBB and FalseBB are always different unless the incoming IR is
2754   // degenerate. This only happens when running llc on weird IR.
2755   if (CB.TrueBB != CB.FalseBB)
2756     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2757   SwitchBB->normalizeSuccProbs();
2758 
2759   // If the lhs block is the next block, invert the condition so that we can
2760   // fall through to the lhs instead of the rhs block.
2761   if (CB.TrueBB == NextBlock(SwitchBB)) {
2762     std::swap(CB.TrueBB, CB.FalseBB);
2763     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2764     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2765   }
2766 
2767   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2768                                MVT::Other, getControlRoot(), Cond,
2769                                DAG.getBasicBlock(CB.TrueBB));
2770 
2771   setValue(CurInst, BrCond);
2772 
2773   // Insert the false branch. Do this even if it's a fall through branch,
2774   // this makes it easier to do DAG optimizations which require inverting
2775   // the branch condition.
2776   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2777                        DAG.getBasicBlock(CB.FalseBB));
2778 
2779   DAG.setRoot(BrCond);
2780 }
2781 
2782 /// visitJumpTable - Emit JumpTable node in the current MBB
2783 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2784   // Emit the code for the jump table
2785   assert(JT.SL && "Should set SDLoc for SelectionDAG!");
2786   assert(JT.Reg != -1U && "Should lower JT Header first!");
2787   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2788   SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy);
2789   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2790   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other,
2791                                     Index.getValue(1), Table, Index);
2792   DAG.setRoot(BrJumpTable);
2793 }
2794 
2795 /// visitJumpTableHeader - This function emits necessary code to produce index
2796 /// in the JumpTable from switch case.
2797 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2798                                                JumpTableHeader &JTH,
2799                                                MachineBasicBlock *SwitchBB) {
2800   assert(JT.SL && "Should set SDLoc for SelectionDAG!");
2801   const SDLoc &dl = *JT.SL;
2802 
2803   // Subtract the lowest switch case value from the value being switched on.
2804   SDValue SwitchOp = getValue(JTH.SValue);
2805   EVT VT = SwitchOp.getValueType();
2806   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2807                             DAG.getConstant(JTH.First, dl, VT));
2808 
2809   // The SDNode we just created, which holds the value being switched on minus
2810   // the smallest case value, needs to be copied to a virtual register so it
2811   // can be used as an index into the jump table in a subsequent basic block.
2812   // This value may be smaller or larger than the target's pointer type, and
2813   // therefore require extension or truncating.
2814   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2815   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2816 
2817   unsigned JumpTableReg =
2818       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2819   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2820                                     JumpTableReg, SwitchOp);
2821   JT.Reg = JumpTableReg;
2822 
2823   if (!JTH.FallthroughUnreachable) {
2824     // Emit the range check for the jump table, and branch to the default block
2825     // for the switch statement if the value being switched on exceeds the
2826     // largest case in the switch.
2827     SDValue CMP = DAG.getSetCC(
2828         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2829                                    Sub.getValueType()),
2830         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2831 
2832     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2833                                  MVT::Other, CopyTo, CMP,
2834                                  DAG.getBasicBlock(JT.Default));
2835 
2836     // Avoid emitting unnecessary branches to the next block.
2837     if (JT.MBB != NextBlock(SwitchBB))
2838       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2839                            DAG.getBasicBlock(JT.MBB));
2840 
2841     DAG.setRoot(BrCond);
2842   } else {
2843     // Avoid emitting unnecessary branches to the next block.
2844     if (JT.MBB != NextBlock(SwitchBB))
2845       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2846                               DAG.getBasicBlock(JT.MBB)));
2847     else
2848       DAG.setRoot(CopyTo);
2849   }
2850 }
2851 
2852 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2853 /// variable if there exists one.
2854 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2855                                  SDValue &Chain) {
2856   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2857   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2858   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2859   MachineFunction &MF = DAG.getMachineFunction();
2860   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2861   MachineSDNode *Node =
2862       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2863   if (Global) {
2864     MachinePointerInfo MPInfo(Global);
2865     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2866                  MachineMemOperand::MODereferenceable;
2867     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2868         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2869     DAG.setNodeMemRefs(Node, {MemRef});
2870   }
2871   if (PtrTy != PtrMemTy)
2872     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2873   return SDValue(Node, 0);
2874 }
2875 
2876 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2877 /// tail spliced into a stack protector check success bb.
2878 ///
2879 /// For a high level explanation of how this fits into the stack protector
2880 /// generation see the comment on the declaration of class
2881 /// StackProtectorDescriptor.
2882 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2883                                                   MachineBasicBlock *ParentBB) {
2884 
2885   // First create the loads to the guard/stack slot for the comparison.
2886   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2887   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2888   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2889 
2890   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2891   int FI = MFI.getStackProtectorIndex();
2892 
2893   SDValue Guard;
2894   SDLoc dl = getCurSDLoc();
2895   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2896   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2897   Align Align =
2898       DAG.getDataLayout().getPrefTypeAlign(PointerType::get(M.getContext(), 0));
2899 
2900   // Generate code to load the content of the guard slot.
2901   SDValue GuardVal = DAG.getLoad(
2902       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2903       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2904       MachineMemOperand::MOVolatile);
2905 
2906   if (TLI.useStackGuardXorFP())
2907     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2908 
2909   // Retrieve guard check function, nullptr if instrumentation is inlined.
2910   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2911     // The target provides a guard check function to validate the guard value.
2912     // Generate a call to that function with the content of the guard slot as
2913     // argument.
2914     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2915     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2916 
2917     TargetLowering::ArgListTy Args;
2918     TargetLowering::ArgListEntry Entry;
2919     Entry.Node = GuardVal;
2920     Entry.Ty = FnTy->getParamType(0);
2921     if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
2922       Entry.IsInReg = true;
2923     Args.push_back(Entry);
2924 
2925     TargetLowering::CallLoweringInfo CLI(DAG);
2926     CLI.setDebugLoc(getCurSDLoc())
2927         .setChain(DAG.getEntryNode())
2928         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2929                    getValue(GuardCheckFn), std::move(Args));
2930 
2931     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2932     DAG.setRoot(Result.second);
2933     return;
2934   }
2935 
2936   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2937   // Otherwise, emit a volatile load to retrieve the stack guard value.
2938   SDValue Chain = DAG.getEntryNode();
2939   if (TLI.useLoadStackGuardNode()) {
2940     Guard = getLoadStackGuard(DAG, dl, Chain);
2941   } else {
2942     const Value *IRGuard = TLI.getSDagStackGuard(M);
2943     SDValue GuardPtr = getValue(IRGuard);
2944 
2945     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2946                         MachinePointerInfo(IRGuard, 0), Align,
2947                         MachineMemOperand::MOVolatile);
2948   }
2949 
2950   // Perform the comparison via a getsetcc.
2951   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2952                                                         *DAG.getContext(),
2953                                                         Guard.getValueType()),
2954                              Guard, GuardVal, ISD::SETNE);
2955 
2956   // If the guard/stackslot do not equal, branch to failure MBB.
2957   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2958                                MVT::Other, GuardVal.getOperand(0),
2959                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2960   // Otherwise branch to success MBB.
2961   SDValue Br = DAG.getNode(ISD::BR, dl,
2962                            MVT::Other, BrCond,
2963                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2964 
2965   DAG.setRoot(Br);
2966 }
2967 
2968 /// Codegen the failure basic block for a stack protector check.
2969 ///
2970 /// A failure stack protector machine basic block consists simply of a call to
2971 /// __stack_chk_fail().
2972 ///
2973 /// For a high level explanation of how this fits into the stack protector
2974 /// generation see the comment on the declaration of class
2975 /// StackProtectorDescriptor.
2976 void
2977 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2978   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2979   TargetLowering::MakeLibCallOptions CallOptions;
2980   CallOptions.setDiscardResult(true);
2981   SDValue Chain =
2982       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2983                       std::nullopt, CallOptions, getCurSDLoc())
2984           .second;
2985   // On PS4/PS5, the "return address" must still be within the calling
2986   // function, even if it's at the very end, so emit an explicit TRAP here.
2987   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2988   if (TM.getTargetTriple().isPS())
2989     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2990   // WebAssembly needs an unreachable instruction after a non-returning call,
2991   // because the function return type can be different from __stack_chk_fail's
2992   // return type (void).
2993   if (TM.getTargetTriple().isWasm())
2994     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2995 
2996   DAG.setRoot(Chain);
2997 }
2998 
2999 /// visitBitTestHeader - This function emits necessary code to produce value
3000 /// suitable for "bit tests"
3001 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
3002                                              MachineBasicBlock *SwitchBB) {
3003   SDLoc dl = getCurSDLoc();
3004 
3005   // Subtract the minimum value.
3006   SDValue SwitchOp = getValue(B.SValue);
3007   EVT VT = SwitchOp.getValueType();
3008   SDValue RangeSub =
3009       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
3010 
3011   // Determine the type of the test operands.
3012   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3013   bool UsePtrType = false;
3014   if (!TLI.isTypeLegal(VT)) {
3015     UsePtrType = true;
3016   } else {
3017     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
3018       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
3019         // Switch table case range are encoded into series of masks.
3020         // Just use pointer type, it's guaranteed to fit.
3021         UsePtrType = true;
3022         break;
3023       }
3024   }
3025   SDValue Sub = RangeSub;
3026   if (UsePtrType) {
3027     VT = TLI.getPointerTy(DAG.getDataLayout());
3028     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
3029   }
3030 
3031   B.RegVT = VT.getSimpleVT();
3032   B.Reg = FuncInfo.CreateReg(B.RegVT);
3033   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
3034 
3035   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
3036 
3037   if (!B.FallthroughUnreachable)
3038     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
3039   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
3040   SwitchBB->normalizeSuccProbs();
3041 
3042   SDValue Root = CopyTo;
3043   if (!B.FallthroughUnreachable) {
3044     // Conditional branch to the default block.
3045     SDValue RangeCmp = DAG.getSetCC(dl,
3046         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3047                                RangeSub.getValueType()),
3048         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
3049         ISD::SETUGT);
3050 
3051     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
3052                        DAG.getBasicBlock(B.Default));
3053   }
3054 
3055   // Avoid emitting unnecessary branches to the next block.
3056   if (MBB != NextBlock(SwitchBB))
3057     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
3058 
3059   DAG.setRoot(Root);
3060 }
3061 
3062 /// visitBitTestCase - this function produces one "bit test"
3063 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
3064                                            MachineBasicBlock* NextMBB,
3065                                            BranchProbability BranchProbToNext,
3066                                            unsigned Reg,
3067                                            BitTestCase &B,
3068                                            MachineBasicBlock *SwitchBB) {
3069   SDLoc dl = getCurSDLoc();
3070   MVT VT = BB.RegVT;
3071   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
3072   SDValue Cmp;
3073   unsigned PopCount = llvm::popcount(B.Mask);
3074   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3075   if (PopCount == 1) {
3076     // Testing for a single bit; just compare the shift count with what it
3077     // would need to be to shift a 1 bit in that position.
3078     Cmp = DAG.getSetCC(
3079         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3080         ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT),
3081         ISD::SETEQ);
3082   } else if (PopCount == BB.Range) {
3083     // There is only one zero bit in the range, test for it directly.
3084     Cmp = DAG.getSetCC(
3085         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3086         ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE);
3087   } else {
3088     // Make desired shift
3089     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
3090                                     DAG.getConstant(1, dl, VT), ShiftOp);
3091 
3092     // Emit bit tests and jumps
3093     SDValue AndOp = DAG.getNode(ISD::AND, dl,
3094                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
3095     Cmp = DAG.getSetCC(
3096         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3097         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
3098   }
3099 
3100   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
3101   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
3102   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
3103   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
3104   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
3105   // one as they are relative probabilities (and thus work more like weights),
3106   // and hence we need to normalize them to let the sum of them become one.
3107   SwitchBB->normalizeSuccProbs();
3108 
3109   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
3110                               MVT::Other, getControlRoot(),
3111                               Cmp, DAG.getBasicBlock(B.TargetBB));
3112 
3113   // Avoid emitting unnecessary branches to the next block.
3114   if (NextMBB != NextBlock(SwitchBB))
3115     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
3116                         DAG.getBasicBlock(NextMBB));
3117 
3118   DAG.setRoot(BrAnd);
3119 }
3120 
3121 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
3122   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
3123 
3124   // Retrieve successors. Look through artificial IR level blocks like
3125   // catchswitch for successors.
3126   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
3127   const BasicBlock *EHPadBB = I.getSuccessor(1);
3128   MachineBasicBlock *EHPadMBB = FuncInfo.MBBMap[EHPadBB];
3129 
3130   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3131   // have to do anything here to lower funclet bundles.
3132   assert(!I.hasOperandBundlesOtherThan(
3133              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
3134               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
3135               LLVMContext::OB_cfguardtarget,
3136               LLVMContext::OB_clang_arc_attachedcall}) &&
3137          "Cannot lower invokes with arbitrary operand bundles yet!");
3138 
3139   const Value *Callee(I.getCalledOperand());
3140   const Function *Fn = dyn_cast<Function>(Callee);
3141   if (isa<InlineAsm>(Callee))
3142     visitInlineAsm(I, EHPadBB);
3143   else if (Fn && Fn->isIntrinsic()) {
3144     switch (Fn->getIntrinsicID()) {
3145     default:
3146       llvm_unreachable("Cannot invoke this intrinsic");
3147     case Intrinsic::donothing:
3148       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
3149     case Intrinsic::seh_try_begin:
3150     case Intrinsic::seh_scope_begin:
3151     case Intrinsic::seh_try_end:
3152     case Intrinsic::seh_scope_end:
3153       if (EHPadMBB)
3154           // a block referenced by EH table
3155           // so dtor-funclet not removed by opts
3156           EHPadMBB->setMachineBlockAddressTaken();
3157       break;
3158     case Intrinsic::experimental_patchpoint_void:
3159     case Intrinsic::experimental_patchpoint_i64:
3160       visitPatchpoint(I, EHPadBB);
3161       break;
3162     case Intrinsic::experimental_gc_statepoint:
3163       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
3164       break;
3165     case Intrinsic::wasm_rethrow: {
3166       // This is usually done in visitTargetIntrinsic, but this intrinsic is
3167       // special because it can be invoked, so we manually lower it to a DAG
3168       // node here.
3169       SmallVector<SDValue, 8> Ops;
3170       Ops.push_back(getRoot()); // inchain
3171       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3172       Ops.push_back(
3173           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
3174                                 TLI.getPointerTy(DAG.getDataLayout())));
3175       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3176       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3177       break;
3178     }
3179     }
3180   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
3181     // Currently we do not lower any intrinsic calls with deopt operand bundles.
3182     // Eventually we will support lowering the @llvm.experimental.deoptimize
3183     // intrinsic, and right now there are no plans to support other intrinsics
3184     // with deopt state.
3185     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
3186   } else {
3187     LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
3188   }
3189 
3190   // If the value of the invoke is used outside of its defining block, make it
3191   // available as a virtual register.
3192   // We already took care of the exported value for the statepoint instruction
3193   // during call to the LowerStatepoint.
3194   if (!isa<GCStatepointInst>(I)) {
3195     CopyToExportRegsIfNeeded(&I);
3196   }
3197 
3198   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
3199   BranchProbabilityInfo *BPI = FuncInfo.BPI;
3200   BranchProbability EHPadBBProb =
3201       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3202           : BranchProbability::getZero();
3203   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
3204 
3205   // Update successor info.
3206   addSuccessorWithProb(InvokeMBB, Return);
3207   for (auto &UnwindDest : UnwindDests) {
3208     UnwindDest.first->setIsEHPad();
3209     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3210   }
3211   InvokeMBB->normalizeSuccProbs();
3212 
3213   // Drop into normal successor.
3214   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
3215                           DAG.getBasicBlock(Return)));
3216 }
3217 
3218 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3219   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3220 
3221   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3222   // have to do anything here to lower funclet bundles.
3223   assert(!I.hasOperandBundlesOtherThan(
3224              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
3225          "Cannot lower callbrs with arbitrary operand bundles yet!");
3226 
3227   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
3228   visitInlineAsm(I);
3229   CopyToExportRegsIfNeeded(&I);
3230 
3231   // Retrieve successors.
3232   SmallPtrSet<BasicBlock *, 8> Dests;
3233   Dests.insert(I.getDefaultDest());
3234   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
3235 
3236   // Update successor info.
3237   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3238   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
3239     BasicBlock *Dest = I.getIndirectDest(i);
3240     MachineBasicBlock *Target = FuncInfo.MBBMap[Dest];
3241     Target->setIsInlineAsmBrIndirectTarget();
3242     Target->setMachineBlockAddressTaken();
3243     Target->setLabelMustBeEmitted();
3244     // Don't add duplicate machine successors.
3245     if (Dests.insert(Dest).second)
3246       addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3247   }
3248   CallBrMBB->normalizeSuccProbs();
3249 
3250   // Drop into default successor.
3251   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3252                           MVT::Other, getControlRoot(),
3253                           DAG.getBasicBlock(Return)));
3254 }
3255 
3256 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3257   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3258 }
3259 
3260 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3261   assert(FuncInfo.MBB->isEHPad() &&
3262          "Call to landingpad not in landing pad!");
3263 
3264   // If there aren't registers to copy the values into (e.g., during SjLj
3265   // exceptions), then don't bother to create these DAG nodes.
3266   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3267   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3268   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3269       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3270     return;
3271 
3272   // If landingpad's return type is token type, we don't create DAG nodes
3273   // for its exception pointer and selector value. The extraction of exception
3274   // pointer or selector value from token type landingpads is not currently
3275   // supported.
3276   if (LP.getType()->isTokenTy())
3277     return;
3278 
3279   SmallVector<EVT, 2> ValueVTs;
3280   SDLoc dl = getCurSDLoc();
3281   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3282   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3283 
3284   // Get the two live-in registers as SDValues. The physregs have already been
3285   // copied into virtual registers.
3286   SDValue Ops[2];
3287   if (FuncInfo.ExceptionPointerVirtReg) {
3288     Ops[0] = DAG.getZExtOrTrunc(
3289         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3290                            FuncInfo.ExceptionPointerVirtReg,
3291                            TLI.getPointerTy(DAG.getDataLayout())),
3292         dl, ValueVTs[0]);
3293   } else {
3294     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3295   }
3296   Ops[1] = DAG.getZExtOrTrunc(
3297       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3298                          FuncInfo.ExceptionSelectorVirtReg,
3299                          TLI.getPointerTy(DAG.getDataLayout())),
3300       dl, ValueVTs[1]);
3301 
3302   // Merge into one.
3303   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3304                             DAG.getVTList(ValueVTs), Ops);
3305   setValue(&LP, Res);
3306 }
3307 
3308 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3309                                            MachineBasicBlock *Last) {
3310   // Update JTCases.
3311   for (JumpTableBlock &JTB : SL->JTCases)
3312     if (JTB.first.HeaderBB == First)
3313       JTB.first.HeaderBB = Last;
3314 
3315   // Update BitTestCases.
3316   for (BitTestBlock &BTB : SL->BitTestCases)
3317     if (BTB.Parent == First)
3318       BTB.Parent = Last;
3319 }
3320 
3321 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3322   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3323 
3324   // Update machine-CFG edges with unique successors.
3325   SmallSet<BasicBlock*, 32> Done;
3326   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3327     BasicBlock *BB = I.getSuccessor(i);
3328     bool Inserted = Done.insert(BB).second;
3329     if (!Inserted)
3330         continue;
3331 
3332     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
3333     addSuccessorWithProb(IndirectBrMBB, Succ);
3334   }
3335   IndirectBrMBB->normalizeSuccProbs();
3336 
3337   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3338                           MVT::Other, getControlRoot(),
3339                           getValue(I.getAddress())));
3340 }
3341 
3342 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3343   if (!DAG.getTarget().Options.TrapUnreachable)
3344     return;
3345 
3346   // We may be able to ignore unreachable behind a noreturn call.
3347   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
3348     if (const CallInst *Call = dyn_cast_or_null<CallInst>(I.getPrevNode())) {
3349       if (Call->doesNotReturn())
3350         return;
3351     }
3352   }
3353 
3354   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3355 }
3356 
3357 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3358   SDNodeFlags Flags;
3359   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3360     Flags.copyFMF(*FPOp);
3361 
3362   SDValue Op = getValue(I.getOperand(0));
3363   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3364                                     Op, Flags);
3365   setValue(&I, UnNodeValue);
3366 }
3367 
3368 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3369   SDNodeFlags Flags;
3370   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3371     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3372     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3373   }
3374   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3375     Flags.setExact(ExactOp->isExact());
3376   if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&I))
3377     Flags.setDisjoint(DisjointOp->isDisjoint());
3378   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3379     Flags.copyFMF(*FPOp);
3380 
3381   SDValue Op1 = getValue(I.getOperand(0));
3382   SDValue Op2 = getValue(I.getOperand(1));
3383   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3384                                      Op1, Op2, Flags);
3385   setValue(&I, BinNodeValue);
3386 }
3387 
3388 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3389   SDValue Op1 = getValue(I.getOperand(0));
3390   SDValue Op2 = getValue(I.getOperand(1));
3391 
3392   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3393       Op1.getValueType(), DAG.getDataLayout());
3394 
3395   // Coerce the shift amount to the right type if we can. This exposes the
3396   // truncate or zext to optimization early.
3397   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3398     assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) &&
3399            "Unexpected shift type");
3400     Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3401   }
3402 
3403   bool nuw = false;
3404   bool nsw = false;
3405   bool exact = false;
3406 
3407   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3408 
3409     if (const OverflowingBinaryOperator *OFBinOp =
3410             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3411       nuw = OFBinOp->hasNoUnsignedWrap();
3412       nsw = OFBinOp->hasNoSignedWrap();
3413     }
3414     if (const PossiblyExactOperator *ExactOp =
3415             dyn_cast<const PossiblyExactOperator>(&I))
3416       exact = ExactOp->isExact();
3417   }
3418   SDNodeFlags Flags;
3419   Flags.setExact(exact);
3420   Flags.setNoSignedWrap(nsw);
3421   Flags.setNoUnsignedWrap(nuw);
3422   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3423                             Flags);
3424   setValue(&I, Res);
3425 }
3426 
3427 void SelectionDAGBuilder::visitSDiv(const User &I) {
3428   SDValue Op1 = getValue(I.getOperand(0));
3429   SDValue Op2 = getValue(I.getOperand(1));
3430 
3431   SDNodeFlags Flags;
3432   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3433                  cast<PossiblyExactOperator>(&I)->isExact());
3434   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3435                            Op2, Flags));
3436 }
3437 
3438 void SelectionDAGBuilder::visitICmp(const User &I) {
3439   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3440   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3441     predicate = IC->getPredicate();
3442   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3443     predicate = ICmpInst::Predicate(IC->getPredicate());
3444   SDValue Op1 = getValue(I.getOperand(0));
3445   SDValue Op2 = getValue(I.getOperand(1));
3446   ISD::CondCode Opcode = getICmpCondCode(predicate);
3447 
3448   auto &TLI = DAG.getTargetLoweringInfo();
3449   EVT MemVT =
3450       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3451 
3452   // If a pointer's DAG type is larger than its memory type then the DAG values
3453   // are zero-extended. This breaks signed comparisons so truncate back to the
3454   // underlying type before doing the compare.
3455   if (Op1.getValueType() != MemVT) {
3456     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3457     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3458   }
3459 
3460   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3461                                                         I.getType());
3462   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3463 }
3464 
3465 void SelectionDAGBuilder::visitFCmp(const User &I) {
3466   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3467   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3468     predicate = FC->getPredicate();
3469   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3470     predicate = FCmpInst::Predicate(FC->getPredicate());
3471   SDValue Op1 = getValue(I.getOperand(0));
3472   SDValue Op2 = getValue(I.getOperand(1));
3473 
3474   ISD::CondCode Condition = getFCmpCondCode(predicate);
3475   auto *FPMO = cast<FPMathOperator>(&I);
3476   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3477     Condition = getFCmpCodeWithoutNaN(Condition);
3478 
3479   SDNodeFlags Flags;
3480   Flags.copyFMF(*FPMO);
3481   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3482 
3483   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3484                                                         I.getType());
3485   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3486 }
3487 
3488 // Check if the condition of the select has one use or two users that are both
3489 // selects with the same condition.
3490 static bool hasOnlySelectUsers(const Value *Cond) {
3491   return llvm::all_of(Cond->users(), [](const Value *V) {
3492     return isa<SelectInst>(V);
3493   });
3494 }
3495 
3496 void SelectionDAGBuilder::visitSelect(const User &I) {
3497   SmallVector<EVT, 4> ValueVTs;
3498   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3499                   ValueVTs);
3500   unsigned NumValues = ValueVTs.size();
3501   if (NumValues == 0) return;
3502 
3503   SmallVector<SDValue, 4> Values(NumValues);
3504   SDValue Cond     = getValue(I.getOperand(0));
3505   SDValue LHSVal   = getValue(I.getOperand(1));
3506   SDValue RHSVal   = getValue(I.getOperand(2));
3507   SmallVector<SDValue, 1> BaseOps(1, Cond);
3508   ISD::NodeType OpCode =
3509       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3510 
3511   bool IsUnaryAbs = false;
3512   bool Negate = false;
3513 
3514   SDNodeFlags Flags;
3515   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3516     Flags.copyFMF(*FPOp);
3517 
3518   Flags.setUnpredictable(
3519       cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable));
3520 
3521   // Min/max matching is only viable if all output VTs are the same.
3522   if (all_equal(ValueVTs)) {
3523     EVT VT = ValueVTs[0];
3524     LLVMContext &Ctx = *DAG.getContext();
3525     auto &TLI = DAG.getTargetLoweringInfo();
3526 
3527     // We care about the legality of the operation after it has been type
3528     // legalized.
3529     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3530       VT = TLI.getTypeToTransformTo(Ctx, VT);
3531 
3532     // If the vselect is legal, assume we want to leave this as a vector setcc +
3533     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3534     // min/max is legal on the scalar type.
3535     bool UseScalarMinMax = VT.isVector() &&
3536       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3537 
3538     // ValueTracking's select pattern matching does not account for -0.0,
3539     // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that
3540     // -0.0 is less than +0.0.
3541     Value *LHS, *RHS;
3542     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3543     ISD::NodeType Opc = ISD::DELETED_NODE;
3544     switch (SPR.Flavor) {
3545     case SPF_UMAX:    Opc = ISD::UMAX; break;
3546     case SPF_UMIN:    Opc = ISD::UMIN; break;
3547     case SPF_SMAX:    Opc = ISD::SMAX; break;
3548     case SPF_SMIN:    Opc = ISD::SMIN; break;
3549     case SPF_FMINNUM:
3550       switch (SPR.NaNBehavior) {
3551       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3552       case SPNB_RETURNS_NAN: break;
3553       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3554       case SPNB_RETURNS_ANY:
3555         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) ||
3556             (UseScalarMinMax &&
3557              TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType())))
3558           Opc = ISD::FMINNUM;
3559         break;
3560       }
3561       break;
3562     case SPF_FMAXNUM:
3563       switch (SPR.NaNBehavior) {
3564       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3565       case SPNB_RETURNS_NAN: break;
3566       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3567       case SPNB_RETURNS_ANY:
3568         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) ||
3569             (UseScalarMinMax &&
3570              TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType())))
3571           Opc = ISD::FMAXNUM;
3572         break;
3573       }
3574       break;
3575     case SPF_NABS:
3576       Negate = true;
3577       [[fallthrough]];
3578     case SPF_ABS:
3579       IsUnaryAbs = true;
3580       Opc = ISD::ABS;
3581       break;
3582     default: break;
3583     }
3584 
3585     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3586         (TLI.isOperationLegalOrCustomOrPromote(Opc, VT) ||
3587          (UseScalarMinMax &&
3588           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3589         // If the underlying comparison instruction is used by any other
3590         // instruction, the consumed instructions won't be destroyed, so it is
3591         // not profitable to convert to a min/max.
3592         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3593       OpCode = Opc;
3594       LHSVal = getValue(LHS);
3595       RHSVal = getValue(RHS);
3596       BaseOps.clear();
3597     }
3598 
3599     if (IsUnaryAbs) {
3600       OpCode = Opc;
3601       LHSVal = getValue(LHS);
3602       BaseOps.clear();
3603     }
3604   }
3605 
3606   if (IsUnaryAbs) {
3607     for (unsigned i = 0; i != NumValues; ++i) {
3608       SDLoc dl = getCurSDLoc();
3609       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3610       Values[i] =
3611           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3612       if (Negate)
3613         Values[i] = DAG.getNegative(Values[i], dl, VT);
3614     }
3615   } else {
3616     for (unsigned i = 0; i != NumValues; ++i) {
3617       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3618       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3619       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3620       Values[i] = DAG.getNode(
3621           OpCode, getCurSDLoc(),
3622           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3623     }
3624   }
3625 
3626   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3627                            DAG.getVTList(ValueVTs), Values));
3628 }
3629 
3630 void SelectionDAGBuilder::visitTrunc(const User &I) {
3631   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3632   SDValue N = getValue(I.getOperand(0));
3633   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3634                                                         I.getType());
3635   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3636 }
3637 
3638 void SelectionDAGBuilder::visitZExt(const User &I) {
3639   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3640   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3641   SDValue N = getValue(I.getOperand(0));
3642   auto &TLI = DAG.getTargetLoweringInfo();
3643   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3644 
3645   SDNodeFlags Flags;
3646   if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
3647     Flags.setNonNeg(PNI->hasNonNeg());
3648 
3649   // Eagerly use nonneg information to canonicalize towards sign_extend if
3650   // that is the target's preference.
3651   // TODO: Let the target do this later.
3652   if (Flags.hasNonNeg() &&
3653       TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) {
3654     setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3655     return;
3656   }
3657 
3658   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags));
3659 }
3660 
3661 void SelectionDAGBuilder::visitSExt(const User &I) {
3662   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3663   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3664   SDValue N = getValue(I.getOperand(0));
3665   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3666                                                         I.getType());
3667   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3668 }
3669 
3670 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3671   // FPTrunc is never a no-op cast, no need to check
3672   SDValue N = getValue(I.getOperand(0));
3673   SDLoc dl = getCurSDLoc();
3674   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3675   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3676   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3677                            DAG.getTargetConstant(
3678                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3679 }
3680 
3681 void SelectionDAGBuilder::visitFPExt(const User &I) {
3682   // FPExt is never a no-op cast, no need to check
3683   SDValue N = getValue(I.getOperand(0));
3684   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3685                                                         I.getType());
3686   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3687 }
3688 
3689 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3690   // FPToUI is never a no-op cast, no need to check
3691   SDValue N = getValue(I.getOperand(0));
3692   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3693                                                         I.getType());
3694   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3695 }
3696 
3697 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3698   // FPToSI is never a no-op cast, no need to check
3699   SDValue N = getValue(I.getOperand(0));
3700   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3701                                                         I.getType());
3702   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3703 }
3704 
3705 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3706   // UIToFP is never a no-op cast, no need to check
3707   SDValue N = getValue(I.getOperand(0));
3708   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3709                                                         I.getType());
3710   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3711 }
3712 
3713 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3714   // SIToFP is never a no-op cast, no need to check
3715   SDValue N = getValue(I.getOperand(0));
3716   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3717                                                         I.getType());
3718   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3719 }
3720 
3721 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3722   // What to do depends on the size of the integer and the size of the pointer.
3723   // We can either truncate, zero extend, or no-op, accordingly.
3724   SDValue N = getValue(I.getOperand(0));
3725   auto &TLI = DAG.getTargetLoweringInfo();
3726   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3727                                                         I.getType());
3728   EVT PtrMemVT =
3729       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3730   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3731   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3732   setValue(&I, N);
3733 }
3734 
3735 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3736   // What to do depends on the size of the integer and the size of the pointer.
3737   // We can either truncate, zero extend, or no-op, accordingly.
3738   SDValue N = getValue(I.getOperand(0));
3739   auto &TLI = DAG.getTargetLoweringInfo();
3740   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3741   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3742   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3743   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3744   setValue(&I, N);
3745 }
3746 
3747 void SelectionDAGBuilder::visitBitCast(const User &I) {
3748   SDValue N = getValue(I.getOperand(0));
3749   SDLoc dl = getCurSDLoc();
3750   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3751                                                         I.getType());
3752 
3753   // BitCast assures us that source and destination are the same size so this is
3754   // either a BITCAST or a no-op.
3755   if (DestVT != N.getValueType())
3756     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3757                              DestVT, N)); // convert types.
3758   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3759   // might fold any kind of constant expression to an integer constant and that
3760   // is not what we are looking for. Only recognize a bitcast of a genuine
3761   // constant integer as an opaque constant.
3762   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3763     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3764                                  /*isOpaque*/true));
3765   else
3766     setValue(&I, N);            // noop cast.
3767 }
3768 
3769 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3770   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3771   const Value *SV = I.getOperand(0);
3772   SDValue N = getValue(SV);
3773   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3774 
3775   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3776   unsigned DestAS = I.getType()->getPointerAddressSpace();
3777 
3778   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3779     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3780 
3781   setValue(&I, N);
3782 }
3783 
3784 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3785   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3786   SDValue InVec = getValue(I.getOperand(0));
3787   SDValue InVal = getValue(I.getOperand(1));
3788   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3789                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3790   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3791                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3792                            InVec, InVal, InIdx));
3793 }
3794 
3795 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3796   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3797   SDValue InVec = getValue(I.getOperand(0));
3798   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3799                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3800   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3801                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3802                            InVec, InIdx));
3803 }
3804 
3805 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3806   SDValue Src1 = getValue(I.getOperand(0));
3807   SDValue Src2 = getValue(I.getOperand(1));
3808   ArrayRef<int> Mask;
3809   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3810     Mask = SVI->getShuffleMask();
3811   else
3812     Mask = cast<ConstantExpr>(I).getShuffleMask();
3813   SDLoc DL = getCurSDLoc();
3814   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3815   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3816   EVT SrcVT = Src1.getValueType();
3817 
3818   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3819       VT.isScalableVector()) {
3820     // Canonical splat form of first element of first input vector.
3821     SDValue FirstElt =
3822         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3823                     DAG.getVectorIdxConstant(0, DL));
3824     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3825     return;
3826   }
3827 
3828   // For now, we only handle splats for scalable vectors.
3829   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3830   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3831   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3832 
3833   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3834   unsigned MaskNumElts = Mask.size();
3835 
3836   if (SrcNumElts == MaskNumElts) {
3837     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3838     return;
3839   }
3840 
3841   // Normalize the shuffle vector since mask and vector length don't match.
3842   if (SrcNumElts < MaskNumElts) {
3843     // Mask is longer than the source vectors. We can use concatenate vector to
3844     // make the mask and vectors lengths match.
3845 
3846     if (MaskNumElts % SrcNumElts == 0) {
3847       // Mask length is a multiple of the source vector length.
3848       // Check if the shuffle is some kind of concatenation of the input
3849       // vectors.
3850       unsigned NumConcat = MaskNumElts / SrcNumElts;
3851       bool IsConcat = true;
3852       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3853       for (unsigned i = 0; i != MaskNumElts; ++i) {
3854         int Idx = Mask[i];
3855         if (Idx < 0)
3856           continue;
3857         // Ensure the indices in each SrcVT sized piece are sequential and that
3858         // the same source is used for the whole piece.
3859         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3860             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3861              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3862           IsConcat = false;
3863           break;
3864         }
3865         // Remember which source this index came from.
3866         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3867       }
3868 
3869       // The shuffle is concatenating multiple vectors together. Just emit
3870       // a CONCAT_VECTORS operation.
3871       if (IsConcat) {
3872         SmallVector<SDValue, 8> ConcatOps;
3873         for (auto Src : ConcatSrcs) {
3874           if (Src < 0)
3875             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3876           else if (Src == 0)
3877             ConcatOps.push_back(Src1);
3878           else
3879             ConcatOps.push_back(Src2);
3880         }
3881         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3882         return;
3883       }
3884     }
3885 
3886     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3887     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3888     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3889                                     PaddedMaskNumElts);
3890 
3891     // Pad both vectors with undefs to make them the same length as the mask.
3892     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3893 
3894     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3895     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3896     MOps1[0] = Src1;
3897     MOps2[0] = Src2;
3898 
3899     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3900     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3901 
3902     // Readjust mask for new input vector length.
3903     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3904     for (unsigned i = 0; i != MaskNumElts; ++i) {
3905       int Idx = Mask[i];
3906       if (Idx >= (int)SrcNumElts)
3907         Idx -= SrcNumElts - PaddedMaskNumElts;
3908       MappedOps[i] = Idx;
3909     }
3910 
3911     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3912 
3913     // If the concatenated vector was padded, extract a subvector with the
3914     // correct number of elements.
3915     if (MaskNumElts != PaddedMaskNumElts)
3916       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3917                            DAG.getVectorIdxConstant(0, DL));
3918 
3919     setValue(&I, Result);
3920     return;
3921   }
3922 
3923   if (SrcNumElts > MaskNumElts) {
3924     // Analyze the access pattern of the vector to see if we can extract
3925     // two subvectors and do the shuffle.
3926     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3927     bool CanExtract = true;
3928     for (int Idx : Mask) {
3929       unsigned Input = 0;
3930       if (Idx < 0)
3931         continue;
3932 
3933       if (Idx >= (int)SrcNumElts) {
3934         Input = 1;
3935         Idx -= SrcNumElts;
3936       }
3937 
3938       // If all the indices come from the same MaskNumElts sized portion of
3939       // the sources we can use extract. Also make sure the extract wouldn't
3940       // extract past the end of the source.
3941       int NewStartIdx = alignDown(Idx, MaskNumElts);
3942       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3943           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3944         CanExtract = false;
3945       // Make sure we always update StartIdx as we use it to track if all
3946       // elements are undef.
3947       StartIdx[Input] = NewStartIdx;
3948     }
3949 
3950     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3951       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3952       return;
3953     }
3954     if (CanExtract) {
3955       // Extract appropriate subvector and generate a vector shuffle
3956       for (unsigned Input = 0; Input < 2; ++Input) {
3957         SDValue &Src = Input == 0 ? Src1 : Src2;
3958         if (StartIdx[Input] < 0)
3959           Src = DAG.getUNDEF(VT);
3960         else {
3961           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3962                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3963         }
3964       }
3965 
3966       // Calculate new mask.
3967       SmallVector<int, 8> MappedOps(Mask);
3968       for (int &Idx : MappedOps) {
3969         if (Idx >= (int)SrcNumElts)
3970           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3971         else if (Idx >= 0)
3972           Idx -= StartIdx[0];
3973       }
3974 
3975       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3976       return;
3977     }
3978   }
3979 
3980   // We can't use either concat vectors or extract subvectors so fall back to
3981   // replacing the shuffle with extract and build vector.
3982   // to insert and build vector.
3983   EVT EltVT = VT.getVectorElementType();
3984   SmallVector<SDValue,8> Ops;
3985   for (int Idx : Mask) {
3986     SDValue Res;
3987 
3988     if (Idx < 0) {
3989       Res = DAG.getUNDEF(EltVT);
3990     } else {
3991       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3992       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3993 
3994       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3995                         DAG.getVectorIdxConstant(Idx, DL));
3996     }
3997 
3998     Ops.push_back(Res);
3999   }
4000 
4001   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
4002 }
4003 
4004 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
4005   ArrayRef<unsigned> Indices = I.getIndices();
4006   const Value *Op0 = I.getOperand(0);
4007   const Value *Op1 = I.getOperand(1);
4008   Type *AggTy = I.getType();
4009   Type *ValTy = Op1->getType();
4010   bool IntoUndef = isa<UndefValue>(Op0);
4011   bool FromUndef = isa<UndefValue>(Op1);
4012 
4013   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4014 
4015   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4016   SmallVector<EVT, 4> AggValueVTs;
4017   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
4018   SmallVector<EVT, 4> ValValueVTs;
4019   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4020 
4021   unsigned NumAggValues = AggValueVTs.size();
4022   unsigned NumValValues = ValValueVTs.size();
4023   SmallVector<SDValue, 4> Values(NumAggValues);
4024 
4025   // Ignore an insertvalue that produces an empty object
4026   if (!NumAggValues) {
4027     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4028     return;
4029   }
4030 
4031   SDValue Agg = getValue(Op0);
4032   unsigned i = 0;
4033   // Copy the beginning value(s) from the original aggregate.
4034   for (; i != LinearIndex; ++i)
4035     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4036                 SDValue(Agg.getNode(), Agg.getResNo() + i);
4037   // Copy values from the inserted value(s).
4038   if (NumValValues) {
4039     SDValue Val = getValue(Op1);
4040     for (; i != LinearIndex + NumValValues; ++i)
4041       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4042                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
4043   }
4044   // Copy remaining value(s) from the original aggregate.
4045   for (; i != NumAggValues; ++i)
4046     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4047                 SDValue(Agg.getNode(), Agg.getResNo() + i);
4048 
4049   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
4050                            DAG.getVTList(AggValueVTs), Values));
4051 }
4052 
4053 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
4054   ArrayRef<unsigned> Indices = I.getIndices();
4055   const Value *Op0 = I.getOperand(0);
4056   Type *AggTy = Op0->getType();
4057   Type *ValTy = I.getType();
4058   bool OutOfUndef = isa<UndefValue>(Op0);
4059 
4060   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4061 
4062   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4063   SmallVector<EVT, 4> ValValueVTs;
4064   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4065 
4066   unsigned NumValValues = ValValueVTs.size();
4067 
4068   // Ignore a extractvalue that produces an empty object
4069   if (!NumValValues) {
4070     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4071     return;
4072   }
4073 
4074   SmallVector<SDValue, 4> Values(NumValValues);
4075 
4076   SDValue Agg = getValue(Op0);
4077   // Copy out the selected value(s).
4078   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
4079     Values[i - LinearIndex] =
4080       OutOfUndef ?
4081         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
4082         SDValue(Agg.getNode(), Agg.getResNo() + i);
4083 
4084   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
4085                            DAG.getVTList(ValValueVTs), Values));
4086 }
4087 
4088 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
4089   Value *Op0 = I.getOperand(0);
4090   // Note that the pointer operand may be a vector of pointers. Take the scalar
4091   // element which holds a pointer.
4092   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
4093   SDValue N = getValue(Op0);
4094   SDLoc dl = getCurSDLoc();
4095   auto &TLI = DAG.getTargetLoweringInfo();
4096 
4097   // Normalize Vector GEP - all scalar operands should be converted to the
4098   // splat vector.
4099   bool IsVectorGEP = I.getType()->isVectorTy();
4100   ElementCount VectorElementCount =
4101       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
4102                   : ElementCount::getFixed(0);
4103 
4104   if (IsVectorGEP && !N.getValueType().isVector()) {
4105     LLVMContext &Context = *DAG.getContext();
4106     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
4107     N = DAG.getSplat(VT, dl, N);
4108   }
4109 
4110   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
4111        GTI != E; ++GTI) {
4112     const Value *Idx = GTI.getOperand();
4113     if (StructType *StTy = GTI.getStructTypeOrNull()) {
4114       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
4115       if (Field) {
4116         // N = N + Offset
4117         uint64_t Offset =
4118             DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
4119 
4120         // In an inbounds GEP with an offset that is nonnegative even when
4121         // interpreted as signed, assume there is no unsigned overflow.
4122         SDNodeFlags Flags;
4123         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
4124           Flags.setNoUnsignedWrap(true);
4125 
4126         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
4127                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
4128       }
4129     } else {
4130       // IdxSize is the width of the arithmetic according to IR semantics.
4131       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
4132       // (and fix up the result later).
4133       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
4134       MVT IdxTy = MVT::getIntegerVT(IdxSize);
4135       TypeSize ElementSize =
4136           GTI.getSequentialElementStride(DAG.getDataLayout());
4137       // We intentionally mask away the high bits here; ElementSize may not
4138       // fit in IdxTy.
4139       APInt ElementMul(IdxSize, ElementSize.getKnownMinValue());
4140       bool ElementScalable = ElementSize.isScalable();
4141 
4142       // If this is a scalar constant or a splat vector of constants,
4143       // handle it quickly.
4144       const auto *C = dyn_cast<Constant>(Idx);
4145       if (C && isa<VectorType>(C->getType()))
4146         C = C->getSplatValue();
4147 
4148       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
4149       if (CI && CI->isZero())
4150         continue;
4151       if (CI && !ElementScalable) {
4152         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
4153         LLVMContext &Context = *DAG.getContext();
4154         SDValue OffsVal;
4155         if (IsVectorGEP)
4156           OffsVal = DAG.getConstant(
4157               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
4158         else
4159           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
4160 
4161         // In an inbounds GEP with an offset that is nonnegative even when
4162         // interpreted as signed, assume there is no unsigned overflow.
4163         SDNodeFlags Flags;
4164         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
4165           Flags.setNoUnsignedWrap(true);
4166 
4167         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
4168 
4169         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
4170         continue;
4171       }
4172 
4173       // N = N + Idx * ElementMul;
4174       SDValue IdxN = getValue(Idx);
4175 
4176       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
4177         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
4178                                   VectorElementCount);
4179         IdxN = DAG.getSplat(VT, dl, IdxN);
4180       }
4181 
4182       // If the index is smaller or larger than intptr_t, truncate or extend
4183       // it.
4184       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
4185 
4186       if (ElementScalable) {
4187         EVT VScaleTy = N.getValueType().getScalarType();
4188         SDValue VScale = DAG.getNode(
4189             ISD::VSCALE, dl, VScaleTy,
4190             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
4191         if (IsVectorGEP)
4192           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
4193         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
4194       } else {
4195         // If this is a multiply by a power of two, turn it into a shl
4196         // immediately.  This is a very common case.
4197         if (ElementMul != 1) {
4198           if (ElementMul.isPowerOf2()) {
4199             unsigned Amt = ElementMul.logBase2();
4200             IdxN = DAG.getNode(ISD::SHL, dl,
4201                                N.getValueType(), IdxN,
4202                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
4203           } else {
4204             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
4205                                             IdxN.getValueType());
4206             IdxN = DAG.getNode(ISD::MUL, dl,
4207                                N.getValueType(), IdxN, Scale);
4208           }
4209         }
4210       }
4211 
4212       N = DAG.getNode(ISD::ADD, dl,
4213                       N.getValueType(), N, IdxN);
4214     }
4215   }
4216 
4217   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4218   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4219   if (IsVectorGEP) {
4220     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4221     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4222   }
4223 
4224   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4225     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4226 
4227   setValue(&I, N);
4228 }
4229 
4230 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4231   // If this is a fixed sized alloca in the entry block of the function,
4232   // allocate it statically on the stack.
4233   if (FuncInfo.StaticAllocaMap.count(&I))
4234     return;   // getValue will auto-populate this.
4235 
4236   SDLoc dl = getCurSDLoc();
4237   Type *Ty = I.getAllocatedType();
4238   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4239   auto &DL = DAG.getDataLayout();
4240   TypeSize TySize = DL.getTypeAllocSize(Ty);
4241   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4242 
4243   SDValue AllocSize = getValue(I.getArraySize());
4244 
4245   EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace());
4246   if (AllocSize.getValueType() != IntPtr)
4247     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4248 
4249   if (TySize.isScalable())
4250     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4251                             DAG.getVScale(dl, IntPtr,
4252                                           APInt(IntPtr.getScalarSizeInBits(),
4253                                                 TySize.getKnownMinValue())));
4254   else {
4255     SDValue TySizeValue =
4256         DAG.getConstant(TySize.getFixedValue(), dl, MVT::getIntegerVT(64));
4257     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4258                             DAG.getZExtOrTrunc(TySizeValue, dl, IntPtr));
4259   }
4260 
4261   // Handle alignment.  If the requested alignment is less than or equal to
4262   // the stack alignment, ignore it.  If the size is greater than or equal to
4263   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4264   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4265   if (*Alignment <= StackAlign)
4266     Alignment = std::nullopt;
4267 
4268   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4269   // Round the size of the allocation up to the stack alignment size
4270   // by add SA-1 to the size. This doesn't overflow because we're computing
4271   // an address inside an alloca.
4272   SDNodeFlags Flags;
4273   Flags.setNoUnsignedWrap(true);
4274   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4275                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4276 
4277   // Mask out the low bits for alignment purposes.
4278   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4279                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
4280 
4281   SDValue Ops[] = {
4282       getRoot(), AllocSize,
4283       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4284   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4285   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4286   setValue(&I, DSA);
4287   DAG.setRoot(DSA.getValue(1));
4288 
4289   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4290 }
4291 
4292 static const MDNode *getRangeMetadata(const Instruction &I) {
4293   // If !noundef is not present, then !range violation results in a poison
4294   // value rather than immediate undefined behavior. In theory, transferring
4295   // these annotations to SDAG is fine, but in practice there are key SDAG
4296   // transforms that are known not to be poison-safe, such as folding logical
4297   // and/or to bitwise and/or. For now, only transfer !range if !noundef is
4298   // also present.
4299   if (!I.hasMetadata(LLVMContext::MD_noundef))
4300     return nullptr;
4301   return I.getMetadata(LLVMContext::MD_range);
4302 }
4303 
4304 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4305   if (I.isAtomic())
4306     return visitAtomicLoad(I);
4307 
4308   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4309   const Value *SV = I.getOperand(0);
4310   if (TLI.supportSwiftError()) {
4311     // Swifterror values can come from either a function parameter with
4312     // swifterror attribute or an alloca with swifterror attribute.
4313     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4314       if (Arg->hasSwiftErrorAttr())
4315         return visitLoadFromSwiftError(I);
4316     }
4317 
4318     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4319       if (Alloca->isSwiftError())
4320         return visitLoadFromSwiftError(I);
4321     }
4322   }
4323 
4324   SDValue Ptr = getValue(SV);
4325 
4326   Type *Ty = I.getType();
4327   SmallVector<EVT, 4> ValueVTs, MemVTs;
4328   SmallVector<TypeSize, 4> Offsets;
4329   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets, 0);
4330   unsigned NumValues = ValueVTs.size();
4331   if (NumValues == 0)
4332     return;
4333 
4334   Align Alignment = I.getAlign();
4335   AAMDNodes AAInfo = I.getAAMetadata();
4336   const MDNode *Ranges = getRangeMetadata(I);
4337   bool isVolatile = I.isVolatile();
4338   MachineMemOperand::Flags MMOFlags =
4339       TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4340 
4341   SDValue Root;
4342   bool ConstantMemory = false;
4343   if (isVolatile)
4344     // Serialize volatile loads with other side effects.
4345     Root = getRoot();
4346   else if (NumValues > MaxParallelChains)
4347     Root = getMemoryRoot();
4348   else if (AA &&
4349            AA->pointsToConstantMemory(MemoryLocation(
4350                SV,
4351                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4352                AAInfo))) {
4353     // Do not serialize (non-volatile) loads of constant memory with anything.
4354     Root = DAG.getEntryNode();
4355     ConstantMemory = true;
4356     MMOFlags |= MachineMemOperand::MOInvariant;
4357   } else {
4358     // Do not serialize non-volatile loads against each other.
4359     Root = DAG.getRoot();
4360   }
4361 
4362   SDLoc dl = getCurSDLoc();
4363 
4364   if (isVolatile)
4365     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4366 
4367   SmallVector<SDValue, 4> Values(NumValues);
4368   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4369 
4370   unsigned ChainI = 0;
4371   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4372     // Serializing loads here may result in excessive register pressure, and
4373     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4374     // could recover a bit by hoisting nodes upward in the chain by recognizing
4375     // they are side-effect free or do not alias. The optimizer should really
4376     // avoid this case by converting large object/array copies to llvm.memcpy
4377     // (MaxParallelChains should always remain as failsafe).
4378     if (ChainI == MaxParallelChains) {
4379       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4380       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4381                                   ArrayRef(Chains.data(), ChainI));
4382       Root = Chain;
4383       ChainI = 0;
4384     }
4385 
4386     // TODO: MachinePointerInfo only supports a fixed length offset.
4387     MachinePointerInfo PtrInfo =
4388         !Offsets[i].isScalable() || Offsets[i].isZero()
4389             ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue())
4390             : MachinePointerInfo();
4391 
4392     SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4393     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment,
4394                             MMOFlags, AAInfo, Ranges);
4395     Chains[ChainI] = L.getValue(1);
4396 
4397     if (MemVTs[i] != ValueVTs[i])
4398       L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]);
4399 
4400     Values[i] = L;
4401   }
4402 
4403   if (!ConstantMemory) {
4404     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4405                                 ArrayRef(Chains.data(), ChainI));
4406     if (isVolatile)
4407       DAG.setRoot(Chain);
4408     else
4409       PendingLoads.push_back(Chain);
4410   }
4411 
4412   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4413                            DAG.getVTList(ValueVTs), Values));
4414 }
4415 
4416 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4417   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4418          "call visitStoreToSwiftError when backend supports swifterror");
4419 
4420   SmallVector<EVT, 4> ValueVTs;
4421   SmallVector<uint64_t, 4> Offsets;
4422   const Value *SrcV = I.getOperand(0);
4423   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4424                   SrcV->getType(), ValueVTs, &Offsets, 0);
4425   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4426          "expect a single EVT for swifterror");
4427 
4428   SDValue Src = getValue(SrcV);
4429   // Create a virtual register, then update the virtual register.
4430   Register VReg =
4431       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4432   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4433   // Chain can be getRoot or getControlRoot.
4434   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4435                                       SDValue(Src.getNode(), Src.getResNo()));
4436   DAG.setRoot(CopyNode);
4437 }
4438 
4439 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4440   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4441          "call visitLoadFromSwiftError when backend supports swifterror");
4442 
4443   assert(!I.isVolatile() &&
4444          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4445          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4446          "Support volatile, non temporal, invariant for load_from_swift_error");
4447 
4448   const Value *SV = I.getOperand(0);
4449   Type *Ty = I.getType();
4450   assert(
4451       (!AA ||
4452        !AA->pointsToConstantMemory(MemoryLocation(
4453            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4454            I.getAAMetadata()))) &&
4455       "load_from_swift_error should not be constant memory");
4456 
4457   SmallVector<EVT, 4> ValueVTs;
4458   SmallVector<uint64_t, 4> Offsets;
4459   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4460                   ValueVTs, &Offsets, 0);
4461   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4462          "expect a single EVT for swifterror");
4463 
4464   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4465   SDValue L = DAG.getCopyFromReg(
4466       getRoot(), getCurSDLoc(),
4467       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4468 
4469   setValue(&I, L);
4470 }
4471 
4472 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4473   if (I.isAtomic())
4474     return visitAtomicStore(I);
4475 
4476   const Value *SrcV = I.getOperand(0);
4477   const Value *PtrV = I.getOperand(1);
4478 
4479   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4480   if (TLI.supportSwiftError()) {
4481     // Swifterror values can come from either a function parameter with
4482     // swifterror attribute or an alloca with swifterror attribute.
4483     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4484       if (Arg->hasSwiftErrorAttr())
4485         return visitStoreToSwiftError(I);
4486     }
4487 
4488     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4489       if (Alloca->isSwiftError())
4490         return visitStoreToSwiftError(I);
4491     }
4492   }
4493 
4494   SmallVector<EVT, 4> ValueVTs, MemVTs;
4495   SmallVector<TypeSize, 4> Offsets;
4496   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4497                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets, 0);
4498   unsigned NumValues = ValueVTs.size();
4499   if (NumValues == 0)
4500     return;
4501 
4502   // Get the lowered operands. Note that we do this after
4503   // checking if NumResults is zero, because with zero results
4504   // the operands won't have values in the map.
4505   SDValue Src = getValue(SrcV);
4506   SDValue Ptr = getValue(PtrV);
4507 
4508   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4509   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4510   SDLoc dl = getCurSDLoc();
4511   Align Alignment = I.getAlign();
4512   AAMDNodes AAInfo = I.getAAMetadata();
4513 
4514   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4515 
4516   unsigned ChainI = 0;
4517   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4518     // See visitLoad comments.
4519     if (ChainI == MaxParallelChains) {
4520       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4521                                   ArrayRef(Chains.data(), ChainI));
4522       Root = Chain;
4523       ChainI = 0;
4524     }
4525 
4526     // TODO: MachinePointerInfo only supports a fixed length offset.
4527     MachinePointerInfo PtrInfo =
4528         !Offsets[i].isScalable() || Offsets[i].isZero()
4529             ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue())
4530             : MachinePointerInfo();
4531 
4532     SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4533     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4534     if (MemVTs[i] != ValueVTs[i])
4535       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4536     SDValue St =
4537         DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags, AAInfo);
4538     Chains[ChainI] = St;
4539   }
4540 
4541   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4542                                   ArrayRef(Chains.data(), ChainI));
4543   setValue(&I, StoreNode);
4544   DAG.setRoot(StoreNode);
4545 }
4546 
4547 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4548                                            bool IsCompressing) {
4549   SDLoc sdl = getCurSDLoc();
4550 
4551   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4552                                MaybeAlign &Alignment) {
4553     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4554     Src0 = I.getArgOperand(0);
4555     Ptr = I.getArgOperand(1);
4556     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
4557     Mask = I.getArgOperand(3);
4558   };
4559   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4560                                     MaybeAlign &Alignment) {
4561     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4562     Src0 = I.getArgOperand(0);
4563     Ptr = I.getArgOperand(1);
4564     Mask = I.getArgOperand(2);
4565     Alignment = std::nullopt;
4566   };
4567 
4568   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4569   MaybeAlign Alignment;
4570   if (IsCompressing)
4571     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4572   else
4573     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4574 
4575   SDValue Ptr = getValue(PtrOperand);
4576   SDValue Src0 = getValue(Src0Operand);
4577   SDValue Mask = getValue(MaskOperand);
4578   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4579 
4580   EVT VT = Src0.getValueType();
4581   if (!Alignment)
4582     Alignment = DAG.getEVTAlign(VT);
4583 
4584   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4585       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4586       MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata());
4587   SDValue StoreNode =
4588       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4589                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4590   DAG.setRoot(StoreNode);
4591   setValue(&I, StoreNode);
4592 }
4593 
4594 // Get a uniform base for the Gather/Scatter intrinsic.
4595 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4596 // We try to represent it as a base pointer + vector of indices.
4597 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4598 // The first operand of the GEP may be a single pointer or a vector of pointers
4599 // Example:
4600 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4601 //  or
4602 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4603 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4604 //
4605 // When the first GEP operand is a single pointer - it is the uniform base we
4606 // are looking for. If first operand of the GEP is a splat vector - we
4607 // extract the splat value and use it as a uniform base.
4608 // In all other cases the function returns 'false'.
4609 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4610                            ISD::MemIndexType &IndexType, SDValue &Scale,
4611                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB,
4612                            uint64_t ElemSize) {
4613   SelectionDAG& DAG = SDB->DAG;
4614   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4615   const DataLayout &DL = DAG.getDataLayout();
4616 
4617   assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4618 
4619   // Handle splat constant pointer.
4620   if (auto *C = dyn_cast<Constant>(Ptr)) {
4621     C = C->getSplatValue();
4622     if (!C)
4623       return false;
4624 
4625     Base = SDB->getValue(C);
4626 
4627     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4628     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4629     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4630     IndexType = ISD::SIGNED_SCALED;
4631     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4632     return true;
4633   }
4634 
4635   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4636   if (!GEP || GEP->getParent() != CurBB)
4637     return false;
4638 
4639   if (GEP->getNumOperands() != 2)
4640     return false;
4641 
4642   const Value *BasePtr = GEP->getPointerOperand();
4643   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4644 
4645   // Make sure the base is scalar and the index is a vector.
4646   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4647     return false;
4648 
4649   TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
4650   if (ScaleVal.isScalable())
4651     return false;
4652 
4653   // Target may not support the required addressing mode.
4654   if (ScaleVal != 1 &&
4655       !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize))
4656     return false;
4657 
4658   Base = SDB->getValue(BasePtr);
4659   Index = SDB->getValue(IndexVal);
4660   IndexType = ISD::SIGNED_SCALED;
4661 
4662   Scale =
4663       DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4664   return true;
4665 }
4666 
4667 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4668   SDLoc sdl = getCurSDLoc();
4669 
4670   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4671   const Value *Ptr = I.getArgOperand(1);
4672   SDValue Src0 = getValue(I.getArgOperand(0));
4673   SDValue Mask = getValue(I.getArgOperand(3));
4674   EVT VT = Src0.getValueType();
4675   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4676                         ->getMaybeAlignValue()
4677                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4678   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4679 
4680   SDValue Base;
4681   SDValue Index;
4682   ISD::MemIndexType IndexType;
4683   SDValue Scale;
4684   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4685                                     I.getParent(), VT.getScalarStoreSize());
4686 
4687   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4688   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4689       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4690       // TODO: Make MachineMemOperands aware of scalable
4691       // vectors.
4692       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata());
4693   if (!UniformBase) {
4694     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4695     Index = getValue(Ptr);
4696     IndexType = ISD::SIGNED_SCALED;
4697     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4698   }
4699 
4700   EVT IdxVT = Index.getValueType();
4701   EVT EltTy = IdxVT.getVectorElementType();
4702   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4703     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4704     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4705   }
4706 
4707   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4708   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4709                                          Ops, MMO, IndexType, false);
4710   DAG.setRoot(Scatter);
4711   setValue(&I, Scatter);
4712 }
4713 
4714 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4715   SDLoc sdl = getCurSDLoc();
4716 
4717   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4718                               MaybeAlign &Alignment) {
4719     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4720     Ptr = I.getArgOperand(0);
4721     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4722     Mask = I.getArgOperand(2);
4723     Src0 = I.getArgOperand(3);
4724   };
4725   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4726                                  MaybeAlign &Alignment) {
4727     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4728     Ptr = I.getArgOperand(0);
4729     Alignment = std::nullopt;
4730     Mask = I.getArgOperand(1);
4731     Src0 = I.getArgOperand(2);
4732   };
4733 
4734   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4735   MaybeAlign Alignment;
4736   if (IsExpanding)
4737     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4738   else
4739     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4740 
4741   SDValue Ptr = getValue(PtrOperand);
4742   SDValue Src0 = getValue(Src0Operand);
4743   SDValue Mask = getValue(MaskOperand);
4744   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4745 
4746   EVT VT = Src0.getValueType();
4747   if (!Alignment)
4748     Alignment = DAG.getEVTAlign(VT);
4749 
4750   AAMDNodes AAInfo = I.getAAMetadata();
4751   const MDNode *Ranges = getRangeMetadata(I);
4752 
4753   // Do not serialize masked loads of constant memory with anything.
4754   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
4755   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4756 
4757   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4758 
4759   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4760       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4761       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
4762 
4763   SDValue Load =
4764       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4765                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4766   if (AddToChain)
4767     PendingLoads.push_back(Load.getValue(1));
4768   setValue(&I, Load);
4769 }
4770 
4771 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4772   SDLoc sdl = getCurSDLoc();
4773 
4774   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4775   const Value *Ptr = I.getArgOperand(0);
4776   SDValue Src0 = getValue(I.getArgOperand(3));
4777   SDValue Mask = getValue(I.getArgOperand(2));
4778 
4779   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4780   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4781   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4782                         ->getMaybeAlignValue()
4783                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4784 
4785   const MDNode *Ranges = getRangeMetadata(I);
4786 
4787   SDValue Root = DAG.getRoot();
4788   SDValue Base;
4789   SDValue Index;
4790   ISD::MemIndexType IndexType;
4791   SDValue Scale;
4792   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4793                                     I.getParent(), VT.getScalarStoreSize());
4794   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4795   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4796       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4797       // TODO: Make MachineMemOperands aware of scalable
4798       // vectors.
4799       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
4800 
4801   if (!UniformBase) {
4802     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4803     Index = getValue(Ptr);
4804     IndexType = ISD::SIGNED_SCALED;
4805     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4806   }
4807 
4808   EVT IdxVT = Index.getValueType();
4809   EVT EltTy = IdxVT.getVectorElementType();
4810   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4811     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4812     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4813   }
4814 
4815   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4816   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4817                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
4818 
4819   PendingLoads.push_back(Gather.getValue(1));
4820   setValue(&I, Gather);
4821 }
4822 
4823 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4824   SDLoc dl = getCurSDLoc();
4825   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4826   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4827   SyncScope::ID SSID = I.getSyncScopeID();
4828 
4829   SDValue InChain = getRoot();
4830 
4831   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4832   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4833 
4834   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4835   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4836 
4837   MachineFunction &MF = DAG.getMachineFunction();
4838   MachineMemOperand *MMO = MF.getMachineMemOperand(
4839       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4840       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4841       FailureOrdering);
4842 
4843   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4844                                    dl, MemVT, VTs, InChain,
4845                                    getValue(I.getPointerOperand()),
4846                                    getValue(I.getCompareOperand()),
4847                                    getValue(I.getNewValOperand()), MMO);
4848 
4849   SDValue OutChain = L.getValue(2);
4850 
4851   setValue(&I, L);
4852   DAG.setRoot(OutChain);
4853 }
4854 
4855 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4856   SDLoc dl = getCurSDLoc();
4857   ISD::NodeType NT;
4858   switch (I.getOperation()) {
4859   default: llvm_unreachable("Unknown atomicrmw operation");
4860   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4861   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4862   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4863   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4864   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4865   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4866   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4867   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4868   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4869   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4870   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4871   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4872   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4873   case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break;
4874   case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break;
4875   case AtomicRMWInst::UIncWrap:
4876     NT = ISD::ATOMIC_LOAD_UINC_WRAP;
4877     break;
4878   case AtomicRMWInst::UDecWrap:
4879     NT = ISD::ATOMIC_LOAD_UDEC_WRAP;
4880     break;
4881   }
4882   AtomicOrdering Ordering = I.getOrdering();
4883   SyncScope::ID SSID = I.getSyncScopeID();
4884 
4885   SDValue InChain = getRoot();
4886 
4887   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4888   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4889   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4890 
4891   MachineFunction &MF = DAG.getMachineFunction();
4892   MachineMemOperand *MMO = MF.getMachineMemOperand(
4893       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4894       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4895 
4896   SDValue L =
4897     DAG.getAtomic(NT, dl, MemVT, InChain,
4898                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4899                   MMO);
4900 
4901   SDValue OutChain = L.getValue(1);
4902 
4903   setValue(&I, L);
4904   DAG.setRoot(OutChain);
4905 }
4906 
4907 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4908   SDLoc dl = getCurSDLoc();
4909   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4910   SDValue Ops[3];
4911   Ops[0] = getRoot();
4912   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4913                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4914   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4915                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4916   SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
4917   setValue(&I, N);
4918   DAG.setRoot(N);
4919 }
4920 
4921 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4922   SDLoc dl = getCurSDLoc();
4923   AtomicOrdering Order = I.getOrdering();
4924   SyncScope::ID SSID = I.getSyncScopeID();
4925 
4926   SDValue InChain = getRoot();
4927 
4928   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4929   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4930   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4931 
4932   if (!TLI.supportsUnalignedAtomics() &&
4933       I.getAlign().value() < MemVT.getSizeInBits() / 8)
4934     report_fatal_error("Cannot generate unaligned atomic load");
4935 
4936   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4937 
4938   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4939       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4940       I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4941 
4942   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4943 
4944   SDValue Ptr = getValue(I.getPointerOperand());
4945   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4946                             Ptr, MMO);
4947 
4948   SDValue OutChain = L.getValue(1);
4949   if (MemVT != VT)
4950     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4951 
4952   setValue(&I, L);
4953   DAG.setRoot(OutChain);
4954 }
4955 
4956 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4957   SDLoc dl = getCurSDLoc();
4958 
4959   AtomicOrdering Ordering = I.getOrdering();
4960   SyncScope::ID SSID = I.getSyncScopeID();
4961 
4962   SDValue InChain = getRoot();
4963 
4964   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4965   EVT MemVT =
4966       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4967 
4968   if (!TLI.supportsUnalignedAtomics() &&
4969       I.getAlign().value() < MemVT.getSizeInBits() / 8)
4970     report_fatal_error("Cannot generate unaligned atomic store");
4971 
4972   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4973 
4974   MachineFunction &MF = DAG.getMachineFunction();
4975   MachineMemOperand *MMO = MF.getMachineMemOperand(
4976       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4977       I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4978 
4979   SDValue Val = getValue(I.getValueOperand());
4980   if (Val.getValueType() != MemVT)
4981     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4982   SDValue Ptr = getValue(I.getPointerOperand());
4983 
4984   SDValue OutChain =
4985       DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO);
4986 
4987   setValue(&I, OutChain);
4988   DAG.setRoot(OutChain);
4989 }
4990 
4991 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4992 /// node.
4993 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4994                                                unsigned Intrinsic) {
4995   // Ignore the callsite's attributes. A specific call site may be marked with
4996   // readnone, but the lowering code will expect the chain based on the
4997   // definition.
4998   const Function *F = I.getCalledFunction();
4999   bool HasChain = !F->doesNotAccessMemory();
5000   bool OnlyLoad = HasChain && F->onlyReadsMemory();
5001 
5002   // Build the operand list.
5003   SmallVector<SDValue, 8> Ops;
5004   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
5005     if (OnlyLoad) {
5006       // We don't need to serialize loads against other loads.
5007       Ops.push_back(DAG.getRoot());
5008     } else {
5009       Ops.push_back(getRoot());
5010     }
5011   }
5012 
5013   // Info is set by getTgtMemIntrinsic
5014   TargetLowering::IntrinsicInfo Info;
5015   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5016   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
5017                                                DAG.getMachineFunction(),
5018                                                Intrinsic);
5019 
5020   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
5021   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
5022       Info.opc == ISD::INTRINSIC_W_CHAIN)
5023     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
5024                                         TLI.getPointerTy(DAG.getDataLayout())));
5025 
5026   // Add all operands of the call to the operand list.
5027   for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
5028     const Value *Arg = I.getArgOperand(i);
5029     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
5030       Ops.push_back(getValue(Arg));
5031       continue;
5032     }
5033 
5034     // Use TargetConstant instead of a regular constant for immarg.
5035     EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
5036     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
5037       assert(CI->getBitWidth() <= 64 &&
5038              "large intrinsic immediates not handled");
5039       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
5040     } else {
5041       Ops.push_back(
5042           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
5043     }
5044   }
5045 
5046   SmallVector<EVT, 4> ValueVTs;
5047   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
5048 
5049   if (HasChain)
5050     ValueVTs.push_back(MVT::Other);
5051 
5052   SDVTList VTs = DAG.getVTList(ValueVTs);
5053 
5054   // Propagate fast-math-flags from IR to node(s).
5055   SDNodeFlags Flags;
5056   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
5057     Flags.copyFMF(*FPMO);
5058   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
5059 
5060   // Create the node.
5061   SDValue Result;
5062   // In some cases, custom collection of operands from CallInst I may be needed.
5063   TLI.CollectTargetIntrinsicOperands(I, Ops, DAG);
5064   if (IsTgtIntrinsic) {
5065     // This is target intrinsic that touches memory
5066     //
5067     // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic
5068     //       didn't yield anything useful.
5069     MachinePointerInfo MPI;
5070     if (Info.ptrVal)
5071       MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
5072     else if (Info.fallbackAddressSpace)
5073       MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
5074     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops,
5075                                      Info.memVT, MPI, Info.align, Info.flags,
5076                                      Info.size, I.getAAMetadata());
5077   } else if (!HasChain) {
5078     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
5079   } else if (!I.getType()->isVoidTy()) {
5080     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
5081   } else {
5082     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
5083   }
5084 
5085   if (HasChain) {
5086     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
5087     if (OnlyLoad)
5088       PendingLoads.push_back(Chain);
5089     else
5090       DAG.setRoot(Chain);
5091   }
5092 
5093   if (!I.getType()->isVoidTy()) {
5094     if (!isa<VectorType>(I.getType()))
5095       Result = lowerRangeToAssertZExt(DAG, I, Result);
5096 
5097     MaybeAlign Alignment = I.getRetAlign();
5098 
5099     // Insert `assertalign` node if there's an alignment.
5100     if (InsertAssertAlign && Alignment) {
5101       Result =
5102           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
5103     }
5104 
5105     setValue(&I, Result);
5106   }
5107 }
5108 
5109 /// GetSignificand - Get the significand and build it into a floating-point
5110 /// number with exponent of 1:
5111 ///
5112 ///   Op = (Op & 0x007fffff) | 0x3f800000;
5113 ///
5114 /// where Op is the hexadecimal representation of floating point value.
5115 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
5116   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5117                            DAG.getConstant(0x007fffff, dl, MVT::i32));
5118   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
5119                            DAG.getConstant(0x3f800000, dl, MVT::i32));
5120   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
5121 }
5122 
5123 /// GetExponent - Get the exponent:
5124 ///
5125 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
5126 ///
5127 /// where Op is the hexadecimal representation of floating point value.
5128 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
5129                            const TargetLowering &TLI, const SDLoc &dl) {
5130   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5131                            DAG.getConstant(0x7f800000, dl, MVT::i32));
5132   SDValue t1 = DAG.getNode(
5133       ISD::SRL, dl, MVT::i32, t0,
5134       DAG.getConstant(23, dl,
5135                       TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout())));
5136   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
5137                            DAG.getConstant(127, dl, MVT::i32));
5138   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
5139 }
5140 
5141 /// getF32Constant - Get 32-bit floating point constant.
5142 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
5143                               const SDLoc &dl) {
5144   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
5145                            MVT::f32);
5146 }
5147 
5148 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
5149                                        SelectionDAG &DAG) {
5150   // TODO: What fast-math-flags should be set on the floating-point nodes?
5151 
5152   //   IntegerPartOfX = ((int32_t)(t0);
5153   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
5154 
5155   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
5156   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
5157   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
5158 
5159   //   IntegerPartOfX <<= 23;
5160   IntegerPartOfX =
5161       DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
5162                   DAG.getConstant(23, dl,
5163                                   DAG.getTargetLoweringInfo().getShiftAmountTy(
5164                                       MVT::i32, DAG.getDataLayout())));
5165 
5166   SDValue TwoToFractionalPartOfX;
5167   if (LimitFloatPrecision <= 6) {
5168     // For floating-point precision of 6:
5169     //
5170     //   TwoToFractionalPartOfX =
5171     //     0.997535578f +
5172     //       (0.735607626f + 0.252464424f * x) * x;
5173     //
5174     // error 0.0144103317, which is 6 bits
5175     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5176                              getF32Constant(DAG, 0x3e814304, dl));
5177     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5178                              getF32Constant(DAG, 0x3f3c50c8, dl));
5179     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5180     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5181                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
5182   } else if (LimitFloatPrecision <= 12) {
5183     // For floating-point precision of 12:
5184     //
5185     //   TwoToFractionalPartOfX =
5186     //     0.999892986f +
5187     //       (0.696457318f +
5188     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
5189     //
5190     // error 0.000107046256, which is 13 to 14 bits
5191     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5192                              getF32Constant(DAG, 0x3da235e3, dl));
5193     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5194                              getF32Constant(DAG, 0x3e65b8f3, dl));
5195     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5196     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5197                              getF32Constant(DAG, 0x3f324b07, dl));
5198     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5199     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5200                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
5201   } else { // LimitFloatPrecision <= 18
5202     // For floating-point precision of 18:
5203     //
5204     //   TwoToFractionalPartOfX =
5205     //     0.999999982f +
5206     //       (0.693148872f +
5207     //         (0.240227044f +
5208     //           (0.554906021e-1f +
5209     //             (0.961591928e-2f +
5210     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5211     // error 2.47208000*10^(-7), which is better than 18 bits
5212     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5213                              getF32Constant(DAG, 0x3924b03e, dl));
5214     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5215                              getF32Constant(DAG, 0x3ab24b87, dl));
5216     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5217     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5218                              getF32Constant(DAG, 0x3c1d8c17, dl));
5219     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5220     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5221                              getF32Constant(DAG, 0x3d634a1d, dl));
5222     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5223     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5224                              getF32Constant(DAG, 0x3e75fe14, dl));
5225     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5226     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5227                               getF32Constant(DAG, 0x3f317234, dl));
5228     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5229     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5230                                          getF32Constant(DAG, 0x3f800000, dl));
5231   }
5232 
5233   // Add the exponent into the result in integer domain.
5234   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5235   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5236                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5237 }
5238 
5239 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5240 /// limited-precision mode.
5241 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5242                          const TargetLowering &TLI, SDNodeFlags Flags) {
5243   if (Op.getValueType() == MVT::f32 &&
5244       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5245 
5246     // Put the exponent in the right bit position for later addition to the
5247     // final result:
5248     //
5249     // t0 = Op * log2(e)
5250 
5251     // TODO: What fast-math-flags should be set here?
5252     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5253                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5254     return getLimitedPrecisionExp2(t0, dl, DAG);
5255   }
5256 
5257   // No special expansion.
5258   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5259 }
5260 
5261 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5262 /// limited-precision mode.
5263 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5264                          const TargetLowering &TLI, SDNodeFlags Flags) {
5265   // TODO: What fast-math-flags should be set on the floating-point nodes?
5266 
5267   if (Op.getValueType() == MVT::f32 &&
5268       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5269     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5270 
5271     // Scale the exponent by log(2).
5272     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5273     SDValue LogOfExponent =
5274         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5275                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5276 
5277     // Get the significand and build it into a floating-point number with
5278     // exponent of 1.
5279     SDValue X = GetSignificand(DAG, Op1, dl);
5280 
5281     SDValue LogOfMantissa;
5282     if (LimitFloatPrecision <= 6) {
5283       // For floating-point precision of 6:
5284       //
5285       //   LogofMantissa =
5286       //     -1.1609546f +
5287       //       (1.4034025f - 0.23903021f * x) * x;
5288       //
5289       // error 0.0034276066, which is better than 8 bits
5290       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5291                                getF32Constant(DAG, 0xbe74c456, dl));
5292       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5293                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5294       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5295       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5296                                   getF32Constant(DAG, 0x3f949a29, dl));
5297     } else if (LimitFloatPrecision <= 12) {
5298       // For floating-point precision of 12:
5299       //
5300       //   LogOfMantissa =
5301       //     -1.7417939f +
5302       //       (2.8212026f +
5303       //         (-1.4699568f +
5304       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5305       //
5306       // error 0.000061011436, which is 14 bits
5307       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5308                                getF32Constant(DAG, 0xbd67b6d6, dl));
5309       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5310                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5311       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5312       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5313                                getF32Constant(DAG, 0x3fbc278b, dl));
5314       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5315       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5316                                getF32Constant(DAG, 0x40348e95, dl));
5317       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5318       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5319                                   getF32Constant(DAG, 0x3fdef31a, dl));
5320     } else { // LimitFloatPrecision <= 18
5321       // For floating-point precision of 18:
5322       //
5323       //   LogOfMantissa =
5324       //     -2.1072184f +
5325       //       (4.2372794f +
5326       //         (-3.7029485f +
5327       //           (2.2781945f +
5328       //             (-0.87823314f +
5329       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5330       //
5331       // error 0.0000023660568, which is better than 18 bits
5332       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5333                                getF32Constant(DAG, 0xbc91e5ac, dl));
5334       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5335                                getF32Constant(DAG, 0x3e4350aa, dl));
5336       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5337       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5338                                getF32Constant(DAG, 0x3f60d3e3, dl));
5339       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5340       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5341                                getF32Constant(DAG, 0x4011cdf0, dl));
5342       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5343       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5344                                getF32Constant(DAG, 0x406cfd1c, dl));
5345       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5346       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5347                                getF32Constant(DAG, 0x408797cb, dl));
5348       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5349       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5350                                   getF32Constant(DAG, 0x4006dcab, dl));
5351     }
5352 
5353     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5354   }
5355 
5356   // No special expansion.
5357   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5358 }
5359 
5360 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5361 /// limited-precision mode.
5362 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5363                           const TargetLowering &TLI, SDNodeFlags Flags) {
5364   // TODO: What fast-math-flags should be set on the floating-point nodes?
5365 
5366   if (Op.getValueType() == MVT::f32 &&
5367       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5368     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5369 
5370     // Get the exponent.
5371     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5372 
5373     // Get the significand and build it into a floating-point number with
5374     // exponent of 1.
5375     SDValue X = GetSignificand(DAG, Op1, dl);
5376 
5377     // Different possible minimax approximations of significand in
5378     // floating-point for various degrees of accuracy over [1,2].
5379     SDValue Log2ofMantissa;
5380     if (LimitFloatPrecision <= 6) {
5381       // For floating-point precision of 6:
5382       //
5383       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5384       //
5385       // error 0.0049451742, which is more than 7 bits
5386       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5387                                getF32Constant(DAG, 0xbeb08fe0, dl));
5388       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5389                                getF32Constant(DAG, 0x40019463, dl));
5390       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5391       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5392                                    getF32Constant(DAG, 0x3fd6633d, dl));
5393     } else if (LimitFloatPrecision <= 12) {
5394       // For floating-point precision of 12:
5395       //
5396       //   Log2ofMantissa =
5397       //     -2.51285454f +
5398       //       (4.07009056f +
5399       //         (-2.12067489f +
5400       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5401       //
5402       // error 0.0000876136000, which is better than 13 bits
5403       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5404                                getF32Constant(DAG, 0xbda7262e, dl));
5405       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5406                                getF32Constant(DAG, 0x3f25280b, dl));
5407       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5408       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5409                                getF32Constant(DAG, 0x4007b923, dl));
5410       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5411       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5412                                getF32Constant(DAG, 0x40823e2f, dl));
5413       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5414       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5415                                    getF32Constant(DAG, 0x4020d29c, dl));
5416     } else { // LimitFloatPrecision <= 18
5417       // For floating-point precision of 18:
5418       //
5419       //   Log2ofMantissa =
5420       //     -3.0400495f +
5421       //       (6.1129976f +
5422       //         (-5.3420409f +
5423       //           (3.2865683f +
5424       //             (-1.2669343f +
5425       //               (0.27515199f -
5426       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5427       //
5428       // error 0.0000018516, which is better than 18 bits
5429       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5430                                getF32Constant(DAG, 0xbcd2769e, dl));
5431       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5432                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5433       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5434       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5435                                getF32Constant(DAG, 0x3fa22ae7, dl));
5436       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5437       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5438                                getF32Constant(DAG, 0x40525723, dl));
5439       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5440       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5441                                getF32Constant(DAG, 0x40aaf200, dl));
5442       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5443       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5444                                getF32Constant(DAG, 0x40c39dad, dl));
5445       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5446       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5447                                    getF32Constant(DAG, 0x4042902c, dl));
5448     }
5449 
5450     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5451   }
5452 
5453   // No special expansion.
5454   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5455 }
5456 
5457 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5458 /// limited-precision mode.
5459 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5460                            const TargetLowering &TLI, SDNodeFlags Flags) {
5461   // TODO: What fast-math-flags should be set on the floating-point nodes?
5462 
5463   if (Op.getValueType() == MVT::f32 &&
5464       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5465     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5466 
5467     // Scale the exponent by log10(2) [0.30102999f].
5468     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5469     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5470                                         getF32Constant(DAG, 0x3e9a209a, dl));
5471 
5472     // Get the significand and build it into a floating-point number with
5473     // exponent of 1.
5474     SDValue X = GetSignificand(DAG, Op1, dl);
5475 
5476     SDValue Log10ofMantissa;
5477     if (LimitFloatPrecision <= 6) {
5478       // For floating-point precision of 6:
5479       //
5480       //   Log10ofMantissa =
5481       //     -0.50419619f +
5482       //       (0.60948995f - 0.10380950f * x) * x;
5483       //
5484       // error 0.0014886165, which is 6 bits
5485       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5486                                getF32Constant(DAG, 0xbdd49a13, dl));
5487       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5488                                getF32Constant(DAG, 0x3f1c0789, dl));
5489       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5490       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5491                                     getF32Constant(DAG, 0x3f011300, dl));
5492     } else if (LimitFloatPrecision <= 12) {
5493       // For floating-point precision of 12:
5494       //
5495       //   Log10ofMantissa =
5496       //     -0.64831180f +
5497       //       (0.91751397f +
5498       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5499       //
5500       // error 0.00019228036, which is better than 12 bits
5501       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5502                                getF32Constant(DAG, 0x3d431f31, dl));
5503       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5504                                getF32Constant(DAG, 0x3ea21fb2, dl));
5505       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5506       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5507                                getF32Constant(DAG, 0x3f6ae232, dl));
5508       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5509       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5510                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5511     } else { // LimitFloatPrecision <= 18
5512       // For floating-point precision of 18:
5513       //
5514       //   Log10ofMantissa =
5515       //     -0.84299375f +
5516       //       (1.5327582f +
5517       //         (-1.0688956f +
5518       //           (0.49102474f +
5519       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5520       //
5521       // error 0.0000037995730, which is better than 18 bits
5522       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5523                                getF32Constant(DAG, 0x3c5d51ce, dl));
5524       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5525                                getF32Constant(DAG, 0x3e00685a, dl));
5526       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5527       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5528                                getF32Constant(DAG, 0x3efb6798, dl));
5529       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5530       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5531                                getF32Constant(DAG, 0x3f88d192, dl));
5532       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5533       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5534                                getF32Constant(DAG, 0x3fc4316c, dl));
5535       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5536       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5537                                     getF32Constant(DAG, 0x3f57ce70, dl));
5538     }
5539 
5540     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5541   }
5542 
5543   // No special expansion.
5544   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5545 }
5546 
5547 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5548 /// limited-precision mode.
5549 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5550                           const TargetLowering &TLI, SDNodeFlags Flags) {
5551   if (Op.getValueType() == MVT::f32 &&
5552       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5553     return getLimitedPrecisionExp2(Op, dl, DAG);
5554 
5555   // No special expansion.
5556   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5557 }
5558 
5559 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5560 /// limited-precision mode with x == 10.0f.
5561 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5562                          SelectionDAG &DAG, const TargetLowering &TLI,
5563                          SDNodeFlags Flags) {
5564   bool IsExp10 = false;
5565   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5566       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5567     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5568       APFloat Ten(10.0f);
5569       IsExp10 = LHSC->isExactlyValue(Ten);
5570     }
5571   }
5572 
5573   // TODO: What fast-math-flags should be set on the FMUL node?
5574   if (IsExp10) {
5575     // Put the exponent in the right bit position for later addition to the
5576     // final result:
5577     //
5578     //   #define LOG2OF10 3.3219281f
5579     //   t0 = Op * LOG2OF10;
5580     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5581                              getF32Constant(DAG, 0x40549a78, dl));
5582     return getLimitedPrecisionExp2(t0, dl, DAG);
5583   }
5584 
5585   // No special expansion.
5586   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5587 }
5588 
5589 /// ExpandPowI - Expand a llvm.powi intrinsic.
5590 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5591                           SelectionDAG &DAG) {
5592   // If RHS is a constant, we can expand this out to a multiplication tree if
5593   // it's beneficial on the target, otherwise we end up lowering to a call to
5594   // __powidf2 (for example).
5595   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5596     unsigned Val = RHSC->getSExtValue();
5597 
5598     // powi(x, 0) -> 1.0
5599     if (Val == 0)
5600       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5601 
5602     if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI(
5603             Val, DAG.shouldOptForSize())) {
5604       // Get the exponent as a positive value.
5605       if ((int)Val < 0)
5606         Val = -Val;
5607       // We use the simple binary decomposition method to generate the multiply
5608       // sequence.  There are more optimal ways to do this (for example,
5609       // powi(x,15) generates one more multiply than it should), but this has
5610       // the benefit of being both really simple and much better than a libcall.
5611       SDValue Res; // Logically starts equal to 1.0
5612       SDValue CurSquare = LHS;
5613       // TODO: Intrinsics should have fast-math-flags that propagate to these
5614       // nodes.
5615       while (Val) {
5616         if (Val & 1) {
5617           if (Res.getNode())
5618             Res =
5619                 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
5620           else
5621             Res = CurSquare; // 1.0*CurSquare.
5622         }
5623 
5624         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5625                                 CurSquare, CurSquare);
5626         Val >>= 1;
5627       }
5628 
5629       // If the original was negative, invert the result, producing 1/(x*x*x).
5630       if (RHSC->getSExtValue() < 0)
5631         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5632                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5633       return Res;
5634     }
5635   }
5636 
5637   // Otherwise, expand to a libcall.
5638   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5639 }
5640 
5641 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5642                             SDValue LHS, SDValue RHS, SDValue Scale,
5643                             SelectionDAG &DAG, const TargetLowering &TLI) {
5644   EVT VT = LHS.getValueType();
5645   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5646   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5647   LLVMContext &Ctx = *DAG.getContext();
5648 
5649   // If the type is legal but the operation isn't, this node might survive all
5650   // the way to operation legalization. If we end up there and we do not have
5651   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5652   // node.
5653 
5654   // Coax the legalizer into expanding the node during type legalization instead
5655   // by bumping the size by one bit. This will force it to Promote, enabling the
5656   // early expansion and avoiding the need to expand later.
5657 
5658   // We don't have to do this if Scale is 0; that can always be expanded, unless
5659   // it's a saturating signed operation. Those can experience true integer
5660   // division overflow, a case which we must avoid.
5661 
5662   // FIXME: We wouldn't have to do this (or any of the early
5663   // expansion/promotion) if it was possible to expand a libcall of an
5664   // illegal type during operation legalization. But it's not, so things
5665   // get a bit hacky.
5666   unsigned ScaleInt = Scale->getAsZExtVal();
5667   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5668       (TLI.isTypeLegal(VT) ||
5669        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5670     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5671         Opcode, VT, ScaleInt);
5672     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5673       EVT PromVT;
5674       if (VT.isScalarInteger())
5675         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5676       else if (VT.isVector()) {
5677         PromVT = VT.getVectorElementType();
5678         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5679         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5680       } else
5681         llvm_unreachable("Wrong VT for DIVFIX?");
5682       LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT);
5683       RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT);
5684       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5685       // For saturating operations, we need to shift up the LHS to get the
5686       // proper saturation width, and then shift down again afterwards.
5687       if (Saturating)
5688         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5689                           DAG.getConstant(1, DL, ShiftTy));
5690       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5691       if (Saturating)
5692         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5693                           DAG.getConstant(1, DL, ShiftTy));
5694       return DAG.getZExtOrTrunc(Res, DL, VT);
5695     }
5696   }
5697 
5698   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5699 }
5700 
5701 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5702 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5703 static void
5704 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5705                      const SDValue &N) {
5706   switch (N.getOpcode()) {
5707   case ISD::CopyFromReg: {
5708     SDValue Op = N.getOperand(1);
5709     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5710                       Op.getValueType().getSizeInBits());
5711     return;
5712   }
5713   case ISD::BITCAST:
5714   case ISD::AssertZext:
5715   case ISD::AssertSext:
5716   case ISD::TRUNCATE:
5717     getUnderlyingArgRegs(Regs, N.getOperand(0));
5718     return;
5719   case ISD::BUILD_PAIR:
5720   case ISD::BUILD_VECTOR:
5721   case ISD::CONCAT_VECTORS:
5722     for (SDValue Op : N->op_values())
5723       getUnderlyingArgRegs(Regs, Op);
5724     return;
5725   default:
5726     return;
5727   }
5728 }
5729 
5730 /// If the DbgValueInst is a dbg_value of a function argument, create the
5731 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5732 /// instruction selection, they will be inserted to the entry BB.
5733 /// We don't currently support this for variadic dbg_values, as they shouldn't
5734 /// appear for function arguments or in the prologue.
5735 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5736     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5737     DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
5738   const Argument *Arg = dyn_cast<Argument>(V);
5739   if (!Arg)
5740     return false;
5741 
5742   MachineFunction &MF = DAG.getMachineFunction();
5743   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5744 
5745   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
5746   // we've been asked to pursue.
5747   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
5748                               bool Indirect) {
5749     if (Reg.isVirtual() && MF.useDebugInstrRef()) {
5750       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
5751       // pointing at the VReg, which will be patched up later.
5752       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
5753       SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg(
5754           /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
5755           /* isKill */ false, /* isDead */ false,
5756           /* isUndef */ false, /* isEarlyClobber */ false,
5757           /* SubReg */ 0, /* isDebug */ true)});
5758 
5759       auto *NewDIExpr = FragExpr;
5760       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
5761       // the DIExpression.
5762       if (Indirect)
5763         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
5764       SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0});
5765       NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops);
5766       return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr);
5767     } else {
5768       // Create a completely standard DBG_VALUE.
5769       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
5770       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
5771     }
5772   };
5773 
5774   if (Kind == FuncArgumentDbgValueKind::Value) {
5775     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5776     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5777     // the entry block.
5778     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5779     if (!IsInEntryBlock)
5780       return false;
5781 
5782     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5783     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5784     // variable that also is a param.
5785     //
5786     // Although, if we are at the top of the entry block already, we can still
5787     // emit using ArgDbgValue. This might catch some situations when the
5788     // dbg.value refers to an argument that isn't used in the entry block, so
5789     // any CopyToReg node would be optimized out and the only way to express
5790     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5791     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5792     // we should only emit as ArgDbgValue if the Variable is an argument to the
5793     // current function, and the dbg.value intrinsic is found in the entry
5794     // block.
5795     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5796         !DL->getInlinedAt();
5797     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5798     if (!IsInPrologue && !VariableIsFunctionInputArg)
5799       return false;
5800 
5801     // Here we assume that a function argument on IR level only can be used to
5802     // describe one input parameter on source level. If we for example have
5803     // source code like this
5804     //
5805     //    struct A { long x, y; };
5806     //    void foo(struct A a, long b) {
5807     //      ...
5808     //      b = a.x;
5809     //      ...
5810     //    }
5811     //
5812     // and IR like this
5813     //
5814     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5815     //  entry:
5816     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5817     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5818     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5819     //    ...
5820     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5821     //    ...
5822     //
5823     // then the last dbg.value is describing a parameter "b" using a value that
5824     // is an argument. But since we already has used %a1 to describe a parameter
5825     // we should not handle that last dbg.value here (that would result in an
5826     // incorrect hoisting of the DBG_VALUE to the function entry).
5827     // Notice that we allow one dbg.value per IR level argument, to accommodate
5828     // for the situation with fragments above.
5829     if (VariableIsFunctionInputArg) {
5830       unsigned ArgNo = Arg->getArgNo();
5831       if (ArgNo >= FuncInfo.DescribedArgs.size())
5832         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5833       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5834         return false;
5835       FuncInfo.DescribedArgs.set(ArgNo);
5836     }
5837   }
5838 
5839   bool IsIndirect = false;
5840   std::optional<MachineOperand> Op;
5841   // Some arguments' frame index is recorded during argument lowering.
5842   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5843   if (FI != std::numeric_limits<int>::max())
5844     Op = MachineOperand::CreateFI(FI);
5845 
5846   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
5847   if (!Op && N.getNode()) {
5848     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5849     Register Reg;
5850     if (ArgRegsAndSizes.size() == 1)
5851       Reg = ArgRegsAndSizes.front().first;
5852 
5853     if (Reg && Reg.isVirtual()) {
5854       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5855       Register PR = RegInfo.getLiveInPhysReg(Reg);
5856       if (PR)
5857         Reg = PR;
5858     }
5859     if (Reg) {
5860       Op = MachineOperand::CreateReg(Reg, false);
5861       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
5862     }
5863   }
5864 
5865   if (!Op && N.getNode()) {
5866     // Check if frame index is available.
5867     SDValue LCandidate = peekThroughBitcasts(N);
5868     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5869       if (FrameIndexSDNode *FINode =
5870           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5871         Op = MachineOperand::CreateFI(FINode->getIndex());
5872   }
5873 
5874   if (!Op) {
5875     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5876     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
5877                                          SplitRegs) {
5878       unsigned Offset = 0;
5879       for (const auto &RegAndSize : SplitRegs) {
5880         // If the expression is already a fragment, the current register
5881         // offset+size might extend beyond the fragment. In this case, only
5882         // the register bits that are inside the fragment are relevant.
5883         int RegFragmentSizeInBits = RegAndSize.second;
5884         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5885           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5886           // The register is entirely outside the expression fragment,
5887           // so is irrelevant for debug info.
5888           if (Offset >= ExprFragmentSizeInBits)
5889             break;
5890           // The register is partially outside the expression fragment, only
5891           // the low bits within the fragment are relevant for debug info.
5892           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5893             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5894           }
5895         }
5896 
5897         auto FragmentExpr = DIExpression::createFragmentExpression(
5898             Expr, Offset, RegFragmentSizeInBits);
5899         Offset += RegAndSize.second;
5900         // If a valid fragment expression cannot be created, the variable's
5901         // correct value cannot be determined and so it is set as Undef.
5902         if (!FragmentExpr) {
5903           SDDbgValue *SDV = DAG.getConstantDbgValue(
5904               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5905           DAG.AddDbgValue(SDV, false);
5906           continue;
5907         }
5908         MachineInstr *NewMI =
5909             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr,
5910                              Kind != FuncArgumentDbgValueKind::Value);
5911         FuncInfo.ArgDbgValues.push_back(NewMI);
5912       }
5913     };
5914 
5915     // Check if ValueMap has reg number.
5916     DenseMap<const Value *, Register>::const_iterator
5917       VMI = FuncInfo.ValueMap.find(V);
5918     if (VMI != FuncInfo.ValueMap.end()) {
5919       const auto &TLI = DAG.getTargetLoweringInfo();
5920       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5921                        V->getType(), std::nullopt);
5922       if (RFV.occupiesMultipleRegs()) {
5923         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5924         return true;
5925       }
5926 
5927       Op = MachineOperand::CreateReg(VMI->second, false);
5928       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
5929     } else if (ArgRegsAndSizes.size() > 1) {
5930       // This was split due to the calling convention, and no virtual register
5931       // mapping exists for the value.
5932       splitMultiRegDbgValue(ArgRegsAndSizes);
5933       return true;
5934     }
5935   }
5936 
5937   if (!Op)
5938     return false;
5939 
5940   assert(Variable->isValidLocationForIntrinsic(DL) &&
5941          "Expected inlined-at fields to agree");
5942   MachineInstr *NewMI = nullptr;
5943 
5944   if (Op->isReg())
5945     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
5946   else
5947     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
5948                     Variable, Expr);
5949 
5950   // Otherwise, use ArgDbgValues.
5951   FuncInfo.ArgDbgValues.push_back(NewMI);
5952   return true;
5953 }
5954 
5955 /// Return the appropriate SDDbgValue based on N.
5956 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5957                                              DILocalVariable *Variable,
5958                                              DIExpression *Expr,
5959                                              const DebugLoc &dl,
5960                                              unsigned DbgSDNodeOrder) {
5961   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5962     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5963     // stack slot locations.
5964     //
5965     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5966     // debug values here after optimization:
5967     //
5968     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5969     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5970     //
5971     // Both describe the direct values of their associated variables.
5972     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5973                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5974   }
5975   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5976                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5977 }
5978 
5979 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5980   switch (Intrinsic) {
5981   case Intrinsic::smul_fix:
5982     return ISD::SMULFIX;
5983   case Intrinsic::umul_fix:
5984     return ISD::UMULFIX;
5985   case Intrinsic::smul_fix_sat:
5986     return ISD::SMULFIXSAT;
5987   case Intrinsic::umul_fix_sat:
5988     return ISD::UMULFIXSAT;
5989   case Intrinsic::sdiv_fix:
5990     return ISD::SDIVFIX;
5991   case Intrinsic::udiv_fix:
5992     return ISD::UDIVFIX;
5993   case Intrinsic::sdiv_fix_sat:
5994     return ISD::SDIVFIXSAT;
5995   case Intrinsic::udiv_fix_sat:
5996     return ISD::UDIVFIXSAT;
5997   default:
5998     llvm_unreachable("Unhandled fixed point intrinsic");
5999   }
6000 }
6001 
6002 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
6003                                            const char *FunctionName) {
6004   assert(FunctionName && "FunctionName must not be nullptr");
6005   SDValue Callee = DAG.getExternalSymbol(
6006       FunctionName,
6007       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6008   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
6009 }
6010 
6011 /// Given a @llvm.call.preallocated.setup, return the corresponding
6012 /// preallocated call.
6013 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
6014   assert(cast<CallBase>(PreallocatedSetup)
6015                  ->getCalledFunction()
6016                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
6017          "expected call_preallocated_setup Value");
6018   for (const auto *U : PreallocatedSetup->users()) {
6019     auto *UseCall = cast<CallBase>(U);
6020     const Function *Fn = UseCall->getCalledFunction();
6021     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
6022       return UseCall;
6023     }
6024   }
6025   llvm_unreachable("expected corresponding call to preallocated setup/arg");
6026 }
6027 
6028 /// If DI is a debug value with an EntryValue expression, lower it using the
6029 /// corresponding physical register of the associated Argument value
6030 /// (guaranteed to exist by the verifier).
6031 bool SelectionDAGBuilder::visitEntryValueDbgValue(
6032     ArrayRef<const Value *> Values, DILocalVariable *Variable,
6033     DIExpression *Expr, DebugLoc DbgLoc) {
6034   if (!Expr->isEntryValue() || !hasSingleElement(Values))
6035     return false;
6036 
6037   // These properties are guaranteed by the verifier.
6038   const Argument *Arg = cast<Argument>(Values[0]);
6039   assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync));
6040 
6041   auto ArgIt = FuncInfo.ValueMap.find(Arg);
6042   if (ArgIt == FuncInfo.ValueMap.end()) {
6043     LLVM_DEBUG(
6044         dbgs() << "Dropping dbg.value: expression is entry_value but "
6045                   "couldn't find an associated register for the Argument\n");
6046     return true;
6047   }
6048   Register ArgVReg = ArgIt->getSecond();
6049 
6050   for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
6051     if (ArgVReg == VirtReg || ArgVReg == PhysReg) {
6052       SDDbgValue *SDV = DAG.getVRegDbgValue(
6053           Variable, Expr, PhysReg, false /*IsIndidrect*/, DbgLoc, SDNodeOrder);
6054       DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/);
6055       return true;
6056     }
6057   LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but "
6058                        "couldn't find a physical register\n");
6059   return true;
6060 }
6061 
6062 /// Lower the call to the specified intrinsic function.
6063 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
6064                                              unsigned Intrinsic) {
6065   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6066   SDLoc sdl = getCurSDLoc();
6067   DebugLoc dl = getCurDebugLoc();
6068   SDValue Res;
6069 
6070   SDNodeFlags Flags;
6071   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
6072     Flags.copyFMF(*FPOp);
6073 
6074   switch (Intrinsic) {
6075   default:
6076     // By default, turn this into a target intrinsic node.
6077     visitTargetIntrinsic(I, Intrinsic);
6078     return;
6079   case Intrinsic::vscale: {
6080     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6081     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
6082     return;
6083   }
6084   case Intrinsic::vastart:  visitVAStart(I); return;
6085   case Intrinsic::vaend:    visitVAEnd(I); return;
6086   case Intrinsic::vacopy:   visitVACopy(I); return;
6087   case Intrinsic::returnaddress:
6088     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
6089                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6090                              getValue(I.getArgOperand(0))));
6091     return;
6092   case Intrinsic::addressofreturnaddress:
6093     setValue(&I,
6094              DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
6095                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6096     return;
6097   case Intrinsic::sponentry:
6098     setValue(&I,
6099              DAG.getNode(ISD::SPONENTRY, sdl,
6100                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6101     return;
6102   case Intrinsic::frameaddress:
6103     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
6104                              TLI.getFrameIndexTy(DAG.getDataLayout()),
6105                              getValue(I.getArgOperand(0))));
6106     return;
6107   case Intrinsic::read_volatile_register:
6108   case Intrinsic::read_register: {
6109     Value *Reg = I.getArgOperand(0);
6110     SDValue Chain = getRoot();
6111     SDValue RegName =
6112         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6113     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6114     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
6115       DAG.getVTList(VT, MVT::Other), Chain, RegName);
6116     setValue(&I, Res);
6117     DAG.setRoot(Res.getValue(1));
6118     return;
6119   }
6120   case Intrinsic::write_register: {
6121     Value *Reg = I.getArgOperand(0);
6122     Value *RegValue = I.getArgOperand(1);
6123     SDValue Chain = getRoot();
6124     SDValue RegName =
6125         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6126     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
6127                             RegName, getValue(RegValue)));
6128     return;
6129   }
6130   case Intrinsic::memcpy: {
6131     const auto &MCI = cast<MemCpyInst>(I);
6132     SDValue Op1 = getValue(I.getArgOperand(0));
6133     SDValue Op2 = getValue(I.getArgOperand(1));
6134     SDValue Op3 = getValue(I.getArgOperand(2));
6135     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
6136     Align DstAlign = MCI.getDestAlign().valueOrOne();
6137     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6138     Align Alignment = std::min(DstAlign, SrcAlign);
6139     bool isVol = MCI.isVolatile();
6140     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6141     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6142     // node.
6143     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6144     SDValue MC = DAG.getMemcpy(
6145         Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6146         /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)),
6147         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
6148     updateDAGForMaybeTailCall(MC);
6149     return;
6150   }
6151   case Intrinsic::memcpy_inline: {
6152     const auto &MCI = cast<MemCpyInlineInst>(I);
6153     SDValue Dst = getValue(I.getArgOperand(0));
6154     SDValue Src = getValue(I.getArgOperand(1));
6155     SDValue Size = getValue(I.getArgOperand(2));
6156     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
6157     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
6158     Align DstAlign = MCI.getDestAlign().valueOrOne();
6159     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6160     Align Alignment = std::min(DstAlign, SrcAlign);
6161     bool isVol = MCI.isVolatile();
6162     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6163     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6164     // node.
6165     SDValue MC = DAG.getMemcpy(
6166         getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
6167         /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)),
6168         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
6169     updateDAGForMaybeTailCall(MC);
6170     return;
6171   }
6172   case Intrinsic::memset: {
6173     const auto &MSI = cast<MemSetInst>(I);
6174     SDValue Op1 = getValue(I.getArgOperand(0));
6175     SDValue Op2 = getValue(I.getArgOperand(1));
6176     SDValue Op3 = getValue(I.getArgOperand(2));
6177     // @llvm.memset defines 0 and 1 to both mean no alignment.
6178     Align Alignment = MSI.getDestAlign().valueOrOne();
6179     bool isVol = MSI.isVolatile();
6180     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6181     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6182     SDValue MS = DAG.getMemset(
6183         Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false,
6184         isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
6185     updateDAGForMaybeTailCall(MS);
6186     return;
6187   }
6188   case Intrinsic::memset_inline: {
6189     const auto &MSII = cast<MemSetInlineInst>(I);
6190     SDValue Dst = getValue(I.getArgOperand(0));
6191     SDValue Value = getValue(I.getArgOperand(1));
6192     SDValue Size = getValue(I.getArgOperand(2));
6193     assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size");
6194     // @llvm.memset defines 0 and 1 to both mean no alignment.
6195     Align DstAlign = MSII.getDestAlign().valueOrOne();
6196     bool isVol = MSII.isVolatile();
6197     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6198     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6199     SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol,
6200                                /* AlwaysInline */ true, isTC,
6201                                MachinePointerInfo(I.getArgOperand(0)),
6202                                I.getAAMetadata());
6203     updateDAGForMaybeTailCall(MC);
6204     return;
6205   }
6206   case Intrinsic::memmove: {
6207     const auto &MMI = cast<MemMoveInst>(I);
6208     SDValue Op1 = getValue(I.getArgOperand(0));
6209     SDValue Op2 = getValue(I.getArgOperand(1));
6210     SDValue Op3 = getValue(I.getArgOperand(2));
6211     // @llvm.memmove defines 0 and 1 to both mean no alignment.
6212     Align DstAlign = MMI.getDestAlign().valueOrOne();
6213     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
6214     Align Alignment = std::min(DstAlign, SrcAlign);
6215     bool isVol = MMI.isVolatile();
6216     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6217     // FIXME: Support passing different dest/src alignments to the memmove DAG
6218     // node.
6219     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6220     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6221                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
6222                                 MachinePointerInfo(I.getArgOperand(1)),
6223                                 I.getAAMetadata(), AA);
6224     updateDAGForMaybeTailCall(MM);
6225     return;
6226   }
6227   case Intrinsic::memcpy_element_unordered_atomic: {
6228     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
6229     SDValue Dst = getValue(MI.getRawDest());
6230     SDValue Src = getValue(MI.getRawSource());
6231     SDValue Length = getValue(MI.getLength());
6232 
6233     Type *LengthTy = MI.getLength()->getType();
6234     unsigned ElemSz = MI.getElementSizeInBytes();
6235     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6236     SDValue MC =
6237         DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6238                             isTC, MachinePointerInfo(MI.getRawDest()),
6239                             MachinePointerInfo(MI.getRawSource()));
6240     updateDAGForMaybeTailCall(MC);
6241     return;
6242   }
6243   case Intrinsic::memmove_element_unordered_atomic: {
6244     auto &MI = cast<AtomicMemMoveInst>(I);
6245     SDValue Dst = getValue(MI.getRawDest());
6246     SDValue Src = getValue(MI.getRawSource());
6247     SDValue Length = getValue(MI.getLength());
6248 
6249     Type *LengthTy = MI.getLength()->getType();
6250     unsigned ElemSz = MI.getElementSizeInBytes();
6251     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6252     SDValue MC =
6253         DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6254                              isTC, MachinePointerInfo(MI.getRawDest()),
6255                              MachinePointerInfo(MI.getRawSource()));
6256     updateDAGForMaybeTailCall(MC);
6257     return;
6258   }
6259   case Intrinsic::memset_element_unordered_atomic: {
6260     auto &MI = cast<AtomicMemSetInst>(I);
6261     SDValue Dst = getValue(MI.getRawDest());
6262     SDValue Val = getValue(MI.getValue());
6263     SDValue Length = getValue(MI.getLength());
6264 
6265     Type *LengthTy = MI.getLength()->getType();
6266     unsigned ElemSz = MI.getElementSizeInBytes();
6267     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6268     SDValue MC =
6269         DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
6270                             isTC, MachinePointerInfo(MI.getRawDest()));
6271     updateDAGForMaybeTailCall(MC);
6272     return;
6273   }
6274   case Intrinsic::call_preallocated_setup: {
6275     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
6276     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6277     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
6278                               getRoot(), SrcValue);
6279     setValue(&I, Res);
6280     DAG.setRoot(Res);
6281     return;
6282   }
6283   case Intrinsic::call_preallocated_arg: {
6284     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6285     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6286     SDValue Ops[3];
6287     Ops[0] = getRoot();
6288     Ops[1] = SrcValue;
6289     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6290                                    MVT::i32); // arg index
6291     SDValue Res = DAG.getNode(
6292         ISD::PREALLOCATED_ARG, sdl,
6293         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6294     setValue(&I, Res);
6295     DAG.setRoot(Res.getValue(1));
6296     return;
6297   }
6298   case Intrinsic::dbg_declare: {
6299     const auto &DI = cast<DbgDeclareInst>(I);
6300     // Debug intrinsics are handled separately in assignment tracking mode.
6301     // Some intrinsics are handled right after Argument lowering.
6302     if (AssignmentTrackingEnabled ||
6303         FuncInfo.PreprocessedDbgDeclares.count(&DI))
6304       return;
6305     LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DI << "\n");
6306     DILocalVariable *Variable = DI.getVariable();
6307     DIExpression *Expression = DI.getExpression();
6308     dropDanglingDebugInfo(Variable, Expression);
6309     // Assume dbg.declare can not currently use DIArgList, i.e.
6310     // it is non-variadic.
6311     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6312     handleDebugDeclare(DI.getVariableLocationOp(0), Variable, Expression,
6313                        DI.getDebugLoc());
6314     return;
6315   }
6316   case Intrinsic::dbg_label: {
6317     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6318     DILabel *Label = DI.getLabel();
6319     assert(Label && "Missing label");
6320 
6321     SDDbgLabel *SDV;
6322     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6323     DAG.AddDbgLabel(SDV);
6324     return;
6325   }
6326   case Intrinsic::dbg_assign: {
6327     // Debug intrinsics are handled seperately in assignment tracking mode.
6328     if (AssignmentTrackingEnabled)
6329       return;
6330     // If assignment tracking hasn't been enabled then fall through and treat
6331     // the dbg.assign as a dbg.value.
6332     [[fallthrough]];
6333   }
6334   case Intrinsic::dbg_value: {
6335     // Debug intrinsics are handled seperately in assignment tracking mode.
6336     if (AssignmentTrackingEnabled)
6337       return;
6338     const DbgValueInst &DI = cast<DbgValueInst>(I);
6339     assert(DI.getVariable() && "Missing variable");
6340 
6341     DILocalVariable *Variable = DI.getVariable();
6342     DIExpression *Expression = DI.getExpression();
6343     dropDanglingDebugInfo(Variable, Expression);
6344 
6345     if (DI.isKillLocation()) {
6346       handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder);
6347       return;
6348     }
6349 
6350     SmallVector<Value *, 4> Values(DI.getValues());
6351     if (Values.empty())
6352       return;
6353 
6354     bool IsVariadic = DI.hasArgList();
6355     if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(),
6356                           SDNodeOrder, IsVariadic))
6357       addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
6358                            DI.getDebugLoc(), SDNodeOrder);
6359     return;
6360   }
6361 
6362   case Intrinsic::eh_typeid_for: {
6363     // Find the type id for the given typeinfo.
6364     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6365     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6366     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6367     setValue(&I, Res);
6368     return;
6369   }
6370 
6371   case Intrinsic::eh_return_i32:
6372   case Intrinsic::eh_return_i64:
6373     DAG.getMachineFunction().setCallsEHReturn(true);
6374     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6375                             MVT::Other,
6376                             getControlRoot(),
6377                             getValue(I.getArgOperand(0)),
6378                             getValue(I.getArgOperand(1))));
6379     return;
6380   case Intrinsic::eh_unwind_init:
6381     DAG.getMachineFunction().setCallsUnwindInit(true);
6382     return;
6383   case Intrinsic::eh_dwarf_cfa:
6384     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6385                              TLI.getPointerTy(DAG.getDataLayout()),
6386                              getValue(I.getArgOperand(0))));
6387     return;
6388   case Intrinsic::eh_sjlj_callsite: {
6389     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6390     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
6391     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6392 
6393     MMI.setCurrentCallSite(CI->getZExtValue());
6394     return;
6395   }
6396   case Intrinsic::eh_sjlj_functioncontext: {
6397     // Get and store the index of the function context.
6398     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6399     AllocaInst *FnCtx =
6400       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6401     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6402     MFI.setFunctionContextIndex(FI);
6403     return;
6404   }
6405   case Intrinsic::eh_sjlj_setjmp: {
6406     SDValue Ops[2];
6407     Ops[0] = getRoot();
6408     Ops[1] = getValue(I.getArgOperand(0));
6409     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6410                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6411     setValue(&I, Op.getValue(0));
6412     DAG.setRoot(Op.getValue(1));
6413     return;
6414   }
6415   case Intrinsic::eh_sjlj_longjmp:
6416     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6417                             getRoot(), getValue(I.getArgOperand(0))));
6418     return;
6419   case Intrinsic::eh_sjlj_setup_dispatch:
6420     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6421                             getRoot()));
6422     return;
6423   case Intrinsic::masked_gather:
6424     visitMaskedGather(I);
6425     return;
6426   case Intrinsic::masked_load:
6427     visitMaskedLoad(I);
6428     return;
6429   case Intrinsic::masked_scatter:
6430     visitMaskedScatter(I);
6431     return;
6432   case Intrinsic::masked_store:
6433     visitMaskedStore(I);
6434     return;
6435   case Intrinsic::masked_expandload:
6436     visitMaskedLoad(I, true /* IsExpanding */);
6437     return;
6438   case Intrinsic::masked_compressstore:
6439     visitMaskedStore(I, true /* IsCompressing */);
6440     return;
6441   case Intrinsic::powi:
6442     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6443                             getValue(I.getArgOperand(1)), DAG));
6444     return;
6445   case Intrinsic::log:
6446     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6447     return;
6448   case Intrinsic::log2:
6449     setValue(&I,
6450              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6451     return;
6452   case Intrinsic::log10:
6453     setValue(&I,
6454              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6455     return;
6456   case Intrinsic::exp:
6457     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6458     return;
6459   case Intrinsic::exp2:
6460     setValue(&I,
6461              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6462     return;
6463   case Intrinsic::pow:
6464     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6465                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6466     return;
6467   case Intrinsic::sqrt:
6468   case Intrinsic::fabs:
6469   case Intrinsic::sin:
6470   case Intrinsic::cos:
6471   case Intrinsic::exp10:
6472   case Intrinsic::floor:
6473   case Intrinsic::ceil:
6474   case Intrinsic::trunc:
6475   case Intrinsic::rint:
6476   case Intrinsic::nearbyint:
6477   case Intrinsic::round:
6478   case Intrinsic::roundeven:
6479   case Intrinsic::canonicalize: {
6480     unsigned Opcode;
6481     switch (Intrinsic) {
6482     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6483     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6484     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6485     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6486     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6487     case Intrinsic::exp10:     Opcode = ISD::FEXP10;     break;
6488     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6489     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6490     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6491     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6492     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6493     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6494     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6495     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6496     }
6497 
6498     setValue(&I, DAG.getNode(Opcode, sdl,
6499                              getValue(I.getArgOperand(0)).getValueType(),
6500                              getValue(I.getArgOperand(0)), Flags));
6501     return;
6502   }
6503   case Intrinsic::lround:
6504   case Intrinsic::llround:
6505   case Intrinsic::lrint:
6506   case Intrinsic::llrint: {
6507     unsigned Opcode;
6508     switch (Intrinsic) {
6509     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6510     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6511     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6512     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6513     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6514     }
6515 
6516     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6517     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6518                              getValue(I.getArgOperand(0))));
6519     return;
6520   }
6521   case Intrinsic::minnum:
6522     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6523                              getValue(I.getArgOperand(0)).getValueType(),
6524                              getValue(I.getArgOperand(0)),
6525                              getValue(I.getArgOperand(1)), Flags));
6526     return;
6527   case Intrinsic::maxnum:
6528     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6529                              getValue(I.getArgOperand(0)).getValueType(),
6530                              getValue(I.getArgOperand(0)),
6531                              getValue(I.getArgOperand(1)), Flags));
6532     return;
6533   case Intrinsic::minimum:
6534     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6535                              getValue(I.getArgOperand(0)).getValueType(),
6536                              getValue(I.getArgOperand(0)),
6537                              getValue(I.getArgOperand(1)), Flags));
6538     return;
6539   case Intrinsic::maximum:
6540     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6541                              getValue(I.getArgOperand(0)).getValueType(),
6542                              getValue(I.getArgOperand(0)),
6543                              getValue(I.getArgOperand(1)), Flags));
6544     return;
6545   case Intrinsic::copysign:
6546     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6547                              getValue(I.getArgOperand(0)).getValueType(),
6548                              getValue(I.getArgOperand(0)),
6549                              getValue(I.getArgOperand(1)), Flags));
6550     return;
6551   case Intrinsic::ldexp:
6552     setValue(&I, DAG.getNode(ISD::FLDEXP, sdl,
6553                              getValue(I.getArgOperand(0)).getValueType(),
6554                              getValue(I.getArgOperand(0)),
6555                              getValue(I.getArgOperand(1)), Flags));
6556     return;
6557   case Intrinsic::frexp: {
6558     SmallVector<EVT, 2> ValueVTs;
6559     ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
6560     SDVTList VTs = DAG.getVTList(ValueVTs);
6561     setValue(&I,
6562              DAG.getNode(ISD::FFREXP, sdl, VTs, getValue(I.getArgOperand(0))));
6563     return;
6564   }
6565   case Intrinsic::arithmetic_fence: {
6566     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6567                              getValue(I.getArgOperand(0)).getValueType(),
6568                              getValue(I.getArgOperand(0)), Flags));
6569     return;
6570   }
6571   case Intrinsic::fma:
6572     setValue(&I, DAG.getNode(
6573                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6574                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6575                      getValue(I.getArgOperand(2)), Flags));
6576     return;
6577 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6578   case Intrinsic::INTRINSIC:
6579 #include "llvm/IR/ConstrainedOps.def"
6580     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6581     return;
6582 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6583 #include "llvm/IR/VPIntrinsics.def"
6584     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6585     return;
6586   case Intrinsic::fptrunc_round: {
6587     // Get the last argument, the metadata and convert it to an integer in the
6588     // call
6589     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
6590     std::optional<RoundingMode> RoundMode =
6591         convertStrToRoundingMode(cast<MDString>(MD)->getString());
6592 
6593     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6594 
6595     // Propagate fast-math-flags from IR to node(s).
6596     SDNodeFlags Flags;
6597     Flags.copyFMF(*cast<FPMathOperator>(&I));
6598     SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
6599 
6600     SDValue Result;
6601     Result = DAG.getNode(
6602         ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
6603         DAG.getTargetConstant((int)*RoundMode, sdl,
6604                               TLI.getPointerTy(DAG.getDataLayout())));
6605     setValue(&I, Result);
6606 
6607     return;
6608   }
6609   case Intrinsic::fmuladd: {
6610     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6611     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6612         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6613       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6614                                getValue(I.getArgOperand(0)).getValueType(),
6615                                getValue(I.getArgOperand(0)),
6616                                getValue(I.getArgOperand(1)),
6617                                getValue(I.getArgOperand(2)), Flags));
6618     } else {
6619       // TODO: Intrinsic calls should have fast-math-flags.
6620       SDValue Mul = DAG.getNode(
6621           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6622           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6623       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6624                                 getValue(I.getArgOperand(0)).getValueType(),
6625                                 Mul, getValue(I.getArgOperand(2)), Flags);
6626       setValue(&I, Add);
6627     }
6628     return;
6629   }
6630   case Intrinsic::convert_to_fp16:
6631     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6632                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6633                                          getValue(I.getArgOperand(0)),
6634                                          DAG.getTargetConstant(0, sdl,
6635                                                                MVT::i32))));
6636     return;
6637   case Intrinsic::convert_from_fp16:
6638     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6639                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6640                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6641                                          getValue(I.getArgOperand(0)))));
6642     return;
6643   case Intrinsic::fptosi_sat: {
6644     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6645     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
6646                              getValue(I.getArgOperand(0)),
6647                              DAG.getValueType(VT.getScalarType())));
6648     return;
6649   }
6650   case Intrinsic::fptoui_sat: {
6651     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6652     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
6653                              getValue(I.getArgOperand(0)),
6654                              DAG.getValueType(VT.getScalarType())));
6655     return;
6656   }
6657   case Intrinsic::set_rounding:
6658     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6659                       {getRoot(), getValue(I.getArgOperand(0))});
6660     setValue(&I, Res);
6661     DAG.setRoot(Res.getValue(0));
6662     return;
6663   case Intrinsic::is_fpclass: {
6664     const DataLayout DLayout = DAG.getDataLayout();
6665     EVT DestVT = TLI.getValueType(DLayout, I.getType());
6666     EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
6667     FPClassTest Test = static_cast<FPClassTest>(
6668         cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
6669     MachineFunction &MF = DAG.getMachineFunction();
6670     const Function &F = MF.getFunction();
6671     SDValue Op = getValue(I.getArgOperand(0));
6672     SDNodeFlags Flags;
6673     Flags.setNoFPExcept(
6674         !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
6675     // If ISD::IS_FPCLASS should be expanded, do it right now, because the
6676     // expansion can use illegal types. Making expansion early allows
6677     // legalizing these types prior to selection.
6678     if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) {
6679       SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
6680       setValue(&I, Result);
6681       return;
6682     }
6683 
6684     SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
6685     SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
6686     setValue(&I, V);
6687     return;
6688   }
6689   case Intrinsic::get_fpenv: {
6690     const DataLayout DLayout = DAG.getDataLayout();
6691     EVT EnvVT = TLI.getValueType(DLayout, I.getType());
6692     Align TempAlign = DAG.getEVTAlign(EnvVT);
6693     SDValue Chain = getRoot();
6694     // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node
6695     // and temporary storage in stack.
6696     if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) {
6697       Res = DAG.getNode(
6698           ISD::GET_FPENV, sdl,
6699           DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
6700                         MVT::Other),
6701           Chain);
6702     } else {
6703       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
6704       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
6705       auto MPI =
6706           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
6707       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6708           MPI, MachineMemOperand::MOStore, MemoryLocation::UnknownSize,
6709           TempAlign);
6710       Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
6711       Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI);
6712     }
6713     setValue(&I, Res);
6714     DAG.setRoot(Res.getValue(1));
6715     return;
6716   }
6717   case Intrinsic::set_fpenv: {
6718     const DataLayout DLayout = DAG.getDataLayout();
6719     SDValue Env = getValue(I.getArgOperand(0));
6720     EVT EnvVT = Env.getValueType();
6721     Align TempAlign = DAG.getEVTAlign(EnvVT);
6722     SDValue Chain = getRoot();
6723     // If SET_FPENV is custom or legal, use it. Otherwise use loading
6724     // environment from memory.
6725     if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) {
6726       Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env);
6727     } else {
6728       // Allocate space in stack, copy environment bits into it and use this
6729       // memory in SET_FPENV_MEM.
6730       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
6731       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
6732       auto MPI =
6733           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
6734       Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign,
6735                            MachineMemOperand::MOStore);
6736       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6737           MPI, MachineMemOperand::MOLoad, MemoryLocation::UnknownSize,
6738           TempAlign);
6739       Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
6740     }
6741     DAG.setRoot(Chain);
6742     return;
6743   }
6744   case Intrinsic::reset_fpenv:
6745     DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot()));
6746     return;
6747   case Intrinsic::get_fpmode:
6748     Res = DAG.getNode(
6749         ISD::GET_FPMODE, sdl,
6750         DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
6751                       MVT::Other),
6752         DAG.getRoot());
6753     setValue(&I, Res);
6754     DAG.setRoot(Res.getValue(1));
6755     return;
6756   case Intrinsic::set_fpmode:
6757     Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()},
6758                       getValue(I.getArgOperand(0)));
6759     DAG.setRoot(Res);
6760     return;
6761   case Intrinsic::reset_fpmode: {
6762     Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot());
6763     DAG.setRoot(Res);
6764     return;
6765   }
6766   case Intrinsic::pcmarker: {
6767     SDValue Tmp = getValue(I.getArgOperand(0));
6768     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6769     return;
6770   }
6771   case Intrinsic::readcyclecounter: {
6772     SDValue Op = getRoot();
6773     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6774                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6775     setValue(&I, Res);
6776     DAG.setRoot(Res.getValue(1));
6777     return;
6778   }
6779   case Intrinsic::bitreverse:
6780     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6781                              getValue(I.getArgOperand(0)).getValueType(),
6782                              getValue(I.getArgOperand(0))));
6783     return;
6784   case Intrinsic::bswap:
6785     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6786                              getValue(I.getArgOperand(0)).getValueType(),
6787                              getValue(I.getArgOperand(0))));
6788     return;
6789   case Intrinsic::cttz: {
6790     SDValue Arg = getValue(I.getArgOperand(0));
6791     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6792     EVT Ty = Arg.getValueType();
6793     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6794                              sdl, Ty, Arg));
6795     return;
6796   }
6797   case Intrinsic::ctlz: {
6798     SDValue Arg = getValue(I.getArgOperand(0));
6799     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6800     EVT Ty = Arg.getValueType();
6801     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6802                              sdl, Ty, Arg));
6803     return;
6804   }
6805   case Intrinsic::ctpop: {
6806     SDValue Arg = getValue(I.getArgOperand(0));
6807     EVT Ty = Arg.getValueType();
6808     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6809     return;
6810   }
6811   case Intrinsic::fshl:
6812   case Intrinsic::fshr: {
6813     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6814     SDValue X = getValue(I.getArgOperand(0));
6815     SDValue Y = getValue(I.getArgOperand(1));
6816     SDValue Z = getValue(I.getArgOperand(2));
6817     EVT VT = X.getValueType();
6818 
6819     if (X == Y) {
6820       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6821       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6822     } else {
6823       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6824       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6825     }
6826     return;
6827   }
6828   case Intrinsic::sadd_sat: {
6829     SDValue Op1 = getValue(I.getArgOperand(0));
6830     SDValue Op2 = getValue(I.getArgOperand(1));
6831     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6832     return;
6833   }
6834   case Intrinsic::uadd_sat: {
6835     SDValue Op1 = getValue(I.getArgOperand(0));
6836     SDValue Op2 = getValue(I.getArgOperand(1));
6837     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6838     return;
6839   }
6840   case Intrinsic::ssub_sat: {
6841     SDValue Op1 = getValue(I.getArgOperand(0));
6842     SDValue Op2 = getValue(I.getArgOperand(1));
6843     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6844     return;
6845   }
6846   case Intrinsic::usub_sat: {
6847     SDValue Op1 = getValue(I.getArgOperand(0));
6848     SDValue Op2 = getValue(I.getArgOperand(1));
6849     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6850     return;
6851   }
6852   case Intrinsic::sshl_sat: {
6853     SDValue Op1 = getValue(I.getArgOperand(0));
6854     SDValue Op2 = getValue(I.getArgOperand(1));
6855     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6856     return;
6857   }
6858   case Intrinsic::ushl_sat: {
6859     SDValue Op1 = getValue(I.getArgOperand(0));
6860     SDValue Op2 = getValue(I.getArgOperand(1));
6861     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6862     return;
6863   }
6864   case Intrinsic::smul_fix:
6865   case Intrinsic::umul_fix:
6866   case Intrinsic::smul_fix_sat:
6867   case Intrinsic::umul_fix_sat: {
6868     SDValue Op1 = getValue(I.getArgOperand(0));
6869     SDValue Op2 = getValue(I.getArgOperand(1));
6870     SDValue Op3 = getValue(I.getArgOperand(2));
6871     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6872                              Op1.getValueType(), Op1, Op2, Op3));
6873     return;
6874   }
6875   case Intrinsic::sdiv_fix:
6876   case Intrinsic::udiv_fix:
6877   case Intrinsic::sdiv_fix_sat:
6878   case Intrinsic::udiv_fix_sat: {
6879     SDValue Op1 = getValue(I.getArgOperand(0));
6880     SDValue Op2 = getValue(I.getArgOperand(1));
6881     SDValue Op3 = getValue(I.getArgOperand(2));
6882     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6883                               Op1, Op2, Op3, DAG, TLI));
6884     return;
6885   }
6886   case Intrinsic::smax: {
6887     SDValue Op1 = getValue(I.getArgOperand(0));
6888     SDValue Op2 = getValue(I.getArgOperand(1));
6889     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
6890     return;
6891   }
6892   case Intrinsic::smin: {
6893     SDValue Op1 = getValue(I.getArgOperand(0));
6894     SDValue Op2 = getValue(I.getArgOperand(1));
6895     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
6896     return;
6897   }
6898   case Intrinsic::umax: {
6899     SDValue Op1 = getValue(I.getArgOperand(0));
6900     SDValue Op2 = getValue(I.getArgOperand(1));
6901     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
6902     return;
6903   }
6904   case Intrinsic::umin: {
6905     SDValue Op1 = getValue(I.getArgOperand(0));
6906     SDValue Op2 = getValue(I.getArgOperand(1));
6907     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
6908     return;
6909   }
6910   case Intrinsic::abs: {
6911     // TODO: Preserve "int min is poison" arg in SDAG?
6912     SDValue Op1 = getValue(I.getArgOperand(0));
6913     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
6914     return;
6915   }
6916   case Intrinsic::stacksave: {
6917     SDValue Op = getRoot();
6918     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6919     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6920     setValue(&I, Res);
6921     DAG.setRoot(Res.getValue(1));
6922     return;
6923   }
6924   case Intrinsic::stackrestore:
6925     Res = getValue(I.getArgOperand(0));
6926     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6927     return;
6928   case Intrinsic::get_dynamic_area_offset: {
6929     SDValue Op = getRoot();
6930     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6931     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6932     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6933     // target.
6934     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
6935       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6936                          " intrinsic!");
6937     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6938                       Op);
6939     DAG.setRoot(Op);
6940     setValue(&I, Res);
6941     return;
6942   }
6943   case Intrinsic::stackguard: {
6944     MachineFunction &MF = DAG.getMachineFunction();
6945     const Module &M = *MF.getFunction().getParent();
6946     SDValue Chain = getRoot();
6947     if (TLI.useLoadStackGuardNode()) {
6948       Res = getLoadStackGuard(DAG, sdl, Chain);
6949     } else {
6950       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6951       const Value *Global = TLI.getSDagStackGuard(M);
6952       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
6953       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6954                         MachinePointerInfo(Global, 0), Align,
6955                         MachineMemOperand::MOVolatile);
6956     }
6957     if (TLI.useStackGuardXorFP())
6958       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6959     DAG.setRoot(Chain);
6960     setValue(&I, Res);
6961     return;
6962   }
6963   case Intrinsic::stackprotector: {
6964     // Emit code into the DAG to store the stack guard onto the stack.
6965     MachineFunction &MF = DAG.getMachineFunction();
6966     MachineFrameInfo &MFI = MF.getFrameInfo();
6967     SDValue Src, Chain = getRoot();
6968 
6969     if (TLI.useLoadStackGuardNode())
6970       Src = getLoadStackGuard(DAG, sdl, Chain);
6971     else
6972       Src = getValue(I.getArgOperand(0));   // The guard's value.
6973 
6974     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6975 
6976     int FI = FuncInfo.StaticAllocaMap[Slot];
6977     MFI.setStackProtectorIndex(FI);
6978     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6979 
6980     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6981 
6982     // Store the stack protector onto the stack.
6983     Res = DAG.getStore(
6984         Chain, sdl, Src, FIN,
6985         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
6986         MaybeAlign(), MachineMemOperand::MOVolatile);
6987     setValue(&I, Res);
6988     DAG.setRoot(Res);
6989     return;
6990   }
6991   case Intrinsic::objectsize:
6992     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6993 
6994   case Intrinsic::is_constant:
6995     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6996 
6997   case Intrinsic::annotation:
6998   case Intrinsic::ptr_annotation:
6999   case Intrinsic::launder_invariant_group:
7000   case Intrinsic::strip_invariant_group:
7001     // Drop the intrinsic, but forward the value
7002     setValue(&I, getValue(I.getOperand(0)));
7003     return;
7004 
7005   case Intrinsic::assume:
7006   case Intrinsic::experimental_noalias_scope_decl:
7007   case Intrinsic::var_annotation:
7008   case Intrinsic::sideeffect:
7009     // Discard annotate attributes, noalias scope declarations, assumptions, and
7010     // artificial side-effects.
7011     return;
7012 
7013   case Intrinsic::codeview_annotation: {
7014     // Emit a label associated with this metadata.
7015     MachineFunction &MF = DAG.getMachineFunction();
7016     MCSymbol *Label =
7017         MF.getMMI().getContext().createTempSymbol("annotation", true);
7018     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
7019     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
7020     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
7021     DAG.setRoot(Res);
7022     return;
7023   }
7024 
7025   case Intrinsic::init_trampoline: {
7026     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
7027 
7028     SDValue Ops[6];
7029     Ops[0] = getRoot();
7030     Ops[1] = getValue(I.getArgOperand(0));
7031     Ops[2] = getValue(I.getArgOperand(1));
7032     Ops[3] = getValue(I.getArgOperand(2));
7033     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
7034     Ops[5] = DAG.getSrcValue(F);
7035 
7036     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
7037 
7038     DAG.setRoot(Res);
7039     return;
7040   }
7041   case Intrinsic::adjust_trampoline:
7042     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
7043                              TLI.getPointerTy(DAG.getDataLayout()),
7044                              getValue(I.getArgOperand(0))));
7045     return;
7046   case Intrinsic::gcroot: {
7047     assert(DAG.getMachineFunction().getFunction().hasGC() &&
7048            "only valid in functions with gc specified, enforced by Verifier");
7049     assert(GFI && "implied by previous");
7050     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
7051     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
7052 
7053     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
7054     GFI->addStackRoot(FI->getIndex(), TypeMap);
7055     return;
7056   }
7057   case Intrinsic::gcread:
7058   case Intrinsic::gcwrite:
7059     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
7060   case Intrinsic::get_rounding:
7061     Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot());
7062     setValue(&I, Res);
7063     DAG.setRoot(Res.getValue(1));
7064     return;
7065 
7066   case Intrinsic::expect:
7067     // Just replace __builtin_expect(exp, c) with EXP.
7068     setValue(&I, getValue(I.getArgOperand(0)));
7069     return;
7070 
7071   case Intrinsic::ubsantrap:
7072   case Intrinsic::debugtrap:
7073   case Intrinsic::trap: {
7074     StringRef TrapFuncName =
7075         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
7076     if (TrapFuncName.empty()) {
7077       switch (Intrinsic) {
7078       case Intrinsic::trap:
7079         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
7080         break;
7081       case Intrinsic::debugtrap:
7082         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
7083         break;
7084       case Intrinsic::ubsantrap:
7085         DAG.setRoot(DAG.getNode(
7086             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
7087             DAG.getTargetConstant(
7088                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
7089                 MVT::i32)));
7090         break;
7091       default: llvm_unreachable("unknown trap intrinsic");
7092       }
7093       return;
7094     }
7095     TargetLowering::ArgListTy Args;
7096     if (Intrinsic == Intrinsic::ubsantrap) {
7097       Args.push_back(TargetLoweringBase::ArgListEntry());
7098       Args[0].Val = I.getArgOperand(0);
7099       Args[0].Node = getValue(Args[0].Val);
7100       Args[0].Ty = Args[0].Val->getType();
7101     }
7102 
7103     TargetLowering::CallLoweringInfo CLI(DAG);
7104     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
7105         CallingConv::C, I.getType(),
7106         DAG.getExternalSymbol(TrapFuncName.data(),
7107                               TLI.getPointerTy(DAG.getDataLayout())),
7108         std::move(Args));
7109 
7110     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7111     DAG.setRoot(Result.second);
7112     return;
7113   }
7114 
7115   case Intrinsic::uadd_with_overflow:
7116   case Intrinsic::sadd_with_overflow:
7117   case Intrinsic::usub_with_overflow:
7118   case Intrinsic::ssub_with_overflow:
7119   case Intrinsic::umul_with_overflow:
7120   case Intrinsic::smul_with_overflow: {
7121     ISD::NodeType Op;
7122     switch (Intrinsic) {
7123     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7124     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
7125     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
7126     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
7127     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
7128     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
7129     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
7130     }
7131     SDValue Op1 = getValue(I.getArgOperand(0));
7132     SDValue Op2 = getValue(I.getArgOperand(1));
7133 
7134     EVT ResultVT = Op1.getValueType();
7135     EVT OverflowVT = MVT::i1;
7136     if (ResultVT.isVector())
7137       OverflowVT = EVT::getVectorVT(
7138           *Context, OverflowVT, ResultVT.getVectorElementCount());
7139 
7140     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
7141     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
7142     return;
7143   }
7144   case Intrinsic::prefetch: {
7145     SDValue Ops[5];
7146     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7147     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
7148     Ops[0] = DAG.getRoot();
7149     Ops[1] = getValue(I.getArgOperand(0));
7150     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
7151                                    MVT::i32);
7152     Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl,
7153                                    MVT::i32);
7154     Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl,
7155                                    MVT::i32);
7156     SDValue Result = DAG.getMemIntrinsicNode(
7157         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
7158         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
7159         /* align */ std::nullopt, Flags);
7160 
7161     // Chain the prefetch in parallel with any pending loads, to stay out of
7162     // the way of later optimizations.
7163     PendingLoads.push_back(Result);
7164     Result = getRoot();
7165     DAG.setRoot(Result);
7166     return;
7167   }
7168   case Intrinsic::lifetime_start:
7169   case Intrinsic::lifetime_end: {
7170     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
7171     // Stack coloring is not enabled in O0, discard region information.
7172     if (TM.getOptLevel() == CodeGenOptLevel::None)
7173       return;
7174 
7175     const int64_t ObjectSize =
7176         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
7177     Value *const ObjectPtr = I.getArgOperand(1);
7178     SmallVector<const Value *, 4> Allocas;
7179     getUnderlyingObjects(ObjectPtr, Allocas);
7180 
7181     for (const Value *Alloca : Allocas) {
7182       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
7183 
7184       // Could not find an Alloca.
7185       if (!LifetimeObject)
7186         continue;
7187 
7188       // First check that the Alloca is static, otherwise it won't have a
7189       // valid frame index.
7190       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
7191       if (SI == FuncInfo.StaticAllocaMap.end())
7192         return;
7193 
7194       const int FrameIndex = SI->second;
7195       int64_t Offset;
7196       if (GetPointerBaseWithConstantOffset(
7197               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
7198         Offset = -1; // Cannot determine offset from alloca to lifetime object.
7199       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
7200                                 Offset);
7201       DAG.setRoot(Res);
7202     }
7203     return;
7204   }
7205   case Intrinsic::pseudoprobe: {
7206     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
7207     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7208     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
7209     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
7210     DAG.setRoot(Res);
7211     return;
7212   }
7213   case Intrinsic::invariant_start:
7214     // Discard region information.
7215     setValue(&I,
7216              DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
7217     return;
7218   case Intrinsic::invariant_end:
7219     // Discard region information.
7220     return;
7221   case Intrinsic::clear_cache:
7222     /// FunctionName may be null.
7223     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
7224       lowerCallToExternalSymbol(I, FunctionName);
7225     return;
7226   case Intrinsic::donothing:
7227   case Intrinsic::seh_try_begin:
7228   case Intrinsic::seh_scope_begin:
7229   case Intrinsic::seh_try_end:
7230   case Intrinsic::seh_scope_end:
7231     // ignore
7232     return;
7233   case Intrinsic::experimental_stackmap:
7234     visitStackmap(I);
7235     return;
7236   case Intrinsic::experimental_patchpoint_void:
7237   case Intrinsic::experimental_patchpoint_i64:
7238     visitPatchpoint(I);
7239     return;
7240   case Intrinsic::experimental_gc_statepoint:
7241     LowerStatepoint(cast<GCStatepointInst>(I));
7242     return;
7243   case Intrinsic::experimental_gc_result:
7244     visitGCResult(cast<GCResultInst>(I));
7245     return;
7246   case Intrinsic::experimental_gc_relocate:
7247     visitGCRelocate(cast<GCRelocateInst>(I));
7248     return;
7249   case Intrinsic::instrprof_cover:
7250     llvm_unreachable("instrprof failed to lower a cover");
7251   case Intrinsic::instrprof_increment:
7252     llvm_unreachable("instrprof failed to lower an increment");
7253   case Intrinsic::instrprof_timestamp:
7254     llvm_unreachable("instrprof failed to lower a timestamp");
7255   case Intrinsic::instrprof_value_profile:
7256     llvm_unreachable("instrprof failed to lower a value profiling call");
7257   case Intrinsic::instrprof_mcdc_parameters:
7258     llvm_unreachable("instrprof failed to lower mcdc parameters");
7259   case Intrinsic::instrprof_mcdc_tvbitmap_update:
7260     llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update");
7261   case Intrinsic::instrprof_mcdc_condbitmap_update:
7262     llvm_unreachable("instrprof failed to lower an mcdc condbitmap update");
7263   case Intrinsic::localescape: {
7264     MachineFunction &MF = DAG.getMachineFunction();
7265     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
7266 
7267     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
7268     // is the same on all targets.
7269     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
7270       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
7271       if (isa<ConstantPointerNull>(Arg))
7272         continue; // Skip null pointers. They represent a hole in index space.
7273       AllocaInst *Slot = cast<AllocaInst>(Arg);
7274       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
7275              "can only escape static allocas");
7276       int FI = FuncInfo.StaticAllocaMap[Slot];
7277       MCSymbol *FrameAllocSym =
7278           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7279               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
7280       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
7281               TII->get(TargetOpcode::LOCAL_ESCAPE))
7282           .addSym(FrameAllocSym)
7283           .addFrameIndex(FI);
7284     }
7285 
7286     return;
7287   }
7288 
7289   case Intrinsic::localrecover: {
7290     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
7291     MachineFunction &MF = DAG.getMachineFunction();
7292 
7293     // Get the symbol that defines the frame offset.
7294     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
7295     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
7296     unsigned IdxVal =
7297         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
7298     MCSymbol *FrameAllocSym =
7299         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7300             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
7301 
7302     Value *FP = I.getArgOperand(1);
7303     SDValue FPVal = getValue(FP);
7304     EVT PtrVT = FPVal.getValueType();
7305 
7306     // Create a MCSymbol for the label to avoid any target lowering
7307     // that would make this PC relative.
7308     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
7309     SDValue OffsetVal =
7310         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
7311 
7312     // Add the offset to the FP.
7313     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
7314     setValue(&I, Add);
7315 
7316     return;
7317   }
7318 
7319   case Intrinsic::eh_exceptionpointer:
7320   case Intrinsic::eh_exceptioncode: {
7321     // Get the exception pointer vreg, copy from it, and resize it to fit.
7322     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
7323     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
7324     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
7325     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
7326     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
7327     if (Intrinsic == Intrinsic::eh_exceptioncode)
7328       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
7329     setValue(&I, N);
7330     return;
7331   }
7332   case Intrinsic::xray_customevent: {
7333     // Here we want to make sure that the intrinsic behaves as if it has a
7334     // specific calling convention.
7335     const auto &Triple = DAG.getTarget().getTargetTriple();
7336     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7337       return;
7338 
7339     SmallVector<SDValue, 8> Ops;
7340 
7341     // We want to say that we always want the arguments in registers.
7342     SDValue LogEntryVal = getValue(I.getArgOperand(0));
7343     SDValue StrSizeVal = getValue(I.getArgOperand(1));
7344     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7345     SDValue Chain = getRoot();
7346     Ops.push_back(LogEntryVal);
7347     Ops.push_back(StrSizeVal);
7348     Ops.push_back(Chain);
7349 
7350     // We need to enforce the calling convention for the callsite, so that
7351     // argument ordering is enforced correctly, and that register allocation can
7352     // see that some registers may be assumed clobbered and have to preserve
7353     // them across calls to the intrinsic.
7354     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
7355                                            sdl, NodeTys, Ops);
7356     SDValue patchableNode = SDValue(MN, 0);
7357     DAG.setRoot(patchableNode);
7358     setValue(&I, patchableNode);
7359     return;
7360   }
7361   case Intrinsic::xray_typedevent: {
7362     // Here we want to make sure that the intrinsic behaves as if it has a
7363     // specific calling convention.
7364     const auto &Triple = DAG.getTarget().getTargetTriple();
7365     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7366       return;
7367 
7368     SmallVector<SDValue, 8> Ops;
7369 
7370     // We want to say that we always want the arguments in registers.
7371     // It's unclear to me how manipulating the selection DAG here forces callers
7372     // to provide arguments in registers instead of on the stack.
7373     SDValue LogTypeId = getValue(I.getArgOperand(0));
7374     SDValue LogEntryVal = getValue(I.getArgOperand(1));
7375     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7376     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7377     SDValue Chain = getRoot();
7378     Ops.push_back(LogTypeId);
7379     Ops.push_back(LogEntryVal);
7380     Ops.push_back(StrSizeVal);
7381     Ops.push_back(Chain);
7382 
7383     // We need to enforce the calling convention for the callsite, so that
7384     // argument ordering is enforced correctly, and that register allocation can
7385     // see that some registers may be assumed clobbered and have to preserve
7386     // them across calls to the intrinsic.
7387     MachineSDNode *MN = DAG.getMachineNode(
7388         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7389     SDValue patchableNode = SDValue(MN, 0);
7390     DAG.setRoot(patchableNode);
7391     setValue(&I, patchableNode);
7392     return;
7393   }
7394   case Intrinsic::experimental_deoptimize:
7395     LowerDeoptimizeCall(&I);
7396     return;
7397   case Intrinsic::experimental_stepvector:
7398     visitStepVector(I);
7399     return;
7400   case Intrinsic::vector_reduce_fadd:
7401   case Intrinsic::vector_reduce_fmul:
7402   case Intrinsic::vector_reduce_add:
7403   case Intrinsic::vector_reduce_mul:
7404   case Intrinsic::vector_reduce_and:
7405   case Intrinsic::vector_reduce_or:
7406   case Intrinsic::vector_reduce_xor:
7407   case Intrinsic::vector_reduce_smax:
7408   case Intrinsic::vector_reduce_smin:
7409   case Intrinsic::vector_reduce_umax:
7410   case Intrinsic::vector_reduce_umin:
7411   case Intrinsic::vector_reduce_fmax:
7412   case Intrinsic::vector_reduce_fmin:
7413   case Intrinsic::vector_reduce_fmaximum:
7414   case Intrinsic::vector_reduce_fminimum:
7415     visitVectorReduce(I, Intrinsic);
7416     return;
7417 
7418   case Intrinsic::icall_branch_funnel: {
7419     SmallVector<SDValue, 16> Ops;
7420     Ops.push_back(getValue(I.getArgOperand(0)));
7421 
7422     int64_t Offset;
7423     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7424         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7425     if (!Base)
7426       report_fatal_error(
7427           "llvm.icall.branch.funnel operand must be a GlobalValue");
7428     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7429 
7430     struct BranchFunnelTarget {
7431       int64_t Offset;
7432       SDValue Target;
7433     };
7434     SmallVector<BranchFunnelTarget, 8> Targets;
7435 
7436     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7437       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7438           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7439       if (ElemBase != Base)
7440         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7441                            "to the same GlobalValue");
7442 
7443       SDValue Val = getValue(I.getArgOperand(Op + 1));
7444       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7445       if (!GA)
7446         report_fatal_error(
7447             "llvm.icall.branch.funnel operand must be a GlobalValue");
7448       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7449                                      GA->getGlobal(), sdl, Val.getValueType(),
7450                                      GA->getOffset())});
7451     }
7452     llvm::sort(Targets,
7453                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7454                  return T1.Offset < T2.Offset;
7455                });
7456 
7457     for (auto &T : Targets) {
7458       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7459       Ops.push_back(T.Target);
7460     }
7461 
7462     Ops.push_back(DAG.getRoot()); // Chain
7463     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7464                                  MVT::Other, Ops),
7465               0);
7466     DAG.setRoot(N);
7467     setValue(&I, N);
7468     HasTailCall = true;
7469     return;
7470   }
7471 
7472   case Intrinsic::wasm_landingpad_index:
7473     // Information this intrinsic contained has been transferred to
7474     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7475     // delete it now.
7476     return;
7477 
7478   case Intrinsic::aarch64_settag:
7479   case Intrinsic::aarch64_settag_zero: {
7480     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7481     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7482     SDValue Val = TSI.EmitTargetCodeForSetTag(
7483         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7484         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7485         ZeroMemory);
7486     DAG.setRoot(Val);
7487     setValue(&I, Val);
7488     return;
7489   }
7490   case Intrinsic::amdgcn_cs_chain: {
7491     assert(I.arg_size() == 5 && "Additional args not supported yet");
7492     assert(cast<ConstantInt>(I.getOperand(4))->isZero() &&
7493            "Non-zero flags not supported yet");
7494 
7495     // At this point we don't care if it's amdgpu_cs_chain or
7496     // amdgpu_cs_chain_preserve.
7497     CallingConv::ID CC = CallingConv::AMDGPU_CS_Chain;
7498 
7499     Type *RetTy = I.getType();
7500     assert(RetTy->isVoidTy() && "Should not return");
7501 
7502     SDValue Callee = getValue(I.getOperand(0));
7503 
7504     // We only have 2 actual args: one for the SGPRs and one for the VGPRs.
7505     // We'll also tack the value of the EXEC mask at the end.
7506     TargetLowering::ArgListTy Args;
7507     Args.reserve(3);
7508 
7509     for (unsigned Idx : {2, 3, 1}) {
7510       TargetLowering::ArgListEntry Arg;
7511       Arg.Node = getValue(I.getOperand(Idx));
7512       Arg.Ty = I.getOperand(Idx)->getType();
7513       Arg.setAttributes(&I, Idx);
7514       Args.push_back(Arg);
7515     }
7516 
7517     assert(Args[0].IsInReg && "SGPR args should be marked inreg");
7518     assert(!Args[1].IsInReg && "VGPR args should not be marked inreg");
7519     Args[2].IsInReg = true; // EXEC should be inreg
7520 
7521     TargetLowering::CallLoweringInfo CLI(DAG);
7522     CLI.setDebugLoc(getCurSDLoc())
7523         .setChain(getRoot())
7524         .setCallee(CC, RetTy, Callee, std::move(Args))
7525         .setNoReturn(true)
7526         .setTailCall(true)
7527         .setConvergent(I.isConvergent());
7528     CLI.CB = &I;
7529     std::pair<SDValue, SDValue> Result =
7530         lowerInvokable(CLI, /*EHPadBB*/ nullptr);
7531     (void)Result;
7532     assert(!Result.first.getNode() && !Result.second.getNode() &&
7533            "Should've lowered as tail call");
7534 
7535     HasTailCall = true;
7536     return;
7537   }
7538   case Intrinsic::ptrmask: {
7539     SDValue Ptr = getValue(I.getOperand(0));
7540     SDValue Mask = getValue(I.getOperand(1));
7541 
7542     EVT PtrVT = Ptr.getValueType();
7543     assert(PtrVT == Mask.getValueType() &&
7544            "Pointers with different index type are not supported by SDAG");
7545     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask));
7546     return;
7547   }
7548   case Intrinsic::threadlocal_address: {
7549     setValue(&I, getValue(I.getOperand(0)));
7550     return;
7551   }
7552   case Intrinsic::get_active_lane_mask: {
7553     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7554     SDValue Index = getValue(I.getOperand(0));
7555     EVT ElementVT = Index.getValueType();
7556 
7557     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
7558       visitTargetIntrinsic(I, Intrinsic);
7559       return;
7560     }
7561 
7562     SDValue TripCount = getValue(I.getOperand(1));
7563     EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT,
7564                                  CCVT.getVectorElementCount());
7565 
7566     SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
7567     SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
7568     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
7569     SDValue VectorInduction = DAG.getNode(
7570         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
7571     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
7572                                  VectorTripCount, ISD::CondCode::SETULT);
7573     setValue(&I, SetCC);
7574     return;
7575   }
7576   case Intrinsic::experimental_get_vector_length: {
7577     assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 &&
7578            "Expected positive VF");
7579     unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue();
7580     bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne();
7581 
7582     SDValue Count = getValue(I.getOperand(0));
7583     EVT CountVT = Count.getValueType();
7584 
7585     if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) {
7586       visitTargetIntrinsic(I, Intrinsic);
7587       return;
7588     }
7589 
7590     // Expand to a umin between the trip count and the maximum elements the type
7591     // can hold.
7592     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7593 
7594     // Extend the trip count to at least the result VT.
7595     if (CountVT.bitsLT(VT)) {
7596       Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count);
7597       CountVT = VT;
7598     }
7599 
7600     SDValue MaxEVL = DAG.getElementCount(sdl, CountVT,
7601                                          ElementCount::get(VF, IsScalable));
7602 
7603     SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL);
7604     // Clip to the result type if needed.
7605     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin);
7606 
7607     setValue(&I, Trunc);
7608     return;
7609   }
7610   case Intrinsic::experimental_cttz_elts: {
7611     auto DL = getCurSDLoc();
7612     SDValue Op = getValue(I.getOperand(0));
7613     EVT OpVT = Op.getValueType();
7614 
7615     if (!TLI.shouldExpandCttzElements(OpVT)) {
7616       visitTargetIntrinsic(I, Intrinsic);
7617       return;
7618     }
7619 
7620     if (OpVT.getScalarType() != MVT::i1) {
7621       // Compare the input vector elements to zero & use to count trailing zeros
7622       SDValue AllZero = DAG.getConstant(0, DL, OpVT);
7623       OpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
7624                               OpVT.getVectorElementCount());
7625       Op = DAG.getSetCC(DL, OpVT, Op, AllZero, ISD::SETNE);
7626     }
7627 
7628     // Find the smallest "sensible" element type to use for the expansion.
7629     ConstantRange CR(
7630         APInt(64, OpVT.getVectorElementCount().getKnownMinValue()));
7631     if (OpVT.isScalableVT())
7632       CR = CR.umul_sat(getVScaleRange(I.getCaller(), 64));
7633 
7634     // If the zero-is-poison flag is set, we can assume the upper limit
7635     // of the result is VF-1.
7636     if (!cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero())
7637       CR = CR.subtract(APInt(64, 1));
7638 
7639     unsigned EltWidth = I.getType()->getScalarSizeInBits();
7640     EltWidth = std::min(EltWidth, (unsigned)CR.getActiveBits());
7641     EltWidth = std::max(llvm::bit_ceil(EltWidth), (unsigned)8);
7642 
7643     MVT NewEltTy = MVT::getIntegerVT(EltWidth);
7644 
7645     // Create the new vector type & get the vector length
7646     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), NewEltTy,
7647                                  OpVT.getVectorElementCount());
7648 
7649     SDValue VL =
7650         DAG.getElementCount(DL, NewEltTy, OpVT.getVectorElementCount());
7651 
7652     SDValue StepVec = DAG.getStepVector(DL, NewVT);
7653     SDValue SplatVL = DAG.getSplat(NewVT, DL, VL);
7654     SDValue StepVL = DAG.getNode(ISD::SUB, DL, NewVT, SplatVL, StepVec);
7655     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, Op);
7656     SDValue And = DAG.getNode(ISD::AND, DL, NewVT, StepVL, Ext);
7657     SDValue Max = DAG.getNode(ISD::VECREDUCE_UMAX, DL, NewEltTy, And);
7658     SDValue Sub = DAG.getNode(ISD::SUB, DL, NewEltTy, VL, Max);
7659 
7660     EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7661     SDValue Ret = DAG.getZExtOrTrunc(Sub, DL, RetTy);
7662 
7663     setValue(&I, Ret);
7664     return;
7665   }
7666   case Intrinsic::vector_insert: {
7667     SDValue Vec = getValue(I.getOperand(0));
7668     SDValue SubVec = getValue(I.getOperand(1));
7669     SDValue Index = getValue(I.getOperand(2));
7670 
7671     // The intrinsic's index type is i64, but the SDNode requires an index type
7672     // suitable for the target. Convert the index as required.
7673     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7674     if (Index.getValueType() != VectorIdxTy)
7675       Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
7676 
7677     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7678     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
7679                              Index));
7680     return;
7681   }
7682   case Intrinsic::vector_extract: {
7683     SDValue Vec = getValue(I.getOperand(0));
7684     SDValue Index = getValue(I.getOperand(1));
7685     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7686 
7687     // The intrinsic's index type is i64, but the SDNode requires an index type
7688     // suitable for the target. Convert the index as required.
7689     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7690     if (Index.getValueType() != VectorIdxTy)
7691       Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
7692 
7693     setValue(&I,
7694              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
7695     return;
7696   }
7697   case Intrinsic::experimental_vector_reverse:
7698     visitVectorReverse(I);
7699     return;
7700   case Intrinsic::experimental_vector_splice:
7701     visitVectorSplice(I);
7702     return;
7703   case Intrinsic::callbr_landingpad:
7704     visitCallBrLandingPad(I);
7705     return;
7706   case Intrinsic::experimental_vector_interleave2:
7707     visitVectorInterleave(I);
7708     return;
7709   case Intrinsic::experimental_vector_deinterleave2:
7710     visitVectorDeinterleave(I);
7711     return;
7712   }
7713 }
7714 
7715 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7716     const ConstrainedFPIntrinsic &FPI) {
7717   SDLoc sdl = getCurSDLoc();
7718 
7719   // We do not need to serialize constrained FP intrinsics against
7720   // each other or against (nonvolatile) loads, so they can be
7721   // chained like loads.
7722   SDValue Chain = DAG.getRoot();
7723   SmallVector<SDValue, 4> Opers;
7724   Opers.push_back(Chain);
7725   if (FPI.isUnaryOp()) {
7726     Opers.push_back(getValue(FPI.getArgOperand(0)));
7727   } else if (FPI.isTernaryOp()) {
7728     Opers.push_back(getValue(FPI.getArgOperand(0)));
7729     Opers.push_back(getValue(FPI.getArgOperand(1)));
7730     Opers.push_back(getValue(FPI.getArgOperand(2)));
7731   } else {
7732     Opers.push_back(getValue(FPI.getArgOperand(0)));
7733     Opers.push_back(getValue(FPI.getArgOperand(1)));
7734   }
7735 
7736   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
7737     assert(Result.getNode()->getNumValues() == 2);
7738 
7739     // Push node to the appropriate list so that future instructions can be
7740     // chained up correctly.
7741     SDValue OutChain = Result.getValue(1);
7742     switch (EB) {
7743     case fp::ExceptionBehavior::ebIgnore:
7744       // The only reason why ebIgnore nodes still need to be chained is that
7745       // they might depend on the current rounding mode, and therefore must
7746       // not be moved across instruction that may change that mode.
7747       [[fallthrough]];
7748     case fp::ExceptionBehavior::ebMayTrap:
7749       // These must not be moved across calls or instructions that may change
7750       // floating-point exception masks.
7751       PendingConstrainedFP.push_back(OutChain);
7752       break;
7753     case fp::ExceptionBehavior::ebStrict:
7754       // These must not be moved across calls or instructions that may change
7755       // floating-point exception masks or read floating-point exception flags.
7756       // In addition, they cannot be optimized out even if unused.
7757       PendingConstrainedFPStrict.push_back(OutChain);
7758       break;
7759     }
7760   };
7761 
7762   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7763   EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
7764   SDVTList VTs = DAG.getVTList(VT, MVT::Other);
7765   fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
7766 
7767   SDNodeFlags Flags;
7768   if (EB == fp::ExceptionBehavior::ebIgnore)
7769     Flags.setNoFPExcept(true);
7770 
7771   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
7772     Flags.copyFMF(*FPOp);
7773 
7774   unsigned Opcode;
7775   switch (FPI.getIntrinsicID()) {
7776   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7777 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7778   case Intrinsic::INTRINSIC:                                                   \
7779     Opcode = ISD::STRICT_##DAGN;                                               \
7780     break;
7781 #include "llvm/IR/ConstrainedOps.def"
7782   case Intrinsic::experimental_constrained_fmuladd: {
7783     Opcode = ISD::STRICT_FMA;
7784     // Break fmuladd into fmul and fadd.
7785     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7786         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
7787       Opers.pop_back();
7788       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
7789       pushOutChain(Mul, EB);
7790       Opcode = ISD::STRICT_FADD;
7791       Opers.clear();
7792       Opers.push_back(Mul.getValue(1));
7793       Opers.push_back(Mul.getValue(0));
7794       Opers.push_back(getValue(FPI.getArgOperand(2)));
7795     }
7796     break;
7797   }
7798   }
7799 
7800   // A few strict DAG nodes carry additional operands that are not
7801   // set up by the default code above.
7802   switch (Opcode) {
7803   default: break;
7804   case ISD::STRICT_FP_ROUND:
7805     Opers.push_back(
7806         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7807     break;
7808   case ISD::STRICT_FSETCC:
7809   case ISD::STRICT_FSETCCS: {
7810     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7811     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
7812     if (TM.Options.NoNaNsFPMath)
7813       Condition = getFCmpCodeWithoutNaN(Condition);
7814     Opers.push_back(DAG.getCondCode(Condition));
7815     break;
7816   }
7817   }
7818 
7819   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7820   pushOutChain(Result, EB);
7821 
7822   SDValue FPResult = Result.getValue(0);
7823   setValue(&FPI, FPResult);
7824 }
7825 
7826 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
7827   std::optional<unsigned> ResOPC;
7828   switch (VPIntrin.getIntrinsicID()) {
7829   case Intrinsic::vp_ctlz: {
7830     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
7831     ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ;
7832     break;
7833   }
7834   case Intrinsic::vp_cttz: {
7835     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
7836     ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ;
7837     break;
7838   }
7839 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD)                                    \
7840   case Intrinsic::VPID:                                                        \
7841     ResOPC = ISD::VPSD;                                                        \
7842     break;
7843 #include "llvm/IR/VPIntrinsics.def"
7844   }
7845 
7846   if (!ResOPC)
7847     llvm_unreachable(
7848         "Inconsistency: no SDNode available for this VPIntrinsic!");
7849 
7850   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
7851       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
7852     if (VPIntrin.getFastMathFlags().allowReassoc())
7853       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
7854                                                 : ISD::VP_REDUCE_FMUL;
7855   }
7856 
7857   return *ResOPC;
7858 }
7859 
7860 void SelectionDAGBuilder::visitVPLoad(
7861     const VPIntrinsic &VPIntrin, EVT VT,
7862     const SmallVectorImpl<SDValue> &OpValues) {
7863   SDLoc DL = getCurSDLoc();
7864   Value *PtrOperand = VPIntrin.getArgOperand(0);
7865   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7866   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7867   const MDNode *Ranges = getRangeMetadata(VPIntrin);
7868   SDValue LD;
7869   // Do not serialize variable-length loads of constant memory with
7870   // anything.
7871   if (!Alignment)
7872     Alignment = DAG.getEVTAlign(VT);
7873   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7874   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7875   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7876   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7877       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7878       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7879   LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
7880                      MMO, false /*IsExpanding */);
7881   if (AddToChain)
7882     PendingLoads.push_back(LD.getValue(1));
7883   setValue(&VPIntrin, LD);
7884 }
7885 
7886 void SelectionDAGBuilder::visitVPGather(
7887     const VPIntrinsic &VPIntrin, EVT VT,
7888     const SmallVectorImpl<SDValue> &OpValues) {
7889   SDLoc DL = getCurSDLoc();
7890   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7891   Value *PtrOperand = VPIntrin.getArgOperand(0);
7892   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7893   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7894   const MDNode *Ranges = getRangeMetadata(VPIntrin);
7895   SDValue LD;
7896   if (!Alignment)
7897     Alignment = DAG.getEVTAlign(VT.getScalarType());
7898   unsigned AS =
7899     PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7900   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7901      MachinePointerInfo(AS), MachineMemOperand::MOLoad,
7902      MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7903   SDValue Base, Index, Scale;
7904   ISD::MemIndexType IndexType;
7905   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7906                                     this, VPIntrin.getParent(),
7907                                     VT.getScalarStoreSize());
7908   if (!UniformBase) {
7909     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7910     Index = getValue(PtrOperand);
7911     IndexType = ISD::SIGNED_SCALED;
7912     Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7913   }
7914   EVT IdxVT = Index.getValueType();
7915   EVT EltTy = IdxVT.getVectorElementType();
7916   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7917     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7918     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7919   }
7920   LD = DAG.getGatherVP(
7921       DAG.getVTList(VT, MVT::Other), VT, DL,
7922       {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
7923       IndexType);
7924   PendingLoads.push_back(LD.getValue(1));
7925   setValue(&VPIntrin, LD);
7926 }
7927 
7928 void SelectionDAGBuilder::visitVPStore(
7929     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
7930   SDLoc DL = getCurSDLoc();
7931   Value *PtrOperand = VPIntrin.getArgOperand(1);
7932   EVT VT = OpValues[0].getValueType();
7933   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7934   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7935   SDValue ST;
7936   if (!Alignment)
7937     Alignment = DAG.getEVTAlign(VT);
7938   SDValue Ptr = OpValues[1];
7939   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
7940   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7941       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7942       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7943   ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
7944                       OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
7945                       /* IsTruncating */ false, /*IsCompressing*/ false);
7946   DAG.setRoot(ST);
7947   setValue(&VPIntrin, ST);
7948 }
7949 
7950 void SelectionDAGBuilder::visitVPScatter(
7951     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
7952   SDLoc DL = getCurSDLoc();
7953   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7954   Value *PtrOperand = VPIntrin.getArgOperand(1);
7955   EVT VT = OpValues[0].getValueType();
7956   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7957   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7958   SDValue ST;
7959   if (!Alignment)
7960     Alignment = DAG.getEVTAlign(VT.getScalarType());
7961   unsigned AS =
7962       PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7963   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7964       MachinePointerInfo(AS), MachineMemOperand::MOStore,
7965       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7966   SDValue Base, Index, Scale;
7967   ISD::MemIndexType IndexType;
7968   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7969                                     this, VPIntrin.getParent(),
7970                                     VT.getScalarStoreSize());
7971   if (!UniformBase) {
7972     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7973     Index = getValue(PtrOperand);
7974     IndexType = ISD::SIGNED_SCALED;
7975     Scale =
7976       DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7977   }
7978   EVT IdxVT = Index.getValueType();
7979   EVT EltTy = IdxVT.getVectorElementType();
7980   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7981     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7982     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7983   }
7984   ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
7985                         {getMemoryRoot(), OpValues[0], Base, Index, Scale,
7986                          OpValues[2], OpValues[3]},
7987                         MMO, IndexType);
7988   DAG.setRoot(ST);
7989   setValue(&VPIntrin, ST);
7990 }
7991 
7992 void SelectionDAGBuilder::visitVPStridedLoad(
7993     const VPIntrinsic &VPIntrin, EVT VT,
7994     const SmallVectorImpl<SDValue> &OpValues) {
7995   SDLoc DL = getCurSDLoc();
7996   Value *PtrOperand = VPIntrin.getArgOperand(0);
7997   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7998   if (!Alignment)
7999     Alignment = DAG.getEVTAlign(VT.getScalarType());
8000   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8001   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8002   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
8003   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
8004   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8005   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8006       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
8007       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
8008 
8009   SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
8010                                     OpValues[2], OpValues[3], MMO,
8011                                     false /*IsExpanding*/);
8012 
8013   if (AddToChain)
8014     PendingLoads.push_back(LD.getValue(1));
8015   setValue(&VPIntrin, LD);
8016 }
8017 
8018 void SelectionDAGBuilder::visitVPStridedStore(
8019     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8020   SDLoc DL = getCurSDLoc();
8021   Value *PtrOperand = VPIntrin.getArgOperand(1);
8022   EVT VT = OpValues[0].getValueType();
8023   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8024   if (!Alignment)
8025     Alignment = DAG.getEVTAlign(VT.getScalarType());
8026   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8027   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8028       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
8029       MemoryLocation::UnknownSize, *Alignment, AAInfo);
8030 
8031   SDValue ST = DAG.getStridedStoreVP(
8032       getMemoryRoot(), DL, OpValues[0], OpValues[1],
8033       DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3],
8034       OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
8035       /*IsCompressing*/ false);
8036 
8037   DAG.setRoot(ST);
8038   setValue(&VPIntrin, ST);
8039 }
8040 
8041 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) {
8042   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8043   SDLoc DL = getCurSDLoc();
8044 
8045   ISD::CondCode Condition;
8046   CmpInst::Predicate CondCode = VPIntrin.getPredicate();
8047   bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy();
8048   if (IsFP) {
8049     // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan)
8050     // flags, but calls that don't return floating-point types can't be
8051     // FPMathOperators, like vp.fcmp. This affects constrained fcmp too.
8052     Condition = getFCmpCondCode(CondCode);
8053     if (TM.Options.NoNaNsFPMath)
8054       Condition = getFCmpCodeWithoutNaN(Condition);
8055   } else {
8056     Condition = getICmpCondCode(CondCode);
8057   }
8058 
8059   SDValue Op1 = getValue(VPIntrin.getOperand(0));
8060   SDValue Op2 = getValue(VPIntrin.getOperand(1));
8061   // #2 is the condition code
8062   SDValue MaskOp = getValue(VPIntrin.getOperand(3));
8063   SDValue EVL = getValue(VPIntrin.getOperand(4));
8064   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8065   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8066          "Unexpected target EVL type");
8067   EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL);
8068 
8069   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8070                                                         VPIntrin.getType());
8071   setValue(&VPIntrin,
8072            DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL));
8073 }
8074 
8075 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
8076     const VPIntrinsic &VPIntrin) {
8077   SDLoc DL = getCurSDLoc();
8078   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
8079 
8080   auto IID = VPIntrin.getIntrinsicID();
8081 
8082   if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin))
8083     return visitVPCmp(*CmpI);
8084 
8085   SmallVector<EVT, 4> ValueVTs;
8086   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8087   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
8088   SDVTList VTs = DAG.getVTList(ValueVTs);
8089 
8090   auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
8091 
8092   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8093   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8094          "Unexpected target EVL type");
8095 
8096   // Request operands.
8097   SmallVector<SDValue, 7> OpValues;
8098   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
8099     auto Op = getValue(VPIntrin.getArgOperand(I));
8100     if (I == EVLParamPos)
8101       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
8102     OpValues.push_back(Op);
8103   }
8104 
8105   switch (Opcode) {
8106   default: {
8107     SDNodeFlags SDFlags;
8108     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8109       SDFlags.copyFMF(*FPMO);
8110     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
8111     setValue(&VPIntrin, Result);
8112     break;
8113   }
8114   case ISD::VP_LOAD:
8115     visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
8116     break;
8117   case ISD::VP_GATHER:
8118     visitVPGather(VPIntrin, ValueVTs[0], OpValues);
8119     break;
8120   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
8121     visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
8122     break;
8123   case ISD::VP_STORE:
8124     visitVPStore(VPIntrin, OpValues);
8125     break;
8126   case ISD::VP_SCATTER:
8127     visitVPScatter(VPIntrin, OpValues);
8128     break;
8129   case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
8130     visitVPStridedStore(VPIntrin, OpValues);
8131     break;
8132   case ISD::VP_FMULADD: {
8133     assert(OpValues.size() == 5 && "Unexpected number of operands");
8134     SDNodeFlags SDFlags;
8135     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8136       SDFlags.copyFMF(*FPMO);
8137     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
8138         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) {
8139       setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags));
8140     } else {
8141       SDValue Mul = DAG.getNode(
8142           ISD::VP_FMUL, DL, VTs,
8143           {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags);
8144       SDValue Add =
8145           DAG.getNode(ISD::VP_FADD, DL, VTs,
8146                       {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags);
8147       setValue(&VPIntrin, Add);
8148     }
8149     break;
8150   }
8151   case ISD::VP_IS_FPCLASS: {
8152     const DataLayout DLayout = DAG.getDataLayout();
8153     EVT DestVT = TLI.getValueType(DLayout, VPIntrin.getType());
8154     auto Constant = OpValues[1]->getAsZExtVal();
8155     SDValue Check = DAG.getTargetConstant(Constant, DL, MVT::i32);
8156     SDValue V = DAG.getNode(ISD::VP_IS_FPCLASS, DL, DestVT,
8157                             {OpValues[0], Check, OpValues[2], OpValues[3]});
8158     setValue(&VPIntrin, V);
8159     return;
8160   }
8161   case ISD::VP_INTTOPTR: {
8162     SDValue N = OpValues[0];
8163     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType());
8164     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType());
8165     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8166                                OpValues[2]);
8167     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8168                              OpValues[2]);
8169     setValue(&VPIntrin, N);
8170     break;
8171   }
8172   case ISD::VP_PTRTOINT: {
8173     SDValue N = OpValues[0];
8174     EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8175                                                           VPIntrin.getType());
8176     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(),
8177                                        VPIntrin.getOperand(0)->getType());
8178     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8179                                OpValues[2]);
8180     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8181                              OpValues[2]);
8182     setValue(&VPIntrin, N);
8183     break;
8184   }
8185   case ISD::VP_ABS:
8186   case ISD::VP_CTLZ:
8187   case ISD::VP_CTLZ_ZERO_UNDEF:
8188   case ISD::VP_CTTZ:
8189   case ISD::VP_CTTZ_ZERO_UNDEF: {
8190     SDValue Result =
8191         DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]});
8192     setValue(&VPIntrin, Result);
8193     break;
8194   }
8195   }
8196 }
8197 
8198 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
8199                                           const BasicBlock *EHPadBB,
8200                                           MCSymbol *&BeginLabel) {
8201   MachineFunction &MF = DAG.getMachineFunction();
8202   MachineModuleInfo &MMI = MF.getMMI();
8203 
8204   // Insert a label before the invoke call to mark the try range.  This can be
8205   // used to detect deletion of the invoke via the MachineModuleInfo.
8206   BeginLabel = MMI.getContext().createTempSymbol();
8207 
8208   // For SjLj, keep track of which landing pads go with which invokes
8209   // so as to maintain the ordering of pads in the LSDA.
8210   unsigned CallSiteIndex = MMI.getCurrentCallSite();
8211   if (CallSiteIndex) {
8212     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
8213     LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
8214 
8215     // Now that the call site is handled, stop tracking it.
8216     MMI.setCurrentCallSite(0);
8217   }
8218 
8219   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
8220 }
8221 
8222 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
8223                                         const BasicBlock *EHPadBB,
8224                                         MCSymbol *BeginLabel) {
8225   assert(BeginLabel && "BeginLabel should've been set");
8226 
8227   MachineFunction &MF = DAG.getMachineFunction();
8228   MachineModuleInfo &MMI = MF.getMMI();
8229 
8230   // Insert a label at the end of the invoke call to mark the try range.  This
8231   // can be used to detect deletion of the invoke via the MachineModuleInfo.
8232   MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
8233   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
8234 
8235   // Inform MachineModuleInfo of range.
8236   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
8237   // There is a platform (e.g. wasm) that uses funclet style IR but does not
8238   // actually use outlined funclets and their LSDA info style.
8239   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
8240     assert(II && "II should've been set");
8241     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
8242     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
8243   } else if (!isScopedEHPersonality(Pers)) {
8244     assert(EHPadBB);
8245     MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
8246   }
8247 
8248   return Chain;
8249 }
8250 
8251 std::pair<SDValue, SDValue>
8252 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
8253                                     const BasicBlock *EHPadBB) {
8254   MCSymbol *BeginLabel = nullptr;
8255 
8256   if (EHPadBB) {
8257     // Both PendingLoads and PendingExports must be flushed here;
8258     // this call might not return.
8259     (void)getRoot();
8260     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
8261     CLI.setChain(getRoot());
8262   }
8263 
8264   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8265   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
8266 
8267   assert((CLI.IsTailCall || Result.second.getNode()) &&
8268          "Non-null chain expected with non-tail call!");
8269   assert((Result.second.getNode() || !Result.first.getNode()) &&
8270          "Null value expected with tail call!");
8271 
8272   if (!Result.second.getNode()) {
8273     // As a special case, a null chain means that a tail call has been emitted
8274     // and the DAG root is already updated.
8275     HasTailCall = true;
8276 
8277     // Since there's no actual continuation from this block, nothing can be
8278     // relying on us setting vregs for them.
8279     PendingExports.clear();
8280   } else {
8281     DAG.setRoot(Result.second);
8282   }
8283 
8284   if (EHPadBB) {
8285     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
8286                            BeginLabel));
8287   }
8288 
8289   return Result;
8290 }
8291 
8292 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
8293                                       bool isTailCall,
8294                                       bool isMustTailCall,
8295                                       const BasicBlock *EHPadBB) {
8296   auto &DL = DAG.getDataLayout();
8297   FunctionType *FTy = CB.getFunctionType();
8298   Type *RetTy = CB.getType();
8299 
8300   TargetLowering::ArgListTy Args;
8301   Args.reserve(CB.arg_size());
8302 
8303   const Value *SwiftErrorVal = nullptr;
8304   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8305 
8306   if (isTailCall) {
8307     // Avoid emitting tail calls in functions with the disable-tail-calls
8308     // attribute.
8309     auto *Caller = CB.getParent()->getParent();
8310     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
8311         "true" && !isMustTailCall)
8312       isTailCall = false;
8313 
8314     // We can't tail call inside a function with a swifterror argument. Lowering
8315     // does not support this yet. It would have to move into the swifterror
8316     // register before the call.
8317     if (TLI.supportSwiftError() &&
8318         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
8319       isTailCall = false;
8320   }
8321 
8322   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
8323     TargetLowering::ArgListEntry Entry;
8324     const Value *V = *I;
8325 
8326     // Skip empty types
8327     if (V->getType()->isEmptyTy())
8328       continue;
8329 
8330     SDValue ArgNode = getValue(V);
8331     Entry.Node = ArgNode; Entry.Ty = V->getType();
8332 
8333     Entry.setAttributes(&CB, I - CB.arg_begin());
8334 
8335     // Use swifterror virtual register as input to the call.
8336     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
8337       SwiftErrorVal = V;
8338       // We find the virtual register for the actual swifterror argument.
8339       // Instead of using the Value, we use the virtual register instead.
8340       Entry.Node =
8341           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
8342                           EVT(TLI.getPointerTy(DL)));
8343     }
8344 
8345     Args.push_back(Entry);
8346 
8347     // If we have an explicit sret argument that is an Instruction, (i.e., it
8348     // might point to function-local memory), we can't meaningfully tail-call.
8349     if (Entry.IsSRet && isa<Instruction>(V))
8350       isTailCall = false;
8351   }
8352 
8353   // If call site has a cfguardtarget operand bundle, create and add an
8354   // additional ArgListEntry.
8355   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
8356     TargetLowering::ArgListEntry Entry;
8357     Value *V = Bundle->Inputs[0];
8358     SDValue ArgNode = getValue(V);
8359     Entry.Node = ArgNode;
8360     Entry.Ty = V->getType();
8361     Entry.IsCFGuardTarget = true;
8362     Args.push_back(Entry);
8363   }
8364 
8365   // Check if target-independent constraints permit a tail call here.
8366   // Target-dependent constraints are checked within TLI->LowerCallTo.
8367   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
8368     isTailCall = false;
8369 
8370   // Disable tail calls if there is an swifterror argument. Targets have not
8371   // been updated to support tail calls.
8372   if (TLI.supportSwiftError() && SwiftErrorVal)
8373     isTailCall = false;
8374 
8375   ConstantInt *CFIType = nullptr;
8376   if (CB.isIndirectCall()) {
8377     if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
8378       if (!TLI.supportKCFIBundles())
8379         report_fatal_error(
8380             "Target doesn't support calls with kcfi operand bundles.");
8381       CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
8382       assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
8383     }
8384   }
8385 
8386   TargetLowering::CallLoweringInfo CLI(DAG);
8387   CLI.setDebugLoc(getCurSDLoc())
8388       .setChain(getRoot())
8389       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
8390       .setTailCall(isTailCall)
8391       .setConvergent(CB.isConvergent())
8392       .setIsPreallocated(
8393           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
8394       .setCFIType(CFIType);
8395   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8396 
8397   if (Result.first.getNode()) {
8398     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
8399     setValue(&CB, Result.first);
8400   }
8401 
8402   // The last element of CLI.InVals has the SDValue for swifterror return.
8403   // Here we copy it to a virtual register and update SwiftErrorMap for
8404   // book-keeping.
8405   if (SwiftErrorVal && TLI.supportSwiftError()) {
8406     // Get the last element of InVals.
8407     SDValue Src = CLI.InVals.back();
8408     Register VReg =
8409         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
8410     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
8411     DAG.setRoot(CopyNode);
8412   }
8413 }
8414 
8415 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
8416                              SelectionDAGBuilder &Builder) {
8417   // Check to see if this load can be trivially constant folded, e.g. if the
8418   // input is from a string literal.
8419   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
8420     // Cast pointer to the type we really want to load.
8421     Type *LoadTy =
8422         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
8423     if (LoadVT.isVector())
8424       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
8425 
8426     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
8427                                          PointerType::getUnqual(LoadTy));
8428 
8429     if (const Constant *LoadCst =
8430             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
8431                                          LoadTy, Builder.DAG.getDataLayout()))
8432       return Builder.getValue(LoadCst);
8433   }
8434 
8435   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
8436   // still constant memory, the input chain can be the entry node.
8437   SDValue Root;
8438   bool ConstantMemory = false;
8439 
8440   // Do not serialize (non-volatile) loads of constant memory with anything.
8441   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
8442     Root = Builder.DAG.getEntryNode();
8443     ConstantMemory = true;
8444   } else {
8445     // Do not serialize non-volatile loads against each other.
8446     Root = Builder.DAG.getRoot();
8447   }
8448 
8449   SDValue Ptr = Builder.getValue(PtrVal);
8450   SDValue LoadVal =
8451       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
8452                           MachinePointerInfo(PtrVal), Align(1));
8453 
8454   if (!ConstantMemory)
8455     Builder.PendingLoads.push_back(LoadVal.getValue(1));
8456   return LoadVal;
8457 }
8458 
8459 /// Record the value for an instruction that produces an integer result,
8460 /// converting the type where necessary.
8461 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
8462                                                   SDValue Value,
8463                                                   bool IsSigned) {
8464   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8465                                                     I.getType(), true);
8466   Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT);
8467   setValue(&I, Value);
8468 }
8469 
8470 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
8471 /// true and lower it. Otherwise return false, and it will be lowered like a
8472 /// normal call.
8473 /// The caller already checked that \p I calls the appropriate LibFunc with a
8474 /// correct prototype.
8475 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
8476   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
8477   const Value *Size = I.getArgOperand(2);
8478   const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
8479   if (CSize && CSize->getZExtValue() == 0) {
8480     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8481                                                           I.getType(), true);
8482     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
8483     return true;
8484   }
8485 
8486   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8487   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
8488       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
8489       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
8490   if (Res.first.getNode()) {
8491     processIntegerCallValue(I, Res.first, true);
8492     PendingLoads.push_back(Res.second);
8493     return true;
8494   }
8495 
8496   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
8497   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
8498   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
8499     return false;
8500 
8501   // If the target has a fast compare for the given size, it will return a
8502   // preferred load type for that size. Require that the load VT is legal and
8503   // that the target supports unaligned loads of that type. Otherwise, return
8504   // INVALID.
8505   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
8506     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8507     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
8508     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
8509       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
8510       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
8511       // TODO: Check alignment of src and dest ptrs.
8512       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
8513       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
8514       if (!TLI.isTypeLegal(LVT) ||
8515           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
8516           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
8517         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
8518     }
8519 
8520     return LVT;
8521   };
8522 
8523   // This turns into unaligned loads. We only do this if the target natively
8524   // supports the MVT we'll be loading or if it is small enough (<= 4) that
8525   // we'll only produce a small number of byte loads.
8526   MVT LoadVT;
8527   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
8528   switch (NumBitsToCompare) {
8529   default:
8530     return false;
8531   case 16:
8532     LoadVT = MVT::i16;
8533     break;
8534   case 32:
8535     LoadVT = MVT::i32;
8536     break;
8537   case 64:
8538   case 128:
8539   case 256:
8540     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
8541     break;
8542   }
8543 
8544   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
8545     return false;
8546 
8547   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
8548   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
8549 
8550   // Bitcast to a wide integer type if the loads are vectors.
8551   if (LoadVT.isVector()) {
8552     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
8553     LoadL = DAG.getBitcast(CmpVT, LoadL);
8554     LoadR = DAG.getBitcast(CmpVT, LoadR);
8555   }
8556 
8557   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
8558   processIntegerCallValue(I, Cmp, false);
8559   return true;
8560 }
8561 
8562 /// See if we can lower a memchr call into an optimized form. If so, return
8563 /// true and lower it. Otherwise return false, and it will be lowered like a
8564 /// normal call.
8565 /// The caller already checked that \p I calls the appropriate LibFunc with a
8566 /// correct prototype.
8567 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
8568   const Value *Src = I.getArgOperand(0);
8569   const Value *Char = I.getArgOperand(1);
8570   const Value *Length = I.getArgOperand(2);
8571 
8572   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8573   std::pair<SDValue, SDValue> Res =
8574     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
8575                                 getValue(Src), getValue(Char), getValue(Length),
8576                                 MachinePointerInfo(Src));
8577   if (Res.first.getNode()) {
8578     setValue(&I, Res.first);
8579     PendingLoads.push_back(Res.second);
8580     return true;
8581   }
8582 
8583   return false;
8584 }
8585 
8586 /// See if we can lower a mempcpy call into an optimized form. If so, return
8587 /// true and lower it. Otherwise return false, and it will be lowered like a
8588 /// normal call.
8589 /// The caller already checked that \p I calls the appropriate LibFunc with a
8590 /// correct prototype.
8591 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
8592   SDValue Dst = getValue(I.getArgOperand(0));
8593   SDValue Src = getValue(I.getArgOperand(1));
8594   SDValue Size = getValue(I.getArgOperand(2));
8595 
8596   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
8597   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
8598   // DAG::getMemcpy needs Alignment to be defined.
8599   Align Alignment = std::min(DstAlign, SrcAlign);
8600 
8601   SDLoc sdl = getCurSDLoc();
8602 
8603   // In the mempcpy context we need to pass in a false value for isTailCall
8604   // because the return pointer needs to be adjusted by the size of
8605   // the copied memory.
8606   SDValue Root = getMemoryRoot();
8607   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, false, false,
8608                              /*isTailCall=*/false,
8609                              MachinePointerInfo(I.getArgOperand(0)),
8610                              MachinePointerInfo(I.getArgOperand(1)),
8611                              I.getAAMetadata());
8612   assert(MC.getNode() != nullptr &&
8613          "** memcpy should not be lowered as TailCall in mempcpy context **");
8614   DAG.setRoot(MC);
8615 
8616   // Check if Size needs to be truncated or extended.
8617   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
8618 
8619   // Adjust return pointer to point just past the last dst byte.
8620   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
8621                                     Dst, Size);
8622   setValue(&I, DstPlusSize);
8623   return true;
8624 }
8625 
8626 /// See if we can lower a strcpy call into an optimized form.  If so, return
8627 /// true and lower it, otherwise return false and it will be lowered like a
8628 /// normal call.
8629 /// The caller already checked that \p I calls the appropriate LibFunc with a
8630 /// correct prototype.
8631 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
8632   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8633 
8634   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8635   std::pair<SDValue, SDValue> Res =
8636     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
8637                                 getValue(Arg0), getValue(Arg1),
8638                                 MachinePointerInfo(Arg0),
8639                                 MachinePointerInfo(Arg1), isStpcpy);
8640   if (Res.first.getNode()) {
8641     setValue(&I, Res.first);
8642     DAG.setRoot(Res.second);
8643     return true;
8644   }
8645 
8646   return false;
8647 }
8648 
8649 /// See if we can lower a strcmp call into an optimized form.  If so, return
8650 /// true and lower it, otherwise return false and it will be lowered like a
8651 /// normal call.
8652 /// The caller already checked that \p I calls the appropriate LibFunc with a
8653 /// correct prototype.
8654 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
8655   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8656 
8657   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8658   std::pair<SDValue, SDValue> Res =
8659     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
8660                                 getValue(Arg0), getValue(Arg1),
8661                                 MachinePointerInfo(Arg0),
8662                                 MachinePointerInfo(Arg1));
8663   if (Res.first.getNode()) {
8664     processIntegerCallValue(I, Res.first, true);
8665     PendingLoads.push_back(Res.second);
8666     return true;
8667   }
8668 
8669   return false;
8670 }
8671 
8672 /// See if we can lower a strlen call into an optimized form.  If so, return
8673 /// true and lower it, otherwise return false and it will be lowered like a
8674 /// normal call.
8675 /// The caller already checked that \p I calls the appropriate LibFunc with a
8676 /// correct prototype.
8677 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
8678   const Value *Arg0 = I.getArgOperand(0);
8679 
8680   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8681   std::pair<SDValue, SDValue> Res =
8682     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
8683                                 getValue(Arg0), MachinePointerInfo(Arg0));
8684   if (Res.first.getNode()) {
8685     processIntegerCallValue(I, Res.first, false);
8686     PendingLoads.push_back(Res.second);
8687     return true;
8688   }
8689 
8690   return false;
8691 }
8692 
8693 /// See if we can lower a strnlen call into an optimized form.  If so, return
8694 /// true and lower it, otherwise return false and it will be lowered like a
8695 /// normal call.
8696 /// The caller already checked that \p I calls the appropriate LibFunc with a
8697 /// correct prototype.
8698 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
8699   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8700 
8701   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8702   std::pair<SDValue, SDValue> Res =
8703     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
8704                                  getValue(Arg0), getValue(Arg1),
8705                                  MachinePointerInfo(Arg0));
8706   if (Res.first.getNode()) {
8707     processIntegerCallValue(I, Res.first, false);
8708     PendingLoads.push_back(Res.second);
8709     return true;
8710   }
8711 
8712   return false;
8713 }
8714 
8715 /// See if we can lower a unary floating-point operation into an SDNode with
8716 /// the specified Opcode.  If so, return true and lower it, otherwise return
8717 /// false and it will be lowered like a normal call.
8718 /// The caller already checked that \p I calls the appropriate LibFunc with a
8719 /// correct prototype.
8720 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
8721                                               unsigned Opcode) {
8722   // We already checked this call's prototype; verify it doesn't modify errno.
8723   if (!I.onlyReadsMemory())
8724     return false;
8725 
8726   SDNodeFlags Flags;
8727   Flags.copyFMF(cast<FPMathOperator>(I));
8728 
8729   SDValue Tmp = getValue(I.getArgOperand(0));
8730   setValue(&I,
8731            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
8732   return true;
8733 }
8734 
8735 /// See if we can lower a binary floating-point operation into an SDNode with
8736 /// the specified Opcode. If so, return true and lower it. Otherwise return
8737 /// false, and it will be lowered like a normal call.
8738 /// The caller already checked that \p I calls the appropriate LibFunc with a
8739 /// correct prototype.
8740 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
8741                                                unsigned Opcode) {
8742   // We already checked this call's prototype; verify it doesn't modify errno.
8743   if (!I.onlyReadsMemory())
8744     return false;
8745 
8746   SDNodeFlags Flags;
8747   Flags.copyFMF(cast<FPMathOperator>(I));
8748 
8749   SDValue Tmp0 = getValue(I.getArgOperand(0));
8750   SDValue Tmp1 = getValue(I.getArgOperand(1));
8751   EVT VT = Tmp0.getValueType();
8752   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
8753   return true;
8754 }
8755 
8756 void SelectionDAGBuilder::visitCall(const CallInst &I) {
8757   // Handle inline assembly differently.
8758   if (I.isInlineAsm()) {
8759     visitInlineAsm(I);
8760     return;
8761   }
8762 
8763   diagnoseDontCall(I);
8764 
8765   if (Function *F = I.getCalledFunction()) {
8766     if (F->isDeclaration()) {
8767       // Is this an LLVM intrinsic or a target-specific intrinsic?
8768       unsigned IID = F->getIntrinsicID();
8769       if (!IID)
8770         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
8771           IID = II->getIntrinsicID(F);
8772 
8773       if (IID) {
8774         visitIntrinsicCall(I, IID);
8775         return;
8776       }
8777     }
8778 
8779     // Check for well-known libc/libm calls.  If the function is internal, it
8780     // can't be a library call.  Don't do the check if marked as nobuiltin for
8781     // some reason or the call site requires strict floating point semantics.
8782     LibFunc Func;
8783     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
8784         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
8785         LibInfo->hasOptimizedCodeGen(Func)) {
8786       switch (Func) {
8787       default: break;
8788       case LibFunc_bcmp:
8789         if (visitMemCmpBCmpCall(I))
8790           return;
8791         break;
8792       case LibFunc_copysign:
8793       case LibFunc_copysignf:
8794       case LibFunc_copysignl:
8795         // We already checked this call's prototype; verify it doesn't modify
8796         // errno.
8797         if (I.onlyReadsMemory()) {
8798           SDValue LHS = getValue(I.getArgOperand(0));
8799           SDValue RHS = getValue(I.getArgOperand(1));
8800           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
8801                                    LHS.getValueType(), LHS, RHS));
8802           return;
8803         }
8804         break;
8805       case LibFunc_fabs:
8806       case LibFunc_fabsf:
8807       case LibFunc_fabsl:
8808         if (visitUnaryFloatCall(I, ISD::FABS))
8809           return;
8810         break;
8811       case LibFunc_fmin:
8812       case LibFunc_fminf:
8813       case LibFunc_fminl:
8814         if (visitBinaryFloatCall(I, ISD::FMINNUM))
8815           return;
8816         break;
8817       case LibFunc_fmax:
8818       case LibFunc_fmaxf:
8819       case LibFunc_fmaxl:
8820         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
8821           return;
8822         break;
8823       case LibFunc_sin:
8824       case LibFunc_sinf:
8825       case LibFunc_sinl:
8826         if (visitUnaryFloatCall(I, ISD::FSIN))
8827           return;
8828         break;
8829       case LibFunc_cos:
8830       case LibFunc_cosf:
8831       case LibFunc_cosl:
8832         if (visitUnaryFloatCall(I, ISD::FCOS))
8833           return;
8834         break;
8835       case LibFunc_sqrt:
8836       case LibFunc_sqrtf:
8837       case LibFunc_sqrtl:
8838       case LibFunc_sqrt_finite:
8839       case LibFunc_sqrtf_finite:
8840       case LibFunc_sqrtl_finite:
8841         if (visitUnaryFloatCall(I, ISD::FSQRT))
8842           return;
8843         break;
8844       case LibFunc_floor:
8845       case LibFunc_floorf:
8846       case LibFunc_floorl:
8847         if (visitUnaryFloatCall(I, ISD::FFLOOR))
8848           return;
8849         break;
8850       case LibFunc_nearbyint:
8851       case LibFunc_nearbyintf:
8852       case LibFunc_nearbyintl:
8853         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
8854           return;
8855         break;
8856       case LibFunc_ceil:
8857       case LibFunc_ceilf:
8858       case LibFunc_ceill:
8859         if (visitUnaryFloatCall(I, ISD::FCEIL))
8860           return;
8861         break;
8862       case LibFunc_rint:
8863       case LibFunc_rintf:
8864       case LibFunc_rintl:
8865         if (visitUnaryFloatCall(I, ISD::FRINT))
8866           return;
8867         break;
8868       case LibFunc_round:
8869       case LibFunc_roundf:
8870       case LibFunc_roundl:
8871         if (visitUnaryFloatCall(I, ISD::FROUND))
8872           return;
8873         break;
8874       case LibFunc_trunc:
8875       case LibFunc_truncf:
8876       case LibFunc_truncl:
8877         if (visitUnaryFloatCall(I, ISD::FTRUNC))
8878           return;
8879         break;
8880       case LibFunc_log2:
8881       case LibFunc_log2f:
8882       case LibFunc_log2l:
8883         if (visitUnaryFloatCall(I, ISD::FLOG2))
8884           return;
8885         break;
8886       case LibFunc_exp2:
8887       case LibFunc_exp2f:
8888       case LibFunc_exp2l:
8889         if (visitUnaryFloatCall(I, ISD::FEXP2))
8890           return;
8891         break;
8892       case LibFunc_exp10:
8893       case LibFunc_exp10f:
8894       case LibFunc_exp10l:
8895         if (visitUnaryFloatCall(I, ISD::FEXP10))
8896           return;
8897         break;
8898       case LibFunc_ldexp:
8899       case LibFunc_ldexpf:
8900       case LibFunc_ldexpl:
8901         if (visitBinaryFloatCall(I, ISD::FLDEXP))
8902           return;
8903         break;
8904       case LibFunc_memcmp:
8905         if (visitMemCmpBCmpCall(I))
8906           return;
8907         break;
8908       case LibFunc_mempcpy:
8909         if (visitMemPCpyCall(I))
8910           return;
8911         break;
8912       case LibFunc_memchr:
8913         if (visitMemChrCall(I))
8914           return;
8915         break;
8916       case LibFunc_strcpy:
8917         if (visitStrCpyCall(I, false))
8918           return;
8919         break;
8920       case LibFunc_stpcpy:
8921         if (visitStrCpyCall(I, true))
8922           return;
8923         break;
8924       case LibFunc_strcmp:
8925         if (visitStrCmpCall(I))
8926           return;
8927         break;
8928       case LibFunc_strlen:
8929         if (visitStrLenCall(I))
8930           return;
8931         break;
8932       case LibFunc_strnlen:
8933         if (visitStrNLenCall(I))
8934           return;
8935         break;
8936       }
8937     }
8938   }
8939 
8940   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
8941   // have to do anything here to lower funclet bundles.
8942   // CFGuardTarget bundles are lowered in LowerCallTo.
8943   assert(!I.hasOperandBundlesOtherThan(
8944              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
8945               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
8946               LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) &&
8947          "Cannot lower calls with arbitrary operand bundles!");
8948 
8949   SDValue Callee = getValue(I.getCalledOperand());
8950 
8951   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
8952     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
8953   else
8954     // Check if we can potentially perform a tail call. More detailed checking
8955     // is be done within LowerCallTo, after more information about the call is
8956     // known.
8957     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
8958 }
8959 
8960 namespace {
8961 
8962 /// AsmOperandInfo - This contains information for each constraint that we are
8963 /// lowering.
8964 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
8965 public:
8966   /// CallOperand - If this is the result output operand or a clobber
8967   /// this is null, otherwise it is the incoming operand to the CallInst.
8968   /// This gets modified as the asm is processed.
8969   SDValue CallOperand;
8970 
8971   /// AssignedRegs - If this is a register or register class operand, this
8972   /// contains the set of register corresponding to the operand.
8973   RegsForValue AssignedRegs;
8974 
8975   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
8976     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
8977   }
8978 
8979   /// Whether or not this operand accesses memory
8980   bool hasMemory(const TargetLowering &TLI) const {
8981     // Indirect operand accesses access memory.
8982     if (isIndirect)
8983       return true;
8984 
8985     for (const auto &Code : Codes)
8986       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
8987         return true;
8988 
8989     return false;
8990   }
8991 };
8992 
8993 
8994 } // end anonymous namespace
8995 
8996 /// Make sure that the output operand \p OpInfo and its corresponding input
8997 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
8998 /// out).
8999 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
9000                                SDISelAsmOperandInfo &MatchingOpInfo,
9001                                SelectionDAG &DAG) {
9002   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
9003     return;
9004 
9005   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
9006   const auto &TLI = DAG.getTargetLoweringInfo();
9007 
9008   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
9009       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
9010                                        OpInfo.ConstraintVT);
9011   std::pair<unsigned, const TargetRegisterClass *> InputRC =
9012       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
9013                                        MatchingOpInfo.ConstraintVT);
9014   if ((OpInfo.ConstraintVT.isInteger() !=
9015        MatchingOpInfo.ConstraintVT.isInteger()) ||
9016       (MatchRC.second != InputRC.second)) {
9017     // FIXME: error out in a more elegant fashion
9018     report_fatal_error("Unsupported asm: input constraint"
9019                        " with a matching output constraint of"
9020                        " incompatible type!");
9021   }
9022   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
9023 }
9024 
9025 /// Get a direct memory input to behave well as an indirect operand.
9026 /// This may introduce stores, hence the need for a \p Chain.
9027 /// \return The (possibly updated) chain.
9028 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
9029                                         SDISelAsmOperandInfo &OpInfo,
9030                                         SelectionDAG &DAG) {
9031   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9032 
9033   // If we don't have an indirect input, put it in the constpool if we can,
9034   // otherwise spill it to a stack slot.
9035   // TODO: This isn't quite right. We need to handle these according to
9036   // the addressing mode that the constraint wants. Also, this may take
9037   // an additional register for the computation and we don't want that
9038   // either.
9039 
9040   // If the operand is a float, integer, or vector constant, spill to a
9041   // constant pool entry to get its address.
9042   const Value *OpVal = OpInfo.CallOperandVal;
9043   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
9044       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
9045     OpInfo.CallOperand = DAG.getConstantPool(
9046         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
9047     return Chain;
9048   }
9049 
9050   // Otherwise, create a stack slot and emit a store to it before the asm.
9051   Type *Ty = OpVal->getType();
9052   auto &DL = DAG.getDataLayout();
9053   uint64_t TySize = DL.getTypeAllocSize(Ty);
9054   MachineFunction &MF = DAG.getMachineFunction();
9055   int SSFI = MF.getFrameInfo().CreateStackObject(
9056       TySize, DL.getPrefTypeAlign(Ty), false);
9057   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
9058   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
9059                             MachinePointerInfo::getFixedStack(MF, SSFI),
9060                             TLI.getMemValueType(DL, Ty));
9061   OpInfo.CallOperand = StackSlot;
9062 
9063   return Chain;
9064 }
9065 
9066 /// GetRegistersForValue - Assign registers (virtual or physical) for the
9067 /// specified operand.  We prefer to assign virtual registers, to allow the
9068 /// register allocator to handle the assignment process.  However, if the asm
9069 /// uses features that we can't model on machineinstrs, we have SDISel do the
9070 /// allocation.  This produces generally horrible, but correct, code.
9071 ///
9072 ///   OpInfo describes the operand
9073 ///   RefOpInfo describes the matching operand if any, the operand otherwise
9074 static std::optional<unsigned>
9075 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
9076                      SDISelAsmOperandInfo &OpInfo,
9077                      SDISelAsmOperandInfo &RefOpInfo) {
9078   LLVMContext &Context = *DAG.getContext();
9079   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9080 
9081   MachineFunction &MF = DAG.getMachineFunction();
9082   SmallVector<unsigned, 4> Regs;
9083   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9084 
9085   // No work to do for memory/address operands.
9086   if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9087       OpInfo.ConstraintType == TargetLowering::C_Address)
9088     return std::nullopt;
9089 
9090   // If this is a constraint for a single physreg, or a constraint for a
9091   // register class, find it.
9092   unsigned AssignedReg;
9093   const TargetRegisterClass *RC;
9094   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
9095       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
9096   // RC is unset only on failure. Return immediately.
9097   if (!RC)
9098     return std::nullopt;
9099 
9100   // Get the actual register value type.  This is important, because the user
9101   // may have asked for (e.g.) the AX register in i32 type.  We need to
9102   // remember that AX is actually i16 to get the right extension.
9103   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
9104 
9105   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
9106     // If this is an FP operand in an integer register (or visa versa), or more
9107     // generally if the operand value disagrees with the register class we plan
9108     // to stick it in, fix the operand type.
9109     //
9110     // If this is an input value, the bitcast to the new type is done now.
9111     // Bitcast for output value is done at the end of visitInlineAsm().
9112     if ((OpInfo.Type == InlineAsm::isOutput ||
9113          OpInfo.Type == InlineAsm::isInput) &&
9114         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
9115       // Try to convert to the first EVT that the reg class contains.  If the
9116       // types are identical size, use a bitcast to convert (e.g. two differing
9117       // vector types).  Note: output bitcast is done at the end of
9118       // visitInlineAsm().
9119       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
9120         // Exclude indirect inputs while they are unsupported because the code
9121         // to perform the load is missing and thus OpInfo.CallOperand still
9122         // refers to the input address rather than the pointed-to value.
9123         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
9124           OpInfo.CallOperand =
9125               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
9126         OpInfo.ConstraintVT = RegVT;
9127         // If the operand is an FP value and we want it in integer registers,
9128         // use the corresponding integer type. This turns an f64 value into
9129         // i64, which can be passed with two i32 values on a 32-bit machine.
9130       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
9131         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
9132         if (OpInfo.Type == InlineAsm::isInput)
9133           OpInfo.CallOperand =
9134               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
9135         OpInfo.ConstraintVT = VT;
9136       }
9137     }
9138   }
9139 
9140   // No need to allocate a matching input constraint since the constraint it's
9141   // matching to has already been allocated.
9142   if (OpInfo.isMatchingInputConstraint())
9143     return std::nullopt;
9144 
9145   EVT ValueVT = OpInfo.ConstraintVT;
9146   if (OpInfo.ConstraintVT == MVT::Other)
9147     ValueVT = RegVT;
9148 
9149   // Initialize NumRegs.
9150   unsigned NumRegs = 1;
9151   if (OpInfo.ConstraintVT != MVT::Other)
9152     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
9153 
9154   // If this is a constraint for a specific physical register, like {r17},
9155   // assign it now.
9156 
9157   // If this associated to a specific register, initialize iterator to correct
9158   // place. If virtual, make sure we have enough registers
9159 
9160   // Initialize iterator if necessary
9161   TargetRegisterClass::iterator I = RC->begin();
9162   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9163 
9164   // Do not check for single registers.
9165   if (AssignedReg) {
9166     I = std::find(I, RC->end(), AssignedReg);
9167     if (I == RC->end()) {
9168       // RC does not contain the selected register, which indicates a
9169       // mismatch between the register and the required type/bitwidth.
9170       return {AssignedReg};
9171     }
9172   }
9173 
9174   for (; NumRegs; --NumRegs, ++I) {
9175     assert(I != RC->end() && "Ran out of registers to allocate!");
9176     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
9177     Regs.push_back(R);
9178   }
9179 
9180   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
9181   return std::nullopt;
9182 }
9183 
9184 static unsigned
9185 findMatchingInlineAsmOperand(unsigned OperandNo,
9186                              const std::vector<SDValue> &AsmNodeOperands) {
9187   // Scan until we find the definition we already emitted of this operand.
9188   unsigned CurOp = InlineAsm::Op_FirstOperand;
9189   for (; OperandNo; --OperandNo) {
9190     // Advance to the next operand.
9191     unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal();
9192     const InlineAsm::Flag F(OpFlag);
9193     assert(
9194         (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) &&
9195         "Skipped past definitions?");
9196     CurOp += F.getNumOperandRegisters() + 1;
9197   }
9198   return CurOp;
9199 }
9200 
9201 namespace {
9202 
9203 class ExtraFlags {
9204   unsigned Flags = 0;
9205 
9206 public:
9207   explicit ExtraFlags(const CallBase &Call) {
9208     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9209     if (IA->hasSideEffects())
9210       Flags |= InlineAsm::Extra_HasSideEffects;
9211     if (IA->isAlignStack())
9212       Flags |= InlineAsm::Extra_IsAlignStack;
9213     if (Call.isConvergent())
9214       Flags |= InlineAsm::Extra_IsConvergent;
9215     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
9216   }
9217 
9218   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
9219     // Ideally, we would only check against memory constraints.  However, the
9220     // meaning of an Other constraint can be target-specific and we can't easily
9221     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
9222     // for Other constraints as well.
9223     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9224         OpInfo.ConstraintType == TargetLowering::C_Other) {
9225       if (OpInfo.Type == InlineAsm::isInput)
9226         Flags |= InlineAsm::Extra_MayLoad;
9227       else if (OpInfo.Type == InlineAsm::isOutput)
9228         Flags |= InlineAsm::Extra_MayStore;
9229       else if (OpInfo.Type == InlineAsm::isClobber)
9230         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
9231     }
9232   }
9233 
9234   unsigned get() const { return Flags; }
9235 };
9236 
9237 } // end anonymous namespace
9238 
9239 static bool isFunction(SDValue Op) {
9240   if (Op && Op.getOpcode() == ISD::GlobalAddress) {
9241     if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
9242       auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
9243 
9244       // In normal "call dllimport func" instruction (non-inlineasm) it force
9245       // indirect access by specifing call opcode. And usually specially print
9246       // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
9247       // not do in this way now. (In fact, this is similar with "Data Access"
9248       // action). So here we ignore dllimport function.
9249       if (Fn && !Fn->hasDLLImportStorageClass())
9250         return true;
9251     }
9252   }
9253   return false;
9254 }
9255 
9256 /// visitInlineAsm - Handle a call to an InlineAsm object.
9257 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
9258                                          const BasicBlock *EHPadBB) {
9259   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9260 
9261   /// ConstraintOperands - Information about all of the constraints.
9262   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
9263 
9264   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9265   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
9266       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
9267 
9268   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
9269   // AsmDialect, MayLoad, MayStore).
9270   bool HasSideEffect = IA->hasSideEffects();
9271   ExtraFlags ExtraInfo(Call);
9272 
9273   for (auto &T : TargetConstraints) {
9274     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
9275     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
9276 
9277     if (OpInfo.CallOperandVal)
9278       OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
9279 
9280     if (!HasSideEffect)
9281       HasSideEffect = OpInfo.hasMemory(TLI);
9282 
9283     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
9284     // FIXME: Could we compute this on OpInfo rather than T?
9285 
9286     // Compute the constraint code and ConstraintType to use.
9287     TLI.ComputeConstraintToUse(T, SDValue());
9288 
9289     if (T.ConstraintType == TargetLowering::C_Immediate &&
9290         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
9291       // We've delayed emitting a diagnostic like the "n" constraint because
9292       // inlining could cause an integer showing up.
9293       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
9294                                           "' expects an integer constant "
9295                                           "expression");
9296 
9297     ExtraInfo.update(T);
9298   }
9299 
9300   // We won't need to flush pending loads if this asm doesn't touch
9301   // memory and is nonvolatile.
9302   SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
9303 
9304   bool EmitEHLabels = isa<InvokeInst>(Call);
9305   if (EmitEHLabels) {
9306     assert(EHPadBB && "InvokeInst must have an EHPadBB");
9307   }
9308   bool IsCallBr = isa<CallBrInst>(Call);
9309 
9310   if (IsCallBr || EmitEHLabels) {
9311     // If this is a callbr or invoke we need to flush pending exports since
9312     // inlineasm_br and invoke are terminators.
9313     // We need to do this before nodes are glued to the inlineasm_br node.
9314     Chain = getControlRoot();
9315   }
9316 
9317   MCSymbol *BeginLabel = nullptr;
9318   if (EmitEHLabels) {
9319     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
9320   }
9321 
9322   int OpNo = -1;
9323   SmallVector<StringRef> AsmStrs;
9324   IA->collectAsmStrs(AsmStrs);
9325 
9326   // Second pass over the constraints: compute which constraint option to use.
9327   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9328     if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
9329       OpNo++;
9330 
9331     // If this is an output operand with a matching input operand, look up the
9332     // matching input. If their types mismatch, e.g. one is an integer, the
9333     // other is floating point, or their sizes are different, flag it as an
9334     // error.
9335     if (OpInfo.hasMatchingInput()) {
9336       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
9337       patchMatchingInput(OpInfo, Input, DAG);
9338     }
9339 
9340     // Compute the constraint code and ConstraintType to use.
9341     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
9342 
9343     if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
9344          OpInfo.Type == InlineAsm::isClobber) ||
9345         OpInfo.ConstraintType == TargetLowering::C_Address)
9346       continue;
9347 
9348     // In Linux PIC model, there are 4 cases about value/label addressing:
9349     //
9350     // 1: Function call or Label jmp inside the module.
9351     // 2: Data access (such as global variable, static variable) inside module.
9352     // 3: Function call or Label jmp outside the module.
9353     // 4: Data access (such as global variable) outside the module.
9354     //
9355     // Due to current llvm inline asm architecture designed to not "recognize"
9356     // the asm code, there are quite troubles for us to treat mem addressing
9357     // differently for same value/adress used in different instuctions.
9358     // For example, in pic model, call a func may in plt way or direclty
9359     // pc-related, but lea/mov a function adress may use got.
9360     //
9361     // Here we try to "recognize" function call for the case 1 and case 3 in
9362     // inline asm. And try to adjust the constraint for them.
9363     //
9364     // TODO: Due to current inline asm didn't encourage to jmp to the outsider
9365     // label, so here we don't handle jmp function label now, but we need to
9366     // enhance it (especilly in PIC model) if we meet meaningful requirements.
9367     if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
9368         TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
9369         TM.getCodeModel() != CodeModel::Large) {
9370       OpInfo.isIndirect = false;
9371       OpInfo.ConstraintType = TargetLowering::C_Address;
9372     }
9373 
9374     // If this is a memory input, and if the operand is not indirect, do what we
9375     // need to provide an address for the memory input.
9376     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
9377         !OpInfo.isIndirect) {
9378       assert((OpInfo.isMultipleAlternative ||
9379               (OpInfo.Type == InlineAsm::isInput)) &&
9380              "Can only indirectify direct input operands!");
9381 
9382       // Memory operands really want the address of the value.
9383       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
9384 
9385       // There is no longer a Value* corresponding to this operand.
9386       OpInfo.CallOperandVal = nullptr;
9387 
9388       // It is now an indirect operand.
9389       OpInfo.isIndirect = true;
9390     }
9391 
9392   }
9393 
9394   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
9395   std::vector<SDValue> AsmNodeOperands;
9396   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
9397   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
9398       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
9399 
9400   // If we have a !srcloc metadata node associated with it, we want to attach
9401   // this to the ultimately generated inline asm machineinstr.  To do this, we
9402   // pass in the third operand as this (potentially null) inline asm MDNode.
9403   const MDNode *SrcLoc = Call.getMetadata("srcloc");
9404   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
9405 
9406   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
9407   // bits as operand 3.
9408   AsmNodeOperands.push_back(DAG.getTargetConstant(
9409       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9410 
9411   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
9412   // this, assign virtual and physical registers for inputs and otput.
9413   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9414     // Assign Registers.
9415     SDISelAsmOperandInfo &RefOpInfo =
9416         OpInfo.isMatchingInputConstraint()
9417             ? ConstraintOperands[OpInfo.getMatchedOperand()]
9418             : OpInfo;
9419     const auto RegError =
9420         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
9421     if (RegError) {
9422       const MachineFunction &MF = DAG.getMachineFunction();
9423       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9424       const char *RegName = TRI.getName(*RegError);
9425       emitInlineAsmError(Call, "register '" + Twine(RegName) +
9426                                    "' allocated for constraint '" +
9427                                    Twine(OpInfo.ConstraintCode) +
9428                                    "' does not match required type");
9429       return;
9430     }
9431 
9432     auto DetectWriteToReservedRegister = [&]() {
9433       const MachineFunction &MF = DAG.getMachineFunction();
9434       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9435       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
9436         if (Register::isPhysicalRegister(Reg) &&
9437             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
9438           const char *RegName = TRI.getName(Reg);
9439           emitInlineAsmError(Call, "write to reserved register '" +
9440                                        Twine(RegName) + "'");
9441           return true;
9442         }
9443       }
9444       return false;
9445     };
9446     assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
9447             (OpInfo.Type == InlineAsm::isInput &&
9448              !OpInfo.isMatchingInputConstraint())) &&
9449            "Only address as input operand is allowed.");
9450 
9451     switch (OpInfo.Type) {
9452     case InlineAsm::isOutput:
9453       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
9454         const InlineAsm::ConstraintCode ConstraintID =
9455             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9456         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
9457                "Failed to convert memory constraint code to constraint id.");
9458 
9459         // Add information to the INLINEASM node to know about this output.
9460         InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1);
9461         OpFlags.setMemConstraint(ConstraintID);
9462         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
9463                                                         MVT::i32));
9464         AsmNodeOperands.push_back(OpInfo.CallOperand);
9465       } else {
9466         // Otherwise, this outputs to a register (directly for C_Register /
9467         // C_RegisterClass, and a target-defined fashion for
9468         // C_Immediate/C_Other). Find a register that we can use.
9469         if (OpInfo.AssignedRegs.Regs.empty()) {
9470           emitInlineAsmError(
9471               Call, "couldn't allocate output register for constraint '" +
9472                         Twine(OpInfo.ConstraintCode) + "'");
9473           return;
9474         }
9475 
9476         if (DetectWriteToReservedRegister())
9477           return;
9478 
9479         // Add information to the INLINEASM node to know that this register is
9480         // set.
9481         OpInfo.AssignedRegs.AddInlineAsmOperands(
9482             OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber
9483                                   : InlineAsm::Kind::RegDef,
9484             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
9485       }
9486       break;
9487 
9488     case InlineAsm::isInput:
9489     case InlineAsm::isLabel: {
9490       SDValue InOperandVal = OpInfo.CallOperand;
9491 
9492       if (OpInfo.isMatchingInputConstraint()) {
9493         // If this is required to match an output register we have already set,
9494         // just use its register.
9495         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
9496                                                   AsmNodeOperands);
9497         InlineAsm::Flag Flag(AsmNodeOperands[CurOp]->getAsZExtVal());
9498         if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) {
9499           if (OpInfo.isIndirect) {
9500             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
9501             emitInlineAsmError(Call, "inline asm not supported yet: "
9502                                      "don't know how to handle tied "
9503                                      "indirect register inputs");
9504             return;
9505           }
9506 
9507           SmallVector<unsigned, 4> Regs;
9508           MachineFunction &MF = DAG.getMachineFunction();
9509           MachineRegisterInfo &MRI = MF.getRegInfo();
9510           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9511           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
9512           Register TiedReg = R->getReg();
9513           MVT RegVT = R->getSimpleValueType(0);
9514           const TargetRegisterClass *RC =
9515               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
9516               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
9517                                       : TRI.getMinimalPhysRegClass(TiedReg);
9518           for (unsigned i = 0, e = Flag.getNumOperandRegisters(); i != e; ++i)
9519             Regs.push_back(MRI.createVirtualRegister(RC));
9520 
9521           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
9522 
9523           SDLoc dl = getCurSDLoc();
9524           // Use the produced MatchedRegs object to
9525           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call);
9526           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, true,
9527                                            OpInfo.getMatchedOperand(), dl, DAG,
9528                                            AsmNodeOperands);
9529           break;
9530         }
9531 
9532         assert(Flag.isMemKind() && "Unknown matching constraint!");
9533         assert(Flag.getNumOperandRegisters() == 1 &&
9534                "Unexpected number of operands");
9535         // Add information to the INLINEASM node to know about this input.
9536         // See InlineAsm.h isUseOperandTiedToDef.
9537         Flag.clearMemConstraint();
9538         Flag.setMatchingOp(OpInfo.getMatchedOperand());
9539         AsmNodeOperands.push_back(DAG.getTargetConstant(
9540             Flag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9541         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
9542         break;
9543       }
9544 
9545       // Treat indirect 'X' constraint as memory.
9546       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
9547           OpInfo.isIndirect)
9548         OpInfo.ConstraintType = TargetLowering::C_Memory;
9549 
9550       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
9551           OpInfo.ConstraintType == TargetLowering::C_Other) {
9552         std::vector<SDValue> Ops;
9553         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
9554                                           Ops, DAG);
9555         if (Ops.empty()) {
9556           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
9557             if (isa<ConstantSDNode>(InOperandVal)) {
9558               emitInlineAsmError(Call, "value out of range for constraint '" +
9559                                            Twine(OpInfo.ConstraintCode) + "'");
9560               return;
9561             }
9562 
9563           emitInlineAsmError(Call,
9564                              "invalid operand for inline asm constraint '" +
9565                                  Twine(OpInfo.ConstraintCode) + "'");
9566           return;
9567         }
9568 
9569         // Add information to the INLINEASM node to know about this input.
9570         InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size());
9571         AsmNodeOperands.push_back(DAG.getTargetConstant(
9572             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9573         llvm::append_range(AsmNodeOperands, Ops);
9574         break;
9575       }
9576 
9577       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
9578         assert((OpInfo.isIndirect ||
9579                 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
9580                "Operand must be indirect to be a mem!");
9581         assert(InOperandVal.getValueType() ==
9582                    TLI.getPointerTy(DAG.getDataLayout()) &&
9583                "Memory operands expect pointer values");
9584 
9585         const InlineAsm::ConstraintCode ConstraintID =
9586             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9587         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
9588                "Failed to convert memory constraint code to constraint id.");
9589 
9590         // Add information to the INLINEASM node to know about this input.
9591         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
9592         ResOpType.setMemConstraint(ConstraintID);
9593         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
9594                                                         getCurSDLoc(),
9595                                                         MVT::i32));
9596         AsmNodeOperands.push_back(InOperandVal);
9597         break;
9598       }
9599 
9600       if (OpInfo.ConstraintType == TargetLowering::C_Address) {
9601         const InlineAsm::ConstraintCode ConstraintID =
9602             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9603         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
9604                "Failed to convert memory constraint code to constraint id.");
9605 
9606         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
9607 
9608         SDValue AsmOp = InOperandVal;
9609         if (isFunction(InOperandVal)) {
9610           auto *GA = cast<GlobalAddressSDNode>(InOperandVal);
9611           ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1);
9612           AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(),
9613                                              InOperandVal.getValueType(),
9614                                              GA->getOffset());
9615         }
9616 
9617         // Add information to the INLINEASM node to know about this input.
9618         ResOpType.setMemConstraint(ConstraintID);
9619 
9620         AsmNodeOperands.push_back(
9621             DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32));
9622 
9623         AsmNodeOperands.push_back(AsmOp);
9624         break;
9625       }
9626 
9627       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
9628               OpInfo.ConstraintType == TargetLowering::C_Register) &&
9629              "Unknown constraint type!");
9630 
9631       // TODO: Support this.
9632       if (OpInfo.isIndirect) {
9633         emitInlineAsmError(
9634             Call, "Don't know how to handle indirect register inputs yet "
9635                   "for constraint '" +
9636                       Twine(OpInfo.ConstraintCode) + "'");
9637         return;
9638       }
9639 
9640       // Copy the input into the appropriate registers.
9641       if (OpInfo.AssignedRegs.Regs.empty()) {
9642         emitInlineAsmError(Call,
9643                            "couldn't allocate input reg for constraint '" +
9644                                Twine(OpInfo.ConstraintCode) + "'");
9645         return;
9646       }
9647 
9648       if (DetectWriteToReservedRegister())
9649         return;
9650 
9651       SDLoc dl = getCurSDLoc();
9652 
9653       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue,
9654                                         &Call);
9655 
9656       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, false,
9657                                                0, dl, DAG, AsmNodeOperands);
9658       break;
9659     }
9660     case InlineAsm::isClobber:
9661       // Add the clobbered value to the operand list, so that the register
9662       // allocator is aware that the physreg got clobbered.
9663       if (!OpInfo.AssignedRegs.Regs.empty())
9664         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::Clobber,
9665                                                  false, 0, getCurSDLoc(), DAG,
9666                                                  AsmNodeOperands);
9667       break;
9668     }
9669   }
9670 
9671   // Finish up input operands.  Set the input chain and add the flag last.
9672   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
9673   if (Glue.getNode()) AsmNodeOperands.push_back(Glue);
9674 
9675   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
9676   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
9677                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
9678   Glue = Chain.getValue(1);
9679 
9680   // Do additional work to generate outputs.
9681 
9682   SmallVector<EVT, 1> ResultVTs;
9683   SmallVector<SDValue, 1> ResultValues;
9684   SmallVector<SDValue, 8> OutChains;
9685 
9686   llvm::Type *CallResultType = Call.getType();
9687   ArrayRef<Type *> ResultTypes;
9688   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
9689     ResultTypes = StructResult->elements();
9690   else if (!CallResultType->isVoidTy())
9691     ResultTypes = ArrayRef(CallResultType);
9692 
9693   auto CurResultType = ResultTypes.begin();
9694   auto handleRegAssign = [&](SDValue V) {
9695     assert(CurResultType != ResultTypes.end() && "Unexpected value");
9696     assert((*CurResultType)->isSized() && "Unexpected unsized type");
9697     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
9698     ++CurResultType;
9699     // If the type of the inline asm call site return value is different but has
9700     // same size as the type of the asm output bitcast it.  One example of this
9701     // is for vectors with different width / number of elements.  This can
9702     // happen for register classes that can contain multiple different value
9703     // types.  The preg or vreg allocated may not have the same VT as was
9704     // expected.
9705     //
9706     // This can also happen for a return value that disagrees with the register
9707     // class it is put in, eg. a double in a general-purpose register on a
9708     // 32-bit machine.
9709     if (ResultVT != V.getValueType() &&
9710         ResultVT.getSizeInBits() == V.getValueSizeInBits())
9711       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
9712     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
9713              V.getValueType().isInteger()) {
9714       // If a result value was tied to an input value, the computed result
9715       // may have a wider width than the expected result.  Extract the
9716       // relevant portion.
9717       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
9718     }
9719     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
9720     ResultVTs.push_back(ResultVT);
9721     ResultValues.push_back(V);
9722   };
9723 
9724   // Deal with output operands.
9725   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9726     if (OpInfo.Type == InlineAsm::isOutput) {
9727       SDValue Val;
9728       // Skip trivial output operands.
9729       if (OpInfo.AssignedRegs.Regs.empty())
9730         continue;
9731 
9732       switch (OpInfo.ConstraintType) {
9733       case TargetLowering::C_Register:
9734       case TargetLowering::C_RegisterClass:
9735         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
9736                                                   Chain, &Glue, &Call);
9737         break;
9738       case TargetLowering::C_Immediate:
9739       case TargetLowering::C_Other:
9740         Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(),
9741                                               OpInfo, DAG);
9742         break;
9743       case TargetLowering::C_Memory:
9744         break; // Already handled.
9745       case TargetLowering::C_Address:
9746         break; // Silence warning.
9747       case TargetLowering::C_Unknown:
9748         assert(false && "Unexpected unknown constraint");
9749       }
9750 
9751       // Indirect output manifest as stores. Record output chains.
9752       if (OpInfo.isIndirect) {
9753         const Value *Ptr = OpInfo.CallOperandVal;
9754         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
9755         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
9756                                      MachinePointerInfo(Ptr));
9757         OutChains.push_back(Store);
9758       } else {
9759         // generate CopyFromRegs to associated registers.
9760         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
9761         if (Val.getOpcode() == ISD::MERGE_VALUES) {
9762           for (const SDValue &V : Val->op_values())
9763             handleRegAssign(V);
9764         } else
9765           handleRegAssign(Val);
9766       }
9767     }
9768   }
9769 
9770   // Set results.
9771   if (!ResultValues.empty()) {
9772     assert(CurResultType == ResultTypes.end() &&
9773            "Mismatch in number of ResultTypes");
9774     assert(ResultValues.size() == ResultTypes.size() &&
9775            "Mismatch in number of output operands in asm result");
9776 
9777     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
9778                             DAG.getVTList(ResultVTs), ResultValues);
9779     setValue(&Call, V);
9780   }
9781 
9782   // Collect store chains.
9783   if (!OutChains.empty())
9784     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
9785 
9786   if (EmitEHLabels) {
9787     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
9788   }
9789 
9790   // Only Update Root if inline assembly has a memory effect.
9791   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
9792       EmitEHLabels)
9793     DAG.setRoot(Chain);
9794 }
9795 
9796 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
9797                                              const Twine &Message) {
9798   LLVMContext &Ctx = *DAG.getContext();
9799   Ctx.emitError(&Call, Message);
9800 
9801   // Make sure we leave the DAG in a valid state
9802   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9803   SmallVector<EVT, 1> ValueVTs;
9804   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
9805 
9806   if (ValueVTs.empty())
9807     return;
9808 
9809   SmallVector<SDValue, 1> Ops;
9810   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
9811     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
9812 
9813   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
9814 }
9815 
9816 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
9817   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
9818                           MVT::Other, getRoot(),
9819                           getValue(I.getArgOperand(0)),
9820                           DAG.getSrcValue(I.getArgOperand(0))));
9821 }
9822 
9823 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
9824   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9825   const DataLayout &DL = DAG.getDataLayout();
9826   SDValue V = DAG.getVAArg(
9827       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
9828       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
9829       DL.getABITypeAlign(I.getType()).value());
9830   DAG.setRoot(V.getValue(1));
9831 
9832   if (I.getType()->isPointerTy())
9833     V = DAG.getPtrExtOrTrunc(
9834         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
9835   setValue(&I, V);
9836 }
9837 
9838 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
9839   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
9840                           MVT::Other, getRoot(),
9841                           getValue(I.getArgOperand(0)),
9842                           DAG.getSrcValue(I.getArgOperand(0))));
9843 }
9844 
9845 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
9846   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
9847                           MVT::Other, getRoot(),
9848                           getValue(I.getArgOperand(0)),
9849                           getValue(I.getArgOperand(1)),
9850                           DAG.getSrcValue(I.getArgOperand(0)),
9851                           DAG.getSrcValue(I.getArgOperand(1))));
9852 }
9853 
9854 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
9855                                                     const Instruction &I,
9856                                                     SDValue Op) {
9857   const MDNode *Range = getRangeMetadata(I);
9858   if (!Range)
9859     return Op;
9860 
9861   ConstantRange CR = getConstantRangeFromMetadata(*Range);
9862   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
9863     return Op;
9864 
9865   APInt Lo = CR.getUnsignedMin();
9866   if (!Lo.isMinValue())
9867     return Op;
9868 
9869   APInt Hi = CR.getUnsignedMax();
9870   unsigned Bits = std::max(Hi.getActiveBits(),
9871                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
9872 
9873   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9874 
9875   SDLoc SL = getCurSDLoc();
9876 
9877   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
9878                              DAG.getValueType(SmallVT));
9879   unsigned NumVals = Op.getNode()->getNumValues();
9880   if (NumVals == 1)
9881     return ZExt;
9882 
9883   SmallVector<SDValue, 4> Ops;
9884 
9885   Ops.push_back(ZExt);
9886   for (unsigned I = 1; I != NumVals; ++I)
9887     Ops.push_back(Op.getValue(I));
9888 
9889   return DAG.getMergeValues(Ops, SL);
9890 }
9891 
9892 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
9893 /// the call being lowered.
9894 ///
9895 /// This is a helper for lowering intrinsics that follow a target calling
9896 /// convention or require stack pointer adjustment. Only a subset of the
9897 /// intrinsic's operands need to participate in the calling convention.
9898 void SelectionDAGBuilder::populateCallLoweringInfo(
9899     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
9900     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
9901     AttributeSet RetAttrs, bool IsPatchPoint) {
9902   TargetLowering::ArgListTy Args;
9903   Args.reserve(NumArgs);
9904 
9905   // Populate the argument list.
9906   // Attributes for args start at offset 1, after the return attribute.
9907   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
9908        ArgI != ArgE; ++ArgI) {
9909     const Value *V = Call->getOperand(ArgI);
9910 
9911     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
9912 
9913     TargetLowering::ArgListEntry Entry;
9914     Entry.Node = getValue(V);
9915     Entry.Ty = V->getType();
9916     Entry.setAttributes(Call, ArgI);
9917     Args.push_back(Entry);
9918   }
9919 
9920   CLI.setDebugLoc(getCurSDLoc())
9921       .setChain(getRoot())
9922       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args),
9923                  RetAttrs)
9924       .setDiscardResult(Call->use_empty())
9925       .setIsPatchPoint(IsPatchPoint)
9926       .setIsPreallocated(
9927           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
9928 }
9929 
9930 /// Add a stack map intrinsic call's live variable operands to a stackmap
9931 /// or patchpoint target node's operand list.
9932 ///
9933 /// Constants are converted to TargetConstants purely as an optimization to
9934 /// avoid constant materialization and register allocation.
9935 ///
9936 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
9937 /// generate addess computation nodes, and so FinalizeISel can convert the
9938 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
9939 /// address materialization and register allocation, but may also be required
9940 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
9941 /// alloca in the entry block, then the runtime may assume that the alloca's
9942 /// StackMap location can be read immediately after compilation and that the
9943 /// location is valid at any point during execution (this is similar to the
9944 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
9945 /// only available in a register, then the runtime would need to trap when
9946 /// execution reaches the StackMap in order to read the alloca's location.
9947 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
9948                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
9949                                 SelectionDAGBuilder &Builder) {
9950   SelectionDAG &DAG = Builder.DAG;
9951   for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
9952     SDValue Op = Builder.getValue(Call.getArgOperand(I));
9953 
9954     // Things on the stack are pointer-typed, meaning that they are already
9955     // legal and can be emitted directly to target nodes.
9956     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
9957       Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
9958     } else {
9959       // Otherwise emit a target independent node to be legalised.
9960       Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
9961     }
9962   }
9963 }
9964 
9965 /// Lower llvm.experimental.stackmap.
9966 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
9967   // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
9968   //                                  [live variables...])
9969 
9970   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
9971 
9972   SDValue Chain, InGlue, Callee;
9973   SmallVector<SDValue, 32> Ops;
9974 
9975   SDLoc DL = getCurSDLoc();
9976   Callee = getValue(CI.getCalledOperand());
9977 
9978   // The stackmap intrinsic only records the live variables (the arguments
9979   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
9980   // intrinsic, this won't be lowered to a function call. This means we don't
9981   // have to worry about calling conventions and target specific lowering code.
9982   // Instead we perform the call lowering right here.
9983   //
9984   // chain, flag = CALLSEQ_START(chain, 0, 0)
9985   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
9986   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
9987   //
9988   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
9989   InGlue = Chain.getValue(1);
9990 
9991   // Add the STACKMAP operands, starting with DAG house-keeping.
9992   Ops.push_back(Chain);
9993   Ops.push_back(InGlue);
9994 
9995   // Add the <id>, <numShadowBytes> operands.
9996   //
9997   // These do not require legalisation, and can be emitted directly to target
9998   // constant nodes.
9999   SDValue ID = getValue(CI.getArgOperand(0));
10000   assert(ID.getValueType() == MVT::i64);
10001   SDValue IDConst =
10002       DAG.getTargetConstant(ID->getAsZExtVal(), DL, ID.getValueType());
10003   Ops.push_back(IDConst);
10004 
10005   SDValue Shad = getValue(CI.getArgOperand(1));
10006   assert(Shad.getValueType() == MVT::i32);
10007   SDValue ShadConst =
10008       DAG.getTargetConstant(Shad->getAsZExtVal(), DL, Shad.getValueType());
10009   Ops.push_back(ShadConst);
10010 
10011   // Add the live variables.
10012   addStackMapLiveVars(CI, 2, DL, Ops, *this);
10013 
10014   // Create the STACKMAP node.
10015   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10016   Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
10017   InGlue = Chain.getValue(1);
10018 
10019   Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL);
10020 
10021   // Stackmaps don't generate values, so nothing goes into the NodeMap.
10022 
10023   // Set the root to the target-lowered call chain.
10024   DAG.setRoot(Chain);
10025 
10026   // Inform the Frame Information that we have a stackmap in this function.
10027   FuncInfo.MF->getFrameInfo().setHasStackMap();
10028 }
10029 
10030 /// Lower llvm.experimental.patchpoint directly to its target opcode.
10031 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
10032                                           const BasicBlock *EHPadBB) {
10033   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
10034   //                                                 i32 <numBytes>,
10035   //                                                 i8* <target>,
10036   //                                                 i32 <numArgs>,
10037   //                                                 [Args...],
10038   //                                                 [live variables...])
10039 
10040   CallingConv::ID CC = CB.getCallingConv();
10041   bool IsAnyRegCC = CC == CallingConv::AnyReg;
10042   bool HasDef = !CB.getType()->isVoidTy();
10043   SDLoc dl = getCurSDLoc();
10044   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
10045 
10046   // Handle immediate and symbolic callees.
10047   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
10048     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
10049                                    /*isTarget=*/true);
10050   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
10051     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
10052                                          SDLoc(SymbolicCallee),
10053                                          SymbolicCallee->getValueType(0));
10054 
10055   // Get the real number of arguments participating in the call <numArgs>
10056   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
10057   unsigned NumArgs = NArgVal->getAsZExtVal();
10058 
10059   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
10060   // Intrinsics include all meta-operands up to but not including CC.
10061   unsigned NumMetaOpers = PatchPointOpers::CCPos;
10062   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
10063          "Not enough arguments provided to the patchpoint intrinsic");
10064 
10065   // For AnyRegCC the arguments are lowered later on manually.
10066   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
10067   Type *ReturnTy =
10068       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
10069 
10070   TargetLowering::CallLoweringInfo CLI(DAG);
10071   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
10072                            ReturnTy, CB.getAttributes().getRetAttrs(), true);
10073   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
10074 
10075   SDNode *CallEnd = Result.second.getNode();
10076   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
10077     CallEnd = CallEnd->getOperand(0).getNode();
10078 
10079   /// Get a call instruction from the call sequence chain.
10080   /// Tail calls are not allowed.
10081   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
10082          "Expected a callseq node.");
10083   SDNode *Call = CallEnd->getOperand(0).getNode();
10084   bool HasGlue = Call->getGluedNode();
10085 
10086   // Replace the target specific call node with the patchable intrinsic.
10087   SmallVector<SDValue, 8> Ops;
10088 
10089   // Push the chain.
10090   Ops.push_back(*(Call->op_begin()));
10091 
10092   // Optionally, push the glue (if any).
10093   if (HasGlue)
10094     Ops.push_back(*(Call->op_end() - 1));
10095 
10096   // Push the register mask info.
10097   if (HasGlue)
10098     Ops.push_back(*(Call->op_end() - 2));
10099   else
10100     Ops.push_back(*(Call->op_end() - 1));
10101 
10102   // Add the <id> and <numBytes> constants.
10103   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
10104   Ops.push_back(DAG.getTargetConstant(IDVal->getAsZExtVal(), dl, MVT::i64));
10105   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
10106   Ops.push_back(DAG.getTargetConstant(NBytesVal->getAsZExtVal(), dl, MVT::i32));
10107 
10108   // Add the callee.
10109   Ops.push_back(Callee);
10110 
10111   // Adjust <numArgs> to account for any arguments that have been passed on the
10112   // stack instead.
10113   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
10114   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
10115   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
10116   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
10117 
10118   // Add the calling convention
10119   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
10120 
10121   // Add the arguments we omitted previously. The register allocator should
10122   // place these in any free register.
10123   if (IsAnyRegCC)
10124     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
10125       Ops.push_back(getValue(CB.getArgOperand(i)));
10126 
10127   // Push the arguments from the call instruction.
10128   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
10129   Ops.append(Call->op_begin() + 2, e);
10130 
10131   // Push live variables for the stack map.
10132   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
10133 
10134   SDVTList NodeTys;
10135   if (IsAnyRegCC && HasDef) {
10136     // Create the return types based on the intrinsic definition
10137     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10138     SmallVector<EVT, 3> ValueVTs;
10139     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
10140     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
10141 
10142     // There is always a chain and a glue type at the end
10143     ValueVTs.push_back(MVT::Other);
10144     ValueVTs.push_back(MVT::Glue);
10145     NodeTys = DAG.getVTList(ValueVTs);
10146   } else
10147     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10148 
10149   // Replace the target specific call node with a PATCHPOINT node.
10150   SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
10151 
10152   // Update the NodeMap.
10153   if (HasDef) {
10154     if (IsAnyRegCC)
10155       setValue(&CB, SDValue(PPV.getNode(), 0));
10156     else
10157       setValue(&CB, Result.first);
10158   }
10159 
10160   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
10161   // call sequence. Furthermore the location of the chain and glue can change
10162   // when the AnyReg calling convention is used and the intrinsic returns a
10163   // value.
10164   if (IsAnyRegCC && HasDef) {
10165     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
10166     SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
10167     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10168   } else
10169     DAG.ReplaceAllUsesWith(Call, PPV.getNode());
10170   DAG.DeleteNode(Call);
10171 
10172   // Inform the Frame Information that we have a patchpoint in this function.
10173   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
10174 }
10175 
10176 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
10177                                             unsigned Intrinsic) {
10178   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10179   SDValue Op1 = getValue(I.getArgOperand(0));
10180   SDValue Op2;
10181   if (I.arg_size() > 1)
10182     Op2 = getValue(I.getArgOperand(1));
10183   SDLoc dl = getCurSDLoc();
10184   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
10185   SDValue Res;
10186   SDNodeFlags SDFlags;
10187   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
10188     SDFlags.copyFMF(*FPMO);
10189 
10190   switch (Intrinsic) {
10191   case Intrinsic::vector_reduce_fadd:
10192     if (SDFlags.hasAllowReassociation())
10193       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
10194                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
10195                         SDFlags);
10196     else
10197       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
10198     break;
10199   case Intrinsic::vector_reduce_fmul:
10200     if (SDFlags.hasAllowReassociation())
10201       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
10202                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
10203                         SDFlags);
10204     else
10205       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
10206     break;
10207   case Intrinsic::vector_reduce_add:
10208     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
10209     break;
10210   case Intrinsic::vector_reduce_mul:
10211     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
10212     break;
10213   case Intrinsic::vector_reduce_and:
10214     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
10215     break;
10216   case Intrinsic::vector_reduce_or:
10217     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
10218     break;
10219   case Intrinsic::vector_reduce_xor:
10220     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
10221     break;
10222   case Intrinsic::vector_reduce_smax:
10223     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
10224     break;
10225   case Intrinsic::vector_reduce_smin:
10226     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
10227     break;
10228   case Intrinsic::vector_reduce_umax:
10229     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
10230     break;
10231   case Intrinsic::vector_reduce_umin:
10232     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
10233     break;
10234   case Intrinsic::vector_reduce_fmax:
10235     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
10236     break;
10237   case Intrinsic::vector_reduce_fmin:
10238     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
10239     break;
10240   case Intrinsic::vector_reduce_fmaximum:
10241     Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags);
10242     break;
10243   case Intrinsic::vector_reduce_fminimum:
10244     Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags);
10245     break;
10246   default:
10247     llvm_unreachable("Unhandled vector reduce intrinsic");
10248   }
10249   setValue(&I, Res);
10250 }
10251 
10252 /// Returns an AttributeList representing the attributes applied to the return
10253 /// value of the given call.
10254 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
10255   SmallVector<Attribute::AttrKind, 2> Attrs;
10256   if (CLI.RetSExt)
10257     Attrs.push_back(Attribute::SExt);
10258   if (CLI.RetZExt)
10259     Attrs.push_back(Attribute::ZExt);
10260   if (CLI.IsInReg)
10261     Attrs.push_back(Attribute::InReg);
10262 
10263   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
10264                             Attrs);
10265 }
10266 
10267 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
10268 /// implementation, which just calls LowerCall.
10269 /// FIXME: When all targets are
10270 /// migrated to using LowerCall, this hook should be integrated into SDISel.
10271 std::pair<SDValue, SDValue>
10272 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
10273   // Handle the incoming return values from the call.
10274   CLI.Ins.clear();
10275   Type *OrigRetTy = CLI.RetTy;
10276   SmallVector<EVT, 4> RetTys;
10277   SmallVector<uint64_t, 4> Offsets;
10278   auto &DL = CLI.DAG.getDataLayout();
10279   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets, 0);
10280 
10281   if (CLI.IsPostTypeLegalization) {
10282     // If we are lowering a libcall after legalization, split the return type.
10283     SmallVector<EVT, 4> OldRetTys;
10284     SmallVector<uint64_t, 4> OldOffsets;
10285     RetTys.swap(OldRetTys);
10286     Offsets.swap(OldOffsets);
10287 
10288     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
10289       EVT RetVT = OldRetTys[i];
10290       uint64_t Offset = OldOffsets[i];
10291       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
10292       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
10293       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
10294       RetTys.append(NumRegs, RegisterVT);
10295       for (unsigned j = 0; j != NumRegs; ++j)
10296         Offsets.push_back(Offset + j * RegisterVTByteSZ);
10297     }
10298   }
10299 
10300   SmallVector<ISD::OutputArg, 4> Outs;
10301   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
10302 
10303   bool CanLowerReturn =
10304       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
10305                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
10306 
10307   SDValue DemoteStackSlot;
10308   int DemoteStackIdx = -100;
10309   if (!CanLowerReturn) {
10310     // FIXME: equivalent assert?
10311     // assert(!CS.hasInAllocaArgument() &&
10312     //        "sret demotion is incompatible with inalloca");
10313     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
10314     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
10315     MachineFunction &MF = CLI.DAG.getMachineFunction();
10316     DemoteStackIdx =
10317         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
10318     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
10319                                               DL.getAllocaAddrSpace());
10320 
10321     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
10322     ArgListEntry Entry;
10323     Entry.Node = DemoteStackSlot;
10324     Entry.Ty = StackSlotPtrType;
10325     Entry.IsSExt = false;
10326     Entry.IsZExt = false;
10327     Entry.IsInReg = false;
10328     Entry.IsSRet = true;
10329     Entry.IsNest = false;
10330     Entry.IsByVal = false;
10331     Entry.IsByRef = false;
10332     Entry.IsReturned = false;
10333     Entry.IsSwiftSelf = false;
10334     Entry.IsSwiftAsync = false;
10335     Entry.IsSwiftError = false;
10336     Entry.IsCFGuardTarget = false;
10337     Entry.Alignment = Alignment;
10338     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
10339     CLI.NumFixedArgs += 1;
10340     CLI.getArgs()[0].IndirectType = CLI.RetTy;
10341     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
10342 
10343     // sret demotion isn't compatible with tail-calls, since the sret argument
10344     // points into the callers stack frame.
10345     CLI.IsTailCall = false;
10346   } else {
10347     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10348         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
10349     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
10350       ISD::ArgFlagsTy Flags;
10351       if (NeedsRegBlock) {
10352         Flags.setInConsecutiveRegs();
10353         if (I == RetTys.size() - 1)
10354           Flags.setInConsecutiveRegsLast();
10355       }
10356       EVT VT = RetTys[I];
10357       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10358                                                      CLI.CallConv, VT);
10359       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10360                                                        CLI.CallConv, VT);
10361       for (unsigned i = 0; i != NumRegs; ++i) {
10362         ISD::InputArg MyFlags;
10363         MyFlags.Flags = Flags;
10364         MyFlags.VT = RegisterVT;
10365         MyFlags.ArgVT = VT;
10366         MyFlags.Used = CLI.IsReturnValueUsed;
10367         if (CLI.RetTy->isPointerTy()) {
10368           MyFlags.Flags.setPointer();
10369           MyFlags.Flags.setPointerAddrSpace(
10370               cast<PointerType>(CLI.RetTy)->getAddressSpace());
10371         }
10372         if (CLI.RetSExt)
10373           MyFlags.Flags.setSExt();
10374         if (CLI.RetZExt)
10375           MyFlags.Flags.setZExt();
10376         if (CLI.IsInReg)
10377           MyFlags.Flags.setInReg();
10378         CLI.Ins.push_back(MyFlags);
10379       }
10380     }
10381   }
10382 
10383   // We push in swifterror return as the last element of CLI.Ins.
10384   ArgListTy &Args = CLI.getArgs();
10385   if (supportSwiftError()) {
10386     for (const ArgListEntry &Arg : Args) {
10387       if (Arg.IsSwiftError) {
10388         ISD::InputArg MyFlags;
10389         MyFlags.VT = getPointerTy(DL);
10390         MyFlags.ArgVT = EVT(getPointerTy(DL));
10391         MyFlags.Flags.setSwiftError();
10392         CLI.Ins.push_back(MyFlags);
10393       }
10394     }
10395   }
10396 
10397   // Handle all of the outgoing arguments.
10398   CLI.Outs.clear();
10399   CLI.OutVals.clear();
10400   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
10401     SmallVector<EVT, 4> ValueVTs;
10402     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
10403     // FIXME: Split arguments if CLI.IsPostTypeLegalization
10404     Type *FinalType = Args[i].Ty;
10405     if (Args[i].IsByVal)
10406       FinalType = Args[i].IndirectType;
10407     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10408         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
10409     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
10410          ++Value) {
10411       EVT VT = ValueVTs[Value];
10412       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
10413       SDValue Op = SDValue(Args[i].Node.getNode(),
10414                            Args[i].Node.getResNo() + Value);
10415       ISD::ArgFlagsTy Flags;
10416 
10417       // Certain targets (such as MIPS), may have a different ABI alignment
10418       // for a type depending on the context. Give the target a chance to
10419       // specify the alignment it wants.
10420       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
10421       Flags.setOrigAlign(OriginalAlignment);
10422 
10423       if (Args[i].Ty->isPointerTy()) {
10424         Flags.setPointer();
10425         Flags.setPointerAddrSpace(
10426             cast<PointerType>(Args[i].Ty)->getAddressSpace());
10427       }
10428       if (Args[i].IsZExt)
10429         Flags.setZExt();
10430       if (Args[i].IsSExt)
10431         Flags.setSExt();
10432       if (Args[i].IsInReg) {
10433         // If we are using vectorcall calling convention, a structure that is
10434         // passed InReg - is surely an HVA
10435         if (CLI.CallConv == CallingConv::X86_VectorCall &&
10436             isa<StructType>(FinalType)) {
10437           // The first value of a structure is marked
10438           if (0 == Value)
10439             Flags.setHvaStart();
10440           Flags.setHva();
10441         }
10442         // Set InReg Flag
10443         Flags.setInReg();
10444       }
10445       if (Args[i].IsSRet)
10446         Flags.setSRet();
10447       if (Args[i].IsSwiftSelf)
10448         Flags.setSwiftSelf();
10449       if (Args[i].IsSwiftAsync)
10450         Flags.setSwiftAsync();
10451       if (Args[i].IsSwiftError)
10452         Flags.setSwiftError();
10453       if (Args[i].IsCFGuardTarget)
10454         Flags.setCFGuardTarget();
10455       if (Args[i].IsByVal)
10456         Flags.setByVal();
10457       if (Args[i].IsByRef)
10458         Flags.setByRef();
10459       if (Args[i].IsPreallocated) {
10460         Flags.setPreallocated();
10461         // Set the byval flag for CCAssignFn callbacks that don't know about
10462         // preallocated.  This way we can know how many bytes we should've
10463         // allocated and how many bytes a callee cleanup function will pop.  If
10464         // we port preallocated to more targets, we'll have to add custom
10465         // preallocated handling in the various CC lowering callbacks.
10466         Flags.setByVal();
10467       }
10468       if (Args[i].IsInAlloca) {
10469         Flags.setInAlloca();
10470         // Set the byval flag for CCAssignFn callbacks that don't know about
10471         // inalloca.  This way we can know how many bytes we should've allocated
10472         // and how many bytes a callee cleanup function will pop.  If we port
10473         // inalloca to more targets, we'll have to add custom inalloca handling
10474         // in the various CC lowering callbacks.
10475         Flags.setByVal();
10476       }
10477       Align MemAlign;
10478       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
10479         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
10480         Flags.setByValSize(FrameSize);
10481 
10482         // info is not there but there are cases it cannot get right.
10483         if (auto MA = Args[i].Alignment)
10484           MemAlign = *MA;
10485         else
10486           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
10487       } else if (auto MA = Args[i].Alignment) {
10488         MemAlign = *MA;
10489       } else {
10490         MemAlign = OriginalAlignment;
10491       }
10492       Flags.setMemAlign(MemAlign);
10493       if (Args[i].IsNest)
10494         Flags.setNest();
10495       if (NeedsRegBlock)
10496         Flags.setInConsecutiveRegs();
10497 
10498       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10499                                                  CLI.CallConv, VT);
10500       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10501                                                         CLI.CallConv, VT);
10502       SmallVector<SDValue, 4> Parts(NumParts);
10503       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
10504 
10505       if (Args[i].IsSExt)
10506         ExtendKind = ISD::SIGN_EXTEND;
10507       else if (Args[i].IsZExt)
10508         ExtendKind = ISD::ZERO_EXTEND;
10509 
10510       // Conservatively only handle 'returned' on non-vectors that can be lowered,
10511       // for now.
10512       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
10513           CanLowerReturn) {
10514         assert((CLI.RetTy == Args[i].Ty ||
10515                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
10516                  CLI.RetTy->getPointerAddressSpace() ==
10517                      Args[i].Ty->getPointerAddressSpace())) &&
10518                RetTys.size() == NumValues && "unexpected use of 'returned'");
10519         // Before passing 'returned' to the target lowering code, ensure that
10520         // either the register MVT and the actual EVT are the same size or that
10521         // the return value and argument are extended in the same way; in these
10522         // cases it's safe to pass the argument register value unchanged as the
10523         // return register value (although it's at the target's option whether
10524         // to do so)
10525         // TODO: allow code generation to take advantage of partially preserved
10526         // registers rather than clobbering the entire register when the
10527         // parameter extension method is not compatible with the return
10528         // extension method
10529         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
10530             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
10531              CLI.RetZExt == Args[i].IsZExt))
10532           Flags.setReturned();
10533       }
10534 
10535       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
10536                      CLI.CallConv, ExtendKind);
10537 
10538       for (unsigned j = 0; j != NumParts; ++j) {
10539         // if it isn't first piece, alignment must be 1
10540         // For scalable vectors the scalable part is currently handled
10541         // by individual targets, so we just use the known minimum size here.
10542         ISD::OutputArg MyFlags(
10543             Flags, Parts[j].getValueType().getSimpleVT(), VT,
10544             i < CLI.NumFixedArgs, i,
10545             j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
10546         if (NumParts > 1 && j == 0)
10547           MyFlags.Flags.setSplit();
10548         else if (j != 0) {
10549           MyFlags.Flags.setOrigAlign(Align(1));
10550           if (j == NumParts - 1)
10551             MyFlags.Flags.setSplitEnd();
10552         }
10553 
10554         CLI.Outs.push_back(MyFlags);
10555         CLI.OutVals.push_back(Parts[j]);
10556       }
10557 
10558       if (NeedsRegBlock && Value == NumValues - 1)
10559         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
10560     }
10561   }
10562 
10563   SmallVector<SDValue, 4> InVals;
10564   CLI.Chain = LowerCall(CLI, InVals);
10565 
10566   // Update CLI.InVals to use outside of this function.
10567   CLI.InVals = InVals;
10568 
10569   // Verify that the target's LowerCall behaved as expected.
10570   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
10571          "LowerCall didn't return a valid chain!");
10572   assert((!CLI.IsTailCall || InVals.empty()) &&
10573          "LowerCall emitted a return value for a tail call!");
10574   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
10575          "LowerCall didn't emit the correct number of values!");
10576 
10577   // For a tail call, the return value is merely live-out and there aren't
10578   // any nodes in the DAG representing it. Return a special value to
10579   // indicate that a tail call has been emitted and no more Instructions
10580   // should be processed in the current block.
10581   if (CLI.IsTailCall) {
10582     CLI.DAG.setRoot(CLI.Chain);
10583     return std::make_pair(SDValue(), SDValue());
10584   }
10585 
10586 #ifndef NDEBUG
10587   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
10588     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
10589     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
10590            "LowerCall emitted a value with the wrong type!");
10591   }
10592 #endif
10593 
10594   SmallVector<SDValue, 4> ReturnValues;
10595   if (!CanLowerReturn) {
10596     // The instruction result is the result of loading from the
10597     // hidden sret parameter.
10598     SmallVector<EVT, 1> PVTs;
10599     Type *PtrRetTy =
10600         PointerType::get(OrigRetTy->getContext(), DL.getAllocaAddrSpace());
10601 
10602     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
10603     assert(PVTs.size() == 1 && "Pointers should fit in one register");
10604     EVT PtrVT = PVTs[0];
10605 
10606     unsigned NumValues = RetTys.size();
10607     ReturnValues.resize(NumValues);
10608     SmallVector<SDValue, 4> Chains(NumValues);
10609 
10610     // An aggregate return value cannot wrap around the address space, so
10611     // offsets to its parts don't wrap either.
10612     SDNodeFlags Flags;
10613     Flags.setNoUnsignedWrap(true);
10614 
10615     MachineFunction &MF = CLI.DAG.getMachineFunction();
10616     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
10617     for (unsigned i = 0; i < NumValues; ++i) {
10618       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
10619                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
10620                                                         PtrVT), Flags);
10621       SDValue L = CLI.DAG.getLoad(
10622           RetTys[i], CLI.DL, CLI.Chain, Add,
10623           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
10624                                             DemoteStackIdx, Offsets[i]),
10625           HiddenSRetAlign);
10626       ReturnValues[i] = L;
10627       Chains[i] = L.getValue(1);
10628     }
10629 
10630     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
10631   } else {
10632     // Collect the legal value parts into potentially illegal values
10633     // that correspond to the original function's return values.
10634     std::optional<ISD::NodeType> AssertOp;
10635     if (CLI.RetSExt)
10636       AssertOp = ISD::AssertSext;
10637     else if (CLI.RetZExt)
10638       AssertOp = ISD::AssertZext;
10639     unsigned CurReg = 0;
10640     for (EVT VT : RetTys) {
10641       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10642                                                      CLI.CallConv, VT);
10643       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10644                                                        CLI.CallConv, VT);
10645 
10646       ReturnValues.push_back(getCopyFromParts(
10647           CLI.DAG, CLI.DL, &InVals[CurReg], NumRegs, RegisterVT, VT, nullptr,
10648           CLI.Chain, CLI.CallConv, AssertOp));
10649       CurReg += NumRegs;
10650     }
10651 
10652     // For a function returning void, there is no return value. We can't create
10653     // such a node, so we just return a null return value in that case. In
10654     // that case, nothing will actually look at the value.
10655     if (ReturnValues.empty())
10656       return std::make_pair(SDValue(), CLI.Chain);
10657   }
10658 
10659   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
10660                                 CLI.DAG.getVTList(RetTys), ReturnValues);
10661   return std::make_pair(Res, CLI.Chain);
10662 }
10663 
10664 /// Places new result values for the node in Results (their number
10665 /// and types must exactly match those of the original return values of
10666 /// the node), or leaves Results empty, which indicates that the node is not
10667 /// to be custom lowered after all.
10668 void TargetLowering::LowerOperationWrapper(SDNode *N,
10669                                            SmallVectorImpl<SDValue> &Results,
10670                                            SelectionDAG &DAG) const {
10671   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
10672 
10673   if (!Res.getNode())
10674     return;
10675 
10676   // If the original node has one result, take the return value from
10677   // LowerOperation as is. It might not be result number 0.
10678   if (N->getNumValues() == 1) {
10679     Results.push_back(Res);
10680     return;
10681   }
10682 
10683   // If the original node has multiple results, then the return node should
10684   // have the same number of results.
10685   assert((N->getNumValues() == Res->getNumValues()) &&
10686       "Lowering returned the wrong number of results!");
10687 
10688   // Places new result values base on N result number.
10689   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
10690     Results.push_back(Res.getValue(I));
10691 }
10692 
10693 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10694   llvm_unreachable("LowerOperation not implemented for this target!");
10695 }
10696 
10697 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
10698                                                      unsigned Reg,
10699                                                      ISD::NodeType ExtendType) {
10700   SDValue Op = getNonRegisterValue(V);
10701   assert((Op.getOpcode() != ISD::CopyFromReg ||
10702           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
10703          "Copy from a reg to the same reg!");
10704   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
10705 
10706   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10707   // If this is an InlineAsm we have to match the registers required, not the
10708   // notional registers required by the type.
10709 
10710   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
10711                    std::nullopt); // This is not an ABI copy.
10712   SDValue Chain = DAG.getEntryNode();
10713 
10714   if (ExtendType == ISD::ANY_EXTEND) {
10715     auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
10716     if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
10717       ExtendType = PreferredExtendIt->second;
10718   }
10719   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
10720   PendingExports.push_back(Chain);
10721 }
10722 
10723 #include "llvm/CodeGen/SelectionDAGISel.h"
10724 
10725 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
10726 /// entry block, return true.  This includes arguments used by switches, since
10727 /// the switch may expand into multiple basic blocks.
10728 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
10729   // With FastISel active, we may be splitting blocks, so force creation
10730   // of virtual registers for all non-dead arguments.
10731   if (FastISel)
10732     return A->use_empty();
10733 
10734   const BasicBlock &Entry = A->getParent()->front();
10735   for (const User *U : A->users())
10736     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
10737       return false;  // Use not in entry block.
10738 
10739   return true;
10740 }
10741 
10742 using ArgCopyElisionMapTy =
10743     DenseMap<const Argument *,
10744              std::pair<const AllocaInst *, const StoreInst *>>;
10745 
10746 /// Scan the entry block of the function in FuncInfo for arguments that look
10747 /// like copies into a local alloca. Record any copied arguments in
10748 /// ArgCopyElisionCandidates.
10749 static void
10750 findArgumentCopyElisionCandidates(const DataLayout &DL,
10751                                   FunctionLoweringInfo *FuncInfo,
10752                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
10753   // Record the state of every static alloca used in the entry block. Argument
10754   // allocas are all used in the entry block, so we need approximately as many
10755   // entries as we have arguments.
10756   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
10757   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
10758   unsigned NumArgs = FuncInfo->Fn->arg_size();
10759   StaticAllocas.reserve(NumArgs * 2);
10760 
10761   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
10762     if (!V)
10763       return nullptr;
10764     V = V->stripPointerCasts();
10765     const auto *AI = dyn_cast<AllocaInst>(V);
10766     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
10767       return nullptr;
10768     auto Iter = StaticAllocas.insert({AI, Unknown});
10769     return &Iter.first->second;
10770   };
10771 
10772   // Look for stores of arguments to static allocas. Look through bitcasts and
10773   // GEPs to handle type coercions, as long as the alloca is fully initialized
10774   // by the store. Any non-store use of an alloca escapes it and any subsequent
10775   // unanalyzed store might write it.
10776   // FIXME: Handle structs initialized with multiple stores.
10777   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
10778     // Look for stores, and handle non-store uses conservatively.
10779     const auto *SI = dyn_cast<StoreInst>(&I);
10780     if (!SI) {
10781       // We will look through cast uses, so ignore them completely.
10782       if (I.isCast())
10783         continue;
10784       // Ignore debug info and pseudo op intrinsics, they don't escape or store
10785       // to allocas.
10786       if (I.isDebugOrPseudoInst())
10787         continue;
10788       // This is an unknown instruction. Assume it escapes or writes to all
10789       // static alloca operands.
10790       for (const Use &U : I.operands()) {
10791         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
10792           *Info = StaticAllocaInfo::Clobbered;
10793       }
10794       continue;
10795     }
10796 
10797     // If the stored value is a static alloca, mark it as escaped.
10798     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
10799       *Info = StaticAllocaInfo::Clobbered;
10800 
10801     // Check if the destination is a static alloca.
10802     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
10803     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
10804     if (!Info)
10805       continue;
10806     const AllocaInst *AI = cast<AllocaInst>(Dst);
10807 
10808     // Skip allocas that have been initialized or clobbered.
10809     if (*Info != StaticAllocaInfo::Unknown)
10810       continue;
10811 
10812     // Check if the stored value is an argument, and that this store fully
10813     // initializes the alloca.
10814     // If the argument type has padding bits we can't directly forward a pointer
10815     // as the upper bits may contain garbage.
10816     // Don't elide copies from the same argument twice.
10817     const Value *Val = SI->getValueOperand()->stripPointerCasts();
10818     const auto *Arg = dyn_cast<Argument>(Val);
10819     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
10820         Arg->getType()->isEmptyTy() ||
10821         DL.getTypeStoreSize(Arg->getType()) !=
10822             DL.getTypeAllocSize(AI->getAllocatedType()) ||
10823         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
10824         ArgCopyElisionCandidates.count(Arg)) {
10825       *Info = StaticAllocaInfo::Clobbered;
10826       continue;
10827     }
10828 
10829     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
10830                       << '\n');
10831 
10832     // Mark this alloca and store for argument copy elision.
10833     *Info = StaticAllocaInfo::Elidable;
10834     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
10835 
10836     // Stop scanning if we've seen all arguments. This will happen early in -O0
10837     // builds, which is useful, because -O0 builds have large entry blocks and
10838     // many allocas.
10839     if (ArgCopyElisionCandidates.size() == NumArgs)
10840       break;
10841   }
10842 }
10843 
10844 /// Try to elide argument copies from memory into a local alloca. Succeeds if
10845 /// ArgVal is a load from a suitable fixed stack object.
10846 static void tryToElideArgumentCopy(
10847     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
10848     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
10849     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
10850     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
10851     ArrayRef<SDValue> ArgVals, bool &ArgHasUses) {
10852   // Check if this is a load from a fixed stack object.
10853   auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]);
10854   if (!LNode)
10855     return;
10856   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
10857   if (!FINode)
10858     return;
10859 
10860   // Check that the fixed stack object is the right size and alignment.
10861   // Look at the alignment that the user wrote on the alloca instead of looking
10862   // at the stack object.
10863   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
10864   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
10865   const AllocaInst *AI = ArgCopyIter->second.first;
10866   int FixedIndex = FINode->getIndex();
10867   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
10868   int OldIndex = AllocaIndex;
10869   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
10870   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
10871     LLVM_DEBUG(
10872         dbgs() << "  argument copy elision failed due to bad fixed stack "
10873                   "object size\n");
10874     return;
10875   }
10876   Align RequiredAlignment = AI->getAlign();
10877   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
10878     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
10879                          "greater than stack argument alignment ("
10880                       << DebugStr(RequiredAlignment) << " vs "
10881                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
10882     return;
10883   }
10884 
10885   // Perform the elision. Delete the old stack object and replace its only use
10886   // in the variable info map. Mark the stack object as mutable.
10887   LLVM_DEBUG({
10888     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
10889            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
10890            << '\n';
10891   });
10892   MFI.RemoveStackObject(OldIndex);
10893   MFI.setIsImmutableObjectIndex(FixedIndex, false);
10894   AllocaIndex = FixedIndex;
10895   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
10896   for (SDValue ArgVal : ArgVals)
10897     Chains.push_back(ArgVal.getValue(1));
10898 
10899   // Avoid emitting code for the store implementing the copy.
10900   const StoreInst *SI = ArgCopyIter->second.second;
10901   ElidedArgCopyInstrs.insert(SI);
10902 
10903   // Check for uses of the argument again so that we can avoid exporting ArgVal
10904   // if it is't used by anything other than the store.
10905   for (const Value *U : Arg.users()) {
10906     if (U != SI) {
10907       ArgHasUses = true;
10908       break;
10909     }
10910   }
10911 }
10912 
10913 void SelectionDAGISel::LowerArguments(const Function &F) {
10914   SelectionDAG &DAG = SDB->DAG;
10915   SDLoc dl = SDB->getCurSDLoc();
10916   const DataLayout &DL = DAG.getDataLayout();
10917   SmallVector<ISD::InputArg, 16> Ins;
10918 
10919   // In Naked functions we aren't going to save any registers.
10920   if (F.hasFnAttribute(Attribute::Naked))
10921     return;
10922 
10923   if (!FuncInfo->CanLowerReturn) {
10924     // Put in an sret pointer parameter before all the other parameters.
10925     SmallVector<EVT, 1> ValueVTs;
10926     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10927                     PointerType::get(F.getContext(),
10928                                      DAG.getDataLayout().getAllocaAddrSpace()),
10929                     ValueVTs);
10930 
10931     // NOTE: Assuming that a pointer will never break down to more than one VT
10932     // or one register.
10933     ISD::ArgFlagsTy Flags;
10934     Flags.setSRet();
10935     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
10936     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
10937                          ISD::InputArg::NoArgIndex, 0);
10938     Ins.push_back(RetArg);
10939   }
10940 
10941   // Look for stores of arguments to static allocas. Mark such arguments with a
10942   // flag to ask the target to give us the memory location of that argument if
10943   // available.
10944   ArgCopyElisionMapTy ArgCopyElisionCandidates;
10945   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
10946                                     ArgCopyElisionCandidates);
10947 
10948   // Set up the incoming argument description vector.
10949   for (const Argument &Arg : F.args()) {
10950     unsigned ArgNo = Arg.getArgNo();
10951     SmallVector<EVT, 4> ValueVTs;
10952     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10953     bool isArgValueUsed = !Arg.use_empty();
10954     unsigned PartBase = 0;
10955     Type *FinalType = Arg.getType();
10956     if (Arg.hasAttribute(Attribute::ByVal))
10957       FinalType = Arg.getParamByValType();
10958     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
10959         FinalType, F.getCallingConv(), F.isVarArg(), DL);
10960     for (unsigned Value = 0, NumValues = ValueVTs.size();
10961          Value != NumValues; ++Value) {
10962       EVT VT = ValueVTs[Value];
10963       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
10964       ISD::ArgFlagsTy Flags;
10965 
10966 
10967       if (Arg.getType()->isPointerTy()) {
10968         Flags.setPointer();
10969         Flags.setPointerAddrSpace(
10970             cast<PointerType>(Arg.getType())->getAddressSpace());
10971       }
10972       if (Arg.hasAttribute(Attribute::ZExt))
10973         Flags.setZExt();
10974       if (Arg.hasAttribute(Attribute::SExt))
10975         Flags.setSExt();
10976       if (Arg.hasAttribute(Attribute::InReg)) {
10977         // If we are using vectorcall calling convention, a structure that is
10978         // passed InReg - is surely an HVA
10979         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
10980             isa<StructType>(Arg.getType())) {
10981           // The first value of a structure is marked
10982           if (0 == Value)
10983             Flags.setHvaStart();
10984           Flags.setHva();
10985         }
10986         // Set InReg Flag
10987         Flags.setInReg();
10988       }
10989       if (Arg.hasAttribute(Attribute::StructRet))
10990         Flags.setSRet();
10991       if (Arg.hasAttribute(Attribute::SwiftSelf))
10992         Flags.setSwiftSelf();
10993       if (Arg.hasAttribute(Attribute::SwiftAsync))
10994         Flags.setSwiftAsync();
10995       if (Arg.hasAttribute(Attribute::SwiftError))
10996         Flags.setSwiftError();
10997       if (Arg.hasAttribute(Attribute::ByVal))
10998         Flags.setByVal();
10999       if (Arg.hasAttribute(Attribute::ByRef))
11000         Flags.setByRef();
11001       if (Arg.hasAttribute(Attribute::InAlloca)) {
11002         Flags.setInAlloca();
11003         // Set the byval flag for CCAssignFn callbacks that don't know about
11004         // inalloca.  This way we can know how many bytes we should've allocated
11005         // and how many bytes a callee cleanup function will pop.  If we port
11006         // inalloca to more targets, we'll have to add custom inalloca handling
11007         // in the various CC lowering callbacks.
11008         Flags.setByVal();
11009       }
11010       if (Arg.hasAttribute(Attribute::Preallocated)) {
11011         Flags.setPreallocated();
11012         // Set the byval flag for CCAssignFn callbacks that don't know about
11013         // preallocated.  This way we can know how many bytes we should've
11014         // allocated and how many bytes a callee cleanup function will pop.  If
11015         // we port preallocated to more targets, we'll have to add custom
11016         // preallocated handling in the various CC lowering callbacks.
11017         Flags.setByVal();
11018       }
11019 
11020       // Certain targets (such as MIPS), may have a different ABI alignment
11021       // for a type depending on the context. Give the target a chance to
11022       // specify the alignment it wants.
11023       const Align OriginalAlignment(
11024           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
11025       Flags.setOrigAlign(OriginalAlignment);
11026 
11027       Align MemAlign;
11028       Type *ArgMemTy = nullptr;
11029       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
11030           Flags.isByRef()) {
11031         if (!ArgMemTy)
11032           ArgMemTy = Arg.getPointeeInMemoryValueType();
11033 
11034         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
11035 
11036         // For in-memory arguments, size and alignment should be passed from FE.
11037         // BE will guess if this info is not there but there are cases it cannot
11038         // get right.
11039         if (auto ParamAlign = Arg.getParamStackAlign())
11040           MemAlign = *ParamAlign;
11041         else if ((ParamAlign = Arg.getParamAlign()))
11042           MemAlign = *ParamAlign;
11043         else
11044           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
11045         if (Flags.isByRef())
11046           Flags.setByRefSize(MemSize);
11047         else
11048           Flags.setByValSize(MemSize);
11049       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
11050         MemAlign = *ParamAlign;
11051       } else {
11052         MemAlign = OriginalAlignment;
11053       }
11054       Flags.setMemAlign(MemAlign);
11055 
11056       if (Arg.hasAttribute(Attribute::Nest))
11057         Flags.setNest();
11058       if (NeedsRegBlock)
11059         Flags.setInConsecutiveRegs();
11060       if (ArgCopyElisionCandidates.count(&Arg))
11061         Flags.setCopyElisionCandidate();
11062       if (Arg.hasAttribute(Attribute::Returned))
11063         Flags.setReturned();
11064 
11065       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
11066           *CurDAG->getContext(), F.getCallingConv(), VT);
11067       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
11068           *CurDAG->getContext(), F.getCallingConv(), VT);
11069       for (unsigned i = 0; i != NumRegs; ++i) {
11070         // For scalable vectors, use the minimum size; individual targets
11071         // are responsible for handling scalable vector arguments and
11072         // return values.
11073         ISD::InputArg MyFlags(
11074             Flags, RegisterVT, VT, isArgValueUsed, ArgNo,
11075             PartBase + i * RegisterVT.getStoreSize().getKnownMinValue());
11076         if (NumRegs > 1 && i == 0)
11077           MyFlags.Flags.setSplit();
11078         // if it isn't first piece, alignment must be 1
11079         else if (i > 0) {
11080           MyFlags.Flags.setOrigAlign(Align(1));
11081           if (i == NumRegs - 1)
11082             MyFlags.Flags.setSplitEnd();
11083         }
11084         Ins.push_back(MyFlags);
11085       }
11086       if (NeedsRegBlock && Value == NumValues - 1)
11087         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
11088       PartBase += VT.getStoreSize().getKnownMinValue();
11089     }
11090   }
11091 
11092   // Call the target to set up the argument values.
11093   SmallVector<SDValue, 8> InVals;
11094   SDValue NewRoot = TLI->LowerFormalArguments(
11095       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
11096 
11097   // Verify that the target's LowerFormalArguments behaved as expected.
11098   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
11099          "LowerFormalArguments didn't return a valid chain!");
11100   assert(InVals.size() == Ins.size() &&
11101          "LowerFormalArguments didn't emit the correct number of values!");
11102   LLVM_DEBUG({
11103     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
11104       assert(InVals[i].getNode() &&
11105              "LowerFormalArguments emitted a null value!");
11106       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
11107              "LowerFormalArguments emitted a value with the wrong type!");
11108     }
11109   });
11110 
11111   // Update the DAG with the new chain value resulting from argument lowering.
11112   DAG.setRoot(NewRoot);
11113 
11114   // Set up the argument values.
11115   unsigned i = 0;
11116   if (!FuncInfo->CanLowerReturn) {
11117     // Create a virtual register for the sret pointer, and put in a copy
11118     // from the sret argument into it.
11119     SmallVector<EVT, 1> ValueVTs;
11120     ComputeValueVTs(*TLI, DAG.getDataLayout(),
11121                     PointerType::get(F.getContext(),
11122                                      DAG.getDataLayout().getAllocaAddrSpace()),
11123                     ValueVTs);
11124     MVT VT = ValueVTs[0].getSimpleVT();
11125     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
11126     std::optional<ISD::NodeType> AssertOp;
11127     SDValue ArgValue =
11128         getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, nullptr, NewRoot,
11129                          F.getCallingConv(), AssertOp);
11130 
11131     MachineFunction& MF = SDB->DAG.getMachineFunction();
11132     MachineRegisterInfo& RegInfo = MF.getRegInfo();
11133     Register SRetReg =
11134         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
11135     FuncInfo->DemoteRegister = SRetReg;
11136     NewRoot =
11137         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
11138     DAG.setRoot(NewRoot);
11139 
11140     // i indexes lowered arguments.  Bump it past the hidden sret argument.
11141     ++i;
11142   }
11143 
11144   SmallVector<SDValue, 4> Chains;
11145   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
11146   for (const Argument &Arg : F.args()) {
11147     SmallVector<SDValue, 4> ArgValues;
11148     SmallVector<EVT, 4> ValueVTs;
11149     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
11150     unsigned NumValues = ValueVTs.size();
11151     if (NumValues == 0)
11152       continue;
11153 
11154     bool ArgHasUses = !Arg.use_empty();
11155 
11156     // Elide the copying store if the target loaded this argument from a
11157     // suitable fixed stack object.
11158     if (Ins[i].Flags.isCopyElisionCandidate()) {
11159       unsigned NumParts = 0;
11160       for (EVT VT : ValueVTs)
11161         NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(),
11162                                                        F.getCallingConv(), VT);
11163 
11164       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
11165                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
11166                              ArrayRef(&InVals[i], NumParts), ArgHasUses);
11167     }
11168 
11169     // If this argument is unused then remember its value. It is used to generate
11170     // debugging information.
11171     bool isSwiftErrorArg =
11172         TLI->supportSwiftError() &&
11173         Arg.hasAttribute(Attribute::SwiftError);
11174     if (!ArgHasUses && !isSwiftErrorArg) {
11175       SDB->setUnusedArgValue(&Arg, InVals[i]);
11176 
11177       // Also remember any frame index for use in FastISel.
11178       if (FrameIndexSDNode *FI =
11179           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
11180         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11181     }
11182 
11183     for (unsigned Val = 0; Val != NumValues; ++Val) {
11184       EVT VT = ValueVTs[Val];
11185       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
11186                                                       F.getCallingConv(), VT);
11187       unsigned NumParts = TLI->getNumRegistersForCallingConv(
11188           *CurDAG->getContext(), F.getCallingConv(), VT);
11189 
11190       // Even an apparent 'unused' swifterror argument needs to be returned. So
11191       // we do generate a copy for it that can be used on return from the
11192       // function.
11193       if (ArgHasUses || isSwiftErrorArg) {
11194         std::optional<ISD::NodeType> AssertOp;
11195         if (Arg.hasAttribute(Attribute::SExt))
11196           AssertOp = ISD::AssertSext;
11197         else if (Arg.hasAttribute(Attribute::ZExt))
11198           AssertOp = ISD::AssertZext;
11199 
11200         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
11201                                              PartVT, VT, nullptr, NewRoot,
11202                                              F.getCallingConv(), AssertOp));
11203       }
11204 
11205       i += NumParts;
11206     }
11207 
11208     // We don't need to do anything else for unused arguments.
11209     if (ArgValues.empty())
11210       continue;
11211 
11212     // Note down frame index.
11213     if (FrameIndexSDNode *FI =
11214         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
11215       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11216 
11217     SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues),
11218                                      SDB->getCurSDLoc());
11219 
11220     SDB->setValue(&Arg, Res);
11221     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
11222       // We want to associate the argument with the frame index, among
11223       // involved operands, that correspond to the lowest address. The
11224       // getCopyFromParts function, called earlier, is swapping the order of
11225       // the operands to BUILD_PAIR depending on endianness. The result of
11226       // that swapping is that the least significant bits of the argument will
11227       // be in the first operand of the BUILD_PAIR node, and the most
11228       // significant bits will be in the second operand.
11229       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
11230       if (LoadSDNode *LNode =
11231           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
11232         if (FrameIndexSDNode *FI =
11233             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
11234           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11235     }
11236 
11237     // Analyses past this point are naive and don't expect an assertion.
11238     if (Res.getOpcode() == ISD::AssertZext)
11239       Res = Res.getOperand(0);
11240 
11241     // Update the SwiftErrorVRegDefMap.
11242     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
11243       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11244       if (Register::isVirtualRegister(Reg))
11245         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
11246                                    Reg);
11247     }
11248 
11249     // If this argument is live outside of the entry block, insert a copy from
11250     // wherever we got it to the vreg that other BB's will reference it as.
11251     if (Res.getOpcode() == ISD::CopyFromReg) {
11252       // If we can, though, try to skip creating an unnecessary vreg.
11253       // FIXME: This isn't very clean... it would be nice to make this more
11254       // general.
11255       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11256       if (Register::isVirtualRegister(Reg)) {
11257         FuncInfo->ValueMap[&Arg] = Reg;
11258         continue;
11259       }
11260     }
11261     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
11262       FuncInfo->InitializeRegForValue(&Arg);
11263       SDB->CopyToExportRegsIfNeeded(&Arg);
11264     }
11265   }
11266 
11267   if (!Chains.empty()) {
11268     Chains.push_back(NewRoot);
11269     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
11270   }
11271 
11272   DAG.setRoot(NewRoot);
11273 
11274   assert(i == InVals.size() && "Argument register count mismatch!");
11275 
11276   // If any argument copy elisions occurred and we have debug info, update the
11277   // stale frame indices used in the dbg.declare variable info table.
11278   if (!ArgCopyElisionFrameIndexMap.empty()) {
11279     for (MachineFunction::VariableDbgInfo &VI :
11280          MF->getInStackSlotVariableDbgInfo()) {
11281       auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot());
11282       if (I != ArgCopyElisionFrameIndexMap.end())
11283         VI.updateStackSlot(I->second);
11284     }
11285   }
11286 
11287   // Finally, if the target has anything special to do, allow it to do so.
11288   emitFunctionEntryCode();
11289 }
11290 
11291 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
11292 /// ensure constants are generated when needed.  Remember the virtual registers
11293 /// that need to be added to the Machine PHI nodes as input.  We cannot just
11294 /// directly add them, because expansion might result in multiple MBB's for one
11295 /// BB.  As such, the start of the BB might correspond to a different MBB than
11296 /// the end.
11297 void
11298 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
11299   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11300 
11301   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
11302 
11303   // Check PHI nodes in successors that expect a value to be available from this
11304   // block.
11305   for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
11306     if (!isa<PHINode>(SuccBB->begin())) continue;
11307     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
11308 
11309     // If this terminator has multiple identical successors (common for
11310     // switches), only handle each succ once.
11311     if (!SuccsHandled.insert(SuccMBB).second)
11312       continue;
11313 
11314     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
11315 
11316     // At this point we know that there is a 1-1 correspondence between LLVM PHI
11317     // nodes and Machine PHI nodes, but the incoming operands have not been
11318     // emitted yet.
11319     for (const PHINode &PN : SuccBB->phis()) {
11320       // Ignore dead phi's.
11321       if (PN.use_empty())
11322         continue;
11323 
11324       // Skip empty types
11325       if (PN.getType()->isEmptyTy())
11326         continue;
11327 
11328       unsigned Reg;
11329       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
11330 
11331       if (const auto *C = dyn_cast<Constant>(PHIOp)) {
11332         unsigned &RegOut = ConstantsOut[C];
11333         if (RegOut == 0) {
11334           RegOut = FuncInfo.CreateRegs(C);
11335           // We need to zero/sign extend ConstantInt phi operands to match
11336           // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
11337           ISD::NodeType ExtendType = ISD::ANY_EXTEND;
11338           if (auto *CI = dyn_cast<ConstantInt>(C))
11339             ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
11340                                                     : ISD::ZERO_EXTEND;
11341           CopyValueToVirtualRegister(C, RegOut, ExtendType);
11342         }
11343         Reg = RegOut;
11344       } else {
11345         DenseMap<const Value *, Register>::iterator I =
11346           FuncInfo.ValueMap.find(PHIOp);
11347         if (I != FuncInfo.ValueMap.end())
11348           Reg = I->second;
11349         else {
11350           assert(isa<AllocaInst>(PHIOp) &&
11351                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
11352                  "Didn't codegen value into a register!??");
11353           Reg = FuncInfo.CreateRegs(PHIOp);
11354           CopyValueToVirtualRegister(PHIOp, Reg);
11355         }
11356       }
11357 
11358       // Remember that this register needs to added to the machine PHI node as
11359       // the input for this MBB.
11360       SmallVector<EVT, 4> ValueVTs;
11361       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
11362       for (EVT VT : ValueVTs) {
11363         const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
11364         for (unsigned i = 0; i != NumRegisters; ++i)
11365           FuncInfo.PHINodesToUpdate.push_back(
11366               std::make_pair(&*MBBI++, Reg + i));
11367         Reg += NumRegisters;
11368       }
11369     }
11370   }
11371 
11372   ConstantsOut.clear();
11373 }
11374 
11375 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
11376   MachineFunction::iterator I(MBB);
11377   if (++I == FuncInfo.MF->end())
11378     return nullptr;
11379   return &*I;
11380 }
11381 
11382 /// During lowering new call nodes can be created (such as memset, etc.).
11383 /// Those will become new roots of the current DAG, but complications arise
11384 /// when they are tail calls. In such cases, the call lowering will update
11385 /// the root, but the builder still needs to know that a tail call has been
11386 /// lowered in order to avoid generating an additional return.
11387 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
11388   // If the node is null, we do have a tail call.
11389   if (MaybeTC.getNode() != nullptr)
11390     DAG.setRoot(MaybeTC);
11391   else
11392     HasTailCall = true;
11393 }
11394 
11395 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
11396                                         MachineBasicBlock *SwitchMBB,
11397                                         MachineBasicBlock *DefaultMBB) {
11398   MachineFunction *CurMF = FuncInfo.MF;
11399   MachineBasicBlock *NextMBB = nullptr;
11400   MachineFunction::iterator BBI(W.MBB);
11401   if (++BBI != FuncInfo.MF->end())
11402     NextMBB = &*BBI;
11403 
11404   unsigned Size = W.LastCluster - W.FirstCluster + 1;
11405 
11406   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11407 
11408   if (Size == 2 && W.MBB == SwitchMBB) {
11409     // If any two of the cases has the same destination, and if one value
11410     // is the same as the other, but has one bit unset that the other has set,
11411     // use bit manipulation to do two compares at once.  For example:
11412     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
11413     // TODO: This could be extended to merge any 2 cases in switches with 3
11414     // cases.
11415     // TODO: Handle cases where W.CaseBB != SwitchBB.
11416     CaseCluster &Small = *W.FirstCluster;
11417     CaseCluster &Big = *W.LastCluster;
11418 
11419     if (Small.Low == Small.High && Big.Low == Big.High &&
11420         Small.MBB == Big.MBB) {
11421       const APInt &SmallValue = Small.Low->getValue();
11422       const APInt &BigValue = Big.Low->getValue();
11423 
11424       // Check that there is only one bit different.
11425       APInt CommonBit = BigValue ^ SmallValue;
11426       if (CommonBit.isPowerOf2()) {
11427         SDValue CondLHS = getValue(Cond);
11428         EVT VT = CondLHS.getValueType();
11429         SDLoc DL = getCurSDLoc();
11430 
11431         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
11432                                  DAG.getConstant(CommonBit, DL, VT));
11433         SDValue Cond = DAG.getSetCC(
11434             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
11435             ISD::SETEQ);
11436 
11437         // Update successor info.
11438         // Both Small and Big will jump to Small.BB, so we sum up the
11439         // probabilities.
11440         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
11441         if (BPI)
11442           addSuccessorWithProb(
11443               SwitchMBB, DefaultMBB,
11444               // The default destination is the first successor in IR.
11445               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
11446         else
11447           addSuccessorWithProb(SwitchMBB, DefaultMBB);
11448 
11449         // Insert the true branch.
11450         SDValue BrCond =
11451             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
11452                         DAG.getBasicBlock(Small.MBB));
11453         // Insert the false branch.
11454         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
11455                              DAG.getBasicBlock(DefaultMBB));
11456 
11457         DAG.setRoot(BrCond);
11458         return;
11459       }
11460     }
11461   }
11462 
11463   if (TM.getOptLevel() != CodeGenOptLevel::None) {
11464     // Here, we order cases by probability so the most likely case will be
11465     // checked first. However, two clusters can have the same probability in
11466     // which case their relative ordering is non-deterministic. So we use Low
11467     // as a tie-breaker as clusters are guaranteed to never overlap.
11468     llvm::sort(W.FirstCluster, W.LastCluster + 1,
11469                [](const CaseCluster &a, const CaseCluster &b) {
11470       return a.Prob != b.Prob ?
11471              a.Prob > b.Prob :
11472              a.Low->getValue().slt(b.Low->getValue());
11473     });
11474 
11475     // Rearrange the case blocks so that the last one falls through if possible
11476     // without changing the order of probabilities.
11477     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
11478       --I;
11479       if (I->Prob > W.LastCluster->Prob)
11480         break;
11481       if (I->Kind == CC_Range && I->MBB == NextMBB) {
11482         std::swap(*I, *W.LastCluster);
11483         break;
11484       }
11485     }
11486   }
11487 
11488   // Compute total probability.
11489   BranchProbability DefaultProb = W.DefaultProb;
11490   BranchProbability UnhandledProbs = DefaultProb;
11491   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
11492     UnhandledProbs += I->Prob;
11493 
11494   MachineBasicBlock *CurMBB = W.MBB;
11495   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
11496     bool FallthroughUnreachable = false;
11497     MachineBasicBlock *Fallthrough;
11498     if (I == W.LastCluster) {
11499       // For the last cluster, fall through to the default destination.
11500       Fallthrough = DefaultMBB;
11501       FallthroughUnreachable = isa<UnreachableInst>(
11502           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
11503     } else {
11504       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
11505       CurMF->insert(BBI, Fallthrough);
11506       // Put Cond in a virtual register to make it available from the new blocks.
11507       ExportFromCurrentBlock(Cond);
11508     }
11509     UnhandledProbs -= I->Prob;
11510 
11511     switch (I->Kind) {
11512       case CC_JumpTable: {
11513         // FIXME: Optimize away range check based on pivot comparisons.
11514         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
11515         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
11516 
11517         // The jump block hasn't been inserted yet; insert it here.
11518         MachineBasicBlock *JumpMBB = JT->MBB;
11519         CurMF->insert(BBI, JumpMBB);
11520 
11521         auto JumpProb = I->Prob;
11522         auto FallthroughProb = UnhandledProbs;
11523 
11524         // If the default statement is a target of the jump table, we evenly
11525         // distribute the default probability to successors of CurMBB. Also
11526         // update the probability on the edge from JumpMBB to Fallthrough.
11527         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
11528                                               SE = JumpMBB->succ_end();
11529              SI != SE; ++SI) {
11530           if (*SI == DefaultMBB) {
11531             JumpProb += DefaultProb / 2;
11532             FallthroughProb -= DefaultProb / 2;
11533             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
11534             JumpMBB->normalizeSuccProbs();
11535             break;
11536           }
11537         }
11538 
11539         // If the default clause is unreachable, propagate that knowledge into
11540         // JTH->FallthroughUnreachable which will use it to suppress the range
11541         // check.
11542         //
11543         // However, don't do this if we're doing branch target enforcement,
11544         // because a table branch _without_ a range check can be a tempting JOP
11545         // gadget - out-of-bounds inputs that are impossible in correct
11546         // execution become possible again if an attacker can influence the
11547         // control flow. So if an attacker doesn't already have a BTI bypass
11548         // available, we don't want them to be able to get one out of this
11549         // table branch.
11550         if (FallthroughUnreachable) {
11551           Function &CurFunc = CurMF->getFunction();
11552           bool HasBranchTargetEnforcement = false;
11553           if (CurFunc.hasFnAttribute("branch-target-enforcement")) {
11554             HasBranchTargetEnforcement =
11555                 CurFunc.getFnAttribute("branch-target-enforcement")
11556                     .getValueAsBool();
11557           } else {
11558             HasBranchTargetEnforcement =
11559                 CurMF->getMMI().getModule()->getModuleFlag(
11560                     "branch-target-enforcement");
11561           }
11562           if (!HasBranchTargetEnforcement)
11563             JTH->FallthroughUnreachable = true;
11564         }
11565 
11566         if (!JTH->FallthroughUnreachable)
11567           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
11568         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
11569         CurMBB->normalizeSuccProbs();
11570 
11571         // The jump table header will be inserted in our current block, do the
11572         // range check, and fall through to our fallthrough block.
11573         JTH->HeaderBB = CurMBB;
11574         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
11575 
11576         // If we're in the right place, emit the jump table header right now.
11577         if (CurMBB == SwitchMBB) {
11578           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
11579           JTH->Emitted = true;
11580         }
11581         break;
11582       }
11583       case CC_BitTests: {
11584         // FIXME: Optimize away range check based on pivot comparisons.
11585         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
11586 
11587         // The bit test blocks haven't been inserted yet; insert them here.
11588         for (BitTestCase &BTC : BTB->Cases)
11589           CurMF->insert(BBI, BTC.ThisBB);
11590 
11591         // Fill in fields of the BitTestBlock.
11592         BTB->Parent = CurMBB;
11593         BTB->Default = Fallthrough;
11594 
11595         BTB->DefaultProb = UnhandledProbs;
11596         // If the cases in bit test don't form a contiguous range, we evenly
11597         // distribute the probability on the edge to Fallthrough to two
11598         // successors of CurMBB.
11599         if (!BTB->ContiguousRange) {
11600           BTB->Prob += DefaultProb / 2;
11601           BTB->DefaultProb -= DefaultProb / 2;
11602         }
11603 
11604         if (FallthroughUnreachable)
11605           BTB->FallthroughUnreachable = true;
11606 
11607         // If we're in the right place, emit the bit test header right now.
11608         if (CurMBB == SwitchMBB) {
11609           visitBitTestHeader(*BTB, SwitchMBB);
11610           BTB->Emitted = true;
11611         }
11612         break;
11613       }
11614       case CC_Range: {
11615         const Value *RHS, *LHS, *MHS;
11616         ISD::CondCode CC;
11617         if (I->Low == I->High) {
11618           // Check Cond == I->Low.
11619           CC = ISD::SETEQ;
11620           LHS = Cond;
11621           RHS=I->Low;
11622           MHS = nullptr;
11623         } else {
11624           // Check I->Low <= Cond <= I->High.
11625           CC = ISD::SETLE;
11626           LHS = I->Low;
11627           MHS = Cond;
11628           RHS = I->High;
11629         }
11630 
11631         // If Fallthrough is unreachable, fold away the comparison.
11632         if (FallthroughUnreachable)
11633           CC = ISD::SETTRUE;
11634 
11635         // The false probability is the sum of all unhandled cases.
11636         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
11637                      getCurSDLoc(), I->Prob, UnhandledProbs);
11638 
11639         if (CurMBB == SwitchMBB)
11640           visitSwitchCase(CB, SwitchMBB);
11641         else
11642           SL->SwitchCases.push_back(CB);
11643 
11644         break;
11645       }
11646     }
11647     CurMBB = Fallthrough;
11648   }
11649 }
11650 
11651 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
11652                                         const SwitchWorkListItem &W,
11653                                         Value *Cond,
11654                                         MachineBasicBlock *SwitchMBB) {
11655   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
11656          "Clusters not sorted?");
11657   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
11658 
11659   auto [LastLeft, FirstRight, LeftProb, RightProb] =
11660       SL->computeSplitWorkItemInfo(W);
11661 
11662   // Use the first element on the right as pivot since we will make less-than
11663   // comparisons against it.
11664   CaseClusterIt PivotCluster = FirstRight;
11665   assert(PivotCluster > W.FirstCluster);
11666   assert(PivotCluster <= W.LastCluster);
11667 
11668   CaseClusterIt FirstLeft = W.FirstCluster;
11669   CaseClusterIt LastRight = W.LastCluster;
11670 
11671   const ConstantInt *Pivot = PivotCluster->Low;
11672 
11673   // New blocks will be inserted immediately after the current one.
11674   MachineFunction::iterator BBI(W.MBB);
11675   ++BBI;
11676 
11677   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
11678   // we can branch to its destination directly if it's squeezed exactly in
11679   // between the known lower bound and Pivot - 1.
11680   MachineBasicBlock *LeftMBB;
11681   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
11682       FirstLeft->Low == W.GE &&
11683       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
11684     LeftMBB = FirstLeft->MBB;
11685   } else {
11686     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11687     FuncInfo.MF->insert(BBI, LeftMBB);
11688     WorkList.push_back(
11689         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
11690     // Put Cond in a virtual register to make it available from the new blocks.
11691     ExportFromCurrentBlock(Cond);
11692   }
11693 
11694   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
11695   // single cluster, RHS.Low == Pivot, and we can branch to its destination
11696   // directly if RHS.High equals the current upper bound.
11697   MachineBasicBlock *RightMBB;
11698   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
11699       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
11700     RightMBB = FirstRight->MBB;
11701   } else {
11702     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11703     FuncInfo.MF->insert(BBI, RightMBB);
11704     WorkList.push_back(
11705         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
11706     // Put Cond in a virtual register to make it available from the new blocks.
11707     ExportFromCurrentBlock(Cond);
11708   }
11709 
11710   // Create the CaseBlock record that will be used to lower the branch.
11711   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
11712                getCurSDLoc(), LeftProb, RightProb);
11713 
11714   if (W.MBB == SwitchMBB)
11715     visitSwitchCase(CB, SwitchMBB);
11716   else
11717     SL->SwitchCases.push_back(CB);
11718 }
11719 
11720 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
11721 // from the swith statement.
11722 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
11723                                             BranchProbability PeeledCaseProb) {
11724   if (PeeledCaseProb == BranchProbability::getOne())
11725     return BranchProbability::getZero();
11726   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
11727 
11728   uint32_t Numerator = CaseProb.getNumerator();
11729   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
11730   return BranchProbability(Numerator, std::max(Numerator, Denominator));
11731 }
11732 
11733 // Try to peel the top probability case if it exceeds the threshold.
11734 // Return current MachineBasicBlock for the switch statement if the peeling
11735 // does not occur.
11736 // If the peeling is performed, return the newly created MachineBasicBlock
11737 // for the peeled switch statement. Also update Clusters to remove the peeled
11738 // case. PeeledCaseProb is the BranchProbability for the peeled case.
11739 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
11740     const SwitchInst &SI, CaseClusterVector &Clusters,
11741     BranchProbability &PeeledCaseProb) {
11742   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11743   // Don't perform if there is only one cluster or optimizing for size.
11744   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
11745       TM.getOptLevel() == CodeGenOptLevel::None ||
11746       SwitchMBB->getParent()->getFunction().hasMinSize())
11747     return SwitchMBB;
11748 
11749   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
11750   unsigned PeeledCaseIndex = 0;
11751   bool SwitchPeeled = false;
11752   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
11753     CaseCluster &CC = Clusters[Index];
11754     if (CC.Prob < TopCaseProb)
11755       continue;
11756     TopCaseProb = CC.Prob;
11757     PeeledCaseIndex = Index;
11758     SwitchPeeled = true;
11759   }
11760   if (!SwitchPeeled)
11761     return SwitchMBB;
11762 
11763   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
11764                     << TopCaseProb << "\n");
11765 
11766   // Record the MBB for the peeled switch statement.
11767   MachineFunction::iterator BBI(SwitchMBB);
11768   ++BBI;
11769   MachineBasicBlock *PeeledSwitchMBB =
11770       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
11771   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
11772 
11773   ExportFromCurrentBlock(SI.getCondition());
11774   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
11775   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
11776                           nullptr,   nullptr,      TopCaseProb.getCompl()};
11777   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
11778 
11779   Clusters.erase(PeeledCaseIt);
11780   for (CaseCluster &CC : Clusters) {
11781     LLVM_DEBUG(
11782         dbgs() << "Scale the probablity for one cluster, before scaling: "
11783                << CC.Prob << "\n");
11784     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
11785     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
11786   }
11787   PeeledCaseProb = TopCaseProb;
11788   return PeeledSwitchMBB;
11789 }
11790 
11791 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
11792   // Extract cases from the switch.
11793   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11794   CaseClusterVector Clusters;
11795   Clusters.reserve(SI.getNumCases());
11796   for (auto I : SI.cases()) {
11797     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
11798     const ConstantInt *CaseVal = I.getCaseValue();
11799     BranchProbability Prob =
11800         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
11801             : BranchProbability(1, SI.getNumCases() + 1);
11802     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
11803   }
11804 
11805   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
11806 
11807   // Cluster adjacent cases with the same destination. We do this at all
11808   // optimization levels because it's cheap to do and will make codegen faster
11809   // if there are many clusters.
11810   sortAndRangeify(Clusters);
11811 
11812   // The branch probablity of the peeled case.
11813   BranchProbability PeeledCaseProb = BranchProbability::getZero();
11814   MachineBasicBlock *PeeledSwitchMBB =
11815       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
11816 
11817   // If there is only the default destination, jump there directly.
11818   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11819   if (Clusters.empty()) {
11820     assert(PeeledSwitchMBB == SwitchMBB);
11821     SwitchMBB->addSuccessor(DefaultMBB);
11822     if (DefaultMBB != NextBlock(SwitchMBB)) {
11823       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
11824                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
11825     }
11826     return;
11827   }
11828 
11829   SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(),
11830                      DAG.getBFI());
11831   SL->findBitTestClusters(Clusters, &SI);
11832 
11833   LLVM_DEBUG({
11834     dbgs() << "Case clusters: ";
11835     for (const CaseCluster &C : Clusters) {
11836       if (C.Kind == CC_JumpTable)
11837         dbgs() << "JT:";
11838       if (C.Kind == CC_BitTests)
11839         dbgs() << "BT:";
11840 
11841       C.Low->getValue().print(dbgs(), true);
11842       if (C.Low != C.High) {
11843         dbgs() << '-';
11844         C.High->getValue().print(dbgs(), true);
11845       }
11846       dbgs() << ' ';
11847     }
11848     dbgs() << '\n';
11849   });
11850 
11851   assert(!Clusters.empty());
11852   SwitchWorkList WorkList;
11853   CaseClusterIt First = Clusters.begin();
11854   CaseClusterIt Last = Clusters.end() - 1;
11855   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
11856   // Scale the branchprobability for DefaultMBB if the peel occurs and
11857   // DefaultMBB is not replaced.
11858   if (PeeledCaseProb != BranchProbability::getZero() &&
11859       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
11860     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
11861   WorkList.push_back(
11862       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
11863 
11864   while (!WorkList.empty()) {
11865     SwitchWorkListItem W = WorkList.pop_back_val();
11866     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
11867 
11868     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None &&
11869         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
11870       // For optimized builds, lower large range as a balanced binary tree.
11871       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
11872       continue;
11873     }
11874 
11875     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
11876   }
11877 }
11878 
11879 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
11880   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11881   auto DL = getCurSDLoc();
11882   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11883   setValue(&I, DAG.getStepVector(DL, ResultVT));
11884 }
11885 
11886 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
11887   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11888   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11889 
11890   SDLoc DL = getCurSDLoc();
11891   SDValue V = getValue(I.getOperand(0));
11892   assert(VT == V.getValueType() && "Malformed vector.reverse!");
11893 
11894   if (VT.isScalableVector()) {
11895     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
11896     return;
11897   }
11898 
11899   // Use VECTOR_SHUFFLE for the fixed-length vector
11900   // to maintain existing behavior.
11901   SmallVector<int, 8> Mask;
11902   unsigned NumElts = VT.getVectorMinNumElements();
11903   for (unsigned i = 0; i != NumElts; ++i)
11904     Mask.push_back(NumElts - 1 - i);
11905 
11906   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
11907 }
11908 
11909 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) {
11910   auto DL = getCurSDLoc();
11911   SDValue InVec = getValue(I.getOperand(0));
11912   EVT OutVT =
11913       InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
11914 
11915   unsigned OutNumElts = OutVT.getVectorMinNumElements();
11916 
11917   // ISD Node needs the input vectors split into two equal parts
11918   SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
11919                            DAG.getVectorIdxConstant(0, DL));
11920   SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
11921                            DAG.getVectorIdxConstant(OutNumElts, DL));
11922 
11923   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
11924   // legalisation and combines.
11925   if (OutVT.isFixedLengthVector()) {
11926     SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
11927                                         createStrideMask(0, 2, OutNumElts));
11928     SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
11929                                        createStrideMask(1, 2, OutNumElts));
11930     SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc());
11931     setValue(&I, Res);
11932     return;
11933   }
11934 
11935   SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL,
11936                             DAG.getVTList(OutVT, OutVT), Lo, Hi);
11937   setValue(&I, Res);
11938 }
11939 
11940 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) {
11941   auto DL = getCurSDLoc();
11942   EVT InVT = getValue(I.getOperand(0)).getValueType();
11943   SDValue InVec0 = getValue(I.getOperand(0));
11944   SDValue InVec1 = getValue(I.getOperand(1));
11945   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11946   EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11947 
11948   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
11949   // legalisation and combines.
11950   if (OutVT.isFixedLengthVector()) {
11951     unsigned NumElts = InVT.getVectorMinNumElements();
11952     SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1);
11953     setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT),
11954                                       createInterleaveMask(NumElts, 2)));
11955     return;
11956   }
11957 
11958   SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL,
11959                             DAG.getVTList(InVT, InVT), InVec0, InVec1);
11960   Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0),
11961                     Res.getValue(1));
11962   setValue(&I, Res);
11963 }
11964 
11965 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
11966   SmallVector<EVT, 4> ValueVTs;
11967   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
11968                   ValueVTs);
11969   unsigned NumValues = ValueVTs.size();
11970   if (NumValues == 0) return;
11971 
11972   SmallVector<SDValue, 4> Values(NumValues);
11973   SDValue Op = getValue(I.getOperand(0));
11974 
11975   for (unsigned i = 0; i != NumValues; ++i)
11976     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
11977                             SDValue(Op.getNode(), Op.getResNo() + i));
11978 
11979   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
11980                            DAG.getVTList(ValueVTs), Values));
11981 }
11982 
11983 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
11984   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11985   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11986 
11987   SDLoc DL = getCurSDLoc();
11988   SDValue V1 = getValue(I.getOperand(0));
11989   SDValue V2 = getValue(I.getOperand(1));
11990   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
11991 
11992   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
11993   if (VT.isScalableVector()) {
11994     MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
11995     setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
11996                              DAG.getConstant(Imm, DL, IdxVT)));
11997     return;
11998   }
11999 
12000   unsigned NumElts = VT.getVectorNumElements();
12001 
12002   uint64_t Idx = (NumElts + Imm) % NumElts;
12003 
12004   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
12005   SmallVector<int, 8> Mask;
12006   for (unsigned i = 0; i < NumElts; ++i)
12007     Mask.push_back(Idx + i);
12008   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
12009 }
12010 
12011 // Consider the following MIR after SelectionDAG, which produces output in
12012 // phyregs in the first case or virtregs in the second case.
12013 //
12014 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx
12015 // %5:gr32 = COPY $ebx
12016 // %6:gr32 = COPY $edx
12017 // %1:gr32 = COPY %6:gr32
12018 // %0:gr32 = COPY %5:gr32
12019 //
12020 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32
12021 // %1:gr32 = COPY %6:gr32
12022 // %0:gr32 = COPY %5:gr32
12023 //
12024 // Given %0, we'd like to return $ebx in the first case and %5 in the second.
12025 // Given %1, we'd like to return $edx in the first case and %6 in the second.
12026 //
12027 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap
12028 // to a single virtreg (such as %0). The remaining outputs monotonically
12029 // increase in virtreg number from there. If a callbr has no outputs, then it
12030 // should not have a corresponding callbr landingpad; in fact, the callbr
12031 // landingpad would not even be able to refer to such a callbr.
12032 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) {
12033   MachineInstr *MI = MRI.def_begin(Reg)->getParent();
12034   // There is definitely at least one copy.
12035   assert(MI->getOpcode() == TargetOpcode::COPY &&
12036          "start of copy chain MUST be COPY");
12037   Reg = MI->getOperand(1).getReg();
12038   MI = MRI.def_begin(Reg)->getParent();
12039   // There may be an optional second copy.
12040   if (MI->getOpcode() == TargetOpcode::COPY) {
12041     assert(Reg.isVirtual() && "expected COPY of virtual register");
12042     Reg = MI->getOperand(1).getReg();
12043     assert(Reg.isPhysical() && "expected COPY of physical register");
12044     MI = MRI.def_begin(Reg)->getParent();
12045   }
12046   // The start of the chain must be an INLINEASM_BR.
12047   assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR &&
12048          "end of copy chain MUST be INLINEASM_BR");
12049   return Reg;
12050 }
12051 
12052 // We must do this walk rather than the simpler
12053 //   setValue(&I, getCopyFromRegs(CBR, CBR->getType()));
12054 // otherwise we will end up with copies of virtregs only valid along direct
12055 // edges.
12056 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) {
12057   SmallVector<EVT, 8> ResultVTs;
12058   SmallVector<SDValue, 8> ResultValues;
12059   const auto *CBR =
12060       cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator());
12061 
12062   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12063   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
12064   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
12065 
12066   unsigned InitialDef = FuncInfo.ValueMap[CBR];
12067   SDValue Chain = DAG.getRoot();
12068 
12069   // Re-parse the asm constraints string.
12070   TargetLowering::AsmOperandInfoVector TargetConstraints =
12071       TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR);
12072   for (auto &T : TargetConstraints) {
12073     SDISelAsmOperandInfo OpInfo(T);
12074     if (OpInfo.Type != InlineAsm::isOutput)
12075       continue;
12076 
12077     // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the
12078     // individual constraint.
12079     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
12080 
12081     switch (OpInfo.ConstraintType) {
12082     case TargetLowering::C_Register:
12083     case TargetLowering::C_RegisterClass: {
12084       // Fill in OpInfo.AssignedRegs.Regs.
12085       getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo);
12086 
12087       // getRegistersForValue may produce 1 to many registers based on whether
12088       // the OpInfo.ConstraintVT is legal on the target or not.
12089       for (size_t i = 0, e = OpInfo.AssignedRegs.Regs.size(); i != e; ++i) {
12090         Register OriginalDef = FollowCopyChain(MRI, InitialDef++);
12091         if (Register::isPhysicalRegister(OriginalDef))
12092           FuncInfo.MBB->addLiveIn(OriginalDef);
12093         // Update the assigned registers to use the original defs.
12094         OpInfo.AssignedRegs.Regs[i] = OriginalDef;
12095       }
12096 
12097       SDValue V = OpInfo.AssignedRegs.getCopyFromRegs(
12098           DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR);
12099       ResultValues.push_back(V);
12100       ResultVTs.push_back(OpInfo.ConstraintVT);
12101       break;
12102     }
12103     case TargetLowering::C_Other: {
12104       SDValue Flag;
12105       SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
12106                                                   OpInfo, DAG);
12107       ++InitialDef;
12108       ResultValues.push_back(V);
12109       ResultVTs.push_back(OpInfo.ConstraintVT);
12110       break;
12111     }
12112     default:
12113       break;
12114     }
12115   }
12116   SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12117                           DAG.getVTList(ResultVTs), ResultValues);
12118   setValue(&I, V);
12119 }
12120