xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 11bf02e0192aea0ddef9a81098c2162cde82dc7e)
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   SmallVector<SDDbgOperand> LocationOps;
1553   SmallVector<SDNode *> Dependencies;
1554   for (const Value *V : Values) {
1555     // Constant value.
1556     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1557         isa<ConstantPointerNull>(V)) {
1558       LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1559       continue;
1560     }
1561 
1562     // Look through IntToPtr constants.
1563     if (auto *CE = dyn_cast<ConstantExpr>(V))
1564       if (CE->getOpcode() == Instruction::IntToPtr) {
1565         LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0)));
1566         continue;
1567       }
1568 
1569     // If the Value is a frame index, we can create a FrameIndex debug value
1570     // without relying on the DAG at all.
1571     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1572       auto SI = FuncInfo.StaticAllocaMap.find(AI);
1573       if (SI != FuncInfo.StaticAllocaMap.end()) {
1574         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1575         continue;
1576       }
1577     }
1578 
1579     // Do not use getValue() in here; we don't want to generate code at
1580     // this point if it hasn't been done yet.
1581     SDValue N = NodeMap[V];
1582     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1583       N = UnusedArgNodeMap[V];
1584     if (N.getNode()) {
1585       // Only emit func arg dbg value for non-variadic dbg.values for now.
1586       if (!IsVariadic &&
1587           EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc,
1588                                    FuncArgumentDbgValueKind::Value, N))
1589         return true;
1590       if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1591         // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1592         // describe stack slot locations.
1593         //
1594         // Consider "int x = 0; int *px = &x;". There are two kinds of
1595         // interesting debug values here after optimization:
1596         //
1597         //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
1598         //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1599         //
1600         // Both describe the direct values of their associated variables.
1601         Dependencies.push_back(N.getNode());
1602         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1603         continue;
1604       }
1605       LocationOps.emplace_back(
1606           SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1607       continue;
1608     }
1609 
1610     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1611     // Special rules apply for the first dbg.values of parameter variables in a
1612     // function. Identify them by the fact they reference Argument Values, that
1613     // they're parameters, and they are parameters of the current function. We
1614     // need to let them dangle until they get an SDNode.
1615     bool IsParamOfFunc =
1616         isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt();
1617     if (IsParamOfFunc)
1618       return false;
1619 
1620     // The value is not used in this block yet (or it would have an SDNode).
1621     // We still want the value to appear for the user if possible -- if it has
1622     // an associated VReg, we can refer to that instead.
1623     auto VMI = FuncInfo.ValueMap.find(V);
1624     if (VMI != FuncInfo.ValueMap.end()) {
1625       unsigned Reg = VMI->second;
1626       // If this is a PHI node, it may be split up into several MI PHI nodes
1627       // (in FunctionLoweringInfo::set).
1628       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1629                        V->getType(), std::nullopt);
1630       if (RFV.occupiesMultipleRegs()) {
1631         // FIXME: We could potentially support variadic dbg_values here.
1632         if (IsVariadic)
1633           return false;
1634         unsigned Offset = 0;
1635         unsigned BitsToDescribe = 0;
1636         if (auto VarSize = Var->getSizeInBits())
1637           BitsToDescribe = *VarSize;
1638         if (auto Fragment = Expr->getFragmentInfo())
1639           BitsToDescribe = Fragment->SizeInBits;
1640         for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1641           // Bail out if all bits are described already.
1642           if (Offset >= BitsToDescribe)
1643             break;
1644           // TODO: handle scalable vectors.
1645           unsigned RegisterSize = RegAndSize.second;
1646           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1647                                       ? BitsToDescribe - Offset
1648                                       : RegisterSize;
1649           auto FragmentExpr = DIExpression::createFragmentExpression(
1650               Expr, Offset, FragmentSize);
1651           if (!FragmentExpr)
1652             continue;
1653           SDDbgValue *SDV = DAG.getVRegDbgValue(
1654               Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, SDNodeOrder);
1655           DAG.AddDbgValue(SDV, false);
1656           Offset += RegisterSize;
1657         }
1658         return true;
1659       }
1660       // We can use simple vreg locations for variadic dbg_values as well.
1661       LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1662       continue;
1663     }
1664     // We failed to create a SDDbgOperand for V.
1665     return false;
1666   }
1667 
1668   // We have created a SDDbgOperand for each Value in Values.
1669   // Should use Order instead of SDNodeOrder?
1670   assert(!LocationOps.empty());
1671   SDDbgValue *SDV = DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1672                                         /*IsIndirect=*/false, DbgLoc,
1673                                         SDNodeOrder, IsVariadic);
1674   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1675   return true;
1676 }
1677 
1678 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1679   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1680   for (auto &Pair : DanglingDebugInfoMap)
1681     for (auto &DDI : Pair.second)
1682       salvageUnresolvedDbgValue(const_cast<Value *>(Pair.first), DDI);
1683   clearDanglingDebugInfo();
1684 }
1685 
1686 /// getCopyFromRegs - If there was virtual register allocated for the value V
1687 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1688 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1689   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1690   SDValue Result;
1691 
1692   if (It != FuncInfo.ValueMap.end()) {
1693     Register InReg = It->second;
1694 
1695     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1696                      DAG.getDataLayout(), InReg, Ty,
1697                      std::nullopt); // This is not an ABI copy.
1698     SDValue Chain = DAG.getEntryNode();
1699     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1700                                  V);
1701     resolveDanglingDebugInfo(V, Result);
1702   }
1703 
1704   return Result;
1705 }
1706 
1707 /// getValue - Return an SDValue for the given Value.
1708 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1709   // If we already have an SDValue for this value, use it. It's important
1710   // to do this first, so that we don't create a CopyFromReg if we already
1711   // have a regular SDValue.
1712   SDValue &N = NodeMap[V];
1713   if (N.getNode()) return N;
1714 
1715   // If there's a virtual register allocated and initialized for this
1716   // value, use it.
1717   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1718     return copyFromReg;
1719 
1720   // Otherwise create a new SDValue and remember it.
1721   SDValue Val = getValueImpl(V);
1722   NodeMap[V] = Val;
1723   resolveDanglingDebugInfo(V, Val);
1724   return Val;
1725 }
1726 
1727 /// getNonRegisterValue - Return an SDValue for the given Value, but
1728 /// don't look in FuncInfo.ValueMap for a virtual register.
1729 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1730   // If we already have an SDValue for this value, use it.
1731   SDValue &N = NodeMap[V];
1732   if (N.getNode()) {
1733     if (isIntOrFPConstant(N)) {
1734       // Remove the debug location from the node as the node is about to be used
1735       // in a location which may differ from the original debug location.  This
1736       // is relevant to Constant and ConstantFP nodes because they can appear
1737       // as constant expressions inside PHI nodes.
1738       N->setDebugLoc(DebugLoc());
1739     }
1740     return N;
1741   }
1742 
1743   // Otherwise create a new SDValue and remember it.
1744   SDValue Val = getValueImpl(V);
1745   NodeMap[V] = Val;
1746   resolveDanglingDebugInfo(V, Val);
1747   return Val;
1748 }
1749 
1750 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1751 /// Create an SDValue for the given value.
1752 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1753   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1754 
1755   if (const Constant *C = dyn_cast<Constant>(V)) {
1756     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1757 
1758     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1759       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1760 
1761     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1762       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1763 
1764     if (isa<ConstantPointerNull>(C)) {
1765       unsigned AS = V->getType()->getPointerAddressSpace();
1766       return DAG.getConstant(0, getCurSDLoc(),
1767                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1768     }
1769 
1770     if (match(C, m_VScale()))
1771       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1772 
1773     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1774       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1775 
1776     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1777       return DAG.getUNDEF(VT);
1778 
1779     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1780       visit(CE->getOpcode(), *CE);
1781       SDValue N1 = NodeMap[V];
1782       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1783       return N1;
1784     }
1785 
1786     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1787       SmallVector<SDValue, 4> Constants;
1788       for (const Use &U : C->operands()) {
1789         SDNode *Val = getValue(U).getNode();
1790         // If the operand is an empty aggregate, there are no values.
1791         if (!Val) continue;
1792         // Add each leaf value from the operand to the Constants list
1793         // to form a flattened list of all the values.
1794         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1795           Constants.push_back(SDValue(Val, i));
1796       }
1797 
1798       return DAG.getMergeValues(Constants, getCurSDLoc());
1799     }
1800 
1801     if (const ConstantDataSequential *CDS =
1802           dyn_cast<ConstantDataSequential>(C)) {
1803       SmallVector<SDValue, 4> Ops;
1804       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1805         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1806         // Add each leaf value from the operand to the Constants list
1807         // to form a flattened list of all the values.
1808         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1809           Ops.push_back(SDValue(Val, i));
1810       }
1811 
1812       if (isa<ArrayType>(CDS->getType()))
1813         return DAG.getMergeValues(Ops, getCurSDLoc());
1814       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1815     }
1816 
1817     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1818       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1819              "Unknown struct or array constant!");
1820 
1821       SmallVector<EVT, 4> ValueVTs;
1822       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1823       unsigned NumElts = ValueVTs.size();
1824       if (NumElts == 0)
1825         return SDValue(); // empty struct
1826       SmallVector<SDValue, 4> Constants(NumElts);
1827       for (unsigned i = 0; i != NumElts; ++i) {
1828         EVT EltVT = ValueVTs[i];
1829         if (isa<UndefValue>(C))
1830           Constants[i] = DAG.getUNDEF(EltVT);
1831         else if (EltVT.isFloatingPoint())
1832           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1833         else
1834           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1835       }
1836 
1837       return DAG.getMergeValues(Constants, getCurSDLoc());
1838     }
1839 
1840     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1841       return DAG.getBlockAddress(BA, VT);
1842 
1843     if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1844       return getValue(Equiv->getGlobalValue());
1845 
1846     if (const auto *NC = dyn_cast<NoCFIValue>(C))
1847       return getValue(NC->getGlobalValue());
1848 
1849     if (VT == MVT::aarch64svcount) {
1850       assert(C->isNullValue() && "Can only zero this target type!");
1851       return DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT,
1852                          DAG.getConstant(0, getCurSDLoc(), MVT::nxv16i1));
1853     }
1854 
1855     VectorType *VecTy = cast<VectorType>(V->getType());
1856 
1857     // Now that we know the number and type of the elements, get that number of
1858     // elements into the Ops array based on what kind of constant it is.
1859     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1860       SmallVector<SDValue, 16> Ops;
1861       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1862       for (unsigned i = 0; i != NumElements; ++i)
1863         Ops.push_back(getValue(CV->getOperand(i)));
1864 
1865       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1866     }
1867 
1868     if (isa<ConstantAggregateZero>(C)) {
1869       EVT EltVT =
1870           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1871 
1872       SDValue Op;
1873       if (EltVT.isFloatingPoint())
1874         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1875       else
1876         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1877 
1878       return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op);
1879     }
1880 
1881     llvm_unreachable("Unknown vector constant");
1882   }
1883 
1884   // If this is a static alloca, generate it as the frameindex instead of
1885   // computation.
1886   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1887     DenseMap<const AllocaInst*, int>::iterator SI =
1888       FuncInfo.StaticAllocaMap.find(AI);
1889     if (SI != FuncInfo.StaticAllocaMap.end())
1890       return DAG.getFrameIndex(
1891           SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType()));
1892   }
1893 
1894   // If this is an instruction which fast-isel has deferred, select it now.
1895   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1896     Register InReg = FuncInfo.InitializeRegForValue(Inst);
1897 
1898     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1899                      Inst->getType(), std::nullopt);
1900     SDValue Chain = DAG.getEntryNode();
1901     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1902   }
1903 
1904   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V))
1905     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1906 
1907   if (const auto *BB = dyn_cast<BasicBlock>(V))
1908     return DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
1909 
1910   llvm_unreachable("Can't get register for value!");
1911 }
1912 
1913 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1914   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1915   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1916   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1917   bool IsSEH = isAsynchronousEHPersonality(Pers);
1918   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1919   if (!IsSEH)
1920     CatchPadMBB->setIsEHScopeEntry();
1921   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1922   if (IsMSVCCXX || IsCoreCLR)
1923     CatchPadMBB->setIsEHFuncletEntry();
1924 }
1925 
1926 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1927   // Update machine-CFG edge.
1928   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1929   FuncInfo.MBB->addSuccessor(TargetMBB);
1930   TargetMBB->setIsEHCatchretTarget(true);
1931   DAG.getMachineFunction().setHasEHCatchret(true);
1932 
1933   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1934   bool IsSEH = isAsynchronousEHPersonality(Pers);
1935   if (IsSEH) {
1936     // If this is not a fall-through branch or optimizations are switched off,
1937     // emit the branch.
1938     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1939         TM.getOptLevel() == CodeGenOptLevel::None)
1940       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1941                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1942     return;
1943   }
1944 
1945   // Figure out the funclet membership for the catchret's successor.
1946   // This will be used by the FuncletLayout pass to determine how to order the
1947   // BB's.
1948   // A 'catchret' returns to the outer scope's color.
1949   Value *ParentPad = I.getCatchSwitchParentPad();
1950   const BasicBlock *SuccessorColor;
1951   if (isa<ConstantTokenNone>(ParentPad))
1952     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1953   else
1954     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1955   assert(SuccessorColor && "No parent funclet for catchret!");
1956   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1957   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1958 
1959   // Create the terminator node.
1960   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1961                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1962                             DAG.getBasicBlock(SuccessorColorMBB));
1963   DAG.setRoot(Ret);
1964 }
1965 
1966 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1967   // Don't emit any special code for the cleanuppad instruction. It just marks
1968   // the start of an EH scope/funclet.
1969   FuncInfo.MBB->setIsEHScopeEntry();
1970   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1971   if (Pers != EHPersonality::Wasm_CXX) {
1972     FuncInfo.MBB->setIsEHFuncletEntry();
1973     FuncInfo.MBB->setIsCleanupFuncletEntry();
1974   }
1975 }
1976 
1977 // In wasm EH, even though a catchpad may not catch an exception if a tag does
1978 // not match, it is OK to add only the first unwind destination catchpad to the
1979 // successors, because there will be at least one invoke instruction within the
1980 // catch scope that points to the next unwind destination, if one exists, so
1981 // CFGSort cannot mess up with BB sorting order.
1982 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
1983 // call within them, and catchpads only consisting of 'catch (...)' have a
1984 // '__cxa_end_catch' call within them, both of which generate invokes in case
1985 // the next unwind destination exists, i.e., the next unwind destination is not
1986 // the caller.)
1987 //
1988 // Having at most one EH pad successor is also simpler and helps later
1989 // transformations.
1990 //
1991 // For example,
1992 // current:
1993 //   invoke void @foo to ... unwind label %catch.dispatch
1994 // catch.dispatch:
1995 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
1996 // catch.start:
1997 //   ...
1998 //   ... in this BB or some other child BB dominated by this BB there will be an
1999 //   invoke that points to 'next' BB as an unwind destination
2000 //
2001 // next: ; We don't need to add this to 'current' BB's successor
2002 //   ...
2003 static void findWasmUnwindDestinations(
2004     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2005     BranchProbability Prob,
2006     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2007         &UnwindDests) {
2008   while (EHPadBB) {
2009     const Instruction *Pad = EHPadBB->getFirstNonPHI();
2010     if (isa<CleanupPadInst>(Pad)) {
2011       // Stop on cleanup pads.
2012       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
2013       UnwindDests.back().first->setIsEHScopeEntry();
2014       break;
2015     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
2016       // Add the catchpad handlers to the possible destinations. We don't
2017       // continue to the unwind destination of the catchswitch for wasm.
2018       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2019         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
2020         UnwindDests.back().first->setIsEHScopeEntry();
2021       }
2022       break;
2023     } else {
2024       continue;
2025     }
2026   }
2027 }
2028 
2029 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
2030 /// many places it could ultimately go. In the IR, we have a single unwind
2031 /// destination, but in the machine CFG, we enumerate all the possible blocks.
2032 /// This function skips over imaginary basic blocks that hold catchswitch
2033 /// instructions, and finds all the "real" machine
2034 /// basic block destinations. As those destinations may not be successors of
2035 /// EHPadBB, here we also calculate the edge probability to those destinations.
2036 /// The passed-in Prob is the edge probability to EHPadBB.
2037 static void findUnwindDestinations(
2038     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2039     BranchProbability Prob,
2040     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2041         &UnwindDests) {
2042   EHPersonality Personality =
2043     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
2044   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
2045   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
2046   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
2047   bool IsSEH = isAsynchronousEHPersonality(Personality);
2048 
2049   if (IsWasmCXX) {
2050     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
2051     assert(UnwindDests.size() <= 1 &&
2052            "There should be at most one unwind destination for wasm");
2053     return;
2054   }
2055 
2056   while (EHPadBB) {
2057     const Instruction *Pad = EHPadBB->getFirstNonPHI();
2058     BasicBlock *NewEHPadBB = nullptr;
2059     if (isa<LandingPadInst>(Pad)) {
2060       // Stop on landingpads. They are not funclets.
2061       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
2062       break;
2063     } else if (isa<CleanupPadInst>(Pad)) {
2064       // Stop on cleanup pads. Cleanups are always funclet entries for all known
2065       // personalities.
2066       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
2067       UnwindDests.back().first->setIsEHScopeEntry();
2068       UnwindDests.back().first->setIsEHFuncletEntry();
2069       break;
2070     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
2071       // Add the catchpad handlers to the possible destinations.
2072       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2073         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
2074         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
2075         if (IsMSVCCXX || IsCoreCLR)
2076           UnwindDests.back().first->setIsEHFuncletEntry();
2077         if (!IsSEH)
2078           UnwindDests.back().first->setIsEHScopeEntry();
2079       }
2080       NewEHPadBB = CatchSwitch->getUnwindDest();
2081     } else {
2082       continue;
2083     }
2084 
2085     BranchProbabilityInfo *BPI = FuncInfo.BPI;
2086     if (BPI && NewEHPadBB)
2087       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
2088     EHPadBB = NewEHPadBB;
2089   }
2090 }
2091 
2092 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
2093   // Update successor info.
2094   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2095   auto UnwindDest = I.getUnwindDest();
2096   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2097   BranchProbability UnwindDestProb =
2098       (BPI && UnwindDest)
2099           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
2100           : BranchProbability::getZero();
2101   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
2102   for (auto &UnwindDest : UnwindDests) {
2103     UnwindDest.first->setIsEHPad();
2104     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
2105   }
2106   FuncInfo.MBB->normalizeSuccProbs();
2107 
2108   // Create the terminator node.
2109   SDValue Ret =
2110       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
2111   DAG.setRoot(Ret);
2112 }
2113 
2114 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
2115   report_fatal_error("visitCatchSwitch not yet implemented!");
2116 }
2117 
2118 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
2119   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2120   auto &DL = DAG.getDataLayout();
2121   SDValue Chain = getControlRoot();
2122   SmallVector<ISD::OutputArg, 8> Outs;
2123   SmallVector<SDValue, 8> OutVals;
2124 
2125   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
2126   // lower
2127   //
2128   //   %val = call <ty> @llvm.experimental.deoptimize()
2129   //   ret <ty> %val
2130   //
2131   // differently.
2132   if (I.getParent()->getTerminatingDeoptimizeCall()) {
2133     LowerDeoptimizingReturn();
2134     return;
2135   }
2136 
2137   if (!FuncInfo.CanLowerReturn) {
2138     unsigned DemoteReg = FuncInfo.DemoteRegister;
2139     const Function *F = I.getParent()->getParent();
2140 
2141     // Emit a store of the return value through the virtual register.
2142     // Leave Outs empty so that LowerReturn won't try to load return
2143     // registers the usual way.
2144     SmallVector<EVT, 1> PtrValueVTs;
2145     ComputeValueVTs(TLI, DL,
2146                     PointerType::get(F->getContext(),
2147                                      DAG.getDataLayout().getAllocaAddrSpace()),
2148                     PtrValueVTs);
2149 
2150     SDValue RetPtr =
2151         DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]);
2152     SDValue RetOp = getValue(I.getOperand(0));
2153 
2154     SmallVector<EVT, 4> ValueVTs, MemVTs;
2155     SmallVector<uint64_t, 4> Offsets;
2156     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
2157                     &Offsets, 0);
2158     unsigned NumValues = ValueVTs.size();
2159 
2160     SmallVector<SDValue, 4> Chains(NumValues);
2161     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
2162     for (unsigned i = 0; i != NumValues; ++i) {
2163       // An aggregate return value cannot wrap around the address space, so
2164       // offsets to its parts don't wrap either.
2165       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
2166                                            TypeSize::getFixed(Offsets[i]));
2167 
2168       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
2169       if (MemVTs[i] != ValueVTs[i])
2170         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
2171       Chains[i] = DAG.getStore(
2172           Chain, getCurSDLoc(), Val,
2173           // FIXME: better loc info would be nice.
2174           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
2175           commonAlignment(BaseAlign, Offsets[i]));
2176     }
2177 
2178     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
2179                         MVT::Other, Chains);
2180   } else if (I.getNumOperands() != 0) {
2181     SmallVector<EVT, 4> ValueVTs;
2182     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
2183     unsigned NumValues = ValueVTs.size();
2184     if (NumValues) {
2185       SDValue RetOp = getValue(I.getOperand(0));
2186 
2187       const Function *F = I.getParent()->getParent();
2188 
2189       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
2190           I.getOperand(0)->getType(), F->getCallingConv(),
2191           /*IsVarArg*/ false, DL);
2192 
2193       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
2194       if (F->getAttributes().hasRetAttr(Attribute::SExt))
2195         ExtendKind = ISD::SIGN_EXTEND;
2196       else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
2197         ExtendKind = ISD::ZERO_EXTEND;
2198 
2199       LLVMContext &Context = F->getContext();
2200       bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
2201 
2202       for (unsigned j = 0; j != NumValues; ++j) {
2203         EVT VT = ValueVTs[j];
2204 
2205         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2206           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
2207 
2208         CallingConv::ID CC = F->getCallingConv();
2209 
2210         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
2211         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2212         SmallVector<SDValue, 4> Parts(NumParts);
2213         getCopyToParts(DAG, getCurSDLoc(),
2214                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2215                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
2216 
2217         // 'inreg' on function refers to return value
2218         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2219         if (RetInReg)
2220           Flags.setInReg();
2221 
2222         if (I.getOperand(0)->getType()->isPointerTy()) {
2223           Flags.setPointer();
2224           Flags.setPointerAddrSpace(
2225               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2226         }
2227 
2228         if (NeedsRegBlock) {
2229           Flags.setInConsecutiveRegs();
2230           if (j == NumValues - 1)
2231             Flags.setInConsecutiveRegsLast();
2232         }
2233 
2234         // Propagate extension type if any
2235         if (ExtendKind == ISD::SIGN_EXTEND)
2236           Flags.setSExt();
2237         else if (ExtendKind == ISD::ZERO_EXTEND)
2238           Flags.setZExt();
2239 
2240         for (unsigned i = 0; i < NumParts; ++i) {
2241           Outs.push_back(ISD::OutputArg(Flags,
2242                                         Parts[i].getValueType().getSimpleVT(),
2243                                         VT, /*isfixed=*/true, 0, 0));
2244           OutVals.push_back(Parts[i]);
2245         }
2246       }
2247     }
2248   }
2249 
2250   // Push in swifterror virtual register as the last element of Outs. This makes
2251   // sure swifterror virtual register will be returned in the swifterror
2252   // physical register.
2253   const Function *F = I.getParent()->getParent();
2254   if (TLI.supportSwiftError() &&
2255       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2256     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2257     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2258     Flags.setSwiftError();
2259     Outs.push_back(ISD::OutputArg(
2260         Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
2261         /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
2262     // Create SDNode for the swifterror virtual register.
2263     OutVals.push_back(
2264         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2265                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2266                         EVT(TLI.getPointerTy(DL))));
2267   }
2268 
2269   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2270   CallingConv::ID CallConv =
2271     DAG.getMachineFunction().getFunction().getCallingConv();
2272   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2273       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2274 
2275   // Verify that the target's LowerReturn behaved as expected.
2276   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2277          "LowerReturn didn't return a valid chain!");
2278 
2279   // Update the DAG with the new chain value resulting from return lowering.
2280   DAG.setRoot(Chain);
2281 }
2282 
2283 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2284 /// created for it, emit nodes to copy the value into the virtual
2285 /// registers.
2286 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2287   // Skip empty types
2288   if (V->getType()->isEmptyTy())
2289     return;
2290 
2291   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2292   if (VMI != FuncInfo.ValueMap.end()) {
2293     assert((!V->use_empty() || isa<CallBrInst>(V)) &&
2294            "Unused value assigned virtual registers!");
2295     CopyValueToVirtualRegister(V, VMI->second);
2296   }
2297 }
2298 
2299 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2300 /// the current basic block, add it to ValueMap now so that we'll get a
2301 /// CopyTo/FromReg.
2302 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2303   // No need to export constants.
2304   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2305 
2306   // Already exported?
2307   if (FuncInfo.isExportedInst(V)) return;
2308 
2309   Register Reg = FuncInfo.InitializeRegForValue(V);
2310   CopyValueToVirtualRegister(V, Reg);
2311 }
2312 
2313 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2314                                                      const BasicBlock *FromBB) {
2315   // The operands of the setcc have to be in this block.  We don't know
2316   // how to export them from some other block.
2317   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2318     // Can export from current BB.
2319     if (VI->getParent() == FromBB)
2320       return true;
2321 
2322     // Is already exported, noop.
2323     return FuncInfo.isExportedInst(V);
2324   }
2325 
2326   // If this is an argument, we can export it if the BB is the entry block or
2327   // if it is already exported.
2328   if (isa<Argument>(V)) {
2329     if (FromBB->isEntryBlock())
2330       return true;
2331 
2332     // Otherwise, can only export this if it is already exported.
2333     return FuncInfo.isExportedInst(V);
2334   }
2335 
2336   // Otherwise, constants can always be exported.
2337   return true;
2338 }
2339 
2340 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2341 BranchProbability
2342 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2343                                         const MachineBasicBlock *Dst) const {
2344   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2345   const BasicBlock *SrcBB = Src->getBasicBlock();
2346   const BasicBlock *DstBB = Dst->getBasicBlock();
2347   if (!BPI) {
2348     // If BPI is not available, set the default probability as 1 / N, where N is
2349     // the number of successors.
2350     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2351     return BranchProbability(1, SuccSize);
2352   }
2353   return BPI->getEdgeProbability(SrcBB, DstBB);
2354 }
2355 
2356 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2357                                                MachineBasicBlock *Dst,
2358                                                BranchProbability Prob) {
2359   if (!FuncInfo.BPI)
2360     Src->addSuccessorWithoutProb(Dst);
2361   else {
2362     if (Prob.isUnknown())
2363       Prob = getEdgeProbability(Src, Dst);
2364     Src->addSuccessor(Dst, Prob);
2365   }
2366 }
2367 
2368 static bool InBlock(const Value *V, const BasicBlock *BB) {
2369   if (const Instruction *I = dyn_cast<Instruction>(V))
2370     return I->getParent() == BB;
2371   return true;
2372 }
2373 
2374 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2375 /// This function emits a branch and is used at the leaves of an OR or an
2376 /// AND operator tree.
2377 void
2378 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2379                                                   MachineBasicBlock *TBB,
2380                                                   MachineBasicBlock *FBB,
2381                                                   MachineBasicBlock *CurBB,
2382                                                   MachineBasicBlock *SwitchBB,
2383                                                   BranchProbability TProb,
2384                                                   BranchProbability FProb,
2385                                                   bool InvertCond) {
2386   const BasicBlock *BB = CurBB->getBasicBlock();
2387 
2388   // If the leaf of the tree is a comparison, merge the condition into
2389   // the caseblock.
2390   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2391     // The operands of the cmp have to be in this block.  We don't know
2392     // how to export them from some other block.  If this is the first block
2393     // of the sequence, no exporting is needed.
2394     if (CurBB == SwitchBB ||
2395         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2396          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2397       ISD::CondCode Condition;
2398       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2399         ICmpInst::Predicate Pred =
2400             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2401         Condition = getICmpCondCode(Pred);
2402       } else {
2403         const FCmpInst *FC = cast<FCmpInst>(Cond);
2404         FCmpInst::Predicate Pred =
2405             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2406         Condition = getFCmpCondCode(Pred);
2407         if (TM.Options.NoNaNsFPMath)
2408           Condition = getFCmpCodeWithoutNaN(Condition);
2409       }
2410 
2411       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2412                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2413       SL->SwitchCases.push_back(CB);
2414       return;
2415     }
2416   }
2417 
2418   // Create a CaseBlock record representing this branch.
2419   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2420   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2421                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2422   SL->SwitchCases.push_back(CB);
2423 }
2424 
2425 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2426                                                MachineBasicBlock *TBB,
2427                                                MachineBasicBlock *FBB,
2428                                                MachineBasicBlock *CurBB,
2429                                                MachineBasicBlock *SwitchBB,
2430                                                Instruction::BinaryOps Opc,
2431                                                BranchProbability TProb,
2432                                                BranchProbability FProb,
2433                                                bool InvertCond) {
2434   // Skip over not part of the tree and remember to invert op and operands at
2435   // next level.
2436   Value *NotCond;
2437   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2438       InBlock(NotCond, CurBB->getBasicBlock())) {
2439     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2440                          !InvertCond);
2441     return;
2442   }
2443 
2444   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2445   const Value *BOpOp0, *BOpOp1;
2446   // Compute the effective opcode for Cond, taking into account whether it needs
2447   // to be inverted, e.g.
2448   //   and (not (or A, B)), C
2449   // gets lowered as
2450   //   and (and (not A, not B), C)
2451   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2452   if (BOp) {
2453     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2454                ? Instruction::And
2455                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2456                       ? Instruction::Or
2457                       : (Instruction::BinaryOps)0);
2458     if (InvertCond) {
2459       if (BOpc == Instruction::And)
2460         BOpc = Instruction::Or;
2461       else if (BOpc == Instruction::Or)
2462         BOpc = Instruction::And;
2463     }
2464   }
2465 
2466   // If this node is not part of the or/and tree, emit it as a branch.
2467   // Note that all nodes in the tree should have same opcode.
2468   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2469   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2470       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2471       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2472     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2473                                  TProb, FProb, InvertCond);
2474     return;
2475   }
2476 
2477   //  Create TmpBB after CurBB.
2478   MachineFunction::iterator BBI(CurBB);
2479   MachineFunction &MF = DAG.getMachineFunction();
2480   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2481   CurBB->getParent()->insert(++BBI, TmpBB);
2482 
2483   if (Opc == Instruction::Or) {
2484     // Codegen X | Y as:
2485     // BB1:
2486     //   jmp_if_X TBB
2487     //   jmp TmpBB
2488     // TmpBB:
2489     //   jmp_if_Y TBB
2490     //   jmp FBB
2491     //
2492 
2493     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2494     // The requirement is that
2495     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2496     //     = TrueProb for original BB.
2497     // Assuming the original probabilities are A and B, one choice is to set
2498     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2499     // A/(1+B) and 2B/(1+B). This choice assumes that
2500     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2501     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2502     // TmpBB, but the math is more complicated.
2503 
2504     auto NewTrueProb = TProb / 2;
2505     auto NewFalseProb = TProb / 2 + FProb;
2506     // Emit the LHS condition.
2507     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2508                          NewFalseProb, InvertCond);
2509 
2510     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2511     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2512     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2513     // Emit the RHS condition into TmpBB.
2514     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2515                          Probs[1], InvertCond);
2516   } else {
2517     assert(Opc == Instruction::And && "Unknown merge op!");
2518     // Codegen X & Y as:
2519     // BB1:
2520     //   jmp_if_X TmpBB
2521     //   jmp FBB
2522     // TmpBB:
2523     //   jmp_if_Y TBB
2524     //   jmp FBB
2525     //
2526     //  This requires creation of TmpBB after CurBB.
2527 
2528     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2529     // The requirement is that
2530     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2531     //     = FalseProb for original BB.
2532     // Assuming the original probabilities are A and B, one choice is to set
2533     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2534     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2535     // TrueProb for BB1 * FalseProb for TmpBB.
2536 
2537     auto NewTrueProb = TProb + FProb / 2;
2538     auto NewFalseProb = FProb / 2;
2539     // Emit the LHS condition.
2540     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2541                          NewFalseProb, InvertCond);
2542 
2543     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2544     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2545     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2546     // Emit the RHS condition into TmpBB.
2547     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2548                          Probs[1], InvertCond);
2549   }
2550 }
2551 
2552 /// If the set of cases should be emitted as a series of branches, return true.
2553 /// If we should emit this as a bunch of and/or'd together conditions, return
2554 /// false.
2555 bool
2556 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2557   if (Cases.size() != 2) return true;
2558 
2559   // If this is two comparisons of the same values or'd or and'd together, they
2560   // will get folded into a single comparison, so don't emit two blocks.
2561   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2562        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2563       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2564        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2565     return false;
2566   }
2567 
2568   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2569   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2570   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2571       Cases[0].CC == Cases[1].CC &&
2572       isa<Constant>(Cases[0].CmpRHS) &&
2573       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2574     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2575       return false;
2576     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2577       return false;
2578   }
2579 
2580   return true;
2581 }
2582 
2583 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2584   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2585 
2586   // Update machine-CFG edges.
2587   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2588 
2589   if (I.isUnconditional()) {
2590     // Update machine-CFG edges.
2591     BrMBB->addSuccessor(Succ0MBB);
2592 
2593     // If this is not a fall-through branch or optimizations are switched off,
2594     // emit the branch.
2595     if (Succ0MBB != NextBlock(BrMBB) ||
2596         TM.getOptLevel() == CodeGenOptLevel::None) {
2597       auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
2598                             getControlRoot(), DAG.getBasicBlock(Succ0MBB));
2599       setValue(&I, Br);
2600       DAG.setRoot(Br);
2601     }
2602 
2603     return;
2604   }
2605 
2606   // If this condition is one of the special cases we handle, do special stuff
2607   // now.
2608   const Value *CondVal = I.getCondition();
2609   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2610 
2611   // If this is a series of conditions that are or'd or and'd together, emit
2612   // this as a sequence of branches instead of setcc's with and/or operations.
2613   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2614   // unpredictable branches, and vector extracts because those jumps are likely
2615   // expensive for any target), this should improve performance.
2616   // For example, instead of something like:
2617   //     cmp A, B
2618   //     C = seteq
2619   //     cmp D, E
2620   //     F = setle
2621   //     or C, F
2622   //     jnz foo
2623   // Emit:
2624   //     cmp A, B
2625   //     je foo
2626   //     cmp D, E
2627   //     jle foo
2628   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2629   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2630       BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2631     Value *Vec;
2632     const Value *BOp0, *BOp1;
2633     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2634     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2635       Opcode = Instruction::And;
2636     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2637       Opcode = Instruction::Or;
2638 
2639     if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2640                     match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
2641       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2642                            getEdgeProbability(BrMBB, Succ0MBB),
2643                            getEdgeProbability(BrMBB, Succ1MBB),
2644                            /*InvertCond=*/false);
2645       // If the compares in later blocks need to use values not currently
2646       // exported from this block, export them now.  This block should always
2647       // be the first entry.
2648       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2649 
2650       // Allow some cases to be rejected.
2651       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2652         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2653           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2654           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2655         }
2656 
2657         // Emit the branch for this block.
2658         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2659         SL->SwitchCases.erase(SL->SwitchCases.begin());
2660         return;
2661       }
2662 
2663       // Okay, we decided not to do this, remove any inserted MBB's and clear
2664       // SwitchCases.
2665       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2666         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2667 
2668       SL->SwitchCases.clear();
2669     }
2670   }
2671 
2672   // Create a CaseBlock record representing this branch.
2673   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2674                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2675 
2676   // Use visitSwitchCase to actually insert the fast branch sequence for this
2677   // cond branch.
2678   visitSwitchCase(CB, BrMBB);
2679 }
2680 
2681 /// visitSwitchCase - Emits the necessary code to represent a single node in
2682 /// the binary search tree resulting from lowering a switch instruction.
2683 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2684                                           MachineBasicBlock *SwitchBB) {
2685   SDValue Cond;
2686   SDValue CondLHS = getValue(CB.CmpLHS);
2687   SDLoc dl = CB.DL;
2688 
2689   if (CB.CC == ISD::SETTRUE) {
2690     // Branch or fall through to TrueBB.
2691     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2692     SwitchBB->normalizeSuccProbs();
2693     if (CB.TrueBB != NextBlock(SwitchBB)) {
2694       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2695                               DAG.getBasicBlock(CB.TrueBB)));
2696     }
2697     return;
2698   }
2699 
2700   auto &TLI = DAG.getTargetLoweringInfo();
2701   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2702 
2703   // Build the setcc now.
2704   if (!CB.CmpMHS) {
2705     // Fold "(X == true)" to X and "(X == false)" to !X to
2706     // handle common cases produced by branch lowering.
2707     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2708         CB.CC == ISD::SETEQ)
2709       Cond = CondLHS;
2710     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2711              CB.CC == ISD::SETEQ) {
2712       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2713       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2714     } else {
2715       SDValue CondRHS = getValue(CB.CmpRHS);
2716 
2717       // If a pointer's DAG type is larger than its memory type then the DAG
2718       // values are zero-extended. This breaks signed comparisons so truncate
2719       // back to the underlying type before doing the compare.
2720       if (CondLHS.getValueType() != MemVT) {
2721         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2722         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2723       }
2724       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2725     }
2726   } else {
2727     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2728 
2729     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2730     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2731 
2732     SDValue CmpOp = getValue(CB.CmpMHS);
2733     EVT VT = CmpOp.getValueType();
2734 
2735     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2736       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2737                           ISD::SETLE);
2738     } else {
2739       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2740                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2741       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2742                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2743     }
2744   }
2745 
2746   // Update successor info
2747   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2748   // TrueBB and FalseBB are always different unless the incoming IR is
2749   // degenerate. This only happens when running llc on weird IR.
2750   if (CB.TrueBB != CB.FalseBB)
2751     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2752   SwitchBB->normalizeSuccProbs();
2753 
2754   // If the lhs block is the next block, invert the condition so that we can
2755   // fall through to the lhs instead of the rhs block.
2756   if (CB.TrueBB == NextBlock(SwitchBB)) {
2757     std::swap(CB.TrueBB, CB.FalseBB);
2758     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2759     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2760   }
2761 
2762   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2763                                MVT::Other, getControlRoot(), Cond,
2764                                DAG.getBasicBlock(CB.TrueBB));
2765 
2766   setValue(CurInst, BrCond);
2767 
2768   // Insert the false branch. Do this even if it's a fall through branch,
2769   // this makes it easier to do DAG optimizations which require inverting
2770   // the branch condition.
2771   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2772                        DAG.getBasicBlock(CB.FalseBB));
2773 
2774   DAG.setRoot(BrCond);
2775 }
2776 
2777 /// visitJumpTable - Emit JumpTable node in the current MBB
2778 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2779   // Emit the code for the jump table
2780   assert(JT.SL && "Should set SDLoc for SelectionDAG!");
2781   assert(JT.Reg != -1U && "Should lower JT Header first!");
2782   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2783   SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy);
2784   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2785   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other,
2786                                     Index.getValue(1), Table, Index);
2787   DAG.setRoot(BrJumpTable);
2788 }
2789 
2790 /// visitJumpTableHeader - This function emits necessary code to produce index
2791 /// in the JumpTable from switch case.
2792 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2793                                                JumpTableHeader &JTH,
2794                                                MachineBasicBlock *SwitchBB) {
2795   assert(JT.SL && "Should set SDLoc for SelectionDAG!");
2796   const SDLoc &dl = *JT.SL;
2797 
2798   // Subtract the lowest switch case value from the value being switched on.
2799   SDValue SwitchOp = getValue(JTH.SValue);
2800   EVT VT = SwitchOp.getValueType();
2801   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2802                             DAG.getConstant(JTH.First, dl, VT));
2803 
2804   // The SDNode we just created, which holds the value being switched on minus
2805   // the smallest case value, needs to be copied to a virtual register so it
2806   // can be used as an index into the jump table in a subsequent basic block.
2807   // This value may be smaller or larger than the target's pointer type, and
2808   // therefore require extension or truncating.
2809   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2810   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2811 
2812   unsigned JumpTableReg =
2813       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2814   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2815                                     JumpTableReg, SwitchOp);
2816   JT.Reg = JumpTableReg;
2817 
2818   if (!JTH.FallthroughUnreachable) {
2819     // Emit the range check for the jump table, and branch to the default block
2820     // for the switch statement if the value being switched on exceeds the
2821     // largest case in the switch.
2822     SDValue CMP = DAG.getSetCC(
2823         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2824                                    Sub.getValueType()),
2825         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2826 
2827     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2828                                  MVT::Other, CopyTo, CMP,
2829                                  DAG.getBasicBlock(JT.Default));
2830 
2831     // Avoid emitting unnecessary branches to the next block.
2832     if (JT.MBB != NextBlock(SwitchBB))
2833       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2834                            DAG.getBasicBlock(JT.MBB));
2835 
2836     DAG.setRoot(BrCond);
2837   } else {
2838     // Avoid emitting unnecessary branches to the next block.
2839     if (JT.MBB != NextBlock(SwitchBB))
2840       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2841                               DAG.getBasicBlock(JT.MBB)));
2842     else
2843       DAG.setRoot(CopyTo);
2844   }
2845 }
2846 
2847 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2848 /// variable if there exists one.
2849 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2850                                  SDValue &Chain) {
2851   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2852   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2853   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2854   MachineFunction &MF = DAG.getMachineFunction();
2855   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2856   MachineSDNode *Node =
2857       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2858   if (Global) {
2859     MachinePointerInfo MPInfo(Global);
2860     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2861                  MachineMemOperand::MODereferenceable;
2862     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2863         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2864     DAG.setNodeMemRefs(Node, {MemRef});
2865   }
2866   if (PtrTy != PtrMemTy)
2867     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2868   return SDValue(Node, 0);
2869 }
2870 
2871 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2872 /// tail spliced into a stack protector check success bb.
2873 ///
2874 /// For a high level explanation of how this fits into the stack protector
2875 /// generation see the comment on the declaration of class
2876 /// StackProtectorDescriptor.
2877 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2878                                                   MachineBasicBlock *ParentBB) {
2879 
2880   // First create the loads to the guard/stack slot for the comparison.
2881   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2882   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2883   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2884 
2885   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2886   int FI = MFI.getStackProtectorIndex();
2887 
2888   SDValue Guard;
2889   SDLoc dl = getCurSDLoc();
2890   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2891   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2892   Align Align =
2893       DAG.getDataLayout().getPrefTypeAlign(PointerType::get(M.getContext(), 0));
2894 
2895   // Generate code to load the content of the guard slot.
2896   SDValue GuardVal = DAG.getLoad(
2897       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2898       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2899       MachineMemOperand::MOVolatile);
2900 
2901   if (TLI.useStackGuardXorFP())
2902     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2903 
2904   // Retrieve guard check function, nullptr if instrumentation is inlined.
2905   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2906     // The target provides a guard check function to validate the guard value.
2907     // Generate a call to that function with the content of the guard slot as
2908     // argument.
2909     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2910     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2911 
2912     TargetLowering::ArgListTy Args;
2913     TargetLowering::ArgListEntry Entry;
2914     Entry.Node = GuardVal;
2915     Entry.Ty = FnTy->getParamType(0);
2916     if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
2917       Entry.IsInReg = true;
2918     Args.push_back(Entry);
2919 
2920     TargetLowering::CallLoweringInfo CLI(DAG);
2921     CLI.setDebugLoc(getCurSDLoc())
2922         .setChain(DAG.getEntryNode())
2923         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2924                    getValue(GuardCheckFn), std::move(Args));
2925 
2926     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2927     DAG.setRoot(Result.second);
2928     return;
2929   }
2930 
2931   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2932   // Otherwise, emit a volatile load to retrieve the stack guard value.
2933   SDValue Chain = DAG.getEntryNode();
2934   if (TLI.useLoadStackGuardNode()) {
2935     Guard = getLoadStackGuard(DAG, dl, Chain);
2936   } else {
2937     const Value *IRGuard = TLI.getSDagStackGuard(M);
2938     SDValue GuardPtr = getValue(IRGuard);
2939 
2940     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2941                         MachinePointerInfo(IRGuard, 0), Align,
2942                         MachineMemOperand::MOVolatile);
2943   }
2944 
2945   // Perform the comparison via a getsetcc.
2946   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2947                                                         *DAG.getContext(),
2948                                                         Guard.getValueType()),
2949                              Guard, GuardVal, ISD::SETNE);
2950 
2951   // If the guard/stackslot do not equal, branch to failure MBB.
2952   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2953                                MVT::Other, GuardVal.getOperand(0),
2954                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2955   // Otherwise branch to success MBB.
2956   SDValue Br = DAG.getNode(ISD::BR, dl,
2957                            MVT::Other, BrCond,
2958                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2959 
2960   DAG.setRoot(Br);
2961 }
2962 
2963 /// Codegen the failure basic block for a stack protector check.
2964 ///
2965 /// A failure stack protector machine basic block consists simply of a call to
2966 /// __stack_chk_fail().
2967 ///
2968 /// For a high level explanation of how this fits into the stack protector
2969 /// generation see the comment on the declaration of class
2970 /// StackProtectorDescriptor.
2971 void
2972 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2973   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2974   TargetLowering::MakeLibCallOptions CallOptions;
2975   CallOptions.setDiscardResult(true);
2976   SDValue Chain =
2977       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2978                       std::nullopt, CallOptions, getCurSDLoc())
2979           .second;
2980   // On PS4/PS5, the "return address" must still be within the calling
2981   // function, even if it's at the very end, so emit an explicit TRAP here.
2982   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2983   if (TM.getTargetTriple().isPS())
2984     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2985   // WebAssembly needs an unreachable instruction after a non-returning call,
2986   // because the function return type can be different from __stack_chk_fail's
2987   // return type (void).
2988   if (TM.getTargetTriple().isWasm())
2989     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2990 
2991   DAG.setRoot(Chain);
2992 }
2993 
2994 /// visitBitTestHeader - This function emits necessary code to produce value
2995 /// suitable for "bit tests"
2996 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2997                                              MachineBasicBlock *SwitchBB) {
2998   SDLoc dl = getCurSDLoc();
2999 
3000   // Subtract the minimum value.
3001   SDValue SwitchOp = getValue(B.SValue);
3002   EVT VT = SwitchOp.getValueType();
3003   SDValue RangeSub =
3004       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
3005 
3006   // Determine the type of the test operands.
3007   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3008   bool UsePtrType = false;
3009   if (!TLI.isTypeLegal(VT)) {
3010     UsePtrType = true;
3011   } else {
3012     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
3013       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
3014         // Switch table case range are encoded into series of masks.
3015         // Just use pointer type, it's guaranteed to fit.
3016         UsePtrType = true;
3017         break;
3018       }
3019   }
3020   SDValue Sub = RangeSub;
3021   if (UsePtrType) {
3022     VT = TLI.getPointerTy(DAG.getDataLayout());
3023     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
3024   }
3025 
3026   B.RegVT = VT.getSimpleVT();
3027   B.Reg = FuncInfo.CreateReg(B.RegVT);
3028   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
3029 
3030   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
3031 
3032   if (!B.FallthroughUnreachable)
3033     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
3034   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
3035   SwitchBB->normalizeSuccProbs();
3036 
3037   SDValue Root = CopyTo;
3038   if (!B.FallthroughUnreachable) {
3039     // Conditional branch to the default block.
3040     SDValue RangeCmp = DAG.getSetCC(dl,
3041         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3042                                RangeSub.getValueType()),
3043         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
3044         ISD::SETUGT);
3045 
3046     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
3047                        DAG.getBasicBlock(B.Default));
3048   }
3049 
3050   // Avoid emitting unnecessary branches to the next block.
3051   if (MBB != NextBlock(SwitchBB))
3052     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
3053 
3054   DAG.setRoot(Root);
3055 }
3056 
3057 /// visitBitTestCase - this function produces one "bit test"
3058 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
3059                                            MachineBasicBlock* NextMBB,
3060                                            BranchProbability BranchProbToNext,
3061                                            unsigned Reg,
3062                                            BitTestCase &B,
3063                                            MachineBasicBlock *SwitchBB) {
3064   SDLoc dl = getCurSDLoc();
3065   MVT VT = BB.RegVT;
3066   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
3067   SDValue Cmp;
3068   unsigned PopCount = llvm::popcount(B.Mask);
3069   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3070   if (PopCount == 1) {
3071     // Testing for a single bit; just compare the shift count with what it
3072     // would need to be to shift a 1 bit in that position.
3073     Cmp = DAG.getSetCC(
3074         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3075         ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT),
3076         ISD::SETEQ);
3077   } else if (PopCount == BB.Range) {
3078     // There is only one zero bit in the range, test for it directly.
3079     Cmp = DAG.getSetCC(
3080         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3081         ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE);
3082   } else {
3083     // Make desired shift
3084     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
3085                                     DAG.getConstant(1, dl, VT), ShiftOp);
3086 
3087     // Emit bit tests and jumps
3088     SDValue AndOp = DAG.getNode(ISD::AND, dl,
3089                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
3090     Cmp = DAG.getSetCC(
3091         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3092         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
3093   }
3094 
3095   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
3096   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
3097   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
3098   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
3099   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
3100   // one as they are relative probabilities (and thus work more like weights),
3101   // and hence we need to normalize them to let the sum of them become one.
3102   SwitchBB->normalizeSuccProbs();
3103 
3104   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
3105                               MVT::Other, getControlRoot(),
3106                               Cmp, DAG.getBasicBlock(B.TargetBB));
3107 
3108   // Avoid emitting unnecessary branches to the next block.
3109   if (NextMBB != NextBlock(SwitchBB))
3110     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
3111                         DAG.getBasicBlock(NextMBB));
3112 
3113   DAG.setRoot(BrAnd);
3114 }
3115 
3116 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
3117   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
3118 
3119   // Retrieve successors. Look through artificial IR level blocks like
3120   // catchswitch for successors.
3121   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
3122   const BasicBlock *EHPadBB = I.getSuccessor(1);
3123   MachineBasicBlock *EHPadMBB = FuncInfo.MBBMap[EHPadBB];
3124 
3125   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3126   // have to do anything here to lower funclet bundles.
3127   assert(!I.hasOperandBundlesOtherThan(
3128              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
3129               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
3130               LLVMContext::OB_cfguardtarget,
3131               LLVMContext::OB_clang_arc_attachedcall}) &&
3132          "Cannot lower invokes with arbitrary operand bundles yet!");
3133 
3134   const Value *Callee(I.getCalledOperand());
3135   const Function *Fn = dyn_cast<Function>(Callee);
3136   if (isa<InlineAsm>(Callee))
3137     visitInlineAsm(I, EHPadBB);
3138   else if (Fn && Fn->isIntrinsic()) {
3139     switch (Fn->getIntrinsicID()) {
3140     default:
3141       llvm_unreachable("Cannot invoke this intrinsic");
3142     case Intrinsic::donothing:
3143       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
3144     case Intrinsic::seh_try_begin:
3145     case Intrinsic::seh_scope_begin:
3146     case Intrinsic::seh_try_end:
3147     case Intrinsic::seh_scope_end:
3148       if (EHPadMBB)
3149           // a block referenced by EH table
3150           // so dtor-funclet not removed by opts
3151           EHPadMBB->setMachineBlockAddressTaken();
3152       break;
3153     case Intrinsic::experimental_patchpoint_void:
3154     case Intrinsic::experimental_patchpoint_i64:
3155       visitPatchpoint(I, EHPadBB);
3156       break;
3157     case Intrinsic::experimental_gc_statepoint:
3158       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
3159       break;
3160     case Intrinsic::wasm_rethrow: {
3161       // This is usually done in visitTargetIntrinsic, but this intrinsic is
3162       // special because it can be invoked, so we manually lower it to a DAG
3163       // node here.
3164       SmallVector<SDValue, 8> Ops;
3165       Ops.push_back(getRoot()); // inchain
3166       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3167       Ops.push_back(
3168           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
3169                                 TLI.getPointerTy(DAG.getDataLayout())));
3170       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3171       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3172       break;
3173     }
3174     }
3175   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
3176     // Currently we do not lower any intrinsic calls with deopt operand bundles.
3177     // Eventually we will support lowering the @llvm.experimental.deoptimize
3178     // intrinsic, and right now there are no plans to support other intrinsics
3179     // with deopt state.
3180     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
3181   } else {
3182     LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
3183   }
3184 
3185   // If the value of the invoke is used outside of its defining block, make it
3186   // available as a virtual register.
3187   // We already took care of the exported value for the statepoint instruction
3188   // during call to the LowerStatepoint.
3189   if (!isa<GCStatepointInst>(I)) {
3190     CopyToExportRegsIfNeeded(&I);
3191   }
3192 
3193   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
3194   BranchProbabilityInfo *BPI = FuncInfo.BPI;
3195   BranchProbability EHPadBBProb =
3196       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3197           : BranchProbability::getZero();
3198   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
3199 
3200   // Update successor info.
3201   addSuccessorWithProb(InvokeMBB, Return);
3202   for (auto &UnwindDest : UnwindDests) {
3203     UnwindDest.first->setIsEHPad();
3204     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3205   }
3206   InvokeMBB->normalizeSuccProbs();
3207 
3208   // Drop into normal successor.
3209   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
3210                           DAG.getBasicBlock(Return)));
3211 }
3212 
3213 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3214   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3215 
3216   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3217   // have to do anything here to lower funclet bundles.
3218   assert(!I.hasOperandBundlesOtherThan(
3219              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
3220          "Cannot lower callbrs with arbitrary operand bundles yet!");
3221 
3222   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
3223   visitInlineAsm(I);
3224   CopyToExportRegsIfNeeded(&I);
3225 
3226   // Retrieve successors.
3227   SmallPtrSet<BasicBlock *, 8> Dests;
3228   Dests.insert(I.getDefaultDest());
3229   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
3230 
3231   // Update successor info.
3232   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3233   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
3234     BasicBlock *Dest = I.getIndirectDest(i);
3235     MachineBasicBlock *Target = FuncInfo.MBBMap[Dest];
3236     Target->setIsInlineAsmBrIndirectTarget();
3237     Target->setMachineBlockAddressTaken();
3238     Target->setLabelMustBeEmitted();
3239     // Don't add duplicate machine successors.
3240     if (Dests.insert(Dest).second)
3241       addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3242   }
3243   CallBrMBB->normalizeSuccProbs();
3244 
3245   // Drop into default successor.
3246   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3247                           MVT::Other, getControlRoot(),
3248                           DAG.getBasicBlock(Return)));
3249 }
3250 
3251 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3252   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3253 }
3254 
3255 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3256   assert(FuncInfo.MBB->isEHPad() &&
3257          "Call to landingpad not in landing pad!");
3258 
3259   // If there aren't registers to copy the values into (e.g., during SjLj
3260   // exceptions), then don't bother to create these DAG nodes.
3261   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3262   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3263   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3264       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3265     return;
3266 
3267   // If landingpad's return type is token type, we don't create DAG nodes
3268   // for its exception pointer and selector value. The extraction of exception
3269   // pointer or selector value from token type landingpads is not currently
3270   // supported.
3271   if (LP.getType()->isTokenTy())
3272     return;
3273 
3274   SmallVector<EVT, 2> ValueVTs;
3275   SDLoc dl = getCurSDLoc();
3276   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3277   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3278 
3279   // Get the two live-in registers as SDValues. The physregs have already been
3280   // copied into virtual registers.
3281   SDValue Ops[2];
3282   if (FuncInfo.ExceptionPointerVirtReg) {
3283     Ops[0] = DAG.getZExtOrTrunc(
3284         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3285                            FuncInfo.ExceptionPointerVirtReg,
3286                            TLI.getPointerTy(DAG.getDataLayout())),
3287         dl, ValueVTs[0]);
3288   } else {
3289     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3290   }
3291   Ops[1] = DAG.getZExtOrTrunc(
3292       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3293                          FuncInfo.ExceptionSelectorVirtReg,
3294                          TLI.getPointerTy(DAG.getDataLayout())),
3295       dl, ValueVTs[1]);
3296 
3297   // Merge into one.
3298   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3299                             DAG.getVTList(ValueVTs), Ops);
3300   setValue(&LP, Res);
3301 }
3302 
3303 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3304                                            MachineBasicBlock *Last) {
3305   // Update JTCases.
3306   for (JumpTableBlock &JTB : SL->JTCases)
3307     if (JTB.first.HeaderBB == First)
3308       JTB.first.HeaderBB = Last;
3309 
3310   // Update BitTestCases.
3311   for (BitTestBlock &BTB : SL->BitTestCases)
3312     if (BTB.Parent == First)
3313       BTB.Parent = Last;
3314 }
3315 
3316 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3317   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3318 
3319   // Update machine-CFG edges with unique successors.
3320   SmallSet<BasicBlock*, 32> Done;
3321   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3322     BasicBlock *BB = I.getSuccessor(i);
3323     bool Inserted = Done.insert(BB).second;
3324     if (!Inserted)
3325         continue;
3326 
3327     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
3328     addSuccessorWithProb(IndirectBrMBB, Succ);
3329   }
3330   IndirectBrMBB->normalizeSuccProbs();
3331 
3332   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3333                           MVT::Other, getControlRoot(),
3334                           getValue(I.getAddress())));
3335 }
3336 
3337 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3338   if (!DAG.getTarget().Options.TrapUnreachable)
3339     return;
3340 
3341   // We may be able to ignore unreachable behind a noreturn call.
3342   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
3343     if (const CallInst *Call = dyn_cast_or_null<CallInst>(I.getPrevNode())) {
3344       if (Call->doesNotReturn())
3345         return;
3346     }
3347   }
3348 
3349   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3350 }
3351 
3352 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3353   SDNodeFlags Flags;
3354   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3355     Flags.copyFMF(*FPOp);
3356 
3357   SDValue Op = getValue(I.getOperand(0));
3358   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3359                                     Op, Flags);
3360   setValue(&I, UnNodeValue);
3361 }
3362 
3363 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3364   SDNodeFlags Flags;
3365   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3366     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3367     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3368   }
3369   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3370     Flags.setExact(ExactOp->isExact());
3371   if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&I))
3372     Flags.setDisjoint(DisjointOp->isDisjoint());
3373   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3374     Flags.copyFMF(*FPOp);
3375 
3376   SDValue Op1 = getValue(I.getOperand(0));
3377   SDValue Op2 = getValue(I.getOperand(1));
3378   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3379                                      Op1, Op2, Flags);
3380   setValue(&I, BinNodeValue);
3381 }
3382 
3383 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3384   SDValue Op1 = getValue(I.getOperand(0));
3385   SDValue Op2 = getValue(I.getOperand(1));
3386 
3387   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3388       Op1.getValueType(), DAG.getDataLayout());
3389 
3390   // Coerce the shift amount to the right type if we can. This exposes the
3391   // truncate or zext to optimization early.
3392   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3393     assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) &&
3394            "Unexpected shift type");
3395     Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3396   }
3397 
3398   bool nuw = false;
3399   bool nsw = false;
3400   bool exact = false;
3401 
3402   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3403 
3404     if (const OverflowingBinaryOperator *OFBinOp =
3405             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3406       nuw = OFBinOp->hasNoUnsignedWrap();
3407       nsw = OFBinOp->hasNoSignedWrap();
3408     }
3409     if (const PossiblyExactOperator *ExactOp =
3410             dyn_cast<const PossiblyExactOperator>(&I))
3411       exact = ExactOp->isExact();
3412   }
3413   SDNodeFlags Flags;
3414   Flags.setExact(exact);
3415   Flags.setNoSignedWrap(nsw);
3416   Flags.setNoUnsignedWrap(nuw);
3417   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3418                             Flags);
3419   setValue(&I, Res);
3420 }
3421 
3422 void SelectionDAGBuilder::visitSDiv(const User &I) {
3423   SDValue Op1 = getValue(I.getOperand(0));
3424   SDValue Op2 = getValue(I.getOperand(1));
3425 
3426   SDNodeFlags Flags;
3427   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3428                  cast<PossiblyExactOperator>(&I)->isExact());
3429   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3430                            Op2, Flags));
3431 }
3432 
3433 void SelectionDAGBuilder::visitICmp(const User &I) {
3434   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3435   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3436     predicate = IC->getPredicate();
3437   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3438     predicate = ICmpInst::Predicate(IC->getPredicate());
3439   SDValue Op1 = getValue(I.getOperand(0));
3440   SDValue Op2 = getValue(I.getOperand(1));
3441   ISD::CondCode Opcode = getICmpCondCode(predicate);
3442 
3443   auto &TLI = DAG.getTargetLoweringInfo();
3444   EVT MemVT =
3445       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3446 
3447   // If a pointer's DAG type is larger than its memory type then the DAG values
3448   // are zero-extended. This breaks signed comparisons so truncate back to the
3449   // underlying type before doing the compare.
3450   if (Op1.getValueType() != MemVT) {
3451     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3452     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3453   }
3454 
3455   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3456                                                         I.getType());
3457   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3458 }
3459 
3460 void SelectionDAGBuilder::visitFCmp(const User &I) {
3461   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3462   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3463     predicate = FC->getPredicate();
3464   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3465     predicate = FCmpInst::Predicate(FC->getPredicate());
3466   SDValue Op1 = getValue(I.getOperand(0));
3467   SDValue Op2 = getValue(I.getOperand(1));
3468 
3469   ISD::CondCode Condition = getFCmpCondCode(predicate);
3470   auto *FPMO = cast<FPMathOperator>(&I);
3471   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3472     Condition = getFCmpCodeWithoutNaN(Condition);
3473 
3474   SDNodeFlags Flags;
3475   Flags.copyFMF(*FPMO);
3476   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3477 
3478   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3479                                                         I.getType());
3480   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3481 }
3482 
3483 // Check if the condition of the select has one use or two users that are both
3484 // selects with the same condition.
3485 static bool hasOnlySelectUsers(const Value *Cond) {
3486   return llvm::all_of(Cond->users(), [](const Value *V) {
3487     return isa<SelectInst>(V);
3488   });
3489 }
3490 
3491 void SelectionDAGBuilder::visitSelect(const User &I) {
3492   SmallVector<EVT, 4> ValueVTs;
3493   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3494                   ValueVTs);
3495   unsigned NumValues = ValueVTs.size();
3496   if (NumValues == 0) return;
3497 
3498   SmallVector<SDValue, 4> Values(NumValues);
3499   SDValue Cond     = getValue(I.getOperand(0));
3500   SDValue LHSVal   = getValue(I.getOperand(1));
3501   SDValue RHSVal   = getValue(I.getOperand(2));
3502   SmallVector<SDValue, 1> BaseOps(1, Cond);
3503   ISD::NodeType OpCode =
3504       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3505 
3506   bool IsUnaryAbs = false;
3507   bool Negate = false;
3508 
3509   SDNodeFlags Flags;
3510   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3511     Flags.copyFMF(*FPOp);
3512 
3513   Flags.setUnpredictable(
3514       cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable));
3515 
3516   // Min/max matching is only viable if all output VTs are the same.
3517   if (all_equal(ValueVTs)) {
3518     EVT VT = ValueVTs[0];
3519     LLVMContext &Ctx = *DAG.getContext();
3520     auto &TLI = DAG.getTargetLoweringInfo();
3521 
3522     // We care about the legality of the operation after it has been type
3523     // legalized.
3524     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3525       VT = TLI.getTypeToTransformTo(Ctx, VT);
3526 
3527     // If the vselect is legal, assume we want to leave this as a vector setcc +
3528     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3529     // min/max is legal on the scalar type.
3530     bool UseScalarMinMax = VT.isVector() &&
3531       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3532 
3533     // ValueTracking's select pattern matching does not account for -0.0,
3534     // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that
3535     // -0.0 is less than +0.0.
3536     Value *LHS, *RHS;
3537     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3538     ISD::NodeType Opc = ISD::DELETED_NODE;
3539     switch (SPR.Flavor) {
3540     case SPF_UMAX:    Opc = ISD::UMAX; break;
3541     case SPF_UMIN:    Opc = ISD::UMIN; break;
3542     case SPF_SMAX:    Opc = ISD::SMAX; break;
3543     case SPF_SMIN:    Opc = ISD::SMIN; break;
3544     case SPF_FMINNUM:
3545       switch (SPR.NaNBehavior) {
3546       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3547       case SPNB_RETURNS_NAN: break;
3548       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3549       case SPNB_RETURNS_ANY:
3550         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) ||
3551             (UseScalarMinMax &&
3552              TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType())))
3553           Opc = ISD::FMINNUM;
3554         break;
3555       }
3556       break;
3557     case SPF_FMAXNUM:
3558       switch (SPR.NaNBehavior) {
3559       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3560       case SPNB_RETURNS_NAN: break;
3561       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3562       case SPNB_RETURNS_ANY:
3563         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) ||
3564             (UseScalarMinMax &&
3565              TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType())))
3566           Opc = ISD::FMAXNUM;
3567         break;
3568       }
3569       break;
3570     case SPF_NABS:
3571       Negate = true;
3572       [[fallthrough]];
3573     case SPF_ABS:
3574       IsUnaryAbs = true;
3575       Opc = ISD::ABS;
3576       break;
3577     default: break;
3578     }
3579 
3580     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3581         (TLI.isOperationLegalOrCustomOrPromote(Opc, VT) ||
3582          (UseScalarMinMax &&
3583           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3584         // If the underlying comparison instruction is used by any other
3585         // instruction, the consumed instructions won't be destroyed, so it is
3586         // not profitable to convert to a min/max.
3587         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3588       OpCode = Opc;
3589       LHSVal = getValue(LHS);
3590       RHSVal = getValue(RHS);
3591       BaseOps.clear();
3592     }
3593 
3594     if (IsUnaryAbs) {
3595       OpCode = Opc;
3596       LHSVal = getValue(LHS);
3597       BaseOps.clear();
3598     }
3599   }
3600 
3601   if (IsUnaryAbs) {
3602     for (unsigned i = 0; i != NumValues; ++i) {
3603       SDLoc dl = getCurSDLoc();
3604       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3605       Values[i] =
3606           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3607       if (Negate)
3608         Values[i] = DAG.getNegative(Values[i], dl, VT);
3609     }
3610   } else {
3611     for (unsigned i = 0; i != NumValues; ++i) {
3612       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3613       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3614       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3615       Values[i] = DAG.getNode(
3616           OpCode, getCurSDLoc(),
3617           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3618     }
3619   }
3620 
3621   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3622                            DAG.getVTList(ValueVTs), Values));
3623 }
3624 
3625 void SelectionDAGBuilder::visitTrunc(const User &I) {
3626   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3627   SDValue N = getValue(I.getOperand(0));
3628   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3629                                                         I.getType());
3630   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3631 }
3632 
3633 void SelectionDAGBuilder::visitZExt(const User &I) {
3634   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3635   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3636   SDValue N = getValue(I.getOperand(0));
3637   auto &TLI = DAG.getTargetLoweringInfo();
3638   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3639 
3640   SDNodeFlags Flags;
3641   if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
3642     Flags.setNonNeg(PNI->hasNonNeg());
3643 
3644   // Eagerly use nonneg information to canonicalize towards sign_extend if
3645   // that is the target's preference.
3646   // TODO: Let the target do this later.
3647   if (Flags.hasNonNeg() &&
3648       TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) {
3649     setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3650     return;
3651   }
3652 
3653   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags));
3654 }
3655 
3656 void SelectionDAGBuilder::visitSExt(const User &I) {
3657   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3658   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3659   SDValue N = getValue(I.getOperand(0));
3660   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3661                                                         I.getType());
3662   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3663 }
3664 
3665 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3666   // FPTrunc is never a no-op cast, no need to check
3667   SDValue N = getValue(I.getOperand(0));
3668   SDLoc dl = getCurSDLoc();
3669   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3670   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3671   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3672                            DAG.getTargetConstant(
3673                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3674 }
3675 
3676 void SelectionDAGBuilder::visitFPExt(const User &I) {
3677   // FPExt is never a no-op cast, no need to check
3678   SDValue N = getValue(I.getOperand(0));
3679   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3680                                                         I.getType());
3681   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3682 }
3683 
3684 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3685   // FPToUI is never a no-op cast, no need to check
3686   SDValue N = getValue(I.getOperand(0));
3687   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3688                                                         I.getType());
3689   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3690 }
3691 
3692 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3693   // FPToSI is never a no-op cast, no need to check
3694   SDValue N = getValue(I.getOperand(0));
3695   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3696                                                         I.getType());
3697   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3698 }
3699 
3700 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3701   // UIToFP is never a no-op cast, no need to check
3702   SDValue N = getValue(I.getOperand(0));
3703   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3704                                                         I.getType());
3705   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3706 }
3707 
3708 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3709   // SIToFP is never a no-op cast, no need to check
3710   SDValue N = getValue(I.getOperand(0));
3711   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3712                                                         I.getType());
3713   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3714 }
3715 
3716 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3717   // What to do depends on the size of the integer and the size of the pointer.
3718   // We can either truncate, zero extend, or no-op, accordingly.
3719   SDValue N = getValue(I.getOperand(0));
3720   auto &TLI = DAG.getTargetLoweringInfo();
3721   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3722                                                         I.getType());
3723   EVT PtrMemVT =
3724       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3725   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3726   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3727   setValue(&I, N);
3728 }
3729 
3730 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3731   // What to do depends on the size of the integer and the size of the pointer.
3732   // We can either truncate, zero extend, or no-op, accordingly.
3733   SDValue N = getValue(I.getOperand(0));
3734   auto &TLI = DAG.getTargetLoweringInfo();
3735   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3736   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3737   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3738   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3739   setValue(&I, N);
3740 }
3741 
3742 void SelectionDAGBuilder::visitBitCast(const User &I) {
3743   SDValue N = getValue(I.getOperand(0));
3744   SDLoc dl = getCurSDLoc();
3745   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3746                                                         I.getType());
3747 
3748   // BitCast assures us that source and destination are the same size so this is
3749   // either a BITCAST or a no-op.
3750   if (DestVT != N.getValueType())
3751     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3752                              DestVT, N)); // convert types.
3753   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3754   // might fold any kind of constant expression to an integer constant and that
3755   // is not what we are looking for. Only recognize a bitcast of a genuine
3756   // constant integer as an opaque constant.
3757   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3758     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3759                                  /*isOpaque*/true));
3760   else
3761     setValue(&I, N);            // noop cast.
3762 }
3763 
3764 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3765   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3766   const Value *SV = I.getOperand(0);
3767   SDValue N = getValue(SV);
3768   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3769 
3770   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3771   unsigned DestAS = I.getType()->getPointerAddressSpace();
3772 
3773   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3774     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3775 
3776   setValue(&I, N);
3777 }
3778 
3779 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3780   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3781   SDValue InVec = getValue(I.getOperand(0));
3782   SDValue InVal = getValue(I.getOperand(1));
3783   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3784                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3785   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3786                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3787                            InVec, InVal, InIdx));
3788 }
3789 
3790 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3791   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3792   SDValue InVec = getValue(I.getOperand(0));
3793   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3794                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3795   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3796                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3797                            InVec, InIdx));
3798 }
3799 
3800 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3801   SDValue Src1 = getValue(I.getOperand(0));
3802   SDValue Src2 = getValue(I.getOperand(1));
3803   ArrayRef<int> Mask;
3804   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3805     Mask = SVI->getShuffleMask();
3806   else
3807     Mask = cast<ConstantExpr>(I).getShuffleMask();
3808   SDLoc DL = getCurSDLoc();
3809   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3810   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3811   EVT SrcVT = Src1.getValueType();
3812 
3813   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3814       VT.isScalableVector()) {
3815     // Canonical splat form of first element of first input vector.
3816     SDValue FirstElt =
3817         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3818                     DAG.getVectorIdxConstant(0, DL));
3819     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3820     return;
3821   }
3822 
3823   // For now, we only handle splats for scalable vectors.
3824   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3825   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3826   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3827 
3828   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3829   unsigned MaskNumElts = Mask.size();
3830 
3831   if (SrcNumElts == MaskNumElts) {
3832     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3833     return;
3834   }
3835 
3836   // Normalize the shuffle vector since mask and vector length don't match.
3837   if (SrcNumElts < MaskNumElts) {
3838     // Mask is longer than the source vectors. We can use concatenate vector to
3839     // make the mask and vectors lengths match.
3840 
3841     if (MaskNumElts % SrcNumElts == 0) {
3842       // Mask length is a multiple of the source vector length.
3843       // Check if the shuffle is some kind of concatenation of the input
3844       // vectors.
3845       unsigned NumConcat = MaskNumElts / SrcNumElts;
3846       bool IsConcat = true;
3847       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3848       for (unsigned i = 0; i != MaskNumElts; ++i) {
3849         int Idx = Mask[i];
3850         if (Idx < 0)
3851           continue;
3852         // Ensure the indices in each SrcVT sized piece are sequential and that
3853         // the same source is used for the whole piece.
3854         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3855             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3856              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3857           IsConcat = false;
3858           break;
3859         }
3860         // Remember which source this index came from.
3861         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3862       }
3863 
3864       // The shuffle is concatenating multiple vectors together. Just emit
3865       // a CONCAT_VECTORS operation.
3866       if (IsConcat) {
3867         SmallVector<SDValue, 8> ConcatOps;
3868         for (auto Src : ConcatSrcs) {
3869           if (Src < 0)
3870             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3871           else if (Src == 0)
3872             ConcatOps.push_back(Src1);
3873           else
3874             ConcatOps.push_back(Src2);
3875         }
3876         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3877         return;
3878       }
3879     }
3880 
3881     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3882     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3883     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3884                                     PaddedMaskNumElts);
3885 
3886     // Pad both vectors with undefs to make them the same length as the mask.
3887     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3888 
3889     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3890     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3891     MOps1[0] = Src1;
3892     MOps2[0] = Src2;
3893 
3894     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3895     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3896 
3897     // Readjust mask for new input vector length.
3898     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3899     for (unsigned i = 0; i != MaskNumElts; ++i) {
3900       int Idx = Mask[i];
3901       if (Idx >= (int)SrcNumElts)
3902         Idx -= SrcNumElts - PaddedMaskNumElts;
3903       MappedOps[i] = Idx;
3904     }
3905 
3906     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3907 
3908     // If the concatenated vector was padded, extract a subvector with the
3909     // correct number of elements.
3910     if (MaskNumElts != PaddedMaskNumElts)
3911       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3912                            DAG.getVectorIdxConstant(0, DL));
3913 
3914     setValue(&I, Result);
3915     return;
3916   }
3917 
3918   if (SrcNumElts > MaskNumElts) {
3919     // Analyze the access pattern of the vector to see if we can extract
3920     // two subvectors and do the shuffle.
3921     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3922     bool CanExtract = true;
3923     for (int Idx : Mask) {
3924       unsigned Input = 0;
3925       if (Idx < 0)
3926         continue;
3927 
3928       if (Idx >= (int)SrcNumElts) {
3929         Input = 1;
3930         Idx -= SrcNumElts;
3931       }
3932 
3933       // If all the indices come from the same MaskNumElts sized portion of
3934       // the sources we can use extract. Also make sure the extract wouldn't
3935       // extract past the end of the source.
3936       int NewStartIdx = alignDown(Idx, MaskNumElts);
3937       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3938           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3939         CanExtract = false;
3940       // Make sure we always update StartIdx as we use it to track if all
3941       // elements are undef.
3942       StartIdx[Input] = NewStartIdx;
3943     }
3944 
3945     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3946       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3947       return;
3948     }
3949     if (CanExtract) {
3950       // Extract appropriate subvector and generate a vector shuffle
3951       for (unsigned Input = 0; Input < 2; ++Input) {
3952         SDValue &Src = Input == 0 ? Src1 : Src2;
3953         if (StartIdx[Input] < 0)
3954           Src = DAG.getUNDEF(VT);
3955         else {
3956           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3957                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3958         }
3959       }
3960 
3961       // Calculate new mask.
3962       SmallVector<int, 8> MappedOps(Mask);
3963       for (int &Idx : MappedOps) {
3964         if (Idx >= (int)SrcNumElts)
3965           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3966         else if (Idx >= 0)
3967           Idx -= StartIdx[0];
3968       }
3969 
3970       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3971       return;
3972     }
3973   }
3974 
3975   // We can't use either concat vectors or extract subvectors so fall back to
3976   // replacing the shuffle with extract and build vector.
3977   // to insert and build vector.
3978   EVT EltVT = VT.getVectorElementType();
3979   SmallVector<SDValue,8> Ops;
3980   for (int Idx : Mask) {
3981     SDValue Res;
3982 
3983     if (Idx < 0) {
3984       Res = DAG.getUNDEF(EltVT);
3985     } else {
3986       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3987       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3988 
3989       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3990                         DAG.getVectorIdxConstant(Idx, DL));
3991     }
3992 
3993     Ops.push_back(Res);
3994   }
3995 
3996   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3997 }
3998 
3999 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
4000   ArrayRef<unsigned> Indices = I.getIndices();
4001   const Value *Op0 = I.getOperand(0);
4002   const Value *Op1 = I.getOperand(1);
4003   Type *AggTy = I.getType();
4004   Type *ValTy = Op1->getType();
4005   bool IntoUndef = isa<UndefValue>(Op0);
4006   bool FromUndef = isa<UndefValue>(Op1);
4007 
4008   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4009 
4010   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4011   SmallVector<EVT, 4> AggValueVTs;
4012   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
4013   SmallVector<EVT, 4> ValValueVTs;
4014   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4015 
4016   unsigned NumAggValues = AggValueVTs.size();
4017   unsigned NumValValues = ValValueVTs.size();
4018   SmallVector<SDValue, 4> Values(NumAggValues);
4019 
4020   // Ignore an insertvalue that produces an empty object
4021   if (!NumAggValues) {
4022     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4023     return;
4024   }
4025 
4026   SDValue Agg = getValue(Op0);
4027   unsigned i = 0;
4028   // Copy the beginning value(s) from the original aggregate.
4029   for (; i != LinearIndex; ++i)
4030     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4031                 SDValue(Agg.getNode(), Agg.getResNo() + i);
4032   // Copy values from the inserted value(s).
4033   if (NumValValues) {
4034     SDValue Val = getValue(Op1);
4035     for (; i != LinearIndex + NumValValues; ++i)
4036       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4037                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
4038   }
4039   // Copy remaining value(s) from the original aggregate.
4040   for (; i != NumAggValues; ++i)
4041     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4042                 SDValue(Agg.getNode(), Agg.getResNo() + i);
4043 
4044   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
4045                            DAG.getVTList(AggValueVTs), Values));
4046 }
4047 
4048 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
4049   ArrayRef<unsigned> Indices = I.getIndices();
4050   const Value *Op0 = I.getOperand(0);
4051   Type *AggTy = Op0->getType();
4052   Type *ValTy = I.getType();
4053   bool OutOfUndef = isa<UndefValue>(Op0);
4054 
4055   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4056 
4057   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4058   SmallVector<EVT, 4> ValValueVTs;
4059   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4060 
4061   unsigned NumValValues = ValValueVTs.size();
4062 
4063   // Ignore a extractvalue that produces an empty object
4064   if (!NumValValues) {
4065     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4066     return;
4067   }
4068 
4069   SmallVector<SDValue, 4> Values(NumValValues);
4070 
4071   SDValue Agg = getValue(Op0);
4072   // Copy out the selected value(s).
4073   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
4074     Values[i - LinearIndex] =
4075       OutOfUndef ?
4076         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
4077         SDValue(Agg.getNode(), Agg.getResNo() + i);
4078 
4079   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
4080                            DAG.getVTList(ValValueVTs), Values));
4081 }
4082 
4083 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
4084   Value *Op0 = I.getOperand(0);
4085   // Note that the pointer operand may be a vector of pointers. Take the scalar
4086   // element which holds a pointer.
4087   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
4088   SDValue N = getValue(Op0);
4089   SDLoc dl = getCurSDLoc();
4090   auto &TLI = DAG.getTargetLoweringInfo();
4091 
4092   // Normalize Vector GEP - all scalar operands should be converted to the
4093   // splat vector.
4094   bool IsVectorGEP = I.getType()->isVectorTy();
4095   ElementCount VectorElementCount =
4096       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
4097                   : ElementCount::getFixed(0);
4098 
4099   if (IsVectorGEP && !N.getValueType().isVector()) {
4100     LLVMContext &Context = *DAG.getContext();
4101     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
4102     N = DAG.getSplat(VT, dl, N);
4103   }
4104 
4105   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
4106        GTI != E; ++GTI) {
4107     const Value *Idx = GTI.getOperand();
4108     if (StructType *StTy = GTI.getStructTypeOrNull()) {
4109       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
4110       if (Field) {
4111         // N = N + Offset
4112         uint64_t Offset =
4113             DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
4114 
4115         // In an inbounds GEP with an offset that is nonnegative even when
4116         // interpreted as signed, assume there is no unsigned overflow.
4117         SDNodeFlags Flags;
4118         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
4119           Flags.setNoUnsignedWrap(true);
4120 
4121         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
4122                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
4123       }
4124     } else {
4125       // IdxSize is the width of the arithmetic according to IR semantics.
4126       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
4127       // (and fix up the result later).
4128       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
4129       MVT IdxTy = MVT::getIntegerVT(IdxSize);
4130       TypeSize ElementSize =
4131           GTI.getSequentialElementStride(DAG.getDataLayout());
4132       // We intentionally mask away the high bits here; ElementSize may not
4133       // fit in IdxTy.
4134       APInt ElementMul(IdxSize, ElementSize.getKnownMinValue());
4135       bool ElementScalable = ElementSize.isScalable();
4136 
4137       // If this is a scalar constant or a splat vector of constants,
4138       // handle it quickly.
4139       const auto *C = dyn_cast<Constant>(Idx);
4140       if (C && isa<VectorType>(C->getType()))
4141         C = C->getSplatValue();
4142 
4143       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
4144       if (CI && CI->isZero())
4145         continue;
4146       if (CI && !ElementScalable) {
4147         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
4148         LLVMContext &Context = *DAG.getContext();
4149         SDValue OffsVal;
4150         if (IsVectorGEP)
4151           OffsVal = DAG.getConstant(
4152               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
4153         else
4154           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
4155 
4156         // In an inbounds GEP with an offset that is nonnegative even when
4157         // interpreted as signed, assume there is no unsigned overflow.
4158         SDNodeFlags Flags;
4159         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
4160           Flags.setNoUnsignedWrap(true);
4161 
4162         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
4163 
4164         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
4165         continue;
4166       }
4167 
4168       // N = N + Idx * ElementMul;
4169       SDValue IdxN = getValue(Idx);
4170 
4171       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
4172         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
4173                                   VectorElementCount);
4174         IdxN = DAG.getSplat(VT, dl, IdxN);
4175       }
4176 
4177       // If the index is smaller or larger than intptr_t, truncate or extend
4178       // it.
4179       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
4180 
4181       if (ElementScalable) {
4182         EVT VScaleTy = N.getValueType().getScalarType();
4183         SDValue VScale = DAG.getNode(
4184             ISD::VSCALE, dl, VScaleTy,
4185             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
4186         if (IsVectorGEP)
4187           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
4188         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
4189       } else {
4190         // If this is a multiply by a power of two, turn it into a shl
4191         // immediately.  This is a very common case.
4192         if (ElementMul != 1) {
4193           if (ElementMul.isPowerOf2()) {
4194             unsigned Amt = ElementMul.logBase2();
4195             IdxN = DAG.getNode(ISD::SHL, dl,
4196                                N.getValueType(), IdxN,
4197                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
4198           } else {
4199             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
4200                                             IdxN.getValueType());
4201             IdxN = DAG.getNode(ISD::MUL, dl,
4202                                N.getValueType(), IdxN, Scale);
4203           }
4204         }
4205       }
4206 
4207       N = DAG.getNode(ISD::ADD, dl,
4208                       N.getValueType(), N, IdxN);
4209     }
4210   }
4211 
4212   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4213   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4214   if (IsVectorGEP) {
4215     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4216     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4217   }
4218 
4219   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4220     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4221 
4222   setValue(&I, N);
4223 }
4224 
4225 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4226   // If this is a fixed sized alloca in the entry block of the function,
4227   // allocate it statically on the stack.
4228   if (FuncInfo.StaticAllocaMap.count(&I))
4229     return;   // getValue will auto-populate this.
4230 
4231   SDLoc dl = getCurSDLoc();
4232   Type *Ty = I.getAllocatedType();
4233   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4234   auto &DL = DAG.getDataLayout();
4235   TypeSize TySize = DL.getTypeAllocSize(Ty);
4236   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4237 
4238   SDValue AllocSize = getValue(I.getArraySize());
4239 
4240   EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace());
4241   if (AllocSize.getValueType() != IntPtr)
4242     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4243 
4244   if (TySize.isScalable())
4245     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4246                             DAG.getVScale(dl, IntPtr,
4247                                           APInt(IntPtr.getScalarSizeInBits(),
4248                                                 TySize.getKnownMinValue())));
4249   else {
4250     SDValue TySizeValue =
4251         DAG.getConstant(TySize.getFixedValue(), dl, MVT::getIntegerVT(64));
4252     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4253                             DAG.getZExtOrTrunc(TySizeValue, dl, IntPtr));
4254   }
4255 
4256   // Handle alignment.  If the requested alignment is less than or equal to
4257   // the stack alignment, ignore it.  If the size is greater than or equal to
4258   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4259   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4260   if (*Alignment <= StackAlign)
4261     Alignment = std::nullopt;
4262 
4263   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4264   // Round the size of the allocation up to the stack alignment size
4265   // by add SA-1 to the size. This doesn't overflow because we're computing
4266   // an address inside an alloca.
4267   SDNodeFlags Flags;
4268   Flags.setNoUnsignedWrap(true);
4269   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4270                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4271 
4272   // Mask out the low bits for alignment purposes.
4273   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4274                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
4275 
4276   SDValue Ops[] = {
4277       getRoot(), AllocSize,
4278       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4279   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4280   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4281   setValue(&I, DSA);
4282   DAG.setRoot(DSA.getValue(1));
4283 
4284   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4285 }
4286 
4287 static const MDNode *getRangeMetadata(const Instruction &I) {
4288   // If !noundef is not present, then !range violation results in a poison
4289   // value rather than immediate undefined behavior. In theory, transferring
4290   // these annotations to SDAG is fine, but in practice there are key SDAG
4291   // transforms that are known not to be poison-safe, such as folding logical
4292   // and/or to bitwise and/or. For now, only transfer !range if !noundef is
4293   // also present.
4294   if (!I.hasMetadata(LLVMContext::MD_noundef))
4295     return nullptr;
4296   return I.getMetadata(LLVMContext::MD_range);
4297 }
4298 
4299 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4300   if (I.isAtomic())
4301     return visitAtomicLoad(I);
4302 
4303   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4304   const Value *SV = I.getOperand(0);
4305   if (TLI.supportSwiftError()) {
4306     // Swifterror values can come from either a function parameter with
4307     // swifterror attribute or an alloca with swifterror attribute.
4308     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4309       if (Arg->hasSwiftErrorAttr())
4310         return visitLoadFromSwiftError(I);
4311     }
4312 
4313     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4314       if (Alloca->isSwiftError())
4315         return visitLoadFromSwiftError(I);
4316     }
4317   }
4318 
4319   SDValue Ptr = getValue(SV);
4320 
4321   Type *Ty = I.getType();
4322   SmallVector<EVT, 4> ValueVTs, MemVTs;
4323   SmallVector<TypeSize, 4> Offsets;
4324   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets, 0);
4325   unsigned NumValues = ValueVTs.size();
4326   if (NumValues == 0)
4327     return;
4328 
4329   Align Alignment = I.getAlign();
4330   AAMDNodes AAInfo = I.getAAMetadata();
4331   const MDNode *Ranges = getRangeMetadata(I);
4332   bool isVolatile = I.isVolatile();
4333   MachineMemOperand::Flags MMOFlags =
4334       TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4335 
4336   SDValue Root;
4337   bool ConstantMemory = false;
4338   if (isVolatile)
4339     // Serialize volatile loads with other side effects.
4340     Root = getRoot();
4341   else if (NumValues > MaxParallelChains)
4342     Root = getMemoryRoot();
4343   else if (AA &&
4344            AA->pointsToConstantMemory(MemoryLocation(
4345                SV,
4346                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4347                AAInfo))) {
4348     // Do not serialize (non-volatile) loads of constant memory with anything.
4349     Root = DAG.getEntryNode();
4350     ConstantMemory = true;
4351     MMOFlags |= MachineMemOperand::MOInvariant;
4352   } else {
4353     // Do not serialize non-volatile loads against each other.
4354     Root = DAG.getRoot();
4355   }
4356 
4357   SDLoc dl = getCurSDLoc();
4358 
4359   if (isVolatile)
4360     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4361 
4362   SmallVector<SDValue, 4> Values(NumValues);
4363   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4364 
4365   unsigned ChainI = 0;
4366   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4367     // Serializing loads here may result in excessive register pressure, and
4368     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4369     // could recover a bit by hoisting nodes upward in the chain by recognizing
4370     // they are side-effect free or do not alias. The optimizer should really
4371     // avoid this case by converting large object/array copies to llvm.memcpy
4372     // (MaxParallelChains should always remain as failsafe).
4373     if (ChainI == MaxParallelChains) {
4374       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4375       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4376                                   ArrayRef(Chains.data(), ChainI));
4377       Root = Chain;
4378       ChainI = 0;
4379     }
4380 
4381     // TODO: MachinePointerInfo only supports a fixed length offset.
4382     MachinePointerInfo PtrInfo =
4383         !Offsets[i].isScalable() || Offsets[i].isZero()
4384             ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue())
4385             : MachinePointerInfo();
4386 
4387     SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4388     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment,
4389                             MMOFlags, AAInfo, Ranges);
4390     Chains[ChainI] = L.getValue(1);
4391 
4392     if (MemVTs[i] != ValueVTs[i])
4393       L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]);
4394 
4395     Values[i] = L;
4396   }
4397 
4398   if (!ConstantMemory) {
4399     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4400                                 ArrayRef(Chains.data(), ChainI));
4401     if (isVolatile)
4402       DAG.setRoot(Chain);
4403     else
4404       PendingLoads.push_back(Chain);
4405   }
4406 
4407   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4408                            DAG.getVTList(ValueVTs), Values));
4409 }
4410 
4411 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4412   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4413          "call visitStoreToSwiftError when backend supports swifterror");
4414 
4415   SmallVector<EVT, 4> ValueVTs;
4416   SmallVector<uint64_t, 4> Offsets;
4417   const Value *SrcV = I.getOperand(0);
4418   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4419                   SrcV->getType(), ValueVTs, &Offsets, 0);
4420   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4421          "expect a single EVT for swifterror");
4422 
4423   SDValue Src = getValue(SrcV);
4424   // Create a virtual register, then update the virtual register.
4425   Register VReg =
4426       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4427   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4428   // Chain can be getRoot or getControlRoot.
4429   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4430                                       SDValue(Src.getNode(), Src.getResNo()));
4431   DAG.setRoot(CopyNode);
4432 }
4433 
4434 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4435   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4436          "call visitLoadFromSwiftError when backend supports swifterror");
4437 
4438   assert(!I.isVolatile() &&
4439          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4440          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4441          "Support volatile, non temporal, invariant for load_from_swift_error");
4442 
4443   const Value *SV = I.getOperand(0);
4444   Type *Ty = I.getType();
4445   assert(
4446       (!AA ||
4447        !AA->pointsToConstantMemory(MemoryLocation(
4448            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4449            I.getAAMetadata()))) &&
4450       "load_from_swift_error should not be constant memory");
4451 
4452   SmallVector<EVT, 4> ValueVTs;
4453   SmallVector<uint64_t, 4> Offsets;
4454   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4455                   ValueVTs, &Offsets, 0);
4456   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4457          "expect a single EVT for swifterror");
4458 
4459   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4460   SDValue L = DAG.getCopyFromReg(
4461       getRoot(), getCurSDLoc(),
4462       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4463 
4464   setValue(&I, L);
4465 }
4466 
4467 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4468   if (I.isAtomic())
4469     return visitAtomicStore(I);
4470 
4471   const Value *SrcV = I.getOperand(0);
4472   const Value *PtrV = I.getOperand(1);
4473 
4474   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4475   if (TLI.supportSwiftError()) {
4476     // Swifterror values can come from either a function parameter with
4477     // swifterror attribute or an alloca with swifterror attribute.
4478     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4479       if (Arg->hasSwiftErrorAttr())
4480         return visitStoreToSwiftError(I);
4481     }
4482 
4483     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4484       if (Alloca->isSwiftError())
4485         return visitStoreToSwiftError(I);
4486     }
4487   }
4488 
4489   SmallVector<EVT, 4> ValueVTs, MemVTs;
4490   SmallVector<TypeSize, 4> Offsets;
4491   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4492                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets, 0);
4493   unsigned NumValues = ValueVTs.size();
4494   if (NumValues == 0)
4495     return;
4496 
4497   // Get the lowered operands. Note that we do this after
4498   // checking if NumResults is zero, because with zero results
4499   // the operands won't have values in the map.
4500   SDValue Src = getValue(SrcV);
4501   SDValue Ptr = getValue(PtrV);
4502 
4503   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4504   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4505   SDLoc dl = getCurSDLoc();
4506   Align Alignment = I.getAlign();
4507   AAMDNodes AAInfo = I.getAAMetadata();
4508 
4509   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4510 
4511   unsigned ChainI = 0;
4512   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4513     // See visitLoad comments.
4514     if (ChainI == MaxParallelChains) {
4515       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4516                                   ArrayRef(Chains.data(), ChainI));
4517       Root = Chain;
4518       ChainI = 0;
4519     }
4520 
4521     // TODO: MachinePointerInfo only supports a fixed length offset.
4522     MachinePointerInfo PtrInfo =
4523         !Offsets[i].isScalable() || Offsets[i].isZero()
4524             ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue())
4525             : MachinePointerInfo();
4526 
4527     SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4528     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4529     if (MemVTs[i] != ValueVTs[i])
4530       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4531     SDValue St =
4532         DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags, AAInfo);
4533     Chains[ChainI] = St;
4534   }
4535 
4536   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4537                                   ArrayRef(Chains.data(), ChainI));
4538   setValue(&I, StoreNode);
4539   DAG.setRoot(StoreNode);
4540 }
4541 
4542 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4543                                            bool IsCompressing) {
4544   SDLoc sdl = getCurSDLoc();
4545 
4546   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4547                                MaybeAlign &Alignment) {
4548     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4549     Src0 = I.getArgOperand(0);
4550     Ptr = I.getArgOperand(1);
4551     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
4552     Mask = I.getArgOperand(3);
4553   };
4554   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4555                                     MaybeAlign &Alignment) {
4556     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4557     Src0 = I.getArgOperand(0);
4558     Ptr = I.getArgOperand(1);
4559     Mask = I.getArgOperand(2);
4560     Alignment = std::nullopt;
4561   };
4562 
4563   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4564   MaybeAlign Alignment;
4565   if (IsCompressing)
4566     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4567   else
4568     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4569 
4570   SDValue Ptr = getValue(PtrOperand);
4571   SDValue Src0 = getValue(Src0Operand);
4572   SDValue Mask = getValue(MaskOperand);
4573   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4574 
4575   EVT VT = Src0.getValueType();
4576   if (!Alignment)
4577     Alignment = DAG.getEVTAlign(VT);
4578 
4579   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4580       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4581       MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata());
4582   SDValue StoreNode =
4583       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4584                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4585   DAG.setRoot(StoreNode);
4586   setValue(&I, StoreNode);
4587 }
4588 
4589 // Get a uniform base for the Gather/Scatter intrinsic.
4590 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4591 // We try to represent it as a base pointer + vector of indices.
4592 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4593 // The first operand of the GEP may be a single pointer or a vector of pointers
4594 // Example:
4595 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4596 //  or
4597 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4598 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4599 //
4600 // When the first GEP operand is a single pointer - it is the uniform base we
4601 // are looking for. If first operand of the GEP is a splat vector - we
4602 // extract the splat value and use it as a uniform base.
4603 // In all other cases the function returns 'false'.
4604 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4605                            ISD::MemIndexType &IndexType, SDValue &Scale,
4606                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB,
4607                            uint64_t ElemSize) {
4608   SelectionDAG& DAG = SDB->DAG;
4609   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4610   const DataLayout &DL = DAG.getDataLayout();
4611 
4612   assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4613 
4614   // Handle splat constant pointer.
4615   if (auto *C = dyn_cast<Constant>(Ptr)) {
4616     C = C->getSplatValue();
4617     if (!C)
4618       return false;
4619 
4620     Base = SDB->getValue(C);
4621 
4622     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4623     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4624     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4625     IndexType = ISD::SIGNED_SCALED;
4626     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4627     return true;
4628   }
4629 
4630   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4631   if (!GEP || GEP->getParent() != CurBB)
4632     return false;
4633 
4634   if (GEP->getNumOperands() != 2)
4635     return false;
4636 
4637   const Value *BasePtr = GEP->getPointerOperand();
4638   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4639 
4640   // Make sure the base is scalar and the index is a vector.
4641   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4642     return false;
4643 
4644   TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
4645   if (ScaleVal.isScalable())
4646     return false;
4647 
4648   // Target may not support the required addressing mode.
4649   if (ScaleVal != 1 &&
4650       !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize))
4651     return false;
4652 
4653   Base = SDB->getValue(BasePtr);
4654   Index = SDB->getValue(IndexVal);
4655   IndexType = ISD::SIGNED_SCALED;
4656 
4657   Scale =
4658       DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4659   return true;
4660 }
4661 
4662 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4663   SDLoc sdl = getCurSDLoc();
4664 
4665   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4666   const Value *Ptr = I.getArgOperand(1);
4667   SDValue Src0 = getValue(I.getArgOperand(0));
4668   SDValue Mask = getValue(I.getArgOperand(3));
4669   EVT VT = Src0.getValueType();
4670   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4671                         ->getMaybeAlignValue()
4672                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4673   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4674 
4675   SDValue Base;
4676   SDValue Index;
4677   ISD::MemIndexType IndexType;
4678   SDValue Scale;
4679   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4680                                     I.getParent(), VT.getScalarStoreSize());
4681 
4682   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4683   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4684       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4685       // TODO: Make MachineMemOperands aware of scalable
4686       // vectors.
4687       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata());
4688   if (!UniformBase) {
4689     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4690     Index = getValue(Ptr);
4691     IndexType = ISD::SIGNED_SCALED;
4692     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4693   }
4694 
4695   EVT IdxVT = Index.getValueType();
4696   EVT EltTy = IdxVT.getVectorElementType();
4697   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4698     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4699     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4700   }
4701 
4702   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4703   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4704                                          Ops, MMO, IndexType, false);
4705   DAG.setRoot(Scatter);
4706   setValue(&I, Scatter);
4707 }
4708 
4709 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4710   SDLoc sdl = getCurSDLoc();
4711 
4712   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4713                               MaybeAlign &Alignment) {
4714     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4715     Ptr = I.getArgOperand(0);
4716     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4717     Mask = I.getArgOperand(2);
4718     Src0 = I.getArgOperand(3);
4719   };
4720   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4721                                  MaybeAlign &Alignment) {
4722     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4723     Ptr = I.getArgOperand(0);
4724     Alignment = std::nullopt;
4725     Mask = I.getArgOperand(1);
4726     Src0 = I.getArgOperand(2);
4727   };
4728 
4729   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4730   MaybeAlign Alignment;
4731   if (IsExpanding)
4732     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4733   else
4734     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4735 
4736   SDValue Ptr = getValue(PtrOperand);
4737   SDValue Src0 = getValue(Src0Operand);
4738   SDValue Mask = getValue(MaskOperand);
4739   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4740 
4741   EVT VT = Src0.getValueType();
4742   if (!Alignment)
4743     Alignment = DAG.getEVTAlign(VT);
4744 
4745   AAMDNodes AAInfo = I.getAAMetadata();
4746   const MDNode *Ranges = getRangeMetadata(I);
4747 
4748   // Do not serialize masked loads of constant memory with anything.
4749   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
4750   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4751 
4752   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4753 
4754   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4755       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4756       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
4757 
4758   SDValue Load =
4759       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4760                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4761   if (AddToChain)
4762     PendingLoads.push_back(Load.getValue(1));
4763   setValue(&I, Load);
4764 }
4765 
4766 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4767   SDLoc sdl = getCurSDLoc();
4768 
4769   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4770   const Value *Ptr = I.getArgOperand(0);
4771   SDValue Src0 = getValue(I.getArgOperand(3));
4772   SDValue Mask = getValue(I.getArgOperand(2));
4773 
4774   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4775   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4776   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4777                         ->getMaybeAlignValue()
4778                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4779 
4780   const MDNode *Ranges = getRangeMetadata(I);
4781 
4782   SDValue Root = DAG.getRoot();
4783   SDValue Base;
4784   SDValue Index;
4785   ISD::MemIndexType IndexType;
4786   SDValue Scale;
4787   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4788                                     I.getParent(), VT.getScalarStoreSize());
4789   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4790   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4791       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4792       // TODO: Make MachineMemOperands aware of scalable
4793       // vectors.
4794       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
4795 
4796   if (!UniformBase) {
4797     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4798     Index = getValue(Ptr);
4799     IndexType = ISD::SIGNED_SCALED;
4800     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4801   }
4802 
4803   EVT IdxVT = Index.getValueType();
4804   EVT EltTy = IdxVT.getVectorElementType();
4805   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4806     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4807     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4808   }
4809 
4810   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4811   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4812                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
4813 
4814   PendingLoads.push_back(Gather.getValue(1));
4815   setValue(&I, Gather);
4816 }
4817 
4818 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4819   SDLoc dl = getCurSDLoc();
4820   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4821   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4822   SyncScope::ID SSID = I.getSyncScopeID();
4823 
4824   SDValue InChain = getRoot();
4825 
4826   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4827   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4828 
4829   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4830   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4831 
4832   MachineFunction &MF = DAG.getMachineFunction();
4833   MachineMemOperand *MMO = MF.getMachineMemOperand(
4834       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4835       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4836       FailureOrdering);
4837 
4838   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4839                                    dl, MemVT, VTs, InChain,
4840                                    getValue(I.getPointerOperand()),
4841                                    getValue(I.getCompareOperand()),
4842                                    getValue(I.getNewValOperand()), MMO);
4843 
4844   SDValue OutChain = L.getValue(2);
4845 
4846   setValue(&I, L);
4847   DAG.setRoot(OutChain);
4848 }
4849 
4850 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4851   SDLoc dl = getCurSDLoc();
4852   ISD::NodeType NT;
4853   switch (I.getOperation()) {
4854   default: llvm_unreachable("Unknown atomicrmw operation");
4855   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4856   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4857   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4858   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4859   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4860   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4861   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4862   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4863   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4864   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4865   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4866   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4867   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4868   case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break;
4869   case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break;
4870   case AtomicRMWInst::UIncWrap:
4871     NT = ISD::ATOMIC_LOAD_UINC_WRAP;
4872     break;
4873   case AtomicRMWInst::UDecWrap:
4874     NT = ISD::ATOMIC_LOAD_UDEC_WRAP;
4875     break;
4876   }
4877   AtomicOrdering Ordering = I.getOrdering();
4878   SyncScope::ID SSID = I.getSyncScopeID();
4879 
4880   SDValue InChain = getRoot();
4881 
4882   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4883   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4884   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4885 
4886   MachineFunction &MF = DAG.getMachineFunction();
4887   MachineMemOperand *MMO = MF.getMachineMemOperand(
4888       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4889       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4890 
4891   SDValue L =
4892     DAG.getAtomic(NT, dl, MemVT, InChain,
4893                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4894                   MMO);
4895 
4896   SDValue OutChain = L.getValue(1);
4897 
4898   setValue(&I, L);
4899   DAG.setRoot(OutChain);
4900 }
4901 
4902 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4903   SDLoc dl = getCurSDLoc();
4904   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4905   SDValue Ops[3];
4906   Ops[0] = getRoot();
4907   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4908                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4909   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4910                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4911   SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
4912   setValue(&I, N);
4913   DAG.setRoot(N);
4914 }
4915 
4916 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4917   SDLoc dl = getCurSDLoc();
4918   AtomicOrdering Order = I.getOrdering();
4919   SyncScope::ID SSID = I.getSyncScopeID();
4920 
4921   SDValue InChain = getRoot();
4922 
4923   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4924   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4925   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4926 
4927   if (!TLI.supportsUnalignedAtomics() &&
4928       I.getAlign().value() < MemVT.getSizeInBits() / 8)
4929     report_fatal_error("Cannot generate unaligned atomic load");
4930 
4931   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4932 
4933   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4934       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4935       I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4936 
4937   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4938 
4939   SDValue Ptr = getValue(I.getPointerOperand());
4940   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4941                             Ptr, MMO);
4942 
4943   SDValue OutChain = L.getValue(1);
4944   if (MemVT != VT)
4945     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4946 
4947   setValue(&I, L);
4948   DAG.setRoot(OutChain);
4949 }
4950 
4951 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4952   SDLoc dl = getCurSDLoc();
4953 
4954   AtomicOrdering Ordering = I.getOrdering();
4955   SyncScope::ID SSID = I.getSyncScopeID();
4956 
4957   SDValue InChain = getRoot();
4958 
4959   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4960   EVT MemVT =
4961       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4962 
4963   if (!TLI.supportsUnalignedAtomics() &&
4964       I.getAlign().value() < MemVT.getSizeInBits() / 8)
4965     report_fatal_error("Cannot generate unaligned atomic store");
4966 
4967   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4968 
4969   MachineFunction &MF = DAG.getMachineFunction();
4970   MachineMemOperand *MMO = MF.getMachineMemOperand(
4971       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4972       I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4973 
4974   SDValue Val = getValue(I.getValueOperand());
4975   if (Val.getValueType() != MemVT)
4976     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4977   SDValue Ptr = getValue(I.getPointerOperand());
4978 
4979   SDValue OutChain =
4980       DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO);
4981 
4982   setValue(&I, OutChain);
4983   DAG.setRoot(OutChain);
4984 }
4985 
4986 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4987 /// node.
4988 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4989                                                unsigned Intrinsic) {
4990   // Ignore the callsite's attributes. A specific call site may be marked with
4991   // readnone, but the lowering code will expect the chain based on the
4992   // definition.
4993   const Function *F = I.getCalledFunction();
4994   bool HasChain = !F->doesNotAccessMemory();
4995   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4996 
4997   // Build the operand list.
4998   SmallVector<SDValue, 8> Ops;
4999   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
5000     if (OnlyLoad) {
5001       // We don't need to serialize loads against other loads.
5002       Ops.push_back(DAG.getRoot());
5003     } else {
5004       Ops.push_back(getRoot());
5005     }
5006   }
5007 
5008   // Info is set by getTgtMemIntrinsic
5009   TargetLowering::IntrinsicInfo Info;
5010   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5011   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
5012                                                DAG.getMachineFunction(),
5013                                                Intrinsic);
5014 
5015   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
5016   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
5017       Info.opc == ISD::INTRINSIC_W_CHAIN)
5018     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
5019                                         TLI.getPointerTy(DAG.getDataLayout())));
5020 
5021   // Add all operands of the call to the operand list.
5022   for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
5023     const Value *Arg = I.getArgOperand(i);
5024     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
5025       Ops.push_back(getValue(Arg));
5026       continue;
5027     }
5028 
5029     // Use TargetConstant instead of a regular constant for immarg.
5030     EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
5031     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
5032       assert(CI->getBitWidth() <= 64 &&
5033              "large intrinsic immediates not handled");
5034       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
5035     } else {
5036       Ops.push_back(
5037           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
5038     }
5039   }
5040 
5041   SmallVector<EVT, 4> ValueVTs;
5042   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
5043 
5044   if (HasChain)
5045     ValueVTs.push_back(MVT::Other);
5046 
5047   SDVTList VTs = DAG.getVTList(ValueVTs);
5048 
5049   // Propagate fast-math-flags from IR to node(s).
5050   SDNodeFlags Flags;
5051   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
5052     Flags.copyFMF(*FPMO);
5053   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
5054 
5055   // Create the node.
5056   SDValue Result;
5057   // In some cases, custom collection of operands from CallInst I may be needed.
5058   TLI.CollectTargetIntrinsicOperands(I, Ops, DAG);
5059   if (IsTgtIntrinsic) {
5060     // This is target intrinsic that touches memory
5061     //
5062     // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic
5063     //       didn't yield anything useful.
5064     MachinePointerInfo MPI;
5065     if (Info.ptrVal)
5066       MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
5067     else if (Info.fallbackAddressSpace)
5068       MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
5069     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops,
5070                                      Info.memVT, MPI, Info.align, Info.flags,
5071                                      Info.size, I.getAAMetadata());
5072   } else if (!HasChain) {
5073     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
5074   } else if (!I.getType()->isVoidTy()) {
5075     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
5076   } else {
5077     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
5078   }
5079 
5080   if (HasChain) {
5081     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
5082     if (OnlyLoad)
5083       PendingLoads.push_back(Chain);
5084     else
5085       DAG.setRoot(Chain);
5086   }
5087 
5088   if (!I.getType()->isVoidTy()) {
5089     if (!isa<VectorType>(I.getType()))
5090       Result = lowerRangeToAssertZExt(DAG, I, Result);
5091 
5092     MaybeAlign Alignment = I.getRetAlign();
5093 
5094     // Insert `assertalign` node if there's an alignment.
5095     if (InsertAssertAlign && Alignment) {
5096       Result =
5097           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
5098     }
5099 
5100     setValue(&I, Result);
5101   }
5102 }
5103 
5104 /// GetSignificand - Get the significand and build it into a floating-point
5105 /// number with exponent of 1:
5106 ///
5107 ///   Op = (Op & 0x007fffff) | 0x3f800000;
5108 ///
5109 /// where Op is the hexadecimal representation of floating point value.
5110 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
5111   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5112                            DAG.getConstant(0x007fffff, dl, MVT::i32));
5113   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
5114                            DAG.getConstant(0x3f800000, dl, MVT::i32));
5115   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
5116 }
5117 
5118 /// GetExponent - Get the exponent:
5119 ///
5120 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
5121 ///
5122 /// where Op is the hexadecimal representation of floating point value.
5123 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
5124                            const TargetLowering &TLI, const SDLoc &dl) {
5125   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5126                            DAG.getConstant(0x7f800000, dl, MVT::i32));
5127   SDValue t1 = DAG.getNode(
5128       ISD::SRL, dl, MVT::i32, t0,
5129       DAG.getConstant(23, dl,
5130                       TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout())));
5131   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
5132                            DAG.getConstant(127, dl, MVT::i32));
5133   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
5134 }
5135 
5136 /// getF32Constant - Get 32-bit floating point constant.
5137 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
5138                               const SDLoc &dl) {
5139   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
5140                            MVT::f32);
5141 }
5142 
5143 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
5144                                        SelectionDAG &DAG) {
5145   // TODO: What fast-math-flags should be set on the floating-point nodes?
5146 
5147   //   IntegerPartOfX = ((int32_t)(t0);
5148   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
5149 
5150   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
5151   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
5152   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
5153 
5154   //   IntegerPartOfX <<= 23;
5155   IntegerPartOfX =
5156       DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
5157                   DAG.getConstant(23, dl,
5158                                   DAG.getTargetLoweringInfo().getShiftAmountTy(
5159                                       MVT::i32, DAG.getDataLayout())));
5160 
5161   SDValue TwoToFractionalPartOfX;
5162   if (LimitFloatPrecision <= 6) {
5163     // For floating-point precision of 6:
5164     //
5165     //   TwoToFractionalPartOfX =
5166     //     0.997535578f +
5167     //       (0.735607626f + 0.252464424f * x) * x;
5168     //
5169     // error 0.0144103317, which is 6 bits
5170     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5171                              getF32Constant(DAG, 0x3e814304, dl));
5172     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5173                              getF32Constant(DAG, 0x3f3c50c8, dl));
5174     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5175     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5176                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
5177   } else if (LimitFloatPrecision <= 12) {
5178     // For floating-point precision of 12:
5179     //
5180     //   TwoToFractionalPartOfX =
5181     //     0.999892986f +
5182     //       (0.696457318f +
5183     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
5184     //
5185     // error 0.000107046256, which is 13 to 14 bits
5186     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5187                              getF32Constant(DAG, 0x3da235e3, dl));
5188     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5189                              getF32Constant(DAG, 0x3e65b8f3, dl));
5190     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5191     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5192                              getF32Constant(DAG, 0x3f324b07, dl));
5193     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5194     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5195                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
5196   } else { // LimitFloatPrecision <= 18
5197     // For floating-point precision of 18:
5198     //
5199     //   TwoToFractionalPartOfX =
5200     //     0.999999982f +
5201     //       (0.693148872f +
5202     //         (0.240227044f +
5203     //           (0.554906021e-1f +
5204     //             (0.961591928e-2f +
5205     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5206     // error 2.47208000*10^(-7), which is better than 18 bits
5207     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5208                              getF32Constant(DAG, 0x3924b03e, dl));
5209     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5210                              getF32Constant(DAG, 0x3ab24b87, dl));
5211     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5212     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5213                              getF32Constant(DAG, 0x3c1d8c17, dl));
5214     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5215     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5216                              getF32Constant(DAG, 0x3d634a1d, dl));
5217     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5218     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5219                              getF32Constant(DAG, 0x3e75fe14, dl));
5220     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5221     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5222                               getF32Constant(DAG, 0x3f317234, dl));
5223     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5224     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5225                                          getF32Constant(DAG, 0x3f800000, dl));
5226   }
5227 
5228   // Add the exponent into the result in integer domain.
5229   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5230   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5231                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5232 }
5233 
5234 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5235 /// limited-precision mode.
5236 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5237                          const TargetLowering &TLI, SDNodeFlags Flags) {
5238   if (Op.getValueType() == MVT::f32 &&
5239       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5240 
5241     // Put the exponent in the right bit position for later addition to the
5242     // final result:
5243     //
5244     // t0 = Op * log2(e)
5245 
5246     // TODO: What fast-math-flags should be set here?
5247     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5248                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5249     return getLimitedPrecisionExp2(t0, dl, DAG);
5250   }
5251 
5252   // No special expansion.
5253   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5254 }
5255 
5256 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5257 /// limited-precision mode.
5258 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5259                          const TargetLowering &TLI, SDNodeFlags Flags) {
5260   // TODO: What fast-math-flags should be set on the floating-point nodes?
5261 
5262   if (Op.getValueType() == MVT::f32 &&
5263       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5264     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5265 
5266     // Scale the exponent by log(2).
5267     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5268     SDValue LogOfExponent =
5269         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5270                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5271 
5272     // Get the significand and build it into a floating-point number with
5273     // exponent of 1.
5274     SDValue X = GetSignificand(DAG, Op1, dl);
5275 
5276     SDValue LogOfMantissa;
5277     if (LimitFloatPrecision <= 6) {
5278       // For floating-point precision of 6:
5279       //
5280       //   LogofMantissa =
5281       //     -1.1609546f +
5282       //       (1.4034025f - 0.23903021f * x) * x;
5283       //
5284       // error 0.0034276066, which is better than 8 bits
5285       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5286                                getF32Constant(DAG, 0xbe74c456, dl));
5287       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5288                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5289       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5290       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5291                                   getF32Constant(DAG, 0x3f949a29, dl));
5292     } else if (LimitFloatPrecision <= 12) {
5293       // For floating-point precision of 12:
5294       //
5295       //   LogOfMantissa =
5296       //     -1.7417939f +
5297       //       (2.8212026f +
5298       //         (-1.4699568f +
5299       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5300       //
5301       // error 0.000061011436, which is 14 bits
5302       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5303                                getF32Constant(DAG, 0xbd67b6d6, dl));
5304       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5305                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5306       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5307       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5308                                getF32Constant(DAG, 0x3fbc278b, dl));
5309       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5310       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5311                                getF32Constant(DAG, 0x40348e95, dl));
5312       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5313       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5314                                   getF32Constant(DAG, 0x3fdef31a, dl));
5315     } else { // LimitFloatPrecision <= 18
5316       // For floating-point precision of 18:
5317       //
5318       //   LogOfMantissa =
5319       //     -2.1072184f +
5320       //       (4.2372794f +
5321       //         (-3.7029485f +
5322       //           (2.2781945f +
5323       //             (-0.87823314f +
5324       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5325       //
5326       // error 0.0000023660568, which is better than 18 bits
5327       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5328                                getF32Constant(DAG, 0xbc91e5ac, dl));
5329       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5330                                getF32Constant(DAG, 0x3e4350aa, dl));
5331       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5332       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5333                                getF32Constant(DAG, 0x3f60d3e3, dl));
5334       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5335       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5336                                getF32Constant(DAG, 0x4011cdf0, dl));
5337       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5338       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5339                                getF32Constant(DAG, 0x406cfd1c, dl));
5340       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5341       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5342                                getF32Constant(DAG, 0x408797cb, dl));
5343       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5344       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5345                                   getF32Constant(DAG, 0x4006dcab, dl));
5346     }
5347 
5348     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5349   }
5350 
5351   // No special expansion.
5352   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5353 }
5354 
5355 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5356 /// limited-precision mode.
5357 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5358                           const TargetLowering &TLI, SDNodeFlags Flags) {
5359   // TODO: What fast-math-flags should be set on the floating-point nodes?
5360 
5361   if (Op.getValueType() == MVT::f32 &&
5362       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5363     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5364 
5365     // Get the exponent.
5366     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5367 
5368     // Get the significand and build it into a floating-point number with
5369     // exponent of 1.
5370     SDValue X = GetSignificand(DAG, Op1, dl);
5371 
5372     // Different possible minimax approximations of significand in
5373     // floating-point for various degrees of accuracy over [1,2].
5374     SDValue Log2ofMantissa;
5375     if (LimitFloatPrecision <= 6) {
5376       // For floating-point precision of 6:
5377       //
5378       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5379       //
5380       // error 0.0049451742, which is more than 7 bits
5381       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5382                                getF32Constant(DAG, 0xbeb08fe0, dl));
5383       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5384                                getF32Constant(DAG, 0x40019463, dl));
5385       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5386       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5387                                    getF32Constant(DAG, 0x3fd6633d, dl));
5388     } else if (LimitFloatPrecision <= 12) {
5389       // For floating-point precision of 12:
5390       //
5391       //   Log2ofMantissa =
5392       //     -2.51285454f +
5393       //       (4.07009056f +
5394       //         (-2.12067489f +
5395       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5396       //
5397       // error 0.0000876136000, which is better than 13 bits
5398       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5399                                getF32Constant(DAG, 0xbda7262e, dl));
5400       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5401                                getF32Constant(DAG, 0x3f25280b, dl));
5402       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5403       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5404                                getF32Constant(DAG, 0x4007b923, dl));
5405       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5406       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5407                                getF32Constant(DAG, 0x40823e2f, dl));
5408       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5409       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5410                                    getF32Constant(DAG, 0x4020d29c, dl));
5411     } else { // LimitFloatPrecision <= 18
5412       // For floating-point precision of 18:
5413       //
5414       //   Log2ofMantissa =
5415       //     -3.0400495f +
5416       //       (6.1129976f +
5417       //         (-5.3420409f +
5418       //           (3.2865683f +
5419       //             (-1.2669343f +
5420       //               (0.27515199f -
5421       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5422       //
5423       // error 0.0000018516, which is better than 18 bits
5424       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5425                                getF32Constant(DAG, 0xbcd2769e, dl));
5426       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5427                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5428       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5429       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5430                                getF32Constant(DAG, 0x3fa22ae7, dl));
5431       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5432       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5433                                getF32Constant(DAG, 0x40525723, dl));
5434       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5435       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5436                                getF32Constant(DAG, 0x40aaf200, dl));
5437       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5438       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5439                                getF32Constant(DAG, 0x40c39dad, dl));
5440       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5441       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5442                                    getF32Constant(DAG, 0x4042902c, dl));
5443     }
5444 
5445     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5446   }
5447 
5448   // No special expansion.
5449   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5450 }
5451 
5452 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5453 /// limited-precision mode.
5454 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5455                            const TargetLowering &TLI, SDNodeFlags Flags) {
5456   // TODO: What fast-math-flags should be set on the floating-point nodes?
5457 
5458   if (Op.getValueType() == MVT::f32 &&
5459       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5460     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5461 
5462     // Scale the exponent by log10(2) [0.30102999f].
5463     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5464     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5465                                         getF32Constant(DAG, 0x3e9a209a, dl));
5466 
5467     // Get the significand and build it into a floating-point number with
5468     // exponent of 1.
5469     SDValue X = GetSignificand(DAG, Op1, dl);
5470 
5471     SDValue Log10ofMantissa;
5472     if (LimitFloatPrecision <= 6) {
5473       // For floating-point precision of 6:
5474       //
5475       //   Log10ofMantissa =
5476       //     -0.50419619f +
5477       //       (0.60948995f - 0.10380950f * x) * x;
5478       //
5479       // error 0.0014886165, which is 6 bits
5480       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5481                                getF32Constant(DAG, 0xbdd49a13, dl));
5482       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5483                                getF32Constant(DAG, 0x3f1c0789, dl));
5484       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5485       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5486                                     getF32Constant(DAG, 0x3f011300, dl));
5487     } else if (LimitFloatPrecision <= 12) {
5488       // For floating-point precision of 12:
5489       //
5490       //   Log10ofMantissa =
5491       //     -0.64831180f +
5492       //       (0.91751397f +
5493       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5494       //
5495       // error 0.00019228036, which is better than 12 bits
5496       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5497                                getF32Constant(DAG, 0x3d431f31, dl));
5498       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5499                                getF32Constant(DAG, 0x3ea21fb2, dl));
5500       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5501       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5502                                getF32Constant(DAG, 0x3f6ae232, dl));
5503       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5504       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5505                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5506     } else { // LimitFloatPrecision <= 18
5507       // For floating-point precision of 18:
5508       //
5509       //   Log10ofMantissa =
5510       //     -0.84299375f +
5511       //       (1.5327582f +
5512       //         (-1.0688956f +
5513       //           (0.49102474f +
5514       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5515       //
5516       // error 0.0000037995730, which is better than 18 bits
5517       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5518                                getF32Constant(DAG, 0x3c5d51ce, dl));
5519       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5520                                getF32Constant(DAG, 0x3e00685a, dl));
5521       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5522       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5523                                getF32Constant(DAG, 0x3efb6798, dl));
5524       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5525       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5526                                getF32Constant(DAG, 0x3f88d192, dl));
5527       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5528       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5529                                getF32Constant(DAG, 0x3fc4316c, dl));
5530       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5531       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5532                                     getF32Constant(DAG, 0x3f57ce70, dl));
5533     }
5534 
5535     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5536   }
5537 
5538   // No special expansion.
5539   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5540 }
5541 
5542 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5543 /// limited-precision mode.
5544 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5545                           const TargetLowering &TLI, SDNodeFlags Flags) {
5546   if (Op.getValueType() == MVT::f32 &&
5547       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5548     return getLimitedPrecisionExp2(Op, dl, DAG);
5549 
5550   // No special expansion.
5551   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5552 }
5553 
5554 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5555 /// limited-precision mode with x == 10.0f.
5556 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5557                          SelectionDAG &DAG, const TargetLowering &TLI,
5558                          SDNodeFlags Flags) {
5559   bool IsExp10 = false;
5560   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5561       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5562     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5563       APFloat Ten(10.0f);
5564       IsExp10 = LHSC->isExactlyValue(Ten);
5565     }
5566   }
5567 
5568   // TODO: What fast-math-flags should be set on the FMUL node?
5569   if (IsExp10) {
5570     // Put the exponent in the right bit position for later addition to the
5571     // final result:
5572     //
5573     //   #define LOG2OF10 3.3219281f
5574     //   t0 = Op * LOG2OF10;
5575     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5576                              getF32Constant(DAG, 0x40549a78, dl));
5577     return getLimitedPrecisionExp2(t0, dl, DAG);
5578   }
5579 
5580   // No special expansion.
5581   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5582 }
5583 
5584 /// ExpandPowI - Expand a llvm.powi intrinsic.
5585 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5586                           SelectionDAG &DAG) {
5587   // If RHS is a constant, we can expand this out to a multiplication tree if
5588   // it's beneficial on the target, otherwise we end up lowering to a call to
5589   // __powidf2 (for example).
5590   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5591     unsigned Val = RHSC->getSExtValue();
5592 
5593     // powi(x, 0) -> 1.0
5594     if (Val == 0)
5595       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5596 
5597     if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI(
5598             Val, DAG.shouldOptForSize())) {
5599       // Get the exponent as a positive value.
5600       if ((int)Val < 0)
5601         Val = -Val;
5602       // We use the simple binary decomposition method to generate the multiply
5603       // sequence.  There are more optimal ways to do this (for example,
5604       // powi(x,15) generates one more multiply than it should), but this has
5605       // the benefit of being both really simple and much better than a libcall.
5606       SDValue Res; // Logically starts equal to 1.0
5607       SDValue CurSquare = LHS;
5608       // TODO: Intrinsics should have fast-math-flags that propagate to these
5609       // nodes.
5610       while (Val) {
5611         if (Val & 1) {
5612           if (Res.getNode())
5613             Res =
5614                 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
5615           else
5616             Res = CurSquare; // 1.0*CurSquare.
5617         }
5618 
5619         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5620                                 CurSquare, CurSquare);
5621         Val >>= 1;
5622       }
5623 
5624       // If the original was negative, invert the result, producing 1/(x*x*x).
5625       if (RHSC->getSExtValue() < 0)
5626         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5627                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5628       return Res;
5629     }
5630   }
5631 
5632   // Otherwise, expand to a libcall.
5633   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5634 }
5635 
5636 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5637                             SDValue LHS, SDValue RHS, SDValue Scale,
5638                             SelectionDAG &DAG, const TargetLowering &TLI) {
5639   EVT VT = LHS.getValueType();
5640   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5641   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5642   LLVMContext &Ctx = *DAG.getContext();
5643 
5644   // If the type is legal but the operation isn't, this node might survive all
5645   // the way to operation legalization. If we end up there and we do not have
5646   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5647   // node.
5648 
5649   // Coax the legalizer into expanding the node during type legalization instead
5650   // by bumping the size by one bit. This will force it to Promote, enabling the
5651   // early expansion and avoiding the need to expand later.
5652 
5653   // We don't have to do this if Scale is 0; that can always be expanded, unless
5654   // it's a saturating signed operation. Those can experience true integer
5655   // division overflow, a case which we must avoid.
5656 
5657   // FIXME: We wouldn't have to do this (or any of the early
5658   // expansion/promotion) if it was possible to expand a libcall of an
5659   // illegal type during operation legalization. But it's not, so things
5660   // get a bit hacky.
5661   unsigned ScaleInt = Scale->getAsZExtVal();
5662   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5663       (TLI.isTypeLegal(VT) ||
5664        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5665     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5666         Opcode, VT, ScaleInt);
5667     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5668       EVT PromVT;
5669       if (VT.isScalarInteger())
5670         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5671       else if (VT.isVector()) {
5672         PromVT = VT.getVectorElementType();
5673         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5674         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5675       } else
5676         llvm_unreachable("Wrong VT for DIVFIX?");
5677       LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT);
5678       RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT);
5679       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5680       // For saturating operations, we need to shift up the LHS to get the
5681       // proper saturation width, and then shift down again afterwards.
5682       if (Saturating)
5683         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5684                           DAG.getConstant(1, DL, ShiftTy));
5685       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5686       if (Saturating)
5687         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5688                           DAG.getConstant(1, DL, ShiftTy));
5689       return DAG.getZExtOrTrunc(Res, DL, VT);
5690     }
5691   }
5692 
5693   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5694 }
5695 
5696 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5697 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5698 static void
5699 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5700                      const SDValue &N) {
5701   switch (N.getOpcode()) {
5702   case ISD::CopyFromReg: {
5703     SDValue Op = N.getOperand(1);
5704     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5705                       Op.getValueType().getSizeInBits());
5706     return;
5707   }
5708   case ISD::BITCAST:
5709   case ISD::AssertZext:
5710   case ISD::AssertSext:
5711   case ISD::TRUNCATE:
5712     getUnderlyingArgRegs(Regs, N.getOperand(0));
5713     return;
5714   case ISD::BUILD_PAIR:
5715   case ISD::BUILD_VECTOR:
5716   case ISD::CONCAT_VECTORS:
5717     for (SDValue Op : N->op_values())
5718       getUnderlyingArgRegs(Regs, Op);
5719     return;
5720   default:
5721     return;
5722   }
5723 }
5724 
5725 /// If the DbgValueInst is a dbg_value of a function argument, create the
5726 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5727 /// instruction selection, they will be inserted to the entry BB.
5728 /// We don't currently support this for variadic dbg_values, as they shouldn't
5729 /// appear for function arguments or in the prologue.
5730 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5731     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5732     DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
5733   const Argument *Arg = dyn_cast<Argument>(V);
5734   if (!Arg)
5735     return false;
5736 
5737   MachineFunction &MF = DAG.getMachineFunction();
5738   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5739 
5740   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
5741   // we've been asked to pursue.
5742   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
5743                               bool Indirect) {
5744     if (Reg.isVirtual() && MF.useDebugInstrRef()) {
5745       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
5746       // pointing at the VReg, which will be patched up later.
5747       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
5748       SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg(
5749           /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
5750           /* isKill */ false, /* isDead */ false,
5751           /* isUndef */ false, /* isEarlyClobber */ false,
5752           /* SubReg */ 0, /* isDebug */ true)});
5753 
5754       auto *NewDIExpr = FragExpr;
5755       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
5756       // the DIExpression.
5757       if (Indirect)
5758         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
5759       SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0});
5760       NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops);
5761       return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr);
5762     } else {
5763       // Create a completely standard DBG_VALUE.
5764       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
5765       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
5766     }
5767   };
5768 
5769   if (Kind == FuncArgumentDbgValueKind::Value) {
5770     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5771     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5772     // the entry block.
5773     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5774     if (!IsInEntryBlock)
5775       return false;
5776 
5777     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5778     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5779     // variable that also is a param.
5780     //
5781     // Although, if we are at the top of the entry block already, we can still
5782     // emit using ArgDbgValue. This might catch some situations when the
5783     // dbg.value refers to an argument that isn't used in the entry block, so
5784     // any CopyToReg node would be optimized out and the only way to express
5785     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5786     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5787     // we should only emit as ArgDbgValue if the Variable is an argument to the
5788     // current function, and the dbg.value intrinsic is found in the entry
5789     // block.
5790     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5791         !DL->getInlinedAt();
5792     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5793     if (!IsInPrologue && !VariableIsFunctionInputArg)
5794       return false;
5795 
5796     // Here we assume that a function argument on IR level only can be used to
5797     // describe one input parameter on source level. If we for example have
5798     // source code like this
5799     //
5800     //    struct A { long x, y; };
5801     //    void foo(struct A a, long b) {
5802     //      ...
5803     //      b = a.x;
5804     //      ...
5805     //    }
5806     //
5807     // and IR like this
5808     //
5809     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5810     //  entry:
5811     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5812     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5813     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5814     //    ...
5815     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5816     //    ...
5817     //
5818     // then the last dbg.value is describing a parameter "b" using a value that
5819     // is an argument. But since we already has used %a1 to describe a parameter
5820     // we should not handle that last dbg.value here (that would result in an
5821     // incorrect hoisting of the DBG_VALUE to the function entry).
5822     // Notice that we allow one dbg.value per IR level argument, to accommodate
5823     // for the situation with fragments above.
5824     if (VariableIsFunctionInputArg) {
5825       unsigned ArgNo = Arg->getArgNo();
5826       if (ArgNo >= FuncInfo.DescribedArgs.size())
5827         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5828       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5829         return false;
5830       FuncInfo.DescribedArgs.set(ArgNo);
5831     }
5832   }
5833 
5834   bool IsIndirect = false;
5835   std::optional<MachineOperand> Op;
5836   // Some arguments' frame index is recorded during argument lowering.
5837   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5838   if (FI != std::numeric_limits<int>::max())
5839     Op = MachineOperand::CreateFI(FI);
5840 
5841   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
5842   if (!Op && N.getNode()) {
5843     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5844     Register Reg;
5845     if (ArgRegsAndSizes.size() == 1)
5846       Reg = ArgRegsAndSizes.front().first;
5847 
5848     if (Reg && Reg.isVirtual()) {
5849       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5850       Register PR = RegInfo.getLiveInPhysReg(Reg);
5851       if (PR)
5852         Reg = PR;
5853     }
5854     if (Reg) {
5855       Op = MachineOperand::CreateReg(Reg, false);
5856       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
5857     }
5858   }
5859 
5860   if (!Op && N.getNode()) {
5861     // Check if frame index is available.
5862     SDValue LCandidate = peekThroughBitcasts(N);
5863     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5864       if (FrameIndexSDNode *FINode =
5865           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5866         Op = MachineOperand::CreateFI(FINode->getIndex());
5867   }
5868 
5869   if (!Op) {
5870     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5871     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
5872                                          SplitRegs) {
5873       unsigned Offset = 0;
5874       for (const auto &RegAndSize : SplitRegs) {
5875         // If the expression is already a fragment, the current register
5876         // offset+size might extend beyond the fragment. In this case, only
5877         // the register bits that are inside the fragment are relevant.
5878         int RegFragmentSizeInBits = RegAndSize.second;
5879         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5880           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5881           // The register is entirely outside the expression fragment,
5882           // so is irrelevant for debug info.
5883           if (Offset >= ExprFragmentSizeInBits)
5884             break;
5885           // The register is partially outside the expression fragment, only
5886           // the low bits within the fragment are relevant for debug info.
5887           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5888             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5889           }
5890         }
5891 
5892         auto FragmentExpr = DIExpression::createFragmentExpression(
5893             Expr, Offset, RegFragmentSizeInBits);
5894         Offset += RegAndSize.second;
5895         // If a valid fragment expression cannot be created, the variable's
5896         // correct value cannot be determined and so it is set as Undef.
5897         if (!FragmentExpr) {
5898           SDDbgValue *SDV = DAG.getConstantDbgValue(
5899               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5900           DAG.AddDbgValue(SDV, false);
5901           continue;
5902         }
5903         MachineInstr *NewMI =
5904             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr,
5905                              Kind != FuncArgumentDbgValueKind::Value);
5906         FuncInfo.ArgDbgValues.push_back(NewMI);
5907       }
5908     };
5909 
5910     // Check if ValueMap has reg number.
5911     DenseMap<const Value *, Register>::const_iterator
5912       VMI = FuncInfo.ValueMap.find(V);
5913     if (VMI != FuncInfo.ValueMap.end()) {
5914       const auto &TLI = DAG.getTargetLoweringInfo();
5915       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5916                        V->getType(), std::nullopt);
5917       if (RFV.occupiesMultipleRegs()) {
5918         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5919         return true;
5920       }
5921 
5922       Op = MachineOperand::CreateReg(VMI->second, false);
5923       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
5924     } else if (ArgRegsAndSizes.size() > 1) {
5925       // This was split due to the calling convention, and no virtual register
5926       // mapping exists for the value.
5927       splitMultiRegDbgValue(ArgRegsAndSizes);
5928       return true;
5929     }
5930   }
5931 
5932   if (!Op)
5933     return false;
5934 
5935   assert(Variable->isValidLocationForIntrinsic(DL) &&
5936          "Expected inlined-at fields to agree");
5937   MachineInstr *NewMI = nullptr;
5938 
5939   if (Op->isReg())
5940     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
5941   else
5942     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
5943                     Variable, Expr);
5944 
5945   // Otherwise, use ArgDbgValues.
5946   FuncInfo.ArgDbgValues.push_back(NewMI);
5947   return true;
5948 }
5949 
5950 /// Return the appropriate SDDbgValue based on N.
5951 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5952                                              DILocalVariable *Variable,
5953                                              DIExpression *Expr,
5954                                              const DebugLoc &dl,
5955                                              unsigned DbgSDNodeOrder) {
5956   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5957     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5958     // stack slot locations.
5959     //
5960     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5961     // debug values here after optimization:
5962     //
5963     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5964     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5965     //
5966     // Both describe the direct values of their associated variables.
5967     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5968                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5969   }
5970   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5971                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5972 }
5973 
5974 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5975   switch (Intrinsic) {
5976   case Intrinsic::smul_fix:
5977     return ISD::SMULFIX;
5978   case Intrinsic::umul_fix:
5979     return ISD::UMULFIX;
5980   case Intrinsic::smul_fix_sat:
5981     return ISD::SMULFIXSAT;
5982   case Intrinsic::umul_fix_sat:
5983     return ISD::UMULFIXSAT;
5984   case Intrinsic::sdiv_fix:
5985     return ISD::SDIVFIX;
5986   case Intrinsic::udiv_fix:
5987     return ISD::UDIVFIX;
5988   case Intrinsic::sdiv_fix_sat:
5989     return ISD::SDIVFIXSAT;
5990   case Intrinsic::udiv_fix_sat:
5991     return ISD::UDIVFIXSAT;
5992   default:
5993     llvm_unreachable("Unhandled fixed point intrinsic");
5994   }
5995 }
5996 
5997 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5998                                            const char *FunctionName) {
5999   assert(FunctionName && "FunctionName must not be nullptr");
6000   SDValue Callee = DAG.getExternalSymbol(
6001       FunctionName,
6002       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6003   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
6004 }
6005 
6006 /// Given a @llvm.call.preallocated.setup, return the corresponding
6007 /// preallocated call.
6008 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
6009   assert(cast<CallBase>(PreallocatedSetup)
6010                  ->getCalledFunction()
6011                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
6012          "expected call_preallocated_setup Value");
6013   for (const auto *U : PreallocatedSetup->users()) {
6014     auto *UseCall = cast<CallBase>(U);
6015     const Function *Fn = UseCall->getCalledFunction();
6016     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
6017       return UseCall;
6018     }
6019   }
6020   llvm_unreachable("expected corresponding call to preallocated setup/arg");
6021 }
6022 
6023 /// If DI is a debug value with an EntryValue expression, lower it using the
6024 /// corresponding physical register of the associated Argument value
6025 /// (guaranteed to exist by the verifier).
6026 bool SelectionDAGBuilder::visitEntryValueDbgValue(const DbgValueInst &DI) {
6027   DILocalVariable *Variable = DI.getVariable();
6028   DIExpression *Expr = DI.getExpression();
6029   if (!Expr->isEntryValue() || !hasSingleElement(DI.getValues()))
6030     return false;
6031 
6032   // These properties are guaranteed by the verifier.
6033   Argument *Arg = cast<Argument>(DI.getValue(0));
6034   assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync));
6035 
6036   auto ArgIt = FuncInfo.ValueMap.find(Arg);
6037   if (ArgIt == FuncInfo.ValueMap.end()) {
6038     LLVM_DEBUG(
6039         dbgs() << "Dropping dbg.value: expression is entry_value but "
6040                   "couldn't find an associated register for the Argument\n");
6041     return true;
6042   }
6043   Register ArgVReg = ArgIt->getSecond();
6044 
6045   for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
6046     if (ArgVReg == VirtReg || ArgVReg == PhysReg) {
6047       SDDbgValue *SDV =
6048           DAG.getVRegDbgValue(Variable, Expr, PhysReg, false /*IsIndidrect*/,
6049                               DI.getDebugLoc(), SDNodeOrder);
6050       DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/);
6051       return true;
6052     }
6053   LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but "
6054                        "couldn't find a physical register\n");
6055   return true;
6056 }
6057 
6058 /// Lower the call to the specified intrinsic function.
6059 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
6060                                              unsigned Intrinsic) {
6061   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6062   SDLoc sdl = getCurSDLoc();
6063   DebugLoc dl = getCurDebugLoc();
6064   SDValue Res;
6065 
6066   SDNodeFlags Flags;
6067   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
6068     Flags.copyFMF(*FPOp);
6069 
6070   switch (Intrinsic) {
6071   default:
6072     // By default, turn this into a target intrinsic node.
6073     visitTargetIntrinsic(I, Intrinsic);
6074     return;
6075   case Intrinsic::vscale: {
6076     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6077     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
6078     return;
6079   }
6080   case Intrinsic::vastart:  visitVAStart(I); return;
6081   case Intrinsic::vaend:    visitVAEnd(I); return;
6082   case Intrinsic::vacopy:   visitVACopy(I); return;
6083   case Intrinsic::returnaddress:
6084     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
6085                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6086                              getValue(I.getArgOperand(0))));
6087     return;
6088   case Intrinsic::addressofreturnaddress:
6089     setValue(&I,
6090              DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
6091                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6092     return;
6093   case Intrinsic::sponentry:
6094     setValue(&I,
6095              DAG.getNode(ISD::SPONENTRY, sdl,
6096                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6097     return;
6098   case Intrinsic::frameaddress:
6099     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
6100                              TLI.getFrameIndexTy(DAG.getDataLayout()),
6101                              getValue(I.getArgOperand(0))));
6102     return;
6103   case Intrinsic::read_volatile_register:
6104   case Intrinsic::read_register: {
6105     Value *Reg = I.getArgOperand(0);
6106     SDValue Chain = getRoot();
6107     SDValue RegName =
6108         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6109     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6110     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
6111       DAG.getVTList(VT, MVT::Other), Chain, RegName);
6112     setValue(&I, Res);
6113     DAG.setRoot(Res.getValue(1));
6114     return;
6115   }
6116   case Intrinsic::write_register: {
6117     Value *Reg = I.getArgOperand(0);
6118     Value *RegValue = I.getArgOperand(1);
6119     SDValue Chain = getRoot();
6120     SDValue RegName =
6121         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6122     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
6123                             RegName, getValue(RegValue)));
6124     return;
6125   }
6126   case Intrinsic::memcpy: {
6127     const auto &MCI = cast<MemCpyInst>(I);
6128     SDValue Op1 = getValue(I.getArgOperand(0));
6129     SDValue Op2 = getValue(I.getArgOperand(1));
6130     SDValue Op3 = getValue(I.getArgOperand(2));
6131     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
6132     Align DstAlign = MCI.getDestAlign().valueOrOne();
6133     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6134     Align Alignment = std::min(DstAlign, SrcAlign);
6135     bool isVol = MCI.isVolatile();
6136     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6137     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6138     // node.
6139     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6140     SDValue MC = DAG.getMemcpy(
6141         Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6142         /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)),
6143         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
6144     updateDAGForMaybeTailCall(MC);
6145     return;
6146   }
6147   case Intrinsic::memcpy_inline: {
6148     const auto &MCI = cast<MemCpyInlineInst>(I);
6149     SDValue Dst = getValue(I.getArgOperand(0));
6150     SDValue Src = getValue(I.getArgOperand(1));
6151     SDValue Size = getValue(I.getArgOperand(2));
6152     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
6153     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
6154     Align DstAlign = MCI.getDestAlign().valueOrOne();
6155     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6156     Align Alignment = std::min(DstAlign, SrcAlign);
6157     bool isVol = MCI.isVolatile();
6158     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6159     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6160     // node.
6161     SDValue MC = DAG.getMemcpy(
6162         getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
6163         /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)),
6164         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
6165     updateDAGForMaybeTailCall(MC);
6166     return;
6167   }
6168   case Intrinsic::memset: {
6169     const auto &MSI = cast<MemSetInst>(I);
6170     SDValue Op1 = getValue(I.getArgOperand(0));
6171     SDValue Op2 = getValue(I.getArgOperand(1));
6172     SDValue Op3 = getValue(I.getArgOperand(2));
6173     // @llvm.memset defines 0 and 1 to both mean no alignment.
6174     Align Alignment = MSI.getDestAlign().valueOrOne();
6175     bool isVol = MSI.isVolatile();
6176     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6177     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6178     SDValue MS = DAG.getMemset(
6179         Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false,
6180         isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
6181     updateDAGForMaybeTailCall(MS);
6182     return;
6183   }
6184   case Intrinsic::memset_inline: {
6185     const auto &MSII = cast<MemSetInlineInst>(I);
6186     SDValue Dst = getValue(I.getArgOperand(0));
6187     SDValue Value = getValue(I.getArgOperand(1));
6188     SDValue Size = getValue(I.getArgOperand(2));
6189     assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size");
6190     // @llvm.memset defines 0 and 1 to both mean no alignment.
6191     Align DstAlign = MSII.getDestAlign().valueOrOne();
6192     bool isVol = MSII.isVolatile();
6193     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6194     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6195     SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol,
6196                                /* AlwaysInline */ true, isTC,
6197                                MachinePointerInfo(I.getArgOperand(0)),
6198                                I.getAAMetadata());
6199     updateDAGForMaybeTailCall(MC);
6200     return;
6201   }
6202   case Intrinsic::memmove: {
6203     const auto &MMI = cast<MemMoveInst>(I);
6204     SDValue Op1 = getValue(I.getArgOperand(0));
6205     SDValue Op2 = getValue(I.getArgOperand(1));
6206     SDValue Op3 = getValue(I.getArgOperand(2));
6207     // @llvm.memmove defines 0 and 1 to both mean no alignment.
6208     Align DstAlign = MMI.getDestAlign().valueOrOne();
6209     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
6210     Align Alignment = std::min(DstAlign, SrcAlign);
6211     bool isVol = MMI.isVolatile();
6212     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6213     // FIXME: Support passing different dest/src alignments to the memmove DAG
6214     // node.
6215     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6216     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6217                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
6218                                 MachinePointerInfo(I.getArgOperand(1)),
6219                                 I.getAAMetadata(), AA);
6220     updateDAGForMaybeTailCall(MM);
6221     return;
6222   }
6223   case Intrinsic::memcpy_element_unordered_atomic: {
6224     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
6225     SDValue Dst = getValue(MI.getRawDest());
6226     SDValue Src = getValue(MI.getRawSource());
6227     SDValue Length = getValue(MI.getLength());
6228 
6229     Type *LengthTy = MI.getLength()->getType();
6230     unsigned ElemSz = MI.getElementSizeInBytes();
6231     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6232     SDValue MC =
6233         DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6234                             isTC, MachinePointerInfo(MI.getRawDest()),
6235                             MachinePointerInfo(MI.getRawSource()));
6236     updateDAGForMaybeTailCall(MC);
6237     return;
6238   }
6239   case Intrinsic::memmove_element_unordered_atomic: {
6240     auto &MI = cast<AtomicMemMoveInst>(I);
6241     SDValue Dst = getValue(MI.getRawDest());
6242     SDValue Src = getValue(MI.getRawSource());
6243     SDValue Length = getValue(MI.getLength());
6244 
6245     Type *LengthTy = MI.getLength()->getType();
6246     unsigned ElemSz = MI.getElementSizeInBytes();
6247     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6248     SDValue MC =
6249         DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6250                              isTC, MachinePointerInfo(MI.getRawDest()),
6251                              MachinePointerInfo(MI.getRawSource()));
6252     updateDAGForMaybeTailCall(MC);
6253     return;
6254   }
6255   case Intrinsic::memset_element_unordered_atomic: {
6256     auto &MI = cast<AtomicMemSetInst>(I);
6257     SDValue Dst = getValue(MI.getRawDest());
6258     SDValue Val = getValue(MI.getValue());
6259     SDValue Length = getValue(MI.getLength());
6260 
6261     Type *LengthTy = MI.getLength()->getType();
6262     unsigned ElemSz = MI.getElementSizeInBytes();
6263     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6264     SDValue MC =
6265         DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
6266                             isTC, MachinePointerInfo(MI.getRawDest()));
6267     updateDAGForMaybeTailCall(MC);
6268     return;
6269   }
6270   case Intrinsic::call_preallocated_setup: {
6271     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
6272     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6273     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
6274                               getRoot(), SrcValue);
6275     setValue(&I, Res);
6276     DAG.setRoot(Res);
6277     return;
6278   }
6279   case Intrinsic::call_preallocated_arg: {
6280     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6281     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6282     SDValue Ops[3];
6283     Ops[0] = getRoot();
6284     Ops[1] = SrcValue;
6285     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6286                                    MVT::i32); // arg index
6287     SDValue Res = DAG.getNode(
6288         ISD::PREALLOCATED_ARG, sdl,
6289         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6290     setValue(&I, Res);
6291     DAG.setRoot(Res.getValue(1));
6292     return;
6293   }
6294   case Intrinsic::dbg_declare: {
6295     const auto &DI = cast<DbgDeclareInst>(I);
6296     // Debug intrinsics are handled separately in assignment tracking mode.
6297     // Some intrinsics are handled right after Argument lowering.
6298     if (AssignmentTrackingEnabled ||
6299         FuncInfo.PreprocessedDbgDeclares.count(&DI))
6300       return;
6301     LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DI << "\n");
6302     DILocalVariable *Variable = DI.getVariable();
6303     DIExpression *Expression = DI.getExpression();
6304     dropDanglingDebugInfo(Variable, Expression);
6305     // Assume dbg.declare can not currently use DIArgList, i.e.
6306     // it is non-variadic.
6307     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6308     handleDebugDeclare(DI.getVariableLocationOp(0), Variable, Expression,
6309                        DI.getDebugLoc());
6310     return;
6311   }
6312   case Intrinsic::dbg_label: {
6313     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6314     DILabel *Label = DI.getLabel();
6315     assert(Label && "Missing label");
6316 
6317     SDDbgLabel *SDV;
6318     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6319     DAG.AddDbgLabel(SDV);
6320     return;
6321   }
6322   case Intrinsic::dbg_assign: {
6323     // Debug intrinsics are handled seperately in assignment tracking mode.
6324     if (AssignmentTrackingEnabled)
6325       return;
6326     // If assignment tracking hasn't been enabled then fall through and treat
6327     // the dbg.assign as a dbg.value.
6328     [[fallthrough]];
6329   }
6330   case Intrinsic::dbg_value: {
6331     // Debug intrinsics are handled seperately in assignment tracking mode.
6332     if (AssignmentTrackingEnabled)
6333       return;
6334     const DbgValueInst &DI = cast<DbgValueInst>(I);
6335     assert(DI.getVariable() && "Missing variable");
6336 
6337     DILocalVariable *Variable = DI.getVariable();
6338     DIExpression *Expression = DI.getExpression();
6339     dropDanglingDebugInfo(Variable, Expression);
6340 
6341     if (visitEntryValueDbgValue(DI))
6342       return;
6343 
6344     if (DI.isKillLocation()) {
6345       handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder);
6346       return;
6347     }
6348 
6349     SmallVector<Value *, 4> Values(DI.getValues());
6350     if (Values.empty())
6351       return;
6352 
6353     bool IsVariadic = DI.hasArgList();
6354     if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(),
6355                           SDNodeOrder, IsVariadic))
6356       addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
6357                            DI.getDebugLoc(), SDNodeOrder);
6358     return;
6359   }
6360 
6361   case Intrinsic::eh_typeid_for: {
6362     // Find the type id for the given typeinfo.
6363     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6364     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6365     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6366     setValue(&I, Res);
6367     return;
6368   }
6369 
6370   case Intrinsic::eh_return_i32:
6371   case Intrinsic::eh_return_i64:
6372     DAG.getMachineFunction().setCallsEHReturn(true);
6373     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6374                             MVT::Other,
6375                             getControlRoot(),
6376                             getValue(I.getArgOperand(0)),
6377                             getValue(I.getArgOperand(1))));
6378     return;
6379   case Intrinsic::eh_unwind_init:
6380     DAG.getMachineFunction().setCallsUnwindInit(true);
6381     return;
6382   case Intrinsic::eh_dwarf_cfa:
6383     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6384                              TLI.getPointerTy(DAG.getDataLayout()),
6385                              getValue(I.getArgOperand(0))));
6386     return;
6387   case Intrinsic::eh_sjlj_callsite: {
6388     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6389     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
6390     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6391 
6392     MMI.setCurrentCallSite(CI->getZExtValue());
6393     return;
6394   }
6395   case Intrinsic::eh_sjlj_functioncontext: {
6396     // Get and store the index of the function context.
6397     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6398     AllocaInst *FnCtx =
6399       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6400     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6401     MFI.setFunctionContextIndex(FI);
6402     return;
6403   }
6404   case Intrinsic::eh_sjlj_setjmp: {
6405     SDValue Ops[2];
6406     Ops[0] = getRoot();
6407     Ops[1] = getValue(I.getArgOperand(0));
6408     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6409                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6410     setValue(&I, Op.getValue(0));
6411     DAG.setRoot(Op.getValue(1));
6412     return;
6413   }
6414   case Intrinsic::eh_sjlj_longjmp:
6415     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6416                             getRoot(), getValue(I.getArgOperand(0))));
6417     return;
6418   case Intrinsic::eh_sjlj_setup_dispatch:
6419     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6420                             getRoot()));
6421     return;
6422   case Intrinsic::masked_gather:
6423     visitMaskedGather(I);
6424     return;
6425   case Intrinsic::masked_load:
6426     visitMaskedLoad(I);
6427     return;
6428   case Intrinsic::masked_scatter:
6429     visitMaskedScatter(I);
6430     return;
6431   case Intrinsic::masked_store:
6432     visitMaskedStore(I);
6433     return;
6434   case Intrinsic::masked_expandload:
6435     visitMaskedLoad(I, true /* IsExpanding */);
6436     return;
6437   case Intrinsic::masked_compressstore:
6438     visitMaskedStore(I, true /* IsCompressing */);
6439     return;
6440   case Intrinsic::powi:
6441     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6442                             getValue(I.getArgOperand(1)), DAG));
6443     return;
6444   case Intrinsic::log:
6445     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6446     return;
6447   case Intrinsic::log2:
6448     setValue(&I,
6449              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6450     return;
6451   case Intrinsic::log10:
6452     setValue(&I,
6453              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6454     return;
6455   case Intrinsic::exp:
6456     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6457     return;
6458   case Intrinsic::exp2:
6459     setValue(&I,
6460              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6461     return;
6462   case Intrinsic::pow:
6463     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6464                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6465     return;
6466   case Intrinsic::sqrt:
6467   case Intrinsic::fabs:
6468   case Intrinsic::sin:
6469   case Intrinsic::cos:
6470   case Intrinsic::exp10:
6471   case Intrinsic::floor:
6472   case Intrinsic::ceil:
6473   case Intrinsic::trunc:
6474   case Intrinsic::rint:
6475   case Intrinsic::nearbyint:
6476   case Intrinsic::round:
6477   case Intrinsic::roundeven:
6478   case Intrinsic::canonicalize: {
6479     unsigned Opcode;
6480     switch (Intrinsic) {
6481     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6482     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6483     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6484     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6485     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6486     case Intrinsic::exp10:     Opcode = ISD::FEXP10;     break;
6487     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6488     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6489     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6490     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6491     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6492     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6493     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6494     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6495     }
6496 
6497     setValue(&I, DAG.getNode(Opcode, sdl,
6498                              getValue(I.getArgOperand(0)).getValueType(),
6499                              getValue(I.getArgOperand(0)), Flags));
6500     return;
6501   }
6502   case Intrinsic::lround:
6503   case Intrinsic::llround:
6504   case Intrinsic::lrint:
6505   case Intrinsic::llrint: {
6506     unsigned Opcode;
6507     switch (Intrinsic) {
6508     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6509     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6510     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6511     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6512     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6513     }
6514 
6515     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6516     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6517                              getValue(I.getArgOperand(0))));
6518     return;
6519   }
6520   case Intrinsic::minnum:
6521     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6522                              getValue(I.getArgOperand(0)).getValueType(),
6523                              getValue(I.getArgOperand(0)),
6524                              getValue(I.getArgOperand(1)), Flags));
6525     return;
6526   case Intrinsic::maxnum:
6527     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6528                              getValue(I.getArgOperand(0)).getValueType(),
6529                              getValue(I.getArgOperand(0)),
6530                              getValue(I.getArgOperand(1)), Flags));
6531     return;
6532   case Intrinsic::minimum:
6533     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6534                              getValue(I.getArgOperand(0)).getValueType(),
6535                              getValue(I.getArgOperand(0)),
6536                              getValue(I.getArgOperand(1)), Flags));
6537     return;
6538   case Intrinsic::maximum:
6539     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6540                              getValue(I.getArgOperand(0)).getValueType(),
6541                              getValue(I.getArgOperand(0)),
6542                              getValue(I.getArgOperand(1)), Flags));
6543     return;
6544   case Intrinsic::copysign:
6545     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6546                              getValue(I.getArgOperand(0)).getValueType(),
6547                              getValue(I.getArgOperand(0)),
6548                              getValue(I.getArgOperand(1)), Flags));
6549     return;
6550   case Intrinsic::ldexp:
6551     setValue(&I, DAG.getNode(ISD::FLDEXP, sdl,
6552                              getValue(I.getArgOperand(0)).getValueType(),
6553                              getValue(I.getArgOperand(0)),
6554                              getValue(I.getArgOperand(1)), Flags));
6555     return;
6556   case Intrinsic::frexp: {
6557     SmallVector<EVT, 2> ValueVTs;
6558     ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
6559     SDVTList VTs = DAG.getVTList(ValueVTs);
6560     setValue(&I,
6561              DAG.getNode(ISD::FFREXP, sdl, VTs, getValue(I.getArgOperand(0))));
6562     return;
6563   }
6564   case Intrinsic::arithmetic_fence: {
6565     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6566                              getValue(I.getArgOperand(0)).getValueType(),
6567                              getValue(I.getArgOperand(0)), Flags));
6568     return;
6569   }
6570   case Intrinsic::fma:
6571     setValue(&I, DAG.getNode(
6572                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6573                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6574                      getValue(I.getArgOperand(2)), Flags));
6575     return;
6576 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6577   case Intrinsic::INTRINSIC:
6578 #include "llvm/IR/ConstrainedOps.def"
6579     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6580     return;
6581 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6582 #include "llvm/IR/VPIntrinsics.def"
6583     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6584     return;
6585   case Intrinsic::fptrunc_round: {
6586     // Get the last argument, the metadata and convert it to an integer in the
6587     // call
6588     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
6589     std::optional<RoundingMode> RoundMode =
6590         convertStrToRoundingMode(cast<MDString>(MD)->getString());
6591 
6592     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6593 
6594     // Propagate fast-math-flags from IR to node(s).
6595     SDNodeFlags Flags;
6596     Flags.copyFMF(*cast<FPMathOperator>(&I));
6597     SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
6598 
6599     SDValue Result;
6600     Result = DAG.getNode(
6601         ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
6602         DAG.getTargetConstant((int)*RoundMode, sdl,
6603                               TLI.getPointerTy(DAG.getDataLayout())));
6604     setValue(&I, Result);
6605 
6606     return;
6607   }
6608   case Intrinsic::fmuladd: {
6609     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6610     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6611         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6612       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6613                                getValue(I.getArgOperand(0)).getValueType(),
6614                                getValue(I.getArgOperand(0)),
6615                                getValue(I.getArgOperand(1)),
6616                                getValue(I.getArgOperand(2)), Flags));
6617     } else {
6618       // TODO: Intrinsic calls should have fast-math-flags.
6619       SDValue Mul = DAG.getNode(
6620           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6621           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6622       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6623                                 getValue(I.getArgOperand(0)).getValueType(),
6624                                 Mul, getValue(I.getArgOperand(2)), Flags);
6625       setValue(&I, Add);
6626     }
6627     return;
6628   }
6629   case Intrinsic::convert_to_fp16:
6630     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6631                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6632                                          getValue(I.getArgOperand(0)),
6633                                          DAG.getTargetConstant(0, sdl,
6634                                                                MVT::i32))));
6635     return;
6636   case Intrinsic::convert_from_fp16:
6637     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6638                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6639                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6640                                          getValue(I.getArgOperand(0)))));
6641     return;
6642   case Intrinsic::fptosi_sat: {
6643     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6644     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
6645                              getValue(I.getArgOperand(0)),
6646                              DAG.getValueType(VT.getScalarType())));
6647     return;
6648   }
6649   case Intrinsic::fptoui_sat: {
6650     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6651     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
6652                              getValue(I.getArgOperand(0)),
6653                              DAG.getValueType(VT.getScalarType())));
6654     return;
6655   }
6656   case Intrinsic::set_rounding:
6657     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6658                       {getRoot(), getValue(I.getArgOperand(0))});
6659     setValue(&I, Res);
6660     DAG.setRoot(Res.getValue(0));
6661     return;
6662   case Intrinsic::is_fpclass: {
6663     const DataLayout DLayout = DAG.getDataLayout();
6664     EVT DestVT = TLI.getValueType(DLayout, I.getType());
6665     EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
6666     FPClassTest Test = static_cast<FPClassTest>(
6667         cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
6668     MachineFunction &MF = DAG.getMachineFunction();
6669     const Function &F = MF.getFunction();
6670     SDValue Op = getValue(I.getArgOperand(0));
6671     SDNodeFlags Flags;
6672     Flags.setNoFPExcept(
6673         !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
6674     // If ISD::IS_FPCLASS should be expanded, do it right now, because the
6675     // expansion can use illegal types. Making expansion early allows
6676     // legalizing these types prior to selection.
6677     if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) {
6678       SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
6679       setValue(&I, Result);
6680       return;
6681     }
6682 
6683     SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
6684     SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
6685     setValue(&I, V);
6686     return;
6687   }
6688   case Intrinsic::get_fpenv: {
6689     const DataLayout DLayout = DAG.getDataLayout();
6690     EVT EnvVT = TLI.getValueType(DLayout, I.getType());
6691     Align TempAlign = DAG.getEVTAlign(EnvVT);
6692     SDValue Chain = getRoot();
6693     // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node
6694     // and temporary storage in stack.
6695     if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) {
6696       Res = DAG.getNode(
6697           ISD::GET_FPENV, sdl,
6698           DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
6699                         MVT::Other),
6700           Chain);
6701     } else {
6702       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
6703       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
6704       auto MPI =
6705           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
6706       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6707           MPI, MachineMemOperand::MOStore, MemoryLocation::UnknownSize,
6708           TempAlign);
6709       Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
6710       Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI);
6711     }
6712     setValue(&I, Res);
6713     DAG.setRoot(Res.getValue(1));
6714     return;
6715   }
6716   case Intrinsic::set_fpenv: {
6717     const DataLayout DLayout = DAG.getDataLayout();
6718     SDValue Env = getValue(I.getArgOperand(0));
6719     EVT EnvVT = Env.getValueType();
6720     Align TempAlign = DAG.getEVTAlign(EnvVT);
6721     SDValue Chain = getRoot();
6722     // If SET_FPENV is custom or legal, use it. Otherwise use loading
6723     // environment from memory.
6724     if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) {
6725       Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env);
6726     } else {
6727       // Allocate space in stack, copy environment bits into it and use this
6728       // memory in SET_FPENV_MEM.
6729       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
6730       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
6731       auto MPI =
6732           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
6733       Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign,
6734                            MachineMemOperand::MOStore);
6735       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6736           MPI, MachineMemOperand::MOLoad, MemoryLocation::UnknownSize,
6737           TempAlign);
6738       Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
6739     }
6740     DAG.setRoot(Chain);
6741     return;
6742   }
6743   case Intrinsic::reset_fpenv:
6744     DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot()));
6745     return;
6746   case Intrinsic::get_fpmode:
6747     Res = DAG.getNode(
6748         ISD::GET_FPMODE, sdl,
6749         DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
6750                       MVT::Other),
6751         DAG.getRoot());
6752     setValue(&I, Res);
6753     DAG.setRoot(Res.getValue(1));
6754     return;
6755   case Intrinsic::set_fpmode:
6756     Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()},
6757                       getValue(I.getArgOperand(0)));
6758     DAG.setRoot(Res);
6759     return;
6760   case Intrinsic::reset_fpmode: {
6761     Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot());
6762     DAG.setRoot(Res);
6763     return;
6764   }
6765   case Intrinsic::pcmarker: {
6766     SDValue Tmp = getValue(I.getArgOperand(0));
6767     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6768     return;
6769   }
6770   case Intrinsic::readcyclecounter: {
6771     SDValue Op = getRoot();
6772     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6773                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6774     setValue(&I, Res);
6775     DAG.setRoot(Res.getValue(1));
6776     return;
6777   }
6778   case Intrinsic::bitreverse:
6779     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6780                              getValue(I.getArgOperand(0)).getValueType(),
6781                              getValue(I.getArgOperand(0))));
6782     return;
6783   case Intrinsic::bswap:
6784     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6785                              getValue(I.getArgOperand(0)).getValueType(),
6786                              getValue(I.getArgOperand(0))));
6787     return;
6788   case Intrinsic::cttz: {
6789     SDValue Arg = getValue(I.getArgOperand(0));
6790     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6791     EVT Ty = Arg.getValueType();
6792     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6793                              sdl, Ty, Arg));
6794     return;
6795   }
6796   case Intrinsic::ctlz: {
6797     SDValue Arg = getValue(I.getArgOperand(0));
6798     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6799     EVT Ty = Arg.getValueType();
6800     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6801                              sdl, Ty, Arg));
6802     return;
6803   }
6804   case Intrinsic::ctpop: {
6805     SDValue Arg = getValue(I.getArgOperand(0));
6806     EVT Ty = Arg.getValueType();
6807     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6808     return;
6809   }
6810   case Intrinsic::fshl:
6811   case Intrinsic::fshr: {
6812     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6813     SDValue X = getValue(I.getArgOperand(0));
6814     SDValue Y = getValue(I.getArgOperand(1));
6815     SDValue Z = getValue(I.getArgOperand(2));
6816     EVT VT = X.getValueType();
6817 
6818     if (X == Y) {
6819       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6820       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6821     } else {
6822       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6823       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6824     }
6825     return;
6826   }
6827   case Intrinsic::sadd_sat: {
6828     SDValue Op1 = getValue(I.getArgOperand(0));
6829     SDValue Op2 = getValue(I.getArgOperand(1));
6830     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6831     return;
6832   }
6833   case Intrinsic::uadd_sat: {
6834     SDValue Op1 = getValue(I.getArgOperand(0));
6835     SDValue Op2 = getValue(I.getArgOperand(1));
6836     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6837     return;
6838   }
6839   case Intrinsic::ssub_sat: {
6840     SDValue Op1 = getValue(I.getArgOperand(0));
6841     SDValue Op2 = getValue(I.getArgOperand(1));
6842     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6843     return;
6844   }
6845   case Intrinsic::usub_sat: {
6846     SDValue Op1 = getValue(I.getArgOperand(0));
6847     SDValue Op2 = getValue(I.getArgOperand(1));
6848     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6849     return;
6850   }
6851   case Intrinsic::sshl_sat: {
6852     SDValue Op1 = getValue(I.getArgOperand(0));
6853     SDValue Op2 = getValue(I.getArgOperand(1));
6854     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6855     return;
6856   }
6857   case Intrinsic::ushl_sat: {
6858     SDValue Op1 = getValue(I.getArgOperand(0));
6859     SDValue Op2 = getValue(I.getArgOperand(1));
6860     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6861     return;
6862   }
6863   case Intrinsic::smul_fix:
6864   case Intrinsic::umul_fix:
6865   case Intrinsic::smul_fix_sat:
6866   case Intrinsic::umul_fix_sat: {
6867     SDValue Op1 = getValue(I.getArgOperand(0));
6868     SDValue Op2 = getValue(I.getArgOperand(1));
6869     SDValue Op3 = getValue(I.getArgOperand(2));
6870     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6871                              Op1.getValueType(), Op1, Op2, Op3));
6872     return;
6873   }
6874   case Intrinsic::sdiv_fix:
6875   case Intrinsic::udiv_fix:
6876   case Intrinsic::sdiv_fix_sat:
6877   case Intrinsic::udiv_fix_sat: {
6878     SDValue Op1 = getValue(I.getArgOperand(0));
6879     SDValue Op2 = getValue(I.getArgOperand(1));
6880     SDValue Op3 = getValue(I.getArgOperand(2));
6881     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6882                               Op1, Op2, Op3, DAG, TLI));
6883     return;
6884   }
6885   case Intrinsic::smax: {
6886     SDValue Op1 = getValue(I.getArgOperand(0));
6887     SDValue Op2 = getValue(I.getArgOperand(1));
6888     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
6889     return;
6890   }
6891   case Intrinsic::smin: {
6892     SDValue Op1 = getValue(I.getArgOperand(0));
6893     SDValue Op2 = getValue(I.getArgOperand(1));
6894     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
6895     return;
6896   }
6897   case Intrinsic::umax: {
6898     SDValue Op1 = getValue(I.getArgOperand(0));
6899     SDValue Op2 = getValue(I.getArgOperand(1));
6900     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
6901     return;
6902   }
6903   case Intrinsic::umin: {
6904     SDValue Op1 = getValue(I.getArgOperand(0));
6905     SDValue Op2 = getValue(I.getArgOperand(1));
6906     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
6907     return;
6908   }
6909   case Intrinsic::abs: {
6910     // TODO: Preserve "int min is poison" arg in SDAG?
6911     SDValue Op1 = getValue(I.getArgOperand(0));
6912     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
6913     return;
6914   }
6915   case Intrinsic::stacksave: {
6916     SDValue Op = getRoot();
6917     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6918     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6919     setValue(&I, Res);
6920     DAG.setRoot(Res.getValue(1));
6921     return;
6922   }
6923   case Intrinsic::stackrestore:
6924     Res = getValue(I.getArgOperand(0));
6925     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6926     return;
6927   case Intrinsic::get_dynamic_area_offset: {
6928     SDValue Op = getRoot();
6929     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6930     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6931     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6932     // target.
6933     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
6934       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6935                          " intrinsic!");
6936     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6937                       Op);
6938     DAG.setRoot(Op);
6939     setValue(&I, Res);
6940     return;
6941   }
6942   case Intrinsic::stackguard: {
6943     MachineFunction &MF = DAG.getMachineFunction();
6944     const Module &M = *MF.getFunction().getParent();
6945     SDValue Chain = getRoot();
6946     if (TLI.useLoadStackGuardNode()) {
6947       Res = getLoadStackGuard(DAG, sdl, Chain);
6948     } else {
6949       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6950       const Value *Global = TLI.getSDagStackGuard(M);
6951       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
6952       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6953                         MachinePointerInfo(Global, 0), Align,
6954                         MachineMemOperand::MOVolatile);
6955     }
6956     if (TLI.useStackGuardXorFP())
6957       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6958     DAG.setRoot(Chain);
6959     setValue(&I, Res);
6960     return;
6961   }
6962   case Intrinsic::stackprotector: {
6963     // Emit code into the DAG to store the stack guard onto the stack.
6964     MachineFunction &MF = DAG.getMachineFunction();
6965     MachineFrameInfo &MFI = MF.getFrameInfo();
6966     SDValue Src, Chain = getRoot();
6967 
6968     if (TLI.useLoadStackGuardNode())
6969       Src = getLoadStackGuard(DAG, sdl, Chain);
6970     else
6971       Src = getValue(I.getArgOperand(0));   // The guard's value.
6972 
6973     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6974 
6975     int FI = FuncInfo.StaticAllocaMap[Slot];
6976     MFI.setStackProtectorIndex(FI);
6977     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6978 
6979     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6980 
6981     // Store the stack protector onto the stack.
6982     Res = DAG.getStore(
6983         Chain, sdl, Src, FIN,
6984         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
6985         MaybeAlign(), MachineMemOperand::MOVolatile);
6986     setValue(&I, Res);
6987     DAG.setRoot(Res);
6988     return;
6989   }
6990   case Intrinsic::objectsize:
6991     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6992 
6993   case Intrinsic::is_constant:
6994     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6995 
6996   case Intrinsic::annotation:
6997   case Intrinsic::ptr_annotation:
6998   case Intrinsic::launder_invariant_group:
6999   case Intrinsic::strip_invariant_group:
7000     // Drop the intrinsic, but forward the value
7001     setValue(&I, getValue(I.getOperand(0)));
7002     return;
7003 
7004   case Intrinsic::assume:
7005   case Intrinsic::experimental_noalias_scope_decl:
7006   case Intrinsic::var_annotation:
7007   case Intrinsic::sideeffect:
7008     // Discard annotate attributes, noalias scope declarations, assumptions, and
7009     // artificial side-effects.
7010     return;
7011 
7012   case Intrinsic::codeview_annotation: {
7013     // Emit a label associated with this metadata.
7014     MachineFunction &MF = DAG.getMachineFunction();
7015     MCSymbol *Label =
7016         MF.getMMI().getContext().createTempSymbol("annotation", true);
7017     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
7018     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
7019     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
7020     DAG.setRoot(Res);
7021     return;
7022   }
7023 
7024   case Intrinsic::init_trampoline: {
7025     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
7026 
7027     SDValue Ops[6];
7028     Ops[0] = getRoot();
7029     Ops[1] = getValue(I.getArgOperand(0));
7030     Ops[2] = getValue(I.getArgOperand(1));
7031     Ops[3] = getValue(I.getArgOperand(2));
7032     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
7033     Ops[5] = DAG.getSrcValue(F);
7034 
7035     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
7036 
7037     DAG.setRoot(Res);
7038     return;
7039   }
7040   case Intrinsic::adjust_trampoline:
7041     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
7042                              TLI.getPointerTy(DAG.getDataLayout()),
7043                              getValue(I.getArgOperand(0))));
7044     return;
7045   case Intrinsic::gcroot: {
7046     assert(DAG.getMachineFunction().getFunction().hasGC() &&
7047            "only valid in functions with gc specified, enforced by Verifier");
7048     assert(GFI && "implied by previous");
7049     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
7050     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
7051 
7052     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
7053     GFI->addStackRoot(FI->getIndex(), TypeMap);
7054     return;
7055   }
7056   case Intrinsic::gcread:
7057   case Intrinsic::gcwrite:
7058     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
7059   case Intrinsic::get_rounding:
7060     Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot());
7061     setValue(&I, Res);
7062     DAG.setRoot(Res.getValue(1));
7063     return;
7064 
7065   case Intrinsic::expect:
7066     // Just replace __builtin_expect(exp, c) with EXP.
7067     setValue(&I, getValue(I.getArgOperand(0)));
7068     return;
7069 
7070   case Intrinsic::ubsantrap:
7071   case Intrinsic::debugtrap:
7072   case Intrinsic::trap: {
7073     StringRef TrapFuncName =
7074         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
7075     if (TrapFuncName.empty()) {
7076       switch (Intrinsic) {
7077       case Intrinsic::trap:
7078         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
7079         break;
7080       case Intrinsic::debugtrap:
7081         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
7082         break;
7083       case Intrinsic::ubsantrap:
7084         DAG.setRoot(DAG.getNode(
7085             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
7086             DAG.getTargetConstant(
7087                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
7088                 MVT::i32)));
7089         break;
7090       default: llvm_unreachable("unknown trap intrinsic");
7091       }
7092       return;
7093     }
7094     TargetLowering::ArgListTy Args;
7095     if (Intrinsic == Intrinsic::ubsantrap) {
7096       Args.push_back(TargetLoweringBase::ArgListEntry());
7097       Args[0].Val = I.getArgOperand(0);
7098       Args[0].Node = getValue(Args[0].Val);
7099       Args[0].Ty = Args[0].Val->getType();
7100     }
7101 
7102     TargetLowering::CallLoweringInfo CLI(DAG);
7103     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
7104         CallingConv::C, I.getType(),
7105         DAG.getExternalSymbol(TrapFuncName.data(),
7106                               TLI.getPointerTy(DAG.getDataLayout())),
7107         std::move(Args));
7108 
7109     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7110     DAG.setRoot(Result.second);
7111     return;
7112   }
7113 
7114   case Intrinsic::uadd_with_overflow:
7115   case Intrinsic::sadd_with_overflow:
7116   case Intrinsic::usub_with_overflow:
7117   case Intrinsic::ssub_with_overflow:
7118   case Intrinsic::umul_with_overflow:
7119   case Intrinsic::smul_with_overflow: {
7120     ISD::NodeType Op;
7121     switch (Intrinsic) {
7122     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7123     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
7124     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
7125     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
7126     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
7127     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
7128     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
7129     }
7130     SDValue Op1 = getValue(I.getArgOperand(0));
7131     SDValue Op2 = getValue(I.getArgOperand(1));
7132 
7133     EVT ResultVT = Op1.getValueType();
7134     EVT OverflowVT = MVT::i1;
7135     if (ResultVT.isVector())
7136       OverflowVT = EVT::getVectorVT(
7137           *Context, OverflowVT, ResultVT.getVectorElementCount());
7138 
7139     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
7140     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
7141     return;
7142   }
7143   case Intrinsic::prefetch: {
7144     SDValue Ops[5];
7145     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7146     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
7147     Ops[0] = DAG.getRoot();
7148     Ops[1] = getValue(I.getArgOperand(0));
7149     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
7150                                    MVT::i32);
7151     Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl,
7152                                    MVT::i32);
7153     Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl,
7154                                    MVT::i32);
7155     SDValue Result = DAG.getMemIntrinsicNode(
7156         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
7157         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
7158         /* align */ std::nullopt, Flags);
7159 
7160     // Chain the prefetch in parallel with any pending loads, to stay out of
7161     // the way of later optimizations.
7162     PendingLoads.push_back(Result);
7163     Result = getRoot();
7164     DAG.setRoot(Result);
7165     return;
7166   }
7167   case Intrinsic::lifetime_start:
7168   case Intrinsic::lifetime_end: {
7169     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
7170     // Stack coloring is not enabled in O0, discard region information.
7171     if (TM.getOptLevel() == CodeGenOptLevel::None)
7172       return;
7173 
7174     const int64_t ObjectSize =
7175         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
7176     Value *const ObjectPtr = I.getArgOperand(1);
7177     SmallVector<const Value *, 4> Allocas;
7178     getUnderlyingObjects(ObjectPtr, Allocas);
7179 
7180     for (const Value *Alloca : Allocas) {
7181       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
7182 
7183       // Could not find an Alloca.
7184       if (!LifetimeObject)
7185         continue;
7186 
7187       // First check that the Alloca is static, otherwise it won't have a
7188       // valid frame index.
7189       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
7190       if (SI == FuncInfo.StaticAllocaMap.end())
7191         return;
7192 
7193       const int FrameIndex = SI->second;
7194       int64_t Offset;
7195       if (GetPointerBaseWithConstantOffset(
7196               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
7197         Offset = -1; // Cannot determine offset from alloca to lifetime object.
7198       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
7199                                 Offset);
7200       DAG.setRoot(Res);
7201     }
7202     return;
7203   }
7204   case Intrinsic::pseudoprobe: {
7205     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
7206     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7207     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
7208     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
7209     DAG.setRoot(Res);
7210     return;
7211   }
7212   case Intrinsic::invariant_start:
7213     // Discard region information.
7214     setValue(&I,
7215              DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
7216     return;
7217   case Intrinsic::invariant_end:
7218     // Discard region information.
7219     return;
7220   case Intrinsic::clear_cache:
7221     /// FunctionName may be null.
7222     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
7223       lowerCallToExternalSymbol(I, FunctionName);
7224     return;
7225   case Intrinsic::donothing:
7226   case Intrinsic::seh_try_begin:
7227   case Intrinsic::seh_scope_begin:
7228   case Intrinsic::seh_try_end:
7229   case Intrinsic::seh_scope_end:
7230     // ignore
7231     return;
7232   case Intrinsic::experimental_stackmap:
7233     visitStackmap(I);
7234     return;
7235   case Intrinsic::experimental_patchpoint_void:
7236   case Intrinsic::experimental_patchpoint_i64:
7237     visitPatchpoint(I);
7238     return;
7239   case Intrinsic::experimental_gc_statepoint:
7240     LowerStatepoint(cast<GCStatepointInst>(I));
7241     return;
7242   case Intrinsic::experimental_gc_result:
7243     visitGCResult(cast<GCResultInst>(I));
7244     return;
7245   case Intrinsic::experimental_gc_relocate:
7246     visitGCRelocate(cast<GCRelocateInst>(I));
7247     return;
7248   case Intrinsic::instrprof_cover:
7249     llvm_unreachable("instrprof failed to lower a cover");
7250   case Intrinsic::instrprof_increment:
7251     llvm_unreachable("instrprof failed to lower an increment");
7252   case Intrinsic::instrprof_timestamp:
7253     llvm_unreachable("instrprof failed to lower a timestamp");
7254   case Intrinsic::instrprof_value_profile:
7255     llvm_unreachable("instrprof failed to lower a value profiling call");
7256   case Intrinsic::instrprof_mcdc_parameters:
7257     llvm_unreachable("instrprof failed to lower mcdc parameters");
7258   case Intrinsic::instrprof_mcdc_tvbitmap_update:
7259     llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update");
7260   case Intrinsic::instrprof_mcdc_condbitmap_update:
7261     llvm_unreachable("instrprof failed to lower an mcdc condbitmap update");
7262   case Intrinsic::localescape: {
7263     MachineFunction &MF = DAG.getMachineFunction();
7264     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
7265 
7266     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
7267     // is the same on all targets.
7268     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
7269       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
7270       if (isa<ConstantPointerNull>(Arg))
7271         continue; // Skip null pointers. They represent a hole in index space.
7272       AllocaInst *Slot = cast<AllocaInst>(Arg);
7273       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
7274              "can only escape static allocas");
7275       int FI = FuncInfo.StaticAllocaMap[Slot];
7276       MCSymbol *FrameAllocSym =
7277           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7278               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
7279       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
7280               TII->get(TargetOpcode::LOCAL_ESCAPE))
7281           .addSym(FrameAllocSym)
7282           .addFrameIndex(FI);
7283     }
7284 
7285     return;
7286   }
7287 
7288   case Intrinsic::localrecover: {
7289     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
7290     MachineFunction &MF = DAG.getMachineFunction();
7291 
7292     // Get the symbol that defines the frame offset.
7293     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
7294     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
7295     unsigned IdxVal =
7296         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
7297     MCSymbol *FrameAllocSym =
7298         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7299             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
7300 
7301     Value *FP = I.getArgOperand(1);
7302     SDValue FPVal = getValue(FP);
7303     EVT PtrVT = FPVal.getValueType();
7304 
7305     // Create a MCSymbol for the label to avoid any target lowering
7306     // that would make this PC relative.
7307     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
7308     SDValue OffsetVal =
7309         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
7310 
7311     // Add the offset to the FP.
7312     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
7313     setValue(&I, Add);
7314 
7315     return;
7316   }
7317 
7318   case Intrinsic::eh_exceptionpointer:
7319   case Intrinsic::eh_exceptioncode: {
7320     // Get the exception pointer vreg, copy from it, and resize it to fit.
7321     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
7322     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
7323     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
7324     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
7325     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
7326     if (Intrinsic == Intrinsic::eh_exceptioncode)
7327       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
7328     setValue(&I, N);
7329     return;
7330   }
7331   case Intrinsic::xray_customevent: {
7332     // Here we want to make sure that the intrinsic behaves as if it has a
7333     // specific calling convention.
7334     const auto &Triple = DAG.getTarget().getTargetTriple();
7335     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7336       return;
7337 
7338     SmallVector<SDValue, 8> Ops;
7339 
7340     // We want to say that we always want the arguments in registers.
7341     SDValue LogEntryVal = getValue(I.getArgOperand(0));
7342     SDValue StrSizeVal = getValue(I.getArgOperand(1));
7343     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7344     SDValue Chain = getRoot();
7345     Ops.push_back(LogEntryVal);
7346     Ops.push_back(StrSizeVal);
7347     Ops.push_back(Chain);
7348 
7349     // We need to enforce the calling convention for the callsite, so that
7350     // argument ordering is enforced correctly, and that register allocation can
7351     // see that some registers may be assumed clobbered and have to preserve
7352     // them across calls to the intrinsic.
7353     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
7354                                            sdl, NodeTys, Ops);
7355     SDValue patchableNode = SDValue(MN, 0);
7356     DAG.setRoot(patchableNode);
7357     setValue(&I, patchableNode);
7358     return;
7359   }
7360   case Intrinsic::xray_typedevent: {
7361     // Here we want to make sure that the intrinsic behaves as if it has a
7362     // specific calling convention.
7363     const auto &Triple = DAG.getTarget().getTargetTriple();
7364     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7365       return;
7366 
7367     SmallVector<SDValue, 8> Ops;
7368 
7369     // We want to say that we always want the arguments in registers.
7370     // It's unclear to me how manipulating the selection DAG here forces callers
7371     // to provide arguments in registers instead of on the stack.
7372     SDValue LogTypeId = getValue(I.getArgOperand(0));
7373     SDValue LogEntryVal = getValue(I.getArgOperand(1));
7374     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7375     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7376     SDValue Chain = getRoot();
7377     Ops.push_back(LogTypeId);
7378     Ops.push_back(LogEntryVal);
7379     Ops.push_back(StrSizeVal);
7380     Ops.push_back(Chain);
7381 
7382     // We need to enforce the calling convention for the callsite, so that
7383     // argument ordering is enforced correctly, and that register allocation can
7384     // see that some registers may be assumed clobbered and have to preserve
7385     // them across calls to the intrinsic.
7386     MachineSDNode *MN = DAG.getMachineNode(
7387         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7388     SDValue patchableNode = SDValue(MN, 0);
7389     DAG.setRoot(patchableNode);
7390     setValue(&I, patchableNode);
7391     return;
7392   }
7393   case Intrinsic::experimental_deoptimize:
7394     LowerDeoptimizeCall(&I);
7395     return;
7396   case Intrinsic::experimental_stepvector:
7397     visitStepVector(I);
7398     return;
7399   case Intrinsic::vector_reduce_fadd:
7400   case Intrinsic::vector_reduce_fmul:
7401   case Intrinsic::vector_reduce_add:
7402   case Intrinsic::vector_reduce_mul:
7403   case Intrinsic::vector_reduce_and:
7404   case Intrinsic::vector_reduce_or:
7405   case Intrinsic::vector_reduce_xor:
7406   case Intrinsic::vector_reduce_smax:
7407   case Intrinsic::vector_reduce_smin:
7408   case Intrinsic::vector_reduce_umax:
7409   case Intrinsic::vector_reduce_umin:
7410   case Intrinsic::vector_reduce_fmax:
7411   case Intrinsic::vector_reduce_fmin:
7412   case Intrinsic::vector_reduce_fmaximum:
7413   case Intrinsic::vector_reduce_fminimum:
7414     visitVectorReduce(I, Intrinsic);
7415     return;
7416 
7417   case Intrinsic::icall_branch_funnel: {
7418     SmallVector<SDValue, 16> Ops;
7419     Ops.push_back(getValue(I.getArgOperand(0)));
7420 
7421     int64_t Offset;
7422     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7423         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7424     if (!Base)
7425       report_fatal_error(
7426           "llvm.icall.branch.funnel operand must be a GlobalValue");
7427     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7428 
7429     struct BranchFunnelTarget {
7430       int64_t Offset;
7431       SDValue Target;
7432     };
7433     SmallVector<BranchFunnelTarget, 8> Targets;
7434 
7435     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7436       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7437           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7438       if (ElemBase != Base)
7439         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7440                            "to the same GlobalValue");
7441 
7442       SDValue Val = getValue(I.getArgOperand(Op + 1));
7443       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7444       if (!GA)
7445         report_fatal_error(
7446             "llvm.icall.branch.funnel operand must be a GlobalValue");
7447       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7448                                      GA->getGlobal(), sdl, Val.getValueType(),
7449                                      GA->getOffset())});
7450     }
7451     llvm::sort(Targets,
7452                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7453                  return T1.Offset < T2.Offset;
7454                });
7455 
7456     for (auto &T : Targets) {
7457       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7458       Ops.push_back(T.Target);
7459     }
7460 
7461     Ops.push_back(DAG.getRoot()); // Chain
7462     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7463                                  MVT::Other, Ops),
7464               0);
7465     DAG.setRoot(N);
7466     setValue(&I, N);
7467     HasTailCall = true;
7468     return;
7469   }
7470 
7471   case Intrinsic::wasm_landingpad_index:
7472     // Information this intrinsic contained has been transferred to
7473     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7474     // delete it now.
7475     return;
7476 
7477   case Intrinsic::aarch64_settag:
7478   case Intrinsic::aarch64_settag_zero: {
7479     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7480     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7481     SDValue Val = TSI.EmitTargetCodeForSetTag(
7482         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7483         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7484         ZeroMemory);
7485     DAG.setRoot(Val);
7486     setValue(&I, Val);
7487     return;
7488   }
7489   case Intrinsic::amdgcn_cs_chain: {
7490     assert(I.arg_size() == 5 && "Additional args not supported yet");
7491     assert(cast<ConstantInt>(I.getOperand(4))->isZero() &&
7492            "Non-zero flags not supported yet");
7493 
7494     // At this point we don't care if it's amdgpu_cs_chain or
7495     // amdgpu_cs_chain_preserve.
7496     CallingConv::ID CC = CallingConv::AMDGPU_CS_Chain;
7497 
7498     Type *RetTy = I.getType();
7499     assert(RetTy->isVoidTy() && "Should not return");
7500 
7501     SDValue Callee = getValue(I.getOperand(0));
7502 
7503     // We only have 2 actual args: one for the SGPRs and one for the VGPRs.
7504     // We'll also tack the value of the EXEC mask at the end.
7505     TargetLowering::ArgListTy Args;
7506     Args.reserve(3);
7507 
7508     for (unsigned Idx : {2, 3, 1}) {
7509       TargetLowering::ArgListEntry Arg;
7510       Arg.Node = getValue(I.getOperand(Idx));
7511       Arg.Ty = I.getOperand(Idx)->getType();
7512       Arg.setAttributes(&I, Idx);
7513       Args.push_back(Arg);
7514     }
7515 
7516     assert(Args[0].IsInReg && "SGPR args should be marked inreg");
7517     assert(!Args[1].IsInReg && "VGPR args should not be marked inreg");
7518     Args[2].IsInReg = true; // EXEC should be inreg
7519 
7520     TargetLowering::CallLoweringInfo CLI(DAG);
7521     CLI.setDebugLoc(getCurSDLoc())
7522         .setChain(getRoot())
7523         .setCallee(CC, RetTy, Callee, std::move(Args))
7524         .setNoReturn(true)
7525         .setTailCall(true)
7526         .setConvergent(I.isConvergent());
7527     CLI.CB = &I;
7528     std::pair<SDValue, SDValue> Result =
7529         lowerInvokable(CLI, /*EHPadBB*/ nullptr);
7530     (void)Result;
7531     assert(!Result.first.getNode() && !Result.second.getNode() &&
7532            "Should've lowered as tail call");
7533 
7534     HasTailCall = true;
7535     return;
7536   }
7537   case Intrinsic::ptrmask: {
7538     SDValue Ptr = getValue(I.getOperand(0));
7539     SDValue Mask = getValue(I.getOperand(1));
7540 
7541     EVT PtrVT = Ptr.getValueType();
7542     assert(PtrVT == Mask.getValueType() &&
7543            "Pointers with different index type are not supported by SDAG");
7544     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask));
7545     return;
7546   }
7547   case Intrinsic::threadlocal_address: {
7548     setValue(&I, getValue(I.getOperand(0)));
7549     return;
7550   }
7551   case Intrinsic::get_active_lane_mask: {
7552     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7553     SDValue Index = getValue(I.getOperand(0));
7554     EVT ElementVT = Index.getValueType();
7555 
7556     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
7557       visitTargetIntrinsic(I, Intrinsic);
7558       return;
7559     }
7560 
7561     SDValue TripCount = getValue(I.getOperand(1));
7562     EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT,
7563                                  CCVT.getVectorElementCount());
7564 
7565     SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
7566     SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
7567     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
7568     SDValue VectorInduction = DAG.getNode(
7569         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
7570     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
7571                                  VectorTripCount, ISD::CondCode::SETULT);
7572     setValue(&I, SetCC);
7573     return;
7574   }
7575   case Intrinsic::experimental_get_vector_length: {
7576     assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 &&
7577            "Expected positive VF");
7578     unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue();
7579     bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne();
7580 
7581     SDValue Count = getValue(I.getOperand(0));
7582     EVT CountVT = Count.getValueType();
7583 
7584     if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) {
7585       visitTargetIntrinsic(I, Intrinsic);
7586       return;
7587     }
7588 
7589     // Expand to a umin between the trip count and the maximum elements the type
7590     // can hold.
7591     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7592 
7593     // Extend the trip count to at least the result VT.
7594     if (CountVT.bitsLT(VT)) {
7595       Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count);
7596       CountVT = VT;
7597     }
7598 
7599     SDValue MaxEVL = DAG.getElementCount(sdl, CountVT,
7600                                          ElementCount::get(VF, IsScalable));
7601 
7602     SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL);
7603     // Clip to the result type if needed.
7604     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin);
7605 
7606     setValue(&I, Trunc);
7607     return;
7608   }
7609   case Intrinsic::experimental_cttz_elts: {
7610     auto DL = getCurSDLoc();
7611     SDValue Op = getValue(I.getOperand(0));
7612     EVT OpVT = Op.getValueType();
7613 
7614     if (!TLI.shouldExpandCttzElements(OpVT)) {
7615       visitTargetIntrinsic(I, Intrinsic);
7616       return;
7617     }
7618 
7619     if (OpVT.getScalarType() != MVT::i1) {
7620       // Compare the input vector elements to zero & use to count trailing zeros
7621       SDValue AllZero = DAG.getConstant(0, DL, OpVT);
7622       OpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
7623                               OpVT.getVectorElementCount());
7624       Op = DAG.getSetCC(DL, OpVT, Op, AllZero, ISD::SETNE);
7625     }
7626 
7627     // Find the smallest "sensible" element type to use for the expansion.
7628     ConstantRange CR(
7629         APInt(64, OpVT.getVectorElementCount().getKnownMinValue()));
7630     if (OpVT.isScalableVT())
7631       CR = CR.umul_sat(getVScaleRange(I.getCaller(), 64));
7632 
7633     // If the zero-is-poison flag is set, we can assume the upper limit
7634     // of the result is VF-1.
7635     if (!cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero())
7636       CR = CR.subtract(APInt(64, 1));
7637 
7638     unsigned EltWidth = I.getType()->getScalarSizeInBits();
7639     EltWidth = std::min(EltWidth, (unsigned)CR.getActiveBits());
7640     EltWidth = std::max(llvm::bit_ceil(EltWidth), (unsigned)8);
7641 
7642     MVT NewEltTy = MVT::getIntegerVT(EltWidth);
7643 
7644     // Create the new vector type & get the vector length
7645     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), NewEltTy,
7646                                  OpVT.getVectorElementCount());
7647 
7648     SDValue VL =
7649         DAG.getElementCount(DL, NewEltTy, OpVT.getVectorElementCount());
7650 
7651     SDValue StepVec = DAG.getStepVector(DL, NewVT);
7652     SDValue SplatVL = DAG.getSplat(NewVT, DL, VL);
7653     SDValue StepVL = DAG.getNode(ISD::SUB, DL, NewVT, SplatVL, StepVec);
7654     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, Op);
7655     SDValue And = DAG.getNode(ISD::AND, DL, NewVT, StepVL, Ext);
7656     SDValue Max = DAG.getNode(ISD::VECREDUCE_UMAX, DL, NewEltTy, And);
7657     SDValue Sub = DAG.getNode(ISD::SUB, DL, NewEltTy, VL, Max);
7658 
7659     EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7660     SDValue Ret = DAG.getZExtOrTrunc(Sub, DL, RetTy);
7661 
7662     setValue(&I, Ret);
7663     return;
7664   }
7665   case Intrinsic::vector_insert: {
7666     SDValue Vec = getValue(I.getOperand(0));
7667     SDValue SubVec = getValue(I.getOperand(1));
7668     SDValue Index = getValue(I.getOperand(2));
7669 
7670     // The intrinsic's index type is i64, but the SDNode requires an index type
7671     // suitable for the target. Convert the index as required.
7672     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7673     if (Index.getValueType() != VectorIdxTy)
7674       Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
7675 
7676     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7677     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
7678                              Index));
7679     return;
7680   }
7681   case Intrinsic::vector_extract: {
7682     SDValue Vec = getValue(I.getOperand(0));
7683     SDValue Index = getValue(I.getOperand(1));
7684     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7685 
7686     // The intrinsic's index type is i64, but the SDNode requires an index type
7687     // suitable for the target. Convert the index as required.
7688     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7689     if (Index.getValueType() != VectorIdxTy)
7690       Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
7691 
7692     setValue(&I,
7693              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
7694     return;
7695   }
7696   case Intrinsic::experimental_vector_reverse:
7697     visitVectorReverse(I);
7698     return;
7699   case Intrinsic::experimental_vector_splice:
7700     visitVectorSplice(I);
7701     return;
7702   case Intrinsic::callbr_landingpad:
7703     visitCallBrLandingPad(I);
7704     return;
7705   case Intrinsic::experimental_vector_interleave2:
7706     visitVectorInterleave(I);
7707     return;
7708   case Intrinsic::experimental_vector_deinterleave2:
7709     visitVectorDeinterleave(I);
7710     return;
7711   }
7712 }
7713 
7714 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7715     const ConstrainedFPIntrinsic &FPI) {
7716   SDLoc sdl = getCurSDLoc();
7717 
7718   // We do not need to serialize constrained FP intrinsics against
7719   // each other or against (nonvolatile) loads, so they can be
7720   // chained like loads.
7721   SDValue Chain = DAG.getRoot();
7722   SmallVector<SDValue, 4> Opers;
7723   Opers.push_back(Chain);
7724   if (FPI.isUnaryOp()) {
7725     Opers.push_back(getValue(FPI.getArgOperand(0)));
7726   } else if (FPI.isTernaryOp()) {
7727     Opers.push_back(getValue(FPI.getArgOperand(0)));
7728     Opers.push_back(getValue(FPI.getArgOperand(1)));
7729     Opers.push_back(getValue(FPI.getArgOperand(2)));
7730   } else {
7731     Opers.push_back(getValue(FPI.getArgOperand(0)));
7732     Opers.push_back(getValue(FPI.getArgOperand(1)));
7733   }
7734 
7735   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
7736     assert(Result.getNode()->getNumValues() == 2);
7737 
7738     // Push node to the appropriate list so that future instructions can be
7739     // chained up correctly.
7740     SDValue OutChain = Result.getValue(1);
7741     switch (EB) {
7742     case fp::ExceptionBehavior::ebIgnore:
7743       // The only reason why ebIgnore nodes still need to be chained is that
7744       // they might depend on the current rounding mode, and therefore must
7745       // not be moved across instruction that may change that mode.
7746       [[fallthrough]];
7747     case fp::ExceptionBehavior::ebMayTrap:
7748       // These must not be moved across calls or instructions that may change
7749       // floating-point exception masks.
7750       PendingConstrainedFP.push_back(OutChain);
7751       break;
7752     case fp::ExceptionBehavior::ebStrict:
7753       // These must not be moved across calls or instructions that may change
7754       // floating-point exception masks or read floating-point exception flags.
7755       // In addition, they cannot be optimized out even if unused.
7756       PendingConstrainedFPStrict.push_back(OutChain);
7757       break;
7758     }
7759   };
7760 
7761   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7762   EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
7763   SDVTList VTs = DAG.getVTList(VT, MVT::Other);
7764   fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
7765 
7766   SDNodeFlags Flags;
7767   if (EB == fp::ExceptionBehavior::ebIgnore)
7768     Flags.setNoFPExcept(true);
7769 
7770   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
7771     Flags.copyFMF(*FPOp);
7772 
7773   unsigned Opcode;
7774   switch (FPI.getIntrinsicID()) {
7775   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7776 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7777   case Intrinsic::INTRINSIC:                                                   \
7778     Opcode = ISD::STRICT_##DAGN;                                               \
7779     break;
7780 #include "llvm/IR/ConstrainedOps.def"
7781   case Intrinsic::experimental_constrained_fmuladd: {
7782     Opcode = ISD::STRICT_FMA;
7783     // Break fmuladd into fmul and fadd.
7784     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7785         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
7786       Opers.pop_back();
7787       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
7788       pushOutChain(Mul, EB);
7789       Opcode = ISD::STRICT_FADD;
7790       Opers.clear();
7791       Opers.push_back(Mul.getValue(1));
7792       Opers.push_back(Mul.getValue(0));
7793       Opers.push_back(getValue(FPI.getArgOperand(2)));
7794     }
7795     break;
7796   }
7797   }
7798 
7799   // A few strict DAG nodes carry additional operands that are not
7800   // set up by the default code above.
7801   switch (Opcode) {
7802   default: break;
7803   case ISD::STRICT_FP_ROUND:
7804     Opers.push_back(
7805         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7806     break;
7807   case ISD::STRICT_FSETCC:
7808   case ISD::STRICT_FSETCCS: {
7809     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7810     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
7811     if (TM.Options.NoNaNsFPMath)
7812       Condition = getFCmpCodeWithoutNaN(Condition);
7813     Opers.push_back(DAG.getCondCode(Condition));
7814     break;
7815   }
7816   }
7817 
7818   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7819   pushOutChain(Result, EB);
7820 
7821   SDValue FPResult = Result.getValue(0);
7822   setValue(&FPI, FPResult);
7823 }
7824 
7825 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
7826   std::optional<unsigned> ResOPC;
7827   switch (VPIntrin.getIntrinsicID()) {
7828   case Intrinsic::vp_ctlz: {
7829     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
7830     ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ;
7831     break;
7832   }
7833   case Intrinsic::vp_cttz: {
7834     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
7835     ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ;
7836     break;
7837   }
7838 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD)                                    \
7839   case Intrinsic::VPID:                                                        \
7840     ResOPC = ISD::VPSD;                                                        \
7841     break;
7842 #include "llvm/IR/VPIntrinsics.def"
7843   }
7844 
7845   if (!ResOPC)
7846     llvm_unreachable(
7847         "Inconsistency: no SDNode available for this VPIntrinsic!");
7848 
7849   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
7850       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
7851     if (VPIntrin.getFastMathFlags().allowReassoc())
7852       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
7853                                                 : ISD::VP_REDUCE_FMUL;
7854   }
7855 
7856   return *ResOPC;
7857 }
7858 
7859 void SelectionDAGBuilder::visitVPLoad(
7860     const VPIntrinsic &VPIntrin, EVT VT,
7861     const SmallVectorImpl<SDValue> &OpValues) {
7862   SDLoc DL = getCurSDLoc();
7863   Value *PtrOperand = VPIntrin.getArgOperand(0);
7864   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7865   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7866   const MDNode *Ranges = getRangeMetadata(VPIntrin);
7867   SDValue LD;
7868   // Do not serialize variable-length loads of constant memory with
7869   // anything.
7870   if (!Alignment)
7871     Alignment = DAG.getEVTAlign(VT);
7872   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7873   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7874   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7875   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7876       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7877       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7878   LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
7879                      MMO, false /*IsExpanding */);
7880   if (AddToChain)
7881     PendingLoads.push_back(LD.getValue(1));
7882   setValue(&VPIntrin, LD);
7883 }
7884 
7885 void SelectionDAGBuilder::visitVPGather(
7886     const VPIntrinsic &VPIntrin, EVT VT,
7887     const SmallVectorImpl<SDValue> &OpValues) {
7888   SDLoc DL = getCurSDLoc();
7889   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7890   Value *PtrOperand = VPIntrin.getArgOperand(0);
7891   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7892   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7893   const MDNode *Ranges = getRangeMetadata(VPIntrin);
7894   SDValue LD;
7895   if (!Alignment)
7896     Alignment = DAG.getEVTAlign(VT.getScalarType());
7897   unsigned AS =
7898     PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7899   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7900      MachinePointerInfo(AS), MachineMemOperand::MOLoad,
7901      MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7902   SDValue Base, Index, Scale;
7903   ISD::MemIndexType IndexType;
7904   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7905                                     this, VPIntrin.getParent(),
7906                                     VT.getScalarStoreSize());
7907   if (!UniformBase) {
7908     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7909     Index = getValue(PtrOperand);
7910     IndexType = ISD::SIGNED_SCALED;
7911     Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7912   }
7913   EVT IdxVT = Index.getValueType();
7914   EVT EltTy = IdxVT.getVectorElementType();
7915   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7916     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7917     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7918   }
7919   LD = DAG.getGatherVP(
7920       DAG.getVTList(VT, MVT::Other), VT, DL,
7921       {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
7922       IndexType);
7923   PendingLoads.push_back(LD.getValue(1));
7924   setValue(&VPIntrin, LD);
7925 }
7926 
7927 void SelectionDAGBuilder::visitVPStore(
7928     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
7929   SDLoc DL = getCurSDLoc();
7930   Value *PtrOperand = VPIntrin.getArgOperand(1);
7931   EVT VT = OpValues[0].getValueType();
7932   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7933   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7934   SDValue ST;
7935   if (!Alignment)
7936     Alignment = DAG.getEVTAlign(VT);
7937   SDValue Ptr = OpValues[1];
7938   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
7939   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7940       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7941       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7942   ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
7943                       OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
7944                       /* IsTruncating */ false, /*IsCompressing*/ false);
7945   DAG.setRoot(ST);
7946   setValue(&VPIntrin, ST);
7947 }
7948 
7949 void SelectionDAGBuilder::visitVPScatter(
7950     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
7951   SDLoc DL = getCurSDLoc();
7952   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7953   Value *PtrOperand = VPIntrin.getArgOperand(1);
7954   EVT VT = OpValues[0].getValueType();
7955   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7956   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7957   SDValue ST;
7958   if (!Alignment)
7959     Alignment = DAG.getEVTAlign(VT.getScalarType());
7960   unsigned AS =
7961       PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7962   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7963       MachinePointerInfo(AS), MachineMemOperand::MOStore,
7964       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7965   SDValue Base, Index, Scale;
7966   ISD::MemIndexType IndexType;
7967   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7968                                     this, VPIntrin.getParent(),
7969                                     VT.getScalarStoreSize());
7970   if (!UniformBase) {
7971     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7972     Index = getValue(PtrOperand);
7973     IndexType = ISD::SIGNED_SCALED;
7974     Scale =
7975       DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7976   }
7977   EVT IdxVT = Index.getValueType();
7978   EVT EltTy = IdxVT.getVectorElementType();
7979   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7980     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7981     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7982   }
7983   ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
7984                         {getMemoryRoot(), OpValues[0], Base, Index, Scale,
7985                          OpValues[2], OpValues[3]},
7986                         MMO, IndexType);
7987   DAG.setRoot(ST);
7988   setValue(&VPIntrin, ST);
7989 }
7990 
7991 void SelectionDAGBuilder::visitVPStridedLoad(
7992     const VPIntrinsic &VPIntrin, EVT VT,
7993     const SmallVectorImpl<SDValue> &OpValues) {
7994   SDLoc DL = getCurSDLoc();
7995   Value *PtrOperand = VPIntrin.getArgOperand(0);
7996   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7997   if (!Alignment)
7998     Alignment = DAG.getEVTAlign(VT.getScalarType());
7999   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8000   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8001   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
8002   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
8003   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8004   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8005       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
8006       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
8007 
8008   SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
8009                                     OpValues[2], OpValues[3], MMO,
8010                                     false /*IsExpanding*/);
8011 
8012   if (AddToChain)
8013     PendingLoads.push_back(LD.getValue(1));
8014   setValue(&VPIntrin, LD);
8015 }
8016 
8017 void SelectionDAGBuilder::visitVPStridedStore(
8018     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8019   SDLoc DL = getCurSDLoc();
8020   Value *PtrOperand = VPIntrin.getArgOperand(1);
8021   EVT VT = OpValues[0].getValueType();
8022   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8023   if (!Alignment)
8024     Alignment = DAG.getEVTAlign(VT.getScalarType());
8025   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8026   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8027       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
8028       MemoryLocation::UnknownSize, *Alignment, AAInfo);
8029 
8030   SDValue ST = DAG.getStridedStoreVP(
8031       getMemoryRoot(), DL, OpValues[0], OpValues[1],
8032       DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3],
8033       OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
8034       /*IsCompressing*/ false);
8035 
8036   DAG.setRoot(ST);
8037   setValue(&VPIntrin, ST);
8038 }
8039 
8040 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) {
8041   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8042   SDLoc DL = getCurSDLoc();
8043 
8044   ISD::CondCode Condition;
8045   CmpInst::Predicate CondCode = VPIntrin.getPredicate();
8046   bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy();
8047   if (IsFP) {
8048     // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan)
8049     // flags, but calls that don't return floating-point types can't be
8050     // FPMathOperators, like vp.fcmp. This affects constrained fcmp too.
8051     Condition = getFCmpCondCode(CondCode);
8052     if (TM.Options.NoNaNsFPMath)
8053       Condition = getFCmpCodeWithoutNaN(Condition);
8054   } else {
8055     Condition = getICmpCondCode(CondCode);
8056   }
8057 
8058   SDValue Op1 = getValue(VPIntrin.getOperand(0));
8059   SDValue Op2 = getValue(VPIntrin.getOperand(1));
8060   // #2 is the condition code
8061   SDValue MaskOp = getValue(VPIntrin.getOperand(3));
8062   SDValue EVL = getValue(VPIntrin.getOperand(4));
8063   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8064   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8065          "Unexpected target EVL type");
8066   EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL);
8067 
8068   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8069                                                         VPIntrin.getType());
8070   setValue(&VPIntrin,
8071            DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL));
8072 }
8073 
8074 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
8075     const VPIntrinsic &VPIntrin) {
8076   SDLoc DL = getCurSDLoc();
8077   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
8078 
8079   auto IID = VPIntrin.getIntrinsicID();
8080 
8081   if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin))
8082     return visitVPCmp(*CmpI);
8083 
8084   SmallVector<EVT, 4> ValueVTs;
8085   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8086   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
8087   SDVTList VTs = DAG.getVTList(ValueVTs);
8088 
8089   auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
8090 
8091   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8092   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8093          "Unexpected target EVL type");
8094 
8095   // Request operands.
8096   SmallVector<SDValue, 7> OpValues;
8097   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
8098     auto Op = getValue(VPIntrin.getArgOperand(I));
8099     if (I == EVLParamPos)
8100       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
8101     OpValues.push_back(Op);
8102   }
8103 
8104   switch (Opcode) {
8105   default: {
8106     SDNodeFlags SDFlags;
8107     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8108       SDFlags.copyFMF(*FPMO);
8109     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
8110     setValue(&VPIntrin, Result);
8111     break;
8112   }
8113   case ISD::VP_LOAD:
8114     visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
8115     break;
8116   case ISD::VP_GATHER:
8117     visitVPGather(VPIntrin, ValueVTs[0], OpValues);
8118     break;
8119   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
8120     visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
8121     break;
8122   case ISD::VP_STORE:
8123     visitVPStore(VPIntrin, OpValues);
8124     break;
8125   case ISD::VP_SCATTER:
8126     visitVPScatter(VPIntrin, OpValues);
8127     break;
8128   case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
8129     visitVPStridedStore(VPIntrin, OpValues);
8130     break;
8131   case ISD::VP_FMULADD: {
8132     assert(OpValues.size() == 5 && "Unexpected number of operands");
8133     SDNodeFlags SDFlags;
8134     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8135       SDFlags.copyFMF(*FPMO);
8136     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
8137         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) {
8138       setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags));
8139     } else {
8140       SDValue Mul = DAG.getNode(
8141           ISD::VP_FMUL, DL, VTs,
8142           {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags);
8143       SDValue Add =
8144           DAG.getNode(ISD::VP_FADD, DL, VTs,
8145                       {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags);
8146       setValue(&VPIntrin, Add);
8147     }
8148     break;
8149   }
8150   case ISD::VP_IS_FPCLASS: {
8151     const DataLayout DLayout = DAG.getDataLayout();
8152     EVT DestVT = TLI.getValueType(DLayout, VPIntrin.getType());
8153     auto Constant = OpValues[1]->getAsZExtVal();
8154     SDValue Check = DAG.getTargetConstant(Constant, DL, MVT::i32);
8155     SDValue V = DAG.getNode(ISD::VP_IS_FPCLASS, DL, DestVT,
8156                             {OpValues[0], Check, OpValues[2], OpValues[3]});
8157     setValue(&VPIntrin, V);
8158     return;
8159   }
8160   case ISD::VP_INTTOPTR: {
8161     SDValue N = OpValues[0];
8162     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType());
8163     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType());
8164     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8165                                OpValues[2]);
8166     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8167                              OpValues[2]);
8168     setValue(&VPIntrin, N);
8169     break;
8170   }
8171   case ISD::VP_PTRTOINT: {
8172     SDValue N = OpValues[0];
8173     EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8174                                                           VPIntrin.getType());
8175     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(),
8176                                        VPIntrin.getOperand(0)->getType());
8177     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8178                                OpValues[2]);
8179     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8180                              OpValues[2]);
8181     setValue(&VPIntrin, N);
8182     break;
8183   }
8184   case ISD::VP_ABS:
8185   case ISD::VP_CTLZ:
8186   case ISD::VP_CTLZ_ZERO_UNDEF:
8187   case ISD::VP_CTTZ:
8188   case ISD::VP_CTTZ_ZERO_UNDEF: {
8189     SDValue Result =
8190         DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]});
8191     setValue(&VPIntrin, Result);
8192     break;
8193   }
8194   }
8195 }
8196 
8197 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
8198                                           const BasicBlock *EHPadBB,
8199                                           MCSymbol *&BeginLabel) {
8200   MachineFunction &MF = DAG.getMachineFunction();
8201   MachineModuleInfo &MMI = MF.getMMI();
8202 
8203   // Insert a label before the invoke call to mark the try range.  This can be
8204   // used to detect deletion of the invoke via the MachineModuleInfo.
8205   BeginLabel = MMI.getContext().createTempSymbol();
8206 
8207   // For SjLj, keep track of which landing pads go with which invokes
8208   // so as to maintain the ordering of pads in the LSDA.
8209   unsigned CallSiteIndex = MMI.getCurrentCallSite();
8210   if (CallSiteIndex) {
8211     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
8212     LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
8213 
8214     // Now that the call site is handled, stop tracking it.
8215     MMI.setCurrentCallSite(0);
8216   }
8217 
8218   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
8219 }
8220 
8221 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
8222                                         const BasicBlock *EHPadBB,
8223                                         MCSymbol *BeginLabel) {
8224   assert(BeginLabel && "BeginLabel should've been set");
8225 
8226   MachineFunction &MF = DAG.getMachineFunction();
8227   MachineModuleInfo &MMI = MF.getMMI();
8228 
8229   // Insert a label at the end of the invoke call to mark the try range.  This
8230   // can be used to detect deletion of the invoke via the MachineModuleInfo.
8231   MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
8232   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
8233 
8234   // Inform MachineModuleInfo of range.
8235   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
8236   // There is a platform (e.g. wasm) that uses funclet style IR but does not
8237   // actually use outlined funclets and their LSDA info style.
8238   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
8239     assert(II && "II should've been set");
8240     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
8241     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
8242   } else if (!isScopedEHPersonality(Pers)) {
8243     assert(EHPadBB);
8244     MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
8245   }
8246 
8247   return Chain;
8248 }
8249 
8250 std::pair<SDValue, SDValue>
8251 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
8252                                     const BasicBlock *EHPadBB) {
8253   MCSymbol *BeginLabel = nullptr;
8254 
8255   if (EHPadBB) {
8256     // Both PendingLoads and PendingExports must be flushed here;
8257     // this call might not return.
8258     (void)getRoot();
8259     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
8260     CLI.setChain(getRoot());
8261   }
8262 
8263   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8264   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
8265 
8266   assert((CLI.IsTailCall || Result.second.getNode()) &&
8267          "Non-null chain expected with non-tail call!");
8268   assert((Result.second.getNode() || !Result.first.getNode()) &&
8269          "Null value expected with tail call!");
8270 
8271   if (!Result.second.getNode()) {
8272     // As a special case, a null chain means that a tail call has been emitted
8273     // and the DAG root is already updated.
8274     HasTailCall = true;
8275 
8276     // Since there's no actual continuation from this block, nothing can be
8277     // relying on us setting vregs for them.
8278     PendingExports.clear();
8279   } else {
8280     DAG.setRoot(Result.second);
8281   }
8282 
8283   if (EHPadBB) {
8284     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
8285                            BeginLabel));
8286   }
8287 
8288   return Result;
8289 }
8290 
8291 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
8292                                       bool isTailCall,
8293                                       bool isMustTailCall,
8294                                       const BasicBlock *EHPadBB) {
8295   auto &DL = DAG.getDataLayout();
8296   FunctionType *FTy = CB.getFunctionType();
8297   Type *RetTy = CB.getType();
8298 
8299   TargetLowering::ArgListTy Args;
8300   Args.reserve(CB.arg_size());
8301 
8302   const Value *SwiftErrorVal = nullptr;
8303   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8304 
8305   if (isTailCall) {
8306     // Avoid emitting tail calls in functions with the disable-tail-calls
8307     // attribute.
8308     auto *Caller = CB.getParent()->getParent();
8309     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
8310         "true" && !isMustTailCall)
8311       isTailCall = false;
8312 
8313     // We can't tail call inside a function with a swifterror argument. Lowering
8314     // does not support this yet. It would have to move into the swifterror
8315     // register before the call.
8316     if (TLI.supportSwiftError() &&
8317         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
8318       isTailCall = false;
8319   }
8320 
8321   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
8322     TargetLowering::ArgListEntry Entry;
8323     const Value *V = *I;
8324 
8325     // Skip empty types
8326     if (V->getType()->isEmptyTy())
8327       continue;
8328 
8329     SDValue ArgNode = getValue(V);
8330     Entry.Node = ArgNode; Entry.Ty = V->getType();
8331 
8332     Entry.setAttributes(&CB, I - CB.arg_begin());
8333 
8334     // Use swifterror virtual register as input to the call.
8335     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
8336       SwiftErrorVal = V;
8337       // We find the virtual register for the actual swifterror argument.
8338       // Instead of using the Value, we use the virtual register instead.
8339       Entry.Node =
8340           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
8341                           EVT(TLI.getPointerTy(DL)));
8342     }
8343 
8344     Args.push_back(Entry);
8345 
8346     // If we have an explicit sret argument that is an Instruction, (i.e., it
8347     // might point to function-local memory), we can't meaningfully tail-call.
8348     if (Entry.IsSRet && isa<Instruction>(V))
8349       isTailCall = false;
8350   }
8351 
8352   // If call site has a cfguardtarget operand bundle, create and add an
8353   // additional ArgListEntry.
8354   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
8355     TargetLowering::ArgListEntry Entry;
8356     Value *V = Bundle->Inputs[0];
8357     SDValue ArgNode = getValue(V);
8358     Entry.Node = ArgNode;
8359     Entry.Ty = V->getType();
8360     Entry.IsCFGuardTarget = true;
8361     Args.push_back(Entry);
8362   }
8363 
8364   // Check if target-independent constraints permit a tail call here.
8365   // Target-dependent constraints are checked within TLI->LowerCallTo.
8366   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
8367     isTailCall = false;
8368 
8369   // Disable tail calls if there is an swifterror argument. Targets have not
8370   // been updated to support tail calls.
8371   if (TLI.supportSwiftError() && SwiftErrorVal)
8372     isTailCall = false;
8373 
8374   ConstantInt *CFIType = nullptr;
8375   if (CB.isIndirectCall()) {
8376     if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
8377       if (!TLI.supportKCFIBundles())
8378         report_fatal_error(
8379             "Target doesn't support calls with kcfi operand bundles.");
8380       CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
8381       assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
8382     }
8383   }
8384 
8385   TargetLowering::CallLoweringInfo CLI(DAG);
8386   CLI.setDebugLoc(getCurSDLoc())
8387       .setChain(getRoot())
8388       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
8389       .setTailCall(isTailCall)
8390       .setConvergent(CB.isConvergent())
8391       .setIsPreallocated(
8392           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
8393       .setCFIType(CFIType);
8394   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8395 
8396   if (Result.first.getNode()) {
8397     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
8398     setValue(&CB, Result.first);
8399   }
8400 
8401   // The last element of CLI.InVals has the SDValue for swifterror return.
8402   // Here we copy it to a virtual register and update SwiftErrorMap for
8403   // book-keeping.
8404   if (SwiftErrorVal && TLI.supportSwiftError()) {
8405     // Get the last element of InVals.
8406     SDValue Src = CLI.InVals.back();
8407     Register VReg =
8408         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
8409     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
8410     DAG.setRoot(CopyNode);
8411   }
8412 }
8413 
8414 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
8415                              SelectionDAGBuilder &Builder) {
8416   // Check to see if this load can be trivially constant folded, e.g. if the
8417   // input is from a string literal.
8418   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
8419     // Cast pointer to the type we really want to load.
8420     Type *LoadTy =
8421         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
8422     if (LoadVT.isVector())
8423       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
8424 
8425     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
8426                                          PointerType::getUnqual(LoadTy));
8427 
8428     if (const Constant *LoadCst =
8429             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
8430                                          LoadTy, Builder.DAG.getDataLayout()))
8431       return Builder.getValue(LoadCst);
8432   }
8433 
8434   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
8435   // still constant memory, the input chain can be the entry node.
8436   SDValue Root;
8437   bool ConstantMemory = false;
8438 
8439   // Do not serialize (non-volatile) loads of constant memory with anything.
8440   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
8441     Root = Builder.DAG.getEntryNode();
8442     ConstantMemory = true;
8443   } else {
8444     // Do not serialize non-volatile loads against each other.
8445     Root = Builder.DAG.getRoot();
8446   }
8447 
8448   SDValue Ptr = Builder.getValue(PtrVal);
8449   SDValue LoadVal =
8450       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
8451                           MachinePointerInfo(PtrVal), Align(1));
8452 
8453   if (!ConstantMemory)
8454     Builder.PendingLoads.push_back(LoadVal.getValue(1));
8455   return LoadVal;
8456 }
8457 
8458 /// Record the value for an instruction that produces an integer result,
8459 /// converting the type where necessary.
8460 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
8461                                                   SDValue Value,
8462                                                   bool IsSigned) {
8463   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8464                                                     I.getType(), true);
8465   Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT);
8466   setValue(&I, Value);
8467 }
8468 
8469 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
8470 /// true and lower it. Otherwise return false, and it will be lowered like a
8471 /// normal call.
8472 /// The caller already checked that \p I calls the appropriate LibFunc with a
8473 /// correct prototype.
8474 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
8475   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
8476   const Value *Size = I.getArgOperand(2);
8477   const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
8478   if (CSize && CSize->getZExtValue() == 0) {
8479     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8480                                                           I.getType(), true);
8481     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
8482     return true;
8483   }
8484 
8485   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8486   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
8487       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
8488       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
8489   if (Res.first.getNode()) {
8490     processIntegerCallValue(I, Res.first, true);
8491     PendingLoads.push_back(Res.second);
8492     return true;
8493   }
8494 
8495   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
8496   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
8497   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
8498     return false;
8499 
8500   // If the target has a fast compare for the given size, it will return a
8501   // preferred load type for that size. Require that the load VT is legal and
8502   // that the target supports unaligned loads of that type. Otherwise, return
8503   // INVALID.
8504   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
8505     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8506     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
8507     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
8508       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
8509       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
8510       // TODO: Check alignment of src and dest ptrs.
8511       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
8512       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
8513       if (!TLI.isTypeLegal(LVT) ||
8514           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
8515           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
8516         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
8517     }
8518 
8519     return LVT;
8520   };
8521 
8522   // This turns into unaligned loads. We only do this if the target natively
8523   // supports the MVT we'll be loading or if it is small enough (<= 4) that
8524   // we'll only produce a small number of byte loads.
8525   MVT LoadVT;
8526   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
8527   switch (NumBitsToCompare) {
8528   default:
8529     return false;
8530   case 16:
8531     LoadVT = MVT::i16;
8532     break;
8533   case 32:
8534     LoadVT = MVT::i32;
8535     break;
8536   case 64:
8537   case 128:
8538   case 256:
8539     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
8540     break;
8541   }
8542 
8543   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
8544     return false;
8545 
8546   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
8547   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
8548 
8549   // Bitcast to a wide integer type if the loads are vectors.
8550   if (LoadVT.isVector()) {
8551     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
8552     LoadL = DAG.getBitcast(CmpVT, LoadL);
8553     LoadR = DAG.getBitcast(CmpVT, LoadR);
8554   }
8555 
8556   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
8557   processIntegerCallValue(I, Cmp, false);
8558   return true;
8559 }
8560 
8561 /// See if we can lower a memchr call into an optimized form. If so, return
8562 /// true and lower it. Otherwise return false, and it will be lowered like a
8563 /// normal call.
8564 /// The caller already checked that \p I calls the appropriate LibFunc with a
8565 /// correct prototype.
8566 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
8567   const Value *Src = I.getArgOperand(0);
8568   const Value *Char = I.getArgOperand(1);
8569   const Value *Length = I.getArgOperand(2);
8570 
8571   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8572   std::pair<SDValue, SDValue> Res =
8573     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
8574                                 getValue(Src), getValue(Char), getValue(Length),
8575                                 MachinePointerInfo(Src));
8576   if (Res.first.getNode()) {
8577     setValue(&I, Res.first);
8578     PendingLoads.push_back(Res.second);
8579     return true;
8580   }
8581 
8582   return false;
8583 }
8584 
8585 /// See if we can lower a mempcpy call into an optimized form. If so, return
8586 /// true and lower it. Otherwise return false, and it will be lowered like a
8587 /// normal call.
8588 /// The caller already checked that \p I calls the appropriate LibFunc with a
8589 /// correct prototype.
8590 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
8591   SDValue Dst = getValue(I.getArgOperand(0));
8592   SDValue Src = getValue(I.getArgOperand(1));
8593   SDValue Size = getValue(I.getArgOperand(2));
8594 
8595   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
8596   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
8597   // DAG::getMemcpy needs Alignment to be defined.
8598   Align Alignment = std::min(DstAlign, SrcAlign);
8599 
8600   SDLoc sdl = getCurSDLoc();
8601 
8602   // In the mempcpy context we need to pass in a false value for isTailCall
8603   // because the return pointer needs to be adjusted by the size of
8604   // the copied memory.
8605   SDValue Root = getMemoryRoot();
8606   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, false, false,
8607                              /*isTailCall=*/false,
8608                              MachinePointerInfo(I.getArgOperand(0)),
8609                              MachinePointerInfo(I.getArgOperand(1)),
8610                              I.getAAMetadata());
8611   assert(MC.getNode() != nullptr &&
8612          "** memcpy should not be lowered as TailCall in mempcpy context **");
8613   DAG.setRoot(MC);
8614 
8615   // Check if Size needs to be truncated or extended.
8616   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
8617 
8618   // Adjust return pointer to point just past the last dst byte.
8619   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
8620                                     Dst, Size);
8621   setValue(&I, DstPlusSize);
8622   return true;
8623 }
8624 
8625 /// See if we can lower a strcpy call into an optimized form.  If so, return
8626 /// true and lower it, otherwise return false and it will be lowered like a
8627 /// normal call.
8628 /// The caller already checked that \p I calls the appropriate LibFunc with a
8629 /// correct prototype.
8630 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
8631   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8632 
8633   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8634   std::pair<SDValue, SDValue> Res =
8635     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
8636                                 getValue(Arg0), getValue(Arg1),
8637                                 MachinePointerInfo(Arg0),
8638                                 MachinePointerInfo(Arg1), isStpcpy);
8639   if (Res.first.getNode()) {
8640     setValue(&I, Res.first);
8641     DAG.setRoot(Res.second);
8642     return true;
8643   }
8644 
8645   return false;
8646 }
8647 
8648 /// See if we can lower a strcmp call into an optimized form.  If so, return
8649 /// true and lower it, otherwise return false and it will be lowered like a
8650 /// normal call.
8651 /// The caller already checked that \p I calls the appropriate LibFunc with a
8652 /// correct prototype.
8653 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
8654   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8655 
8656   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8657   std::pair<SDValue, SDValue> Res =
8658     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
8659                                 getValue(Arg0), getValue(Arg1),
8660                                 MachinePointerInfo(Arg0),
8661                                 MachinePointerInfo(Arg1));
8662   if (Res.first.getNode()) {
8663     processIntegerCallValue(I, Res.first, true);
8664     PendingLoads.push_back(Res.second);
8665     return true;
8666   }
8667 
8668   return false;
8669 }
8670 
8671 /// See if we can lower a strlen call into an optimized form.  If so, return
8672 /// true and lower it, otherwise return false and it will be lowered like a
8673 /// normal call.
8674 /// The caller already checked that \p I calls the appropriate LibFunc with a
8675 /// correct prototype.
8676 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
8677   const Value *Arg0 = I.getArgOperand(0);
8678 
8679   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8680   std::pair<SDValue, SDValue> Res =
8681     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
8682                                 getValue(Arg0), MachinePointerInfo(Arg0));
8683   if (Res.first.getNode()) {
8684     processIntegerCallValue(I, Res.first, false);
8685     PendingLoads.push_back(Res.second);
8686     return true;
8687   }
8688 
8689   return false;
8690 }
8691 
8692 /// See if we can lower a strnlen call into an optimized form.  If so, return
8693 /// true and lower it, otherwise return false and it will be lowered like a
8694 /// normal call.
8695 /// The caller already checked that \p I calls the appropriate LibFunc with a
8696 /// correct prototype.
8697 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
8698   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8699 
8700   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8701   std::pair<SDValue, SDValue> Res =
8702     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
8703                                  getValue(Arg0), getValue(Arg1),
8704                                  MachinePointerInfo(Arg0));
8705   if (Res.first.getNode()) {
8706     processIntegerCallValue(I, Res.first, false);
8707     PendingLoads.push_back(Res.second);
8708     return true;
8709   }
8710 
8711   return false;
8712 }
8713 
8714 /// See if we can lower a unary floating-point operation into an SDNode with
8715 /// the specified Opcode.  If so, return true and lower it, otherwise return
8716 /// false and it will be lowered like a normal call.
8717 /// The caller already checked that \p I calls the appropriate LibFunc with a
8718 /// correct prototype.
8719 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
8720                                               unsigned Opcode) {
8721   // We already checked this call's prototype; verify it doesn't modify errno.
8722   if (!I.onlyReadsMemory())
8723     return false;
8724 
8725   SDNodeFlags Flags;
8726   Flags.copyFMF(cast<FPMathOperator>(I));
8727 
8728   SDValue Tmp = getValue(I.getArgOperand(0));
8729   setValue(&I,
8730            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
8731   return true;
8732 }
8733 
8734 /// See if we can lower a binary floating-point operation into an SDNode with
8735 /// the specified Opcode. If so, return true and lower it. Otherwise return
8736 /// false, and it will be lowered like a normal call.
8737 /// The caller already checked that \p I calls the appropriate LibFunc with a
8738 /// correct prototype.
8739 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
8740                                                unsigned Opcode) {
8741   // We already checked this call's prototype; verify it doesn't modify errno.
8742   if (!I.onlyReadsMemory())
8743     return false;
8744 
8745   SDNodeFlags Flags;
8746   Flags.copyFMF(cast<FPMathOperator>(I));
8747 
8748   SDValue Tmp0 = getValue(I.getArgOperand(0));
8749   SDValue Tmp1 = getValue(I.getArgOperand(1));
8750   EVT VT = Tmp0.getValueType();
8751   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
8752   return true;
8753 }
8754 
8755 void SelectionDAGBuilder::visitCall(const CallInst &I) {
8756   // Handle inline assembly differently.
8757   if (I.isInlineAsm()) {
8758     visitInlineAsm(I);
8759     return;
8760   }
8761 
8762   diagnoseDontCall(I);
8763 
8764   if (Function *F = I.getCalledFunction()) {
8765     if (F->isDeclaration()) {
8766       // Is this an LLVM intrinsic or a target-specific intrinsic?
8767       unsigned IID = F->getIntrinsicID();
8768       if (!IID)
8769         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
8770           IID = II->getIntrinsicID(F);
8771 
8772       if (IID) {
8773         visitIntrinsicCall(I, IID);
8774         return;
8775       }
8776     }
8777 
8778     // Check for well-known libc/libm calls.  If the function is internal, it
8779     // can't be a library call.  Don't do the check if marked as nobuiltin for
8780     // some reason or the call site requires strict floating point semantics.
8781     LibFunc Func;
8782     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
8783         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
8784         LibInfo->hasOptimizedCodeGen(Func)) {
8785       switch (Func) {
8786       default: break;
8787       case LibFunc_bcmp:
8788         if (visitMemCmpBCmpCall(I))
8789           return;
8790         break;
8791       case LibFunc_copysign:
8792       case LibFunc_copysignf:
8793       case LibFunc_copysignl:
8794         // We already checked this call's prototype; verify it doesn't modify
8795         // errno.
8796         if (I.onlyReadsMemory()) {
8797           SDValue LHS = getValue(I.getArgOperand(0));
8798           SDValue RHS = getValue(I.getArgOperand(1));
8799           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
8800                                    LHS.getValueType(), LHS, RHS));
8801           return;
8802         }
8803         break;
8804       case LibFunc_fabs:
8805       case LibFunc_fabsf:
8806       case LibFunc_fabsl:
8807         if (visitUnaryFloatCall(I, ISD::FABS))
8808           return;
8809         break;
8810       case LibFunc_fmin:
8811       case LibFunc_fminf:
8812       case LibFunc_fminl:
8813         if (visitBinaryFloatCall(I, ISD::FMINNUM))
8814           return;
8815         break;
8816       case LibFunc_fmax:
8817       case LibFunc_fmaxf:
8818       case LibFunc_fmaxl:
8819         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
8820           return;
8821         break;
8822       case LibFunc_sin:
8823       case LibFunc_sinf:
8824       case LibFunc_sinl:
8825         if (visitUnaryFloatCall(I, ISD::FSIN))
8826           return;
8827         break;
8828       case LibFunc_cos:
8829       case LibFunc_cosf:
8830       case LibFunc_cosl:
8831         if (visitUnaryFloatCall(I, ISD::FCOS))
8832           return;
8833         break;
8834       case LibFunc_sqrt:
8835       case LibFunc_sqrtf:
8836       case LibFunc_sqrtl:
8837       case LibFunc_sqrt_finite:
8838       case LibFunc_sqrtf_finite:
8839       case LibFunc_sqrtl_finite:
8840         if (visitUnaryFloatCall(I, ISD::FSQRT))
8841           return;
8842         break;
8843       case LibFunc_floor:
8844       case LibFunc_floorf:
8845       case LibFunc_floorl:
8846         if (visitUnaryFloatCall(I, ISD::FFLOOR))
8847           return;
8848         break;
8849       case LibFunc_nearbyint:
8850       case LibFunc_nearbyintf:
8851       case LibFunc_nearbyintl:
8852         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
8853           return;
8854         break;
8855       case LibFunc_ceil:
8856       case LibFunc_ceilf:
8857       case LibFunc_ceill:
8858         if (visitUnaryFloatCall(I, ISD::FCEIL))
8859           return;
8860         break;
8861       case LibFunc_rint:
8862       case LibFunc_rintf:
8863       case LibFunc_rintl:
8864         if (visitUnaryFloatCall(I, ISD::FRINT))
8865           return;
8866         break;
8867       case LibFunc_round:
8868       case LibFunc_roundf:
8869       case LibFunc_roundl:
8870         if (visitUnaryFloatCall(I, ISD::FROUND))
8871           return;
8872         break;
8873       case LibFunc_trunc:
8874       case LibFunc_truncf:
8875       case LibFunc_truncl:
8876         if (visitUnaryFloatCall(I, ISD::FTRUNC))
8877           return;
8878         break;
8879       case LibFunc_log2:
8880       case LibFunc_log2f:
8881       case LibFunc_log2l:
8882         if (visitUnaryFloatCall(I, ISD::FLOG2))
8883           return;
8884         break;
8885       case LibFunc_exp2:
8886       case LibFunc_exp2f:
8887       case LibFunc_exp2l:
8888         if (visitUnaryFloatCall(I, ISD::FEXP2))
8889           return;
8890         break;
8891       case LibFunc_exp10:
8892       case LibFunc_exp10f:
8893       case LibFunc_exp10l:
8894         if (visitUnaryFloatCall(I, ISD::FEXP10))
8895           return;
8896         break;
8897       case LibFunc_ldexp:
8898       case LibFunc_ldexpf:
8899       case LibFunc_ldexpl:
8900         if (visitBinaryFloatCall(I, ISD::FLDEXP))
8901           return;
8902         break;
8903       case LibFunc_memcmp:
8904         if (visitMemCmpBCmpCall(I))
8905           return;
8906         break;
8907       case LibFunc_mempcpy:
8908         if (visitMemPCpyCall(I))
8909           return;
8910         break;
8911       case LibFunc_memchr:
8912         if (visitMemChrCall(I))
8913           return;
8914         break;
8915       case LibFunc_strcpy:
8916         if (visitStrCpyCall(I, false))
8917           return;
8918         break;
8919       case LibFunc_stpcpy:
8920         if (visitStrCpyCall(I, true))
8921           return;
8922         break;
8923       case LibFunc_strcmp:
8924         if (visitStrCmpCall(I))
8925           return;
8926         break;
8927       case LibFunc_strlen:
8928         if (visitStrLenCall(I))
8929           return;
8930         break;
8931       case LibFunc_strnlen:
8932         if (visitStrNLenCall(I))
8933           return;
8934         break;
8935       }
8936     }
8937   }
8938 
8939   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
8940   // have to do anything here to lower funclet bundles.
8941   // CFGuardTarget bundles are lowered in LowerCallTo.
8942   assert(!I.hasOperandBundlesOtherThan(
8943              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
8944               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
8945               LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) &&
8946          "Cannot lower calls with arbitrary operand bundles!");
8947 
8948   SDValue Callee = getValue(I.getCalledOperand());
8949 
8950   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
8951     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
8952   else
8953     // Check if we can potentially perform a tail call. More detailed checking
8954     // is be done within LowerCallTo, after more information about the call is
8955     // known.
8956     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
8957 }
8958 
8959 namespace {
8960 
8961 /// AsmOperandInfo - This contains information for each constraint that we are
8962 /// lowering.
8963 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
8964 public:
8965   /// CallOperand - If this is the result output operand or a clobber
8966   /// this is null, otherwise it is the incoming operand to the CallInst.
8967   /// This gets modified as the asm is processed.
8968   SDValue CallOperand;
8969 
8970   /// AssignedRegs - If this is a register or register class operand, this
8971   /// contains the set of register corresponding to the operand.
8972   RegsForValue AssignedRegs;
8973 
8974   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
8975     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
8976   }
8977 
8978   /// Whether or not this operand accesses memory
8979   bool hasMemory(const TargetLowering &TLI) const {
8980     // Indirect operand accesses access memory.
8981     if (isIndirect)
8982       return true;
8983 
8984     for (const auto &Code : Codes)
8985       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
8986         return true;
8987 
8988     return false;
8989   }
8990 };
8991 
8992 
8993 } // end anonymous namespace
8994 
8995 /// Make sure that the output operand \p OpInfo and its corresponding input
8996 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
8997 /// out).
8998 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
8999                                SDISelAsmOperandInfo &MatchingOpInfo,
9000                                SelectionDAG &DAG) {
9001   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
9002     return;
9003 
9004   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
9005   const auto &TLI = DAG.getTargetLoweringInfo();
9006 
9007   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
9008       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
9009                                        OpInfo.ConstraintVT);
9010   std::pair<unsigned, const TargetRegisterClass *> InputRC =
9011       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
9012                                        MatchingOpInfo.ConstraintVT);
9013   if ((OpInfo.ConstraintVT.isInteger() !=
9014        MatchingOpInfo.ConstraintVT.isInteger()) ||
9015       (MatchRC.second != InputRC.second)) {
9016     // FIXME: error out in a more elegant fashion
9017     report_fatal_error("Unsupported asm: input constraint"
9018                        " with a matching output constraint of"
9019                        " incompatible type!");
9020   }
9021   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
9022 }
9023 
9024 /// Get a direct memory input to behave well as an indirect operand.
9025 /// This may introduce stores, hence the need for a \p Chain.
9026 /// \return The (possibly updated) chain.
9027 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
9028                                         SDISelAsmOperandInfo &OpInfo,
9029                                         SelectionDAG &DAG) {
9030   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9031 
9032   // If we don't have an indirect input, put it in the constpool if we can,
9033   // otherwise spill it to a stack slot.
9034   // TODO: This isn't quite right. We need to handle these according to
9035   // the addressing mode that the constraint wants. Also, this may take
9036   // an additional register for the computation and we don't want that
9037   // either.
9038 
9039   // If the operand is a float, integer, or vector constant, spill to a
9040   // constant pool entry to get its address.
9041   const Value *OpVal = OpInfo.CallOperandVal;
9042   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
9043       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
9044     OpInfo.CallOperand = DAG.getConstantPool(
9045         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
9046     return Chain;
9047   }
9048 
9049   // Otherwise, create a stack slot and emit a store to it before the asm.
9050   Type *Ty = OpVal->getType();
9051   auto &DL = DAG.getDataLayout();
9052   uint64_t TySize = DL.getTypeAllocSize(Ty);
9053   MachineFunction &MF = DAG.getMachineFunction();
9054   int SSFI = MF.getFrameInfo().CreateStackObject(
9055       TySize, DL.getPrefTypeAlign(Ty), false);
9056   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
9057   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
9058                             MachinePointerInfo::getFixedStack(MF, SSFI),
9059                             TLI.getMemValueType(DL, Ty));
9060   OpInfo.CallOperand = StackSlot;
9061 
9062   return Chain;
9063 }
9064 
9065 /// GetRegistersForValue - Assign registers (virtual or physical) for the
9066 /// specified operand.  We prefer to assign virtual registers, to allow the
9067 /// register allocator to handle the assignment process.  However, if the asm
9068 /// uses features that we can't model on machineinstrs, we have SDISel do the
9069 /// allocation.  This produces generally horrible, but correct, code.
9070 ///
9071 ///   OpInfo describes the operand
9072 ///   RefOpInfo describes the matching operand if any, the operand otherwise
9073 static std::optional<unsigned>
9074 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
9075                      SDISelAsmOperandInfo &OpInfo,
9076                      SDISelAsmOperandInfo &RefOpInfo) {
9077   LLVMContext &Context = *DAG.getContext();
9078   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9079 
9080   MachineFunction &MF = DAG.getMachineFunction();
9081   SmallVector<unsigned, 4> Regs;
9082   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9083 
9084   // No work to do for memory/address operands.
9085   if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9086       OpInfo.ConstraintType == TargetLowering::C_Address)
9087     return std::nullopt;
9088 
9089   // If this is a constraint for a single physreg, or a constraint for a
9090   // register class, find it.
9091   unsigned AssignedReg;
9092   const TargetRegisterClass *RC;
9093   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
9094       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
9095   // RC is unset only on failure. Return immediately.
9096   if (!RC)
9097     return std::nullopt;
9098 
9099   // Get the actual register value type.  This is important, because the user
9100   // may have asked for (e.g.) the AX register in i32 type.  We need to
9101   // remember that AX is actually i16 to get the right extension.
9102   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
9103 
9104   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
9105     // If this is an FP operand in an integer register (or visa versa), or more
9106     // generally if the operand value disagrees with the register class we plan
9107     // to stick it in, fix the operand type.
9108     //
9109     // If this is an input value, the bitcast to the new type is done now.
9110     // Bitcast for output value is done at the end of visitInlineAsm().
9111     if ((OpInfo.Type == InlineAsm::isOutput ||
9112          OpInfo.Type == InlineAsm::isInput) &&
9113         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
9114       // Try to convert to the first EVT that the reg class contains.  If the
9115       // types are identical size, use a bitcast to convert (e.g. two differing
9116       // vector types).  Note: output bitcast is done at the end of
9117       // visitInlineAsm().
9118       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
9119         // Exclude indirect inputs while they are unsupported because the code
9120         // to perform the load is missing and thus OpInfo.CallOperand still
9121         // refers to the input address rather than the pointed-to value.
9122         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
9123           OpInfo.CallOperand =
9124               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
9125         OpInfo.ConstraintVT = RegVT;
9126         // If the operand is an FP value and we want it in integer registers,
9127         // use the corresponding integer type. This turns an f64 value into
9128         // i64, which can be passed with two i32 values on a 32-bit machine.
9129       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
9130         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
9131         if (OpInfo.Type == InlineAsm::isInput)
9132           OpInfo.CallOperand =
9133               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
9134         OpInfo.ConstraintVT = VT;
9135       }
9136     }
9137   }
9138 
9139   // No need to allocate a matching input constraint since the constraint it's
9140   // matching to has already been allocated.
9141   if (OpInfo.isMatchingInputConstraint())
9142     return std::nullopt;
9143 
9144   EVT ValueVT = OpInfo.ConstraintVT;
9145   if (OpInfo.ConstraintVT == MVT::Other)
9146     ValueVT = RegVT;
9147 
9148   // Initialize NumRegs.
9149   unsigned NumRegs = 1;
9150   if (OpInfo.ConstraintVT != MVT::Other)
9151     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
9152 
9153   // If this is a constraint for a specific physical register, like {r17},
9154   // assign it now.
9155 
9156   // If this associated to a specific register, initialize iterator to correct
9157   // place. If virtual, make sure we have enough registers
9158 
9159   // Initialize iterator if necessary
9160   TargetRegisterClass::iterator I = RC->begin();
9161   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9162 
9163   // Do not check for single registers.
9164   if (AssignedReg) {
9165     I = std::find(I, RC->end(), AssignedReg);
9166     if (I == RC->end()) {
9167       // RC does not contain the selected register, which indicates a
9168       // mismatch between the register and the required type/bitwidth.
9169       return {AssignedReg};
9170     }
9171   }
9172 
9173   for (; NumRegs; --NumRegs, ++I) {
9174     assert(I != RC->end() && "Ran out of registers to allocate!");
9175     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
9176     Regs.push_back(R);
9177   }
9178 
9179   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
9180   return std::nullopt;
9181 }
9182 
9183 static unsigned
9184 findMatchingInlineAsmOperand(unsigned OperandNo,
9185                              const std::vector<SDValue> &AsmNodeOperands) {
9186   // Scan until we find the definition we already emitted of this operand.
9187   unsigned CurOp = InlineAsm::Op_FirstOperand;
9188   for (; OperandNo; --OperandNo) {
9189     // Advance to the next operand.
9190     unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal();
9191     const InlineAsm::Flag F(OpFlag);
9192     assert(
9193         (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) &&
9194         "Skipped past definitions?");
9195     CurOp += F.getNumOperandRegisters() + 1;
9196   }
9197   return CurOp;
9198 }
9199 
9200 namespace {
9201 
9202 class ExtraFlags {
9203   unsigned Flags = 0;
9204 
9205 public:
9206   explicit ExtraFlags(const CallBase &Call) {
9207     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9208     if (IA->hasSideEffects())
9209       Flags |= InlineAsm::Extra_HasSideEffects;
9210     if (IA->isAlignStack())
9211       Flags |= InlineAsm::Extra_IsAlignStack;
9212     if (Call.isConvergent())
9213       Flags |= InlineAsm::Extra_IsConvergent;
9214     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
9215   }
9216 
9217   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
9218     // Ideally, we would only check against memory constraints.  However, the
9219     // meaning of an Other constraint can be target-specific and we can't easily
9220     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
9221     // for Other constraints as well.
9222     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9223         OpInfo.ConstraintType == TargetLowering::C_Other) {
9224       if (OpInfo.Type == InlineAsm::isInput)
9225         Flags |= InlineAsm::Extra_MayLoad;
9226       else if (OpInfo.Type == InlineAsm::isOutput)
9227         Flags |= InlineAsm::Extra_MayStore;
9228       else if (OpInfo.Type == InlineAsm::isClobber)
9229         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
9230     }
9231   }
9232 
9233   unsigned get() const { return Flags; }
9234 };
9235 
9236 } // end anonymous namespace
9237 
9238 static bool isFunction(SDValue Op) {
9239   if (Op && Op.getOpcode() == ISD::GlobalAddress) {
9240     if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
9241       auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
9242 
9243       // In normal "call dllimport func" instruction (non-inlineasm) it force
9244       // indirect access by specifing call opcode. And usually specially print
9245       // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
9246       // not do in this way now. (In fact, this is similar with "Data Access"
9247       // action). So here we ignore dllimport function.
9248       if (Fn && !Fn->hasDLLImportStorageClass())
9249         return true;
9250     }
9251   }
9252   return false;
9253 }
9254 
9255 /// visitInlineAsm - Handle a call to an InlineAsm object.
9256 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
9257                                          const BasicBlock *EHPadBB) {
9258   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9259 
9260   /// ConstraintOperands - Information about all of the constraints.
9261   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
9262 
9263   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9264   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
9265       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
9266 
9267   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
9268   // AsmDialect, MayLoad, MayStore).
9269   bool HasSideEffect = IA->hasSideEffects();
9270   ExtraFlags ExtraInfo(Call);
9271 
9272   for (auto &T : TargetConstraints) {
9273     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
9274     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
9275 
9276     if (OpInfo.CallOperandVal)
9277       OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
9278 
9279     if (!HasSideEffect)
9280       HasSideEffect = OpInfo.hasMemory(TLI);
9281 
9282     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
9283     // FIXME: Could we compute this on OpInfo rather than T?
9284 
9285     // Compute the constraint code and ConstraintType to use.
9286     TLI.ComputeConstraintToUse(T, SDValue());
9287 
9288     if (T.ConstraintType == TargetLowering::C_Immediate &&
9289         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
9290       // We've delayed emitting a diagnostic like the "n" constraint because
9291       // inlining could cause an integer showing up.
9292       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
9293                                           "' expects an integer constant "
9294                                           "expression");
9295 
9296     ExtraInfo.update(T);
9297   }
9298 
9299   // We won't need to flush pending loads if this asm doesn't touch
9300   // memory and is nonvolatile.
9301   SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
9302 
9303   bool EmitEHLabels = isa<InvokeInst>(Call);
9304   if (EmitEHLabels) {
9305     assert(EHPadBB && "InvokeInst must have an EHPadBB");
9306   }
9307   bool IsCallBr = isa<CallBrInst>(Call);
9308 
9309   if (IsCallBr || EmitEHLabels) {
9310     // If this is a callbr or invoke we need to flush pending exports since
9311     // inlineasm_br and invoke are terminators.
9312     // We need to do this before nodes are glued to the inlineasm_br node.
9313     Chain = getControlRoot();
9314   }
9315 
9316   MCSymbol *BeginLabel = nullptr;
9317   if (EmitEHLabels) {
9318     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
9319   }
9320 
9321   int OpNo = -1;
9322   SmallVector<StringRef> AsmStrs;
9323   IA->collectAsmStrs(AsmStrs);
9324 
9325   // Second pass over the constraints: compute which constraint option to use.
9326   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9327     if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
9328       OpNo++;
9329 
9330     // If this is an output operand with a matching input operand, look up the
9331     // matching input. If their types mismatch, e.g. one is an integer, the
9332     // other is floating point, or their sizes are different, flag it as an
9333     // error.
9334     if (OpInfo.hasMatchingInput()) {
9335       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
9336       patchMatchingInput(OpInfo, Input, DAG);
9337     }
9338 
9339     // Compute the constraint code and ConstraintType to use.
9340     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
9341 
9342     if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
9343          OpInfo.Type == InlineAsm::isClobber) ||
9344         OpInfo.ConstraintType == TargetLowering::C_Address)
9345       continue;
9346 
9347     // In Linux PIC model, there are 4 cases about value/label addressing:
9348     //
9349     // 1: Function call or Label jmp inside the module.
9350     // 2: Data access (such as global variable, static variable) inside module.
9351     // 3: Function call or Label jmp outside the module.
9352     // 4: Data access (such as global variable) outside the module.
9353     //
9354     // Due to current llvm inline asm architecture designed to not "recognize"
9355     // the asm code, there are quite troubles for us to treat mem addressing
9356     // differently for same value/adress used in different instuctions.
9357     // For example, in pic model, call a func may in plt way or direclty
9358     // pc-related, but lea/mov a function adress may use got.
9359     //
9360     // Here we try to "recognize" function call for the case 1 and case 3 in
9361     // inline asm. And try to adjust the constraint for them.
9362     //
9363     // TODO: Due to current inline asm didn't encourage to jmp to the outsider
9364     // label, so here we don't handle jmp function label now, but we need to
9365     // enhance it (especilly in PIC model) if we meet meaningful requirements.
9366     if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
9367         TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
9368         TM.getCodeModel() != CodeModel::Large) {
9369       OpInfo.isIndirect = false;
9370       OpInfo.ConstraintType = TargetLowering::C_Address;
9371     }
9372 
9373     // If this is a memory input, and if the operand is not indirect, do what we
9374     // need to provide an address for the memory input.
9375     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
9376         !OpInfo.isIndirect) {
9377       assert((OpInfo.isMultipleAlternative ||
9378               (OpInfo.Type == InlineAsm::isInput)) &&
9379              "Can only indirectify direct input operands!");
9380 
9381       // Memory operands really want the address of the value.
9382       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
9383 
9384       // There is no longer a Value* corresponding to this operand.
9385       OpInfo.CallOperandVal = nullptr;
9386 
9387       // It is now an indirect operand.
9388       OpInfo.isIndirect = true;
9389     }
9390 
9391   }
9392 
9393   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
9394   std::vector<SDValue> AsmNodeOperands;
9395   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
9396   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
9397       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
9398 
9399   // If we have a !srcloc metadata node associated with it, we want to attach
9400   // this to the ultimately generated inline asm machineinstr.  To do this, we
9401   // pass in the third operand as this (potentially null) inline asm MDNode.
9402   const MDNode *SrcLoc = Call.getMetadata("srcloc");
9403   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
9404 
9405   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
9406   // bits as operand 3.
9407   AsmNodeOperands.push_back(DAG.getTargetConstant(
9408       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9409 
9410   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
9411   // this, assign virtual and physical registers for inputs and otput.
9412   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9413     // Assign Registers.
9414     SDISelAsmOperandInfo &RefOpInfo =
9415         OpInfo.isMatchingInputConstraint()
9416             ? ConstraintOperands[OpInfo.getMatchedOperand()]
9417             : OpInfo;
9418     const auto RegError =
9419         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
9420     if (RegError) {
9421       const MachineFunction &MF = DAG.getMachineFunction();
9422       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9423       const char *RegName = TRI.getName(*RegError);
9424       emitInlineAsmError(Call, "register '" + Twine(RegName) +
9425                                    "' allocated for constraint '" +
9426                                    Twine(OpInfo.ConstraintCode) +
9427                                    "' does not match required type");
9428       return;
9429     }
9430 
9431     auto DetectWriteToReservedRegister = [&]() {
9432       const MachineFunction &MF = DAG.getMachineFunction();
9433       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9434       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
9435         if (Register::isPhysicalRegister(Reg) &&
9436             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
9437           const char *RegName = TRI.getName(Reg);
9438           emitInlineAsmError(Call, "write to reserved register '" +
9439                                        Twine(RegName) + "'");
9440           return true;
9441         }
9442       }
9443       return false;
9444     };
9445     assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
9446             (OpInfo.Type == InlineAsm::isInput &&
9447              !OpInfo.isMatchingInputConstraint())) &&
9448            "Only address as input operand is allowed.");
9449 
9450     switch (OpInfo.Type) {
9451     case InlineAsm::isOutput:
9452       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
9453         const InlineAsm::ConstraintCode ConstraintID =
9454             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9455         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
9456                "Failed to convert memory constraint code to constraint id.");
9457 
9458         // Add information to the INLINEASM node to know about this output.
9459         InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1);
9460         OpFlags.setMemConstraint(ConstraintID);
9461         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
9462                                                         MVT::i32));
9463         AsmNodeOperands.push_back(OpInfo.CallOperand);
9464       } else {
9465         // Otherwise, this outputs to a register (directly for C_Register /
9466         // C_RegisterClass, and a target-defined fashion for
9467         // C_Immediate/C_Other). Find a register that we can use.
9468         if (OpInfo.AssignedRegs.Regs.empty()) {
9469           emitInlineAsmError(
9470               Call, "couldn't allocate output register for constraint '" +
9471                         Twine(OpInfo.ConstraintCode) + "'");
9472           return;
9473         }
9474 
9475         if (DetectWriteToReservedRegister())
9476           return;
9477 
9478         // Add information to the INLINEASM node to know that this register is
9479         // set.
9480         OpInfo.AssignedRegs.AddInlineAsmOperands(
9481             OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber
9482                                   : InlineAsm::Kind::RegDef,
9483             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
9484       }
9485       break;
9486 
9487     case InlineAsm::isInput:
9488     case InlineAsm::isLabel: {
9489       SDValue InOperandVal = OpInfo.CallOperand;
9490 
9491       if (OpInfo.isMatchingInputConstraint()) {
9492         // If this is required to match an output register we have already set,
9493         // just use its register.
9494         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
9495                                                   AsmNodeOperands);
9496         InlineAsm::Flag Flag(AsmNodeOperands[CurOp]->getAsZExtVal());
9497         if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) {
9498           if (OpInfo.isIndirect) {
9499             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
9500             emitInlineAsmError(Call, "inline asm not supported yet: "
9501                                      "don't know how to handle tied "
9502                                      "indirect register inputs");
9503             return;
9504           }
9505 
9506           SmallVector<unsigned, 4> Regs;
9507           MachineFunction &MF = DAG.getMachineFunction();
9508           MachineRegisterInfo &MRI = MF.getRegInfo();
9509           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9510           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
9511           Register TiedReg = R->getReg();
9512           MVT RegVT = R->getSimpleValueType(0);
9513           const TargetRegisterClass *RC =
9514               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
9515               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
9516                                       : TRI.getMinimalPhysRegClass(TiedReg);
9517           for (unsigned i = 0, e = Flag.getNumOperandRegisters(); i != e; ++i)
9518             Regs.push_back(MRI.createVirtualRegister(RC));
9519 
9520           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
9521 
9522           SDLoc dl = getCurSDLoc();
9523           // Use the produced MatchedRegs object to
9524           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call);
9525           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, true,
9526                                            OpInfo.getMatchedOperand(), dl, DAG,
9527                                            AsmNodeOperands);
9528           break;
9529         }
9530 
9531         assert(Flag.isMemKind() && "Unknown matching constraint!");
9532         assert(Flag.getNumOperandRegisters() == 1 &&
9533                "Unexpected number of operands");
9534         // Add information to the INLINEASM node to know about this input.
9535         // See InlineAsm.h isUseOperandTiedToDef.
9536         Flag.clearMemConstraint();
9537         Flag.setMatchingOp(OpInfo.getMatchedOperand());
9538         AsmNodeOperands.push_back(DAG.getTargetConstant(
9539             Flag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9540         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
9541         break;
9542       }
9543 
9544       // Treat indirect 'X' constraint as memory.
9545       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
9546           OpInfo.isIndirect)
9547         OpInfo.ConstraintType = TargetLowering::C_Memory;
9548 
9549       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
9550           OpInfo.ConstraintType == TargetLowering::C_Other) {
9551         std::vector<SDValue> Ops;
9552         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
9553                                           Ops, DAG);
9554         if (Ops.empty()) {
9555           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
9556             if (isa<ConstantSDNode>(InOperandVal)) {
9557               emitInlineAsmError(Call, "value out of range for constraint '" +
9558                                            Twine(OpInfo.ConstraintCode) + "'");
9559               return;
9560             }
9561 
9562           emitInlineAsmError(Call,
9563                              "invalid operand for inline asm constraint '" +
9564                                  Twine(OpInfo.ConstraintCode) + "'");
9565           return;
9566         }
9567 
9568         // Add information to the INLINEASM node to know about this input.
9569         InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size());
9570         AsmNodeOperands.push_back(DAG.getTargetConstant(
9571             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9572         llvm::append_range(AsmNodeOperands, Ops);
9573         break;
9574       }
9575 
9576       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
9577         assert((OpInfo.isIndirect ||
9578                 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
9579                "Operand must be indirect to be a mem!");
9580         assert(InOperandVal.getValueType() ==
9581                    TLI.getPointerTy(DAG.getDataLayout()) &&
9582                "Memory operands expect pointer values");
9583 
9584         const InlineAsm::ConstraintCode ConstraintID =
9585             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9586         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
9587                "Failed to convert memory constraint code to constraint id.");
9588 
9589         // Add information to the INLINEASM node to know about this input.
9590         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
9591         ResOpType.setMemConstraint(ConstraintID);
9592         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
9593                                                         getCurSDLoc(),
9594                                                         MVT::i32));
9595         AsmNodeOperands.push_back(InOperandVal);
9596         break;
9597       }
9598 
9599       if (OpInfo.ConstraintType == TargetLowering::C_Address) {
9600         const InlineAsm::ConstraintCode ConstraintID =
9601             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9602         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
9603                "Failed to convert memory constraint code to constraint id.");
9604 
9605         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
9606 
9607         SDValue AsmOp = InOperandVal;
9608         if (isFunction(InOperandVal)) {
9609           auto *GA = cast<GlobalAddressSDNode>(InOperandVal);
9610           ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1);
9611           AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(),
9612                                              InOperandVal.getValueType(),
9613                                              GA->getOffset());
9614         }
9615 
9616         // Add information to the INLINEASM node to know about this input.
9617         ResOpType.setMemConstraint(ConstraintID);
9618 
9619         AsmNodeOperands.push_back(
9620             DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32));
9621 
9622         AsmNodeOperands.push_back(AsmOp);
9623         break;
9624       }
9625 
9626       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
9627               OpInfo.ConstraintType == TargetLowering::C_Register) &&
9628              "Unknown constraint type!");
9629 
9630       // TODO: Support this.
9631       if (OpInfo.isIndirect) {
9632         emitInlineAsmError(
9633             Call, "Don't know how to handle indirect register inputs yet "
9634                   "for constraint '" +
9635                       Twine(OpInfo.ConstraintCode) + "'");
9636         return;
9637       }
9638 
9639       // Copy the input into the appropriate registers.
9640       if (OpInfo.AssignedRegs.Regs.empty()) {
9641         emitInlineAsmError(Call,
9642                            "couldn't allocate input reg for constraint '" +
9643                                Twine(OpInfo.ConstraintCode) + "'");
9644         return;
9645       }
9646 
9647       if (DetectWriteToReservedRegister())
9648         return;
9649 
9650       SDLoc dl = getCurSDLoc();
9651 
9652       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue,
9653                                         &Call);
9654 
9655       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, false,
9656                                                0, dl, DAG, AsmNodeOperands);
9657       break;
9658     }
9659     case InlineAsm::isClobber:
9660       // Add the clobbered value to the operand list, so that the register
9661       // allocator is aware that the physreg got clobbered.
9662       if (!OpInfo.AssignedRegs.Regs.empty())
9663         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::Clobber,
9664                                                  false, 0, getCurSDLoc(), DAG,
9665                                                  AsmNodeOperands);
9666       break;
9667     }
9668   }
9669 
9670   // Finish up input operands.  Set the input chain and add the flag last.
9671   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
9672   if (Glue.getNode()) AsmNodeOperands.push_back(Glue);
9673 
9674   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
9675   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
9676                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
9677   Glue = Chain.getValue(1);
9678 
9679   // Do additional work to generate outputs.
9680 
9681   SmallVector<EVT, 1> ResultVTs;
9682   SmallVector<SDValue, 1> ResultValues;
9683   SmallVector<SDValue, 8> OutChains;
9684 
9685   llvm::Type *CallResultType = Call.getType();
9686   ArrayRef<Type *> ResultTypes;
9687   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
9688     ResultTypes = StructResult->elements();
9689   else if (!CallResultType->isVoidTy())
9690     ResultTypes = ArrayRef(CallResultType);
9691 
9692   auto CurResultType = ResultTypes.begin();
9693   auto handleRegAssign = [&](SDValue V) {
9694     assert(CurResultType != ResultTypes.end() && "Unexpected value");
9695     assert((*CurResultType)->isSized() && "Unexpected unsized type");
9696     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
9697     ++CurResultType;
9698     // If the type of the inline asm call site return value is different but has
9699     // same size as the type of the asm output bitcast it.  One example of this
9700     // is for vectors with different width / number of elements.  This can
9701     // happen for register classes that can contain multiple different value
9702     // types.  The preg or vreg allocated may not have the same VT as was
9703     // expected.
9704     //
9705     // This can also happen for a return value that disagrees with the register
9706     // class it is put in, eg. a double in a general-purpose register on a
9707     // 32-bit machine.
9708     if (ResultVT != V.getValueType() &&
9709         ResultVT.getSizeInBits() == V.getValueSizeInBits())
9710       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
9711     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
9712              V.getValueType().isInteger()) {
9713       // If a result value was tied to an input value, the computed result
9714       // may have a wider width than the expected result.  Extract the
9715       // relevant portion.
9716       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
9717     }
9718     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
9719     ResultVTs.push_back(ResultVT);
9720     ResultValues.push_back(V);
9721   };
9722 
9723   // Deal with output operands.
9724   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9725     if (OpInfo.Type == InlineAsm::isOutput) {
9726       SDValue Val;
9727       // Skip trivial output operands.
9728       if (OpInfo.AssignedRegs.Regs.empty())
9729         continue;
9730 
9731       switch (OpInfo.ConstraintType) {
9732       case TargetLowering::C_Register:
9733       case TargetLowering::C_RegisterClass:
9734         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
9735                                                   Chain, &Glue, &Call);
9736         break;
9737       case TargetLowering::C_Immediate:
9738       case TargetLowering::C_Other:
9739         Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(),
9740                                               OpInfo, DAG);
9741         break;
9742       case TargetLowering::C_Memory:
9743         break; // Already handled.
9744       case TargetLowering::C_Address:
9745         break; // Silence warning.
9746       case TargetLowering::C_Unknown:
9747         assert(false && "Unexpected unknown constraint");
9748       }
9749 
9750       // Indirect output manifest as stores. Record output chains.
9751       if (OpInfo.isIndirect) {
9752         const Value *Ptr = OpInfo.CallOperandVal;
9753         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
9754         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
9755                                      MachinePointerInfo(Ptr));
9756         OutChains.push_back(Store);
9757       } else {
9758         // generate CopyFromRegs to associated registers.
9759         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
9760         if (Val.getOpcode() == ISD::MERGE_VALUES) {
9761           for (const SDValue &V : Val->op_values())
9762             handleRegAssign(V);
9763         } else
9764           handleRegAssign(Val);
9765       }
9766     }
9767   }
9768 
9769   // Set results.
9770   if (!ResultValues.empty()) {
9771     assert(CurResultType == ResultTypes.end() &&
9772            "Mismatch in number of ResultTypes");
9773     assert(ResultValues.size() == ResultTypes.size() &&
9774            "Mismatch in number of output operands in asm result");
9775 
9776     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
9777                             DAG.getVTList(ResultVTs), ResultValues);
9778     setValue(&Call, V);
9779   }
9780 
9781   // Collect store chains.
9782   if (!OutChains.empty())
9783     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
9784 
9785   if (EmitEHLabels) {
9786     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
9787   }
9788 
9789   // Only Update Root if inline assembly has a memory effect.
9790   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
9791       EmitEHLabels)
9792     DAG.setRoot(Chain);
9793 }
9794 
9795 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
9796                                              const Twine &Message) {
9797   LLVMContext &Ctx = *DAG.getContext();
9798   Ctx.emitError(&Call, Message);
9799 
9800   // Make sure we leave the DAG in a valid state
9801   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9802   SmallVector<EVT, 1> ValueVTs;
9803   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
9804 
9805   if (ValueVTs.empty())
9806     return;
9807 
9808   SmallVector<SDValue, 1> Ops;
9809   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
9810     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
9811 
9812   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
9813 }
9814 
9815 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
9816   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
9817                           MVT::Other, getRoot(),
9818                           getValue(I.getArgOperand(0)),
9819                           DAG.getSrcValue(I.getArgOperand(0))));
9820 }
9821 
9822 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
9823   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9824   const DataLayout &DL = DAG.getDataLayout();
9825   SDValue V = DAG.getVAArg(
9826       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
9827       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
9828       DL.getABITypeAlign(I.getType()).value());
9829   DAG.setRoot(V.getValue(1));
9830 
9831   if (I.getType()->isPointerTy())
9832     V = DAG.getPtrExtOrTrunc(
9833         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
9834   setValue(&I, V);
9835 }
9836 
9837 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
9838   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
9839                           MVT::Other, getRoot(),
9840                           getValue(I.getArgOperand(0)),
9841                           DAG.getSrcValue(I.getArgOperand(0))));
9842 }
9843 
9844 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
9845   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
9846                           MVT::Other, getRoot(),
9847                           getValue(I.getArgOperand(0)),
9848                           getValue(I.getArgOperand(1)),
9849                           DAG.getSrcValue(I.getArgOperand(0)),
9850                           DAG.getSrcValue(I.getArgOperand(1))));
9851 }
9852 
9853 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
9854                                                     const Instruction &I,
9855                                                     SDValue Op) {
9856   const MDNode *Range = getRangeMetadata(I);
9857   if (!Range)
9858     return Op;
9859 
9860   ConstantRange CR = getConstantRangeFromMetadata(*Range);
9861   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
9862     return Op;
9863 
9864   APInt Lo = CR.getUnsignedMin();
9865   if (!Lo.isMinValue())
9866     return Op;
9867 
9868   APInt Hi = CR.getUnsignedMax();
9869   unsigned Bits = std::max(Hi.getActiveBits(),
9870                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
9871 
9872   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9873 
9874   SDLoc SL = getCurSDLoc();
9875 
9876   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
9877                              DAG.getValueType(SmallVT));
9878   unsigned NumVals = Op.getNode()->getNumValues();
9879   if (NumVals == 1)
9880     return ZExt;
9881 
9882   SmallVector<SDValue, 4> Ops;
9883 
9884   Ops.push_back(ZExt);
9885   for (unsigned I = 1; I != NumVals; ++I)
9886     Ops.push_back(Op.getValue(I));
9887 
9888   return DAG.getMergeValues(Ops, SL);
9889 }
9890 
9891 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
9892 /// the call being lowered.
9893 ///
9894 /// This is a helper for lowering intrinsics that follow a target calling
9895 /// convention or require stack pointer adjustment. Only a subset of the
9896 /// intrinsic's operands need to participate in the calling convention.
9897 void SelectionDAGBuilder::populateCallLoweringInfo(
9898     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
9899     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
9900     AttributeSet RetAttrs, bool IsPatchPoint) {
9901   TargetLowering::ArgListTy Args;
9902   Args.reserve(NumArgs);
9903 
9904   // Populate the argument list.
9905   // Attributes for args start at offset 1, after the return attribute.
9906   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
9907        ArgI != ArgE; ++ArgI) {
9908     const Value *V = Call->getOperand(ArgI);
9909 
9910     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
9911 
9912     TargetLowering::ArgListEntry Entry;
9913     Entry.Node = getValue(V);
9914     Entry.Ty = V->getType();
9915     Entry.setAttributes(Call, ArgI);
9916     Args.push_back(Entry);
9917   }
9918 
9919   CLI.setDebugLoc(getCurSDLoc())
9920       .setChain(getRoot())
9921       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args),
9922                  RetAttrs)
9923       .setDiscardResult(Call->use_empty())
9924       .setIsPatchPoint(IsPatchPoint)
9925       .setIsPreallocated(
9926           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
9927 }
9928 
9929 /// Add a stack map intrinsic call's live variable operands to a stackmap
9930 /// or patchpoint target node's operand list.
9931 ///
9932 /// Constants are converted to TargetConstants purely as an optimization to
9933 /// avoid constant materialization and register allocation.
9934 ///
9935 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
9936 /// generate addess computation nodes, and so FinalizeISel can convert the
9937 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
9938 /// address materialization and register allocation, but may also be required
9939 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
9940 /// alloca in the entry block, then the runtime may assume that the alloca's
9941 /// StackMap location can be read immediately after compilation and that the
9942 /// location is valid at any point during execution (this is similar to the
9943 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
9944 /// only available in a register, then the runtime would need to trap when
9945 /// execution reaches the StackMap in order to read the alloca's location.
9946 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
9947                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
9948                                 SelectionDAGBuilder &Builder) {
9949   SelectionDAG &DAG = Builder.DAG;
9950   for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
9951     SDValue Op = Builder.getValue(Call.getArgOperand(I));
9952 
9953     // Things on the stack are pointer-typed, meaning that they are already
9954     // legal and can be emitted directly to target nodes.
9955     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
9956       Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
9957     } else {
9958       // Otherwise emit a target independent node to be legalised.
9959       Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
9960     }
9961   }
9962 }
9963 
9964 /// Lower llvm.experimental.stackmap.
9965 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
9966   // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
9967   //                                  [live variables...])
9968 
9969   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
9970 
9971   SDValue Chain, InGlue, Callee;
9972   SmallVector<SDValue, 32> Ops;
9973 
9974   SDLoc DL = getCurSDLoc();
9975   Callee = getValue(CI.getCalledOperand());
9976 
9977   // The stackmap intrinsic only records the live variables (the arguments
9978   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
9979   // intrinsic, this won't be lowered to a function call. This means we don't
9980   // have to worry about calling conventions and target specific lowering code.
9981   // Instead we perform the call lowering right here.
9982   //
9983   // chain, flag = CALLSEQ_START(chain, 0, 0)
9984   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
9985   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
9986   //
9987   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
9988   InGlue = Chain.getValue(1);
9989 
9990   // Add the STACKMAP operands, starting with DAG house-keeping.
9991   Ops.push_back(Chain);
9992   Ops.push_back(InGlue);
9993 
9994   // Add the <id>, <numShadowBytes> operands.
9995   //
9996   // These do not require legalisation, and can be emitted directly to target
9997   // constant nodes.
9998   SDValue ID = getValue(CI.getArgOperand(0));
9999   assert(ID.getValueType() == MVT::i64);
10000   SDValue IDConst =
10001       DAG.getTargetConstant(ID->getAsZExtVal(), DL, ID.getValueType());
10002   Ops.push_back(IDConst);
10003 
10004   SDValue Shad = getValue(CI.getArgOperand(1));
10005   assert(Shad.getValueType() == MVT::i32);
10006   SDValue ShadConst =
10007       DAG.getTargetConstant(Shad->getAsZExtVal(), DL, Shad.getValueType());
10008   Ops.push_back(ShadConst);
10009 
10010   // Add the live variables.
10011   addStackMapLiveVars(CI, 2, DL, Ops, *this);
10012 
10013   // Create the STACKMAP node.
10014   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10015   Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
10016   InGlue = Chain.getValue(1);
10017 
10018   Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL);
10019 
10020   // Stackmaps don't generate values, so nothing goes into the NodeMap.
10021 
10022   // Set the root to the target-lowered call chain.
10023   DAG.setRoot(Chain);
10024 
10025   // Inform the Frame Information that we have a stackmap in this function.
10026   FuncInfo.MF->getFrameInfo().setHasStackMap();
10027 }
10028 
10029 /// Lower llvm.experimental.patchpoint directly to its target opcode.
10030 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
10031                                           const BasicBlock *EHPadBB) {
10032   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
10033   //                                                 i32 <numBytes>,
10034   //                                                 i8* <target>,
10035   //                                                 i32 <numArgs>,
10036   //                                                 [Args...],
10037   //                                                 [live variables...])
10038 
10039   CallingConv::ID CC = CB.getCallingConv();
10040   bool IsAnyRegCC = CC == CallingConv::AnyReg;
10041   bool HasDef = !CB.getType()->isVoidTy();
10042   SDLoc dl = getCurSDLoc();
10043   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
10044 
10045   // Handle immediate and symbolic callees.
10046   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
10047     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
10048                                    /*isTarget=*/true);
10049   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
10050     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
10051                                          SDLoc(SymbolicCallee),
10052                                          SymbolicCallee->getValueType(0));
10053 
10054   // Get the real number of arguments participating in the call <numArgs>
10055   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
10056   unsigned NumArgs = NArgVal->getAsZExtVal();
10057 
10058   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
10059   // Intrinsics include all meta-operands up to but not including CC.
10060   unsigned NumMetaOpers = PatchPointOpers::CCPos;
10061   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
10062          "Not enough arguments provided to the patchpoint intrinsic");
10063 
10064   // For AnyRegCC the arguments are lowered later on manually.
10065   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
10066   Type *ReturnTy =
10067       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
10068 
10069   TargetLowering::CallLoweringInfo CLI(DAG);
10070   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
10071                            ReturnTy, CB.getAttributes().getRetAttrs(), true);
10072   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
10073 
10074   SDNode *CallEnd = Result.second.getNode();
10075   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
10076     CallEnd = CallEnd->getOperand(0).getNode();
10077 
10078   /// Get a call instruction from the call sequence chain.
10079   /// Tail calls are not allowed.
10080   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
10081          "Expected a callseq node.");
10082   SDNode *Call = CallEnd->getOperand(0).getNode();
10083   bool HasGlue = Call->getGluedNode();
10084 
10085   // Replace the target specific call node with the patchable intrinsic.
10086   SmallVector<SDValue, 8> Ops;
10087 
10088   // Push the chain.
10089   Ops.push_back(*(Call->op_begin()));
10090 
10091   // Optionally, push the glue (if any).
10092   if (HasGlue)
10093     Ops.push_back(*(Call->op_end() - 1));
10094 
10095   // Push the register mask info.
10096   if (HasGlue)
10097     Ops.push_back(*(Call->op_end() - 2));
10098   else
10099     Ops.push_back(*(Call->op_end() - 1));
10100 
10101   // Add the <id> and <numBytes> constants.
10102   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
10103   Ops.push_back(DAG.getTargetConstant(IDVal->getAsZExtVal(), dl, MVT::i64));
10104   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
10105   Ops.push_back(DAG.getTargetConstant(NBytesVal->getAsZExtVal(), dl, MVT::i32));
10106 
10107   // Add the callee.
10108   Ops.push_back(Callee);
10109 
10110   // Adjust <numArgs> to account for any arguments that have been passed on the
10111   // stack instead.
10112   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
10113   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
10114   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
10115   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
10116 
10117   // Add the calling convention
10118   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
10119 
10120   // Add the arguments we omitted previously. The register allocator should
10121   // place these in any free register.
10122   if (IsAnyRegCC)
10123     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
10124       Ops.push_back(getValue(CB.getArgOperand(i)));
10125 
10126   // Push the arguments from the call instruction.
10127   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
10128   Ops.append(Call->op_begin() + 2, e);
10129 
10130   // Push live variables for the stack map.
10131   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
10132 
10133   SDVTList NodeTys;
10134   if (IsAnyRegCC && HasDef) {
10135     // Create the return types based on the intrinsic definition
10136     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10137     SmallVector<EVT, 3> ValueVTs;
10138     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
10139     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
10140 
10141     // There is always a chain and a glue type at the end
10142     ValueVTs.push_back(MVT::Other);
10143     ValueVTs.push_back(MVT::Glue);
10144     NodeTys = DAG.getVTList(ValueVTs);
10145   } else
10146     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10147 
10148   // Replace the target specific call node with a PATCHPOINT node.
10149   SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
10150 
10151   // Update the NodeMap.
10152   if (HasDef) {
10153     if (IsAnyRegCC)
10154       setValue(&CB, SDValue(PPV.getNode(), 0));
10155     else
10156       setValue(&CB, Result.first);
10157   }
10158 
10159   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
10160   // call sequence. Furthermore the location of the chain and glue can change
10161   // when the AnyReg calling convention is used and the intrinsic returns a
10162   // value.
10163   if (IsAnyRegCC && HasDef) {
10164     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
10165     SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
10166     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10167   } else
10168     DAG.ReplaceAllUsesWith(Call, PPV.getNode());
10169   DAG.DeleteNode(Call);
10170 
10171   // Inform the Frame Information that we have a patchpoint in this function.
10172   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
10173 }
10174 
10175 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
10176                                             unsigned Intrinsic) {
10177   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10178   SDValue Op1 = getValue(I.getArgOperand(0));
10179   SDValue Op2;
10180   if (I.arg_size() > 1)
10181     Op2 = getValue(I.getArgOperand(1));
10182   SDLoc dl = getCurSDLoc();
10183   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
10184   SDValue Res;
10185   SDNodeFlags SDFlags;
10186   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
10187     SDFlags.copyFMF(*FPMO);
10188 
10189   switch (Intrinsic) {
10190   case Intrinsic::vector_reduce_fadd:
10191     if (SDFlags.hasAllowReassociation())
10192       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
10193                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
10194                         SDFlags);
10195     else
10196       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
10197     break;
10198   case Intrinsic::vector_reduce_fmul:
10199     if (SDFlags.hasAllowReassociation())
10200       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
10201                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
10202                         SDFlags);
10203     else
10204       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
10205     break;
10206   case Intrinsic::vector_reduce_add:
10207     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
10208     break;
10209   case Intrinsic::vector_reduce_mul:
10210     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
10211     break;
10212   case Intrinsic::vector_reduce_and:
10213     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
10214     break;
10215   case Intrinsic::vector_reduce_or:
10216     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
10217     break;
10218   case Intrinsic::vector_reduce_xor:
10219     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
10220     break;
10221   case Intrinsic::vector_reduce_smax:
10222     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
10223     break;
10224   case Intrinsic::vector_reduce_smin:
10225     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
10226     break;
10227   case Intrinsic::vector_reduce_umax:
10228     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
10229     break;
10230   case Intrinsic::vector_reduce_umin:
10231     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
10232     break;
10233   case Intrinsic::vector_reduce_fmax:
10234     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
10235     break;
10236   case Intrinsic::vector_reduce_fmin:
10237     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
10238     break;
10239   case Intrinsic::vector_reduce_fmaximum:
10240     Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags);
10241     break;
10242   case Intrinsic::vector_reduce_fminimum:
10243     Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags);
10244     break;
10245   default:
10246     llvm_unreachable("Unhandled vector reduce intrinsic");
10247   }
10248   setValue(&I, Res);
10249 }
10250 
10251 /// Returns an AttributeList representing the attributes applied to the return
10252 /// value of the given call.
10253 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
10254   SmallVector<Attribute::AttrKind, 2> Attrs;
10255   if (CLI.RetSExt)
10256     Attrs.push_back(Attribute::SExt);
10257   if (CLI.RetZExt)
10258     Attrs.push_back(Attribute::ZExt);
10259   if (CLI.IsInReg)
10260     Attrs.push_back(Attribute::InReg);
10261 
10262   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
10263                             Attrs);
10264 }
10265 
10266 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
10267 /// implementation, which just calls LowerCall.
10268 /// FIXME: When all targets are
10269 /// migrated to using LowerCall, this hook should be integrated into SDISel.
10270 std::pair<SDValue, SDValue>
10271 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
10272   // Handle the incoming return values from the call.
10273   CLI.Ins.clear();
10274   Type *OrigRetTy = CLI.RetTy;
10275   SmallVector<EVT, 4> RetTys;
10276   SmallVector<uint64_t, 4> Offsets;
10277   auto &DL = CLI.DAG.getDataLayout();
10278   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets, 0);
10279 
10280   if (CLI.IsPostTypeLegalization) {
10281     // If we are lowering a libcall after legalization, split the return type.
10282     SmallVector<EVT, 4> OldRetTys;
10283     SmallVector<uint64_t, 4> OldOffsets;
10284     RetTys.swap(OldRetTys);
10285     Offsets.swap(OldOffsets);
10286 
10287     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
10288       EVT RetVT = OldRetTys[i];
10289       uint64_t Offset = OldOffsets[i];
10290       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
10291       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
10292       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
10293       RetTys.append(NumRegs, RegisterVT);
10294       for (unsigned j = 0; j != NumRegs; ++j)
10295         Offsets.push_back(Offset + j * RegisterVTByteSZ);
10296     }
10297   }
10298 
10299   SmallVector<ISD::OutputArg, 4> Outs;
10300   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
10301 
10302   bool CanLowerReturn =
10303       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
10304                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
10305 
10306   SDValue DemoteStackSlot;
10307   int DemoteStackIdx = -100;
10308   if (!CanLowerReturn) {
10309     // FIXME: equivalent assert?
10310     // assert(!CS.hasInAllocaArgument() &&
10311     //        "sret demotion is incompatible with inalloca");
10312     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
10313     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
10314     MachineFunction &MF = CLI.DAG.getMachineFunction();
10315     DemoteStackIdx =
10316         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
10317     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
10318                                               DL.getAllocaAddrSpace());
10319 
10320     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
10321     ArgListEntry Entry;
10322     Entry.Node = DemoteStackSlot;
10323     Entry.Ty = StackSlotPtrType;
10324     Entry.IsSExt = false;
10325     Entry.IsZExt = false;
10326     Entry.IsInReg = false;
10327     Entry.IsSRet = true;
10328     Entry.IsNest = false;
10329     Entry.IsByVal = false;
10330     Entry.IsByRef = false;
10331     Entry.IsReturned = false;
10332     Entry.IsSwiftSelf = false;
10333     Entry.IsSwiftAsync = false;
10334     Entry.IsSwiftError = false;
10335     Entry.IsCFGuardTarget = false;
10336     Entry.Alignment = Alignment;
10337     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
10338     CLI.NumFixedArgs += 1;
10339     CLI.getArgs()[0].IndirectType = CLI.RetTy;
10340     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
10341 
10342     // sret demotion isn't compatible with tail-calls, since the sret argument
10343     // points into the callers stack frame.
10344     CLI.IsTailCall = false;
10345   } else {
10346     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10347         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
10348     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
10349       ISD::ArgFlagsTy Flags;
10350       if (NeedsRegBlock) {
10351         Flags.setInConsecutiveRegs();
10352         if (I == RetTys.size() - 1)
10353           Flags.setInConsecutiveRegsLast();
10354       }
10355       EVT VT = RetTys[I];
10356       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10357                                                      CLI.CallConv, VT);
10358       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10359                                                        CLI.CallConv, VT);
10360       for (unsigned i = 0; i != NumRegs; ++i) {
10361         ISD::InputArg MyFlags;
10362         MyFlags.Flags = Flags;
10363         MyFlags.VT = RegisterVT;
10364         MyFlags.ArgVT = VT;
10365         MyFlags.Used = CLI.IsReturnValueUsed;
10366         if (CLI.RetTy->isPointerTy()) {
10367           MyFlags.Flags.setPointer();
10368           MyFlags.Flags.setPointerAddrSpace(
10369               cast<PointerType>(CLI.RetTy)->getAddressSpace());
10370         }
10371         if (CLI.RetSExt)
10372           MyFlags.Flags.setSExt();
10373         if (CLI.RetZExt)
10374           MyFlags.Flags.setZExt();
10375         if (CLI.IsInReg)
10376           MyFlags.Flags.setInReg();
10377         CLI.Ins.push_back(MyFlags);
10378       }
10379     }
10380   }
10381 
10382   // We push in swifterror return as the last element of CLI.Ins.
10383   ArgListTy &Args = CLI.getArgs();
10384   if (supportSwiftError()) {
10385     for (const ArgListEntry &Arg : Args) {
10386       if (Arg.IsSwiftError) {
10387         ISD::InputArg MyFlags;
10388         MyFlags.VT = getPointerTy(DL);
10389         MyFlags.ArgVT = EVT(getPointerTy(DL));
10390         MyFlags.Flags.setSwiftError();
10391         CLI.Ins.push_back(MyFlags);
10392       }
10393     }
10394   }
10395 
10396   // Handle all of the outgoing arguments.
10397   CLI.Outs.clear();
10398   CLI.OutVals.clear();
10399   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
10400     SmallVector<EVT, 4> ValueVTs;
10401     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
10402     // FIXME: Split arguments if CLI.IsPostTypeLegalization
10403     Type *FinalType = Args[i].Ty;
10404     if (Args[i].IsByVal)
10405       FinalType = Args[i].IndirectType;
10406     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10407         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
10408     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
10409          ++Value) {
10410       EVT VT = ValueVTs[Value];
10411       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
10412       SDValue Op = SDValue(Args[i].Node.getNode(),
10413                            Args[i].Node.getResNo() + Value);
10414       ISD::ArgFlagsTy Flags;
10415 
10416       // Certain targets (such as MIPS), may have a different ABI alignment
10417       // for a type depending on the context. Give the target a chance to
10418       // specify the alignment it wants.
10419       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
10420       Flags.setOrigAlign(OriginalAlignment);
10421 
10422       if (Args[i].Ty->isPointerTy()) {
10423         Flags.setPointer();
10424         Flags.setPointerAddrSpace(
10425             cast<PointerType>(Args[i].Ty)->getAddressSpace());
10426       }
10427       if (Args[i].IsZExt)
10428         Flags.setZExt();
10429       if (Args[i].IsSExt)
10430         Flags.setSExt();
10431       if (Args[i].IsInReg) {
10432         // If we are using vectorcall calling convention, a structure that is
10433         // passed InReg - is surely an HVA
10434         if (CLI.CallConv == CallingConv::X86_VectorCall &&
10435             isa<StructType>(FinalType)) {
10436           // The first value of a structure is marked
10437           if (0 == Value)
10438             Flags.setHvaStart();
10439           Flags.setHva();
10440         }
10441         // Set InReg Flag
10442         Flags.setInReg();
10443       }
10444       if (Args[i].IsSRet)
10445         Flags.setSRet();
10446       if (Args[i].IsSwiftSelf)
10447         Flags.setSwiftSelf();
10448       if (Args[i].IsSwiftAsync)
10449         Flags.setSwiftAsync();
10450       if (Args[i].IsSwiftError)
10451         Flags.setSwiftError();
10452       if (Args[i].IsCFGuardTarget)
10453         Flags.setCFGuardTarget();
10454       if (Args[i].IsByVal)
10455         Flags.setByVal();
10456       if (Args[i].IsByRef)
10457         Flags.setByRef();
10458       if (Args[i].IsPreallocated) {
10459         Flags.setPreallocated();
10460         // Set the byval flag for CCAssignFn callbacks that don't know about
10461         // preallocated.  This way we can know how many bytes we should've
10462         // allocated and how many bytes a callee cleanup function will pop.  If
10463         // we port preallocated to more targets, we'll have to add custom
10464         // preallocated handling in the various CC lowering callbacks.
10465         Flags.setByVal();
10466       }
10467       if (Args[i].IsInAlloca) {
10468         Flags.setInAlloca();
10469         // Set the byval flag for CCAssignFn callbacks that don't know about
10470         // inalloca.  This way we can know how many bytes we should've allocated
10471         // and how many bytes a callee cleanup function will pop.  If we port
10472         // inalloca to more targets, we'll have to add custom inalloca handling
10473         // in the various CC lowering callbacks.
10474         Flags.setByVal();
10475       }
10476       Align MemAlign;
10477       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
10478         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
10479         Flags.setByValSize(FrameSize);
10480 
10481         // info is not there but there are cases it cannot get right.
10482         if (auto MA = Args[i].Alignment)
10483           MemAlign = *MA;
10484         else
10485           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
10486       } else if (auto MA = Args[i].Alignment) {
10487         MemAlign = *MA;
10488       } else {
10489         MemAlign = OriginalAlignment;
10490       }
10491       Flags.setMemAlign(MemAlign);
10492       if (Args[i].IsNest)
10493         Flags.setNest();
10494       if (NeedsRegBlock)
10495         Flags.setInConsecutiveRegs();
10496 
10497       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10498                                                  CLI.CallConv, VT);
10499       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10500                                                         CLI.CallConv, VT);
10501       SmallVector<SDValue, 4> Parts(NumParts);
10502       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
10503 
10504       if (Args[i].IsSExt)
10505         ExtendKind = ISD::SIGN_EXTEND;
10506       else if (Args[i].IsZExt)
10507         ExtendKind = ISD::ZERO_EXTEND;
10508 
10509       // Conservatively only handle 'returned' on non-vectors that can be lowered,
10510       // for now.
10511       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
10512           CanLowerReturn) {
10513         assert((CLI.RetTy == Args[i].Ty ||
10514                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
10515                  CLI.RetTy->getPointerAddressSpace() ==
10516                      Args[i].Ty->getPointerAddressSpace())) &&
10517                RetTys.size() == NumValues && "unexpected use of 'returned'");
10518         // Before passing 'returned' to the target lowering code, ensure that
10519         // either the register MVT and the actual EVT are the same size or that
10520         // the return value and argument are extended in the same way; in these
10521         // cases it's safe to pass the argument register value unchanged as the
10522         // return register value (although it's at the target's option whether
10523         // to do so)
10524         // TODO: allow code generation to take advantage of partially preserved
10525         // registers rather than clobbering the entire register when the
10526         // parameter extension method is not compatible with the return
10527         // extension method
10528         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
10529             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
10530              CLI.RetZExt == Args[i].IsZExt))
10531           Flags.setReturned();
10532       }
10533 
10534       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
10535                      CLI.CallConv, ExtendKind);
10536 
10537       for (unsigned j = 0; j != NumParts; ++j) {
10538         // if it isn't first piece, alignment must be 1
10539         // For scalable vectors the scalable part is currently handled
10540         // by individual targets, so we just use the known minimum size here.
10541         ISD::OutputArg MyFlags(
10542             Flags, Parts[j].getValueType().getSimpleVT(), VT,
10543             i < CLI.NumFixedArgs, i,
10544             j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
10545         if (NumParts > 1 && j == 0)
10546           MyFlags.Flags.setSplit();
10547         else if (j != 0) {
10548           MyFlags.Flags.setOrigAlign(Align(1));
10549           if (j == NumParts - 1)
10550             MyFlags.Flags.setSplitEnd();
10551         }
10552 
10553         CLI.Outs.push_back(MyFlags);
10554         CLI.OutVals.push_back(Parts[j]);
10555       }
10556 
10557       if (NeedsRegBlock && Value == NumValues - 1)
10558         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
10559     }
10560   }
10561 
10562   SmallVector<SDValue, 4> InVals;
10563   CLI.Chain = LowerCall(CLI, InVals);
10564 
10565   // Update CLI.InVals to use outside of this function.
10566   CLI.InVals = InVals;
10567 
10568   // Verify that the target's LowerCall behaved as expected.
10569   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
10570          "LowerCall didn't return a valid chain!");
10571   assert((!CLI.IsTailCall || InVals.empty()) &&
10572          "LowerCall emitted a return value for a tail call!");
10573   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
10574          "LowerCall didn't emit the correct number of values!");
10575 
10576   // For a tail call, the return value is merely live-out and there aren't
10577   // any nodes in the DAG representing it. Return a special value to
10578   // indicate that a tail call has been emitted and no more Instructions
10579   // should be processed in the current block.
10580   if (CLI.IsTailCall) {
10581     CLI.DAG.setRoot(CLI.Chain);
10582     return std::make_pair(SDValue(), SDValue());
10583   }
10584 
10585 #ifndef NDEBUG
10586   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
10587     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
10588     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
10589            "LowerCall emitted a value with the wrong type!");
10590   }
10591 #endif
10592 
10593   SmallVector<SDValue, 4> ReturnValues;
10594   if (!CanLowerReturn) {
10595     // The instruction result is the result of loading from the
10596     // hidden sret parameter.
10597     SmallVector<EVT, 1> PVTs;
10598     Type *PtrRetTy =
10599         PointerType::get(OrigRetTy->getContext(), DL.getAllocaAddrSpace());
10600 
10601     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
10602     assert(PVTs.size() == 1 && "Pointers should fit in one register");
10603     EVT PtrVT = PVTs[0];
10604 
10605     unsigned NumValues = RetTys.size();
10606     ReturnValues.resize(NumValues);
10607     SmallVector<SDValue, 4> Chains(NumValues);
10608 
10609     // An aggregate return value cannot wrap around the address space, so
10610     // offsets to its parts don't wrap either.
10611     SDNodeFlags Flags;
10612     Flags.setNoUnsignedWrap(true);
10613 
10614     MachineFunction &MF = CLI.DAG.getMachineFunction();
10615     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
10616     for (unsigned i = 0; i < NumValues; ++i) {
10617       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
10618                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
10619                                                         PtrVT), Flags);
10620       SDValue L = CLI.DAG.getLoad(
10621           RetTys[i], CLI.DL, CLI.Chain, Add,
10622           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
10623                                             DemoteStackIdx, Offsets[i]),
10624           HiddenSRetAlign);
10625       ReturnValues[i] = L;
10626       Chains[i] = L.getValue(1);
10627     }
10628 
10629     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
10630   } else {
10631     // Collect the legal value parts into potentially illegal values
10632     // that correspond to the original function's return values.
10633     std::optional<ISD::NodeType> AssertOp;
10634     if (CLI.RetSExt)
10635       AssertOp = ISD::AssertSext;
10636     else if (CLI.RetZExt)
10637       AssertOp = ISD::AssertZext;
10638     unsigned CurReg = 0;
10639     for (EVT VT : RetTys) {
10640       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10641                                                      CLI.CallConv, VT);
10642       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10643                                                        CLI.CallConv, VT);
10644 
10645       ReturnValues.push_back(getCopyFromParts(
10646           CLI.DAG, CLI.DL, &InVals[CurReg], NumRegs, RegisterVT, VT, nullptr,
10647           CLI.Chain, CLI.CallConv, AssertOp));
10648       CurReg += NumRegs;
10649     }
10650 
10651     // For a function returning void, there is no return value. We can't create
10652     // such a node, so we just return a null return value in that case. In
10653     // that case, nothing will actually look at the value.
10654     if (ReturnValues.empty())
10655       return std::make_pair(SDValue(), CLI.Chain);
10656   }
10657 
10658   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
10659                                 CLI.DAG.getVTList(RetTys), ReturnValues);
10660   return std::make_pair(Res, CLI.Chain);
10661 }
10662 
10663 /// Places new result values for the node in Results (their number
10664 /// and types must exactly match those of the original return values of
10665 /// the node), or leaves Results empty, which indicates that the node is not
10666 /// to be custom lowered after all.
10667 void TargetLowering::LowerOperationWrapper(SDNode *N,
10668                                            SmallVectorImpl<SDValue> &Results,
10669                                            SelectionDAG &DAG) const {
10670   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
10671 
10672   if (!Res.getNode())
10673     return;
10674 
10675   // If the original node has one result, take the return value from
10676   // LowerOperation as is. It might not be result number 0.
10677   if (N->getNumValues() == 1) {
10678     Results.push_back(Res);
10679     return;
10680   }
10681 
10682   // If the original node has multiple results, then the return node should
10683   // have the same number of results.
10684   assert((N->getNumValues() == Res->getNumValues()) &&
10685       "Lowering returned the wrong number of results!");
10686 
10687   // Places new result values base on N result number.
10688   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
10689     Results.push_back(Res.getValue(I));
10690 }
10691 
10692 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10693   llvm_unreachable("LowerOperation not implemented for this target!");
10694 }
10695 
10696 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
10697                                                      unsigned Reg,
10698                                                      ISD::NodeType ExtendType) {
10699   SDValue Op = getNonRegisterValue(V);
10700   assert((Op.getOpcode() != ISD::CopyFromReg ||
10701           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
10702          "Copy from a reg to the same reg!");
10703   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
10704 
10705   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10706   // If this is an InlineAsm we have to match the registers required, not the
10707   // notional registers required by the type.
10708 
10709   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
10710                    std::nullopt); // This is not an ABI copy.
10711   SDValue Chain = DAG.getEntryNode();
10712 
10713   if (ExtendType == ISD::ANY_EXTEND) {
10714     auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
10715     if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
10716       ExtendType = PreferredExtendIt->second;
10717   }
10718   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
10719   PendingExports.push_back(Chain);
10720 }
10721 
10722 #include "llvm/CodeGen/SelectionDAGISel.h"
10723 
10724 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
10725 /// entry block, return true.  This includes arguments used by switches, since
10726 /// the switch may expand into multiple basic blocks.
10727 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
10728   // With FastISel active, we may be splitting blocks, so force creation
10729   // of virtual registers for all non-dead arguments.
10730   if (FastISel)
10731     return A->use_empty();
10732 
10733   const BasicBlock &Entry = A->getParent()->front();
10734   for (const User *U : A->users())
10735     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
10736       return false;  // Use not in entry block.
10737 
10738   return true;
10739 }
10740 
10741 using ArgCopyElisionMapTy =
10742     DenseMap<const Argument *,
10743              std::pair<const AllocaInst *, const StoreInst *>>;
10744 
10745 /// Scan the entry block of the function in FuncInfo for arguments that look
10746 /// like copies into a local alloca. Record any copied arguments in
10747 /// ArgCopyElisionCandidates.
10748 static void
10749 findArgumentCopyElisionCandidates(const DataLayout &DL,
10750                                   FunctionLoweringInfo *FuncInfo,
10751                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
10752   // Record the state of every static alloca used in the entry block. Argument
10753   // allocas are all used in the entry block, so we need approximately as many
10754   // entries as we have arguments.
10755   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
10756   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
10757   unsigned NumArgs = FuncInfo->Fn->arg_size();
10758   StaticAllocas.reserve(NumArgs * 2);
10759 
10760   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
10761     if (!V)
10762       return nullptr;
10763     V = V->stripPointerCasts();
10764     const auto *AI = dyn_cast<AllocaInst>(V);
10765     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
10766       return nullptr;
10767     auto Iter = StaticAllocas.insert({AI, Unknown});
10768     return &Iter.first->second;
10769   };
10770 
10771   // Look for stores of arguments to static allocas. Look through bitcasts and
10772   // GEPs to handle type coercions, as long as the alloca is fully initialized
10773   // by the store. Any non-store use of an alloca escapes it and any subsequent
10774   // unanalyzed store might write it.
10775   // FIXME: Handle structs initialized with multiple stores.
10776   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
10777     // Look for stores, and handle non-store uses conservatively.
10778     const auto *SI = dyn_cast<StoreInst>(&I);
10779     if (!SI) {
10780       // We will look through cast uses, so ignore them completely.
10781       if (I.isCast())
10782         continue;
10783       // Ignore debug info and pseudo op intrinsics, they don't escape or store
10784       // to allocas.
10785       if (I.isDebugOrPseudoInst())
10786         continue;
10787       // This is an unknown instruction. Assume it escapes or writes to all
10788       // static alloca operands.
10789       for (const Use &U : I.operands()) {
10790         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
10791           *Info = StaticAllocaInfo::Clobbered;
10792       }
10793       continue;
10794     }
10795 
10796     // If the stored value is a static alloca, mark it as escaped.
10797     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
10798       *Info = StaticAllocaInfo::Clobbered;
10799 
10800     // Check if the destination is a static alloca.
10801     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
10802     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
10803     if (!Info)
10804       continue;
10805     const AllocaInst *AI = cast<AllocaInst>(Dst);
10806 
10807     // Skip allocas that have been initialized or clobbered.
10808     if (*Info != StaticAllocaInfo::Unknown)
10809       continue;
10810 
10811     // Check if the stored value is an argument, and that this store fully
10812     // initializes the alloca.
10813     // If the argument type has padding bits we can't directly forward a pointer
10814     // as the upper bits may contain garbage.
10815     // Don't elide copies from the same argument twice.
10816     const Value *Val = SI->getValueOperand()->stripPointerCasts();
10817     const auto *Arg = dyn_cast<Argument>(Val);
10818     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
10819         Arg->getType()->isEmptyTy() ||
10820         DL.getTypeStoreSize(Arg->getType()) !=
10821             DL.getTypeAllocSize(AI->getAllocatedType()) ||
10822         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
10823         ArgCopyElisionCandidates.count(Arg)) {
10824       *Info = StaticAllocaInfo::Clobbered;
10825       continue;
10826     }
10827 
10828     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
10829                       << '\n');
10830 
10831     // Mark this alloca and store for argument copy elision.
10832     *Info = StaticAllocaInfo::Elidable;
10833     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
10834 
10835     // Stop scanning if we've seen all arguments. This will happen early in -O0
10836     // builds, which is useful, because -O0 builds have large entry blocks and
10837     // many allocas.
10838     if (ArgCopyElisionCandidates.size() == NumArgs)
10839       break;
10840   }
10841 }
10842 
10843 /// Try to elide argument copies from memory into a local alloca. Succeeds if
10844 /// ArgVal is a load from a suitable fixed stack object.
10845 static void tryToElideArgumentCopy(
10846     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
10847     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
10848     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
10849     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
10850     ArrayRef<SDValue> ArgVals, bool &ArgHasUses) {
10851   // Check if this is a load from a fixed stack object.
10852   auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]);
10853   if (!LNode)
10854     return;
10855   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
10856   if (!FINode)
10857     return;
10858 
10859   // Check that the fixed stack object is the right size and alignment.
10860   // Look at the alignment that the user wrote on the alloca instead of looking
10861   // at the stack object.
10862   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
10863   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
10864   const AllocaInst *AI = ArgCopyIter->second.first;
10865   int FixedIndex = FINode->getIndex();
10866   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
10867   int OldIndex = AllocaIndex;
10868   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
10869   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
10870     LLVM_DEBUG(
10871         dbgs() << "  argument copy elision failed due to bad fixed stack "
10872                   "object size\n");
10873     return;
10874   }
10875   Align RequiredAlignment = AI->getAlign();
10876   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
10877     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
10878                          "greater than stack argument alignment ("
10879                       << DebugStr(RequiredAlignment) << " vs "
10880                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
10881     return;
10882   }
10883 
10884   // Perform the elision. Delete the old stack object and replace its only use
10885   // in the variable info map. Mark the stack object as mutable.
10886   LLVM_DEBUG({
10887     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
10888            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
10889            << '\n';
10890   });
10891   MFI.RemoveStackObject(OldIndex);
10892   MFI.setIsImmutableObjectIndex(FixedIndex, false);
10893   AllocaIndex = FixedIndex;
10894   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
10895   for (SDValue ArgVal : ArgVals)
10896     Chains.push_back(ArgVal.getValue(1));
10897 
10898   // Avoid emitting code for the store implementing the copy.
10899   const StoreInst *SI = ArgCopyIter->second.second;
10900   ElidedArgCopyInstrs.insert(SI);
10901 
10902   // Check for uses of the argument again so that we can avoid exporting ArgVal
10903   // if it is't used by anything other than the store.
10904   for (const Value *U : Arg.users()) {
10905     if (U != SI) {
10906       ArgHasUses = true;
10907       break;
10908     }
10909   }
10910 }
10911 
10912 void SelectionDAGISel::LowerArguments(const Function &F) {
10913   SelectionDAG &DAG = SDB->DAG;
10914   SDLoc dl = SDB->getCurSDLoc();
10915   const DataLayout &DL = DAG.getDataLayout();
10916   SmallVector<ISD::InputArg, 16> Ins;
10917 
10918   // In Naked functions we aren't going to save any registers.
10919   if (F.hasFnAttribute(Attribute::Naked))
10920     return;
10921 
10922   if (!FuncInfo->CanLowerReturn) {
10923     // Put in an sret pointer parameter before all the other parameters.
10924     SmallVector<EVT, 1> ValueVTs;
10925     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10926                     PointerType::get(F.getContext(),
10927                                      DAG.getDataLayout().getAllocaAddrSpace()),
10928                     ValueVTs);
10929 
10930     // NOTE: Assuming that a pointer will never break down to more than one VT
10931     // or one register.
10932     ISD::ArgFlagsTy Flags;
10933     Flags.setSRet();
10934     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
10935     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
10936                          ISD::InputArg::NoArgIndex, 0);
10937     Ins.push_back(RetArg);
10938   }
10939 
10940   // Look for stores of arguments to static allocas. Mark such arguments with a
10941   // flag to ask the target to give us the memory location of that argument if
10942   // available.
10943   ArgCopyElisionMapTy ArgCopyElisionCandidates;
10944   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
10945                                     ArgCopyElisionCandidates);
10946 
10947   // Set up the incoming argument description vector.
10948   for (const Argument &Arg : F.args()) {
10949     unsigned ArgNo = Arg.getArgNo();
10950     SmallVector<EVT, 4> ValueVTs;
10951     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10952     bool isArgValueUsed = !Arg.use_empty();
10953     unsigned PartBase = 0;
10954     Type *FinalType = Arg.getType();
10955     if (Arg.hasAttribute(Attribute::ByVal))
10956       FinalType = Arg.getParamByValType();
10957     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
10958         FinalType, F.getCallingConv(), F.isVarArg(), DL);
10959     for (unsigned Value = 0, NumValues = ValueVTs.size();
10960          Value != NumValues; ++Value) {
10961       EVT VT = ValueVTs[Value];
10962       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
10963       ISD::ArgFlagsTy Flags;
10964 
10965 
10966       if (Arg.getType()->isPointerTy()) {
10967         Flags.setPointer();
10968         Flags.setPointerAddrSpace(
10969             cast<PointerType>(Arg.getType())->getAddressSpace());
10970       }
10971       if (Arg.hasAttribute(Attribute::ZExt))
10972         Flags.setZExt();
10973       if (Arg.hasAttribute(Attribute::SExt))
10974         Flags.setSExt();
10975       if (Arg.hasAttribute(Attribute::InReg)) {
10976         // If we are using vectorcall calling convention, a structure that is
10977         // passed InReg - is surely an HVA
10978         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
10979             isa<StructType>(Arg.getType())) {
10980           // The first value of a structure is marked
10981           if (0 == Value)
10982             Flags.setHvaStart();
10983           Flags.setHva();
10984         }
10985         // Set InReg Flag
10986         Flags.setInReg();
10987       }
10988       if (Arg.hasAttribute(Attribute::StructRet))
10989         Flags.setSRet();
10990       if (Arg.hasAttribute(Attribute::SwiftSelf))
10991         Flags.setSwiftSelf();
10992       if (Arg.hasAttribute(Attribute::SwiftAsync))
10993         Flags.setSwiftAsync();
10994       if (Arg.hasAttribute(Attribute::SwiftError))
10995         Flags.setSwiftError();
10996       if (Arg.hasAttribute(Attribute::ByVal))
10997         Flags.setByVal();
10998       if (Arg.hasAttribute(Attribute::ByRef))
10999         Flags.setByRef();
11000       if (Arg.hasAttribute(Attribute::InAlloca)) {
11001         Flags.setInAlloca();
11002         // Set the byval flag for CCAssignFn callbacks that don't know about
11003         // inalloca.  This way we can know how many bytes we should've allocated
11004         // and how many bytes a callee cleanup function will pop.  If we port
11005         // inalloca to more targets, we'll have to add custom inalloca handling
11006         // in the various CC lowering callbacks.
11007         Flags.setByVal();
11008       }
11009       if (Arg.hasAttribute(Attribute::Preallocated)) {
11010         Flags.setPreallocated();
11011         // Set the byval flag for CCAssignFn callbacks that don't know about
11012         // preallocated.  This way we can know how many bytes we should've
11013         // allocated and how many bytes a callee cleanup function will pop.  If
11014         // we port preallocated to more targets, we'll have to add custom
11015         // preallocated handling in the various CC lowering callbacks.
11016         Flags.setByVal();
11017       }
11018 
11019       // Certain targets (such as MIPS), may have a different ABI alignment
11020       // for a type depending on the context. Give the target a chance to
11021       // specify the alignment it wants.
11022       const Align OriginalAlignment(
11023           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
11024       Flags.setOrigAlign(OriginalAlignment);
11025 
11026       Align MemAlign;
11027       Type *ArgMemTy = nullptr;
11028       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
11029           Flags.isByRef()) {
11030         if (!ArgMemTy)
11031           ArgMemTy = Arg.getPointeeInMemoryValueType();
11032 
11033         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
11034 
11035         // For in-memory arguments, size and alignment should be passed from FE.
11036         // BE will guess if this info is not there but there are cases it cannot
11037         // get right.
11038         if (auto ParamAlign = Arg.getParamStackAlign())
11039           MemAlign = *ParamAlign;
11040         else if ((ParamAlign = Arg.getParamAlign()))
11041           MemAlign = *ParamAlign;
11042         else
11043           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
11044         if (Flags.isByRef())
11045           Flags.setByRefSize(MemSize);
11046         else
11047           Flags.setByValSize(MemSize);
11048       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
11049         MemAlign = *ParamAlign;
11050       } else {
11051         MemAlign = OriginalAlignment;
11052       }
11053       Flags.setMemAlign(MemAlign);
11054 
11055       if (Arg.hasAttribute(Attribute::Nest))
11056         Flags.setNest();
11057       if (NeedsRegBlock)
11058         Flags.setInConsecutiveRegs();
11059       if (ArgCopyElisionCandidates.count(&Arg))
11060         Flags.setCopyElisionCandidate();
11061       if (Arg.hasAttribute(Attribute::Returned))
11062         Flags.setReturned();
11063 
11064       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
11065           *CurDAG->getContext(), F.getCallingConv(), VT);
11066       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
11067           *CurDAG->getContext(), F.getCallingConv(), VT);
11068       for (unsigned i = 0; i != NumRegs; ++i) {
11069         // For scalable vectors, use the minimum size; individual targets
11070         // are responsible for handling scalable vector arguments and
11071         // return values.
11072         ISD::InputArg MyFlags(
11073             Flags, RegisterVT, VT, isArgValueUsed, ArgNo,
11074             PartBase + i * RegisterVT.getStoreSize().getKnownMinValue());
11075         if (NumRegs > 1 && i == 0)
11076           MyFlags.Flags.setSplit();
11077         // if it isn't first piece, alignment must be 1
11078         else if (i > 0) {
11079           MyFlags.Flags.setOrigAlign(Align(1));
11080           if (i == NumRegs - 1)
11081             MyFlags.Flags.setSplitEnd();
11082         }
11083         Ins.push_back(MyFlags);
11084       }
11085       if (NeedsRegBlock && Value == NumValues - 1)
11086         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
11087       PartBase += VT.getStoreSize().getKnownMinValue();
11088     }
11089   }
11090 
11091   // Call the target to set up the argument values.
11092   SmallVector<SDValue, 8> InVals;
11093   SDValue NewRoot = TLI->LowerFormalArguments(
11094       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
11095 
11096   // Verify that the target's LowerFormalArguments behaved as expected.
11097   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
11098          "LowerFormalArguments didn't return a valid chain!");
11099   assert(InVals.size() == Ins.size() &&
11100          "LowerFormalArguments didn't emit the correct number of values!");
11101   LLVM_DEBUG({
11102     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
11103       assert(InVals[i].getNode() &&
11104              "LowerFormalArguments emitted a null value!");
11105       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
11106              "LowerFormalArguments emitted a value with the wrong type!");
11107     }
11108   });
11109 
11110   // Update the DAG with the new chain value resulting from argument lowering.
11111   DAG.setRoot(NewRoot);
11112 
11113   // Set up the argument values.
11114   unsigned i = 0;
11115   if (!FuncInfo->CanLowerReturn) {
11116     // Create a virtual register for the sret pointer, and put in a copy
11117     // from the sret argument into it.
11118     SmallVector<EVT, 1> ValueVTs;
11119     ComputeValueVTs(*TLI, DAG.getDataLayout(),
11120                     PointerType::get(F.getContext(),
11121                                      DAG.getDataLayout().getAllocaAddrSpace()),
11122                     ValueVTs);
11123     MVT VT = ValueVTs[0].getSimpleVT();
11124     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
11125     std::optional<ISD::NodeType> AssertOp;
11126     SDValue ArgValue =
11127         getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, nullptr, NewRoot,
11128                          F.getCallingConv(), AssertOp);
11129 
11130     MachineFunction& MF = SDB->DAG.getMachineFunction();
11131     MachineRegisterInfo& RegInfo = MF.getRegInfo();
11132     Register SRetReg =
11133         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
11134     FuncInfo->DemoteRegister = SRetReg;
11135     NewRoot =
11136         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
11137     DAG.setRoot(NewRoot);
11138 
11139     // i indexes lowered arguments.  Bump it past the hidden sret argument.
11140     ++i;
11141   }
11142 
11143   SmallVector<SDValue, 4> Chains;
11144   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
11145   for (const Argument &Arg : F.args()) {
11146     SmallVector<SDValue, 4> ArgValues;
11147     SmallVector<EVT, 4> ValueVTs;
11148     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
11149     unsigned NumValues = ValueVTs.size();
11150     if (NumValues == 0)
11151       continue;
11152 
11153     bool ArgHasUses = !Arg.use_empty();
11154 
11155     // Elide the copying store if the target loaded this argument from a
11156     // suitable fixed stack object.
11157     if (Ins[i].Flags.isCopyElisionCandidate()) {
11158       unsigned NumParts = 0;
11159       for (EVT VT : ValueVTs)
11160         NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(),
11161                                                        F.getCallingConv(), VT);
11162 
11163       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
11164                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
11165                              ArrayRef(&InVals[i], NumParts), ArgHasUses);
11166     }
11167 
11168     // If this argument is unused then remember its value. It is used to generate
11169     // debugging information.
11170     bool isSwiftErrorArg =
11171         TLI->supportSwiftError() &&
11172         Arg.hasAttribute(Attribute::SwiftError);
11173     if (!ArgHasUses && !isSwiftErrorArg) {
11174       SDB->setUnusedArgValue(&Arg, InVals[i]);
11175 
11176       // Also remember any frame index for use in FastISel.
11177       if (FrameIndexSDNode *FI =
11178           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
11179         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11180     }
11181 
11182     for (unsigned Val = 0; Val != NumValues; ++Val) {
11183       EVT VT = ValueVTs[Val];
11184       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
11185                                                       F.getCallingConv(), VT);
11186       unsigned NumParts = TLI->getNumRegistersForCallingConv(
11187           *CurDAG->getContext(), F.getCallingConv(), VT);
11188 
11189       // Even an apparent 'unused' swifterror argument needs to be returned. So
11190       // we do generate a copy for it that can be used on return from the
11191       // function.
11192       if (ArgHasUses || isSwiftErrorArg) {
11193         std::optional<ISD::NodeType> AssertOp;
11194         if (Arg.hasAttribute(Attribute::SExt))
11195           AssertOp = ISD::AssertSext;
11196         else if (Arg.hasAttribute(Attribute::ZExt))
11197           AssertOp = ISD::AssertZext;
11198 
11199         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
11200                                              PartVT, VT, nullptr, NewRoot,
11201                                              F.getCallingConv(), AssertOp));
11202       }
11203 
11204       i += NumParts;
11205     }
11206 
11207     // We don't need to do anything else for unused arguments.
11208     if (ArgValues.empty())
11209       continue;
11210 
11211     // Note down frame index.
11212     if (FrameIndexSDNode *FI =
11213         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
11214       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11215 
11216     SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues),
11217                                      SDB->getCurSDLoc());
11218 
11219     SDB->setValue(&Arg, Res);
11220     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
11221       // We want to associate the argument with the frame index, among
11222       // involved operands, that correspond to the lowest address. The
11223       // getCopyFromParts function, called earlier, is swapping the order of
11224       // the operands to BUILD_PAIR depending on endianness. The result of
11225       // that swapping is that the least significant bits of the argument will
11226       // be in the first operand of the BUILD_PAIR node, and the most
11227       // significant bits will be in the second operand.
11228       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
11229       if (LoadSDNode *LNode =
11230           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
11231         if (FrameIndexSDNode *FI =
11232             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
11233           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11234     }
11235 
11236     // Analyses past this point are naive and don't expect an assertion.
11237     if (Res.getOpcode() == ISD::AssertZext)
11238       Res = Res.getOperand(0);
11239 
11240     // Update the SwiftErrorVRegDefMap.
11241     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
11242       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11243       if (Register::isVirtualRegister(Reg))
11244         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
11245                                    Reg);
11246     }
11247 
11248     // If this argument is live outside of the entry block, insert a copy from
11249     // wherever we got it to the vreg that other BB's will reference it as.
11250     if (Res.getOpcode() == ISD::CopyFromReg) {
11251       // If we can, though, try to skip creating an unnecessary vreg.
11252       // FIXME: This isn't very clean... it would be nice to make this more
11253       // general.
11254       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11255       if (Register::isVirtualRegister(Reg)) {
11256         FuncInfo->ValueMap[&Arg] = Reg;
11257         continue;
11258       }
11259     }
11260     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
11261       FuncInfo->InitializeRegForValue(&Arg);
11262       SDB->CopyToExportRegsIfNeeded(&Arg);
11263     }
11264   }
11265 
11266   if (!Chains.empty()) {
11267     Chains.push_back(NewRoot);
11268     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
11269   }
11270 
11271   DAG.setRoot(NewRoot);
11272 
11273   assert(i == InVals.size() && "Argument register count mismatch!");
11274 
11275   // If any argument copy elisions occurred and we have debug info, update the
11276   // stale frame indices used in the dbg.declare variable info table.
11277   if (!ArgCopyElisionFrameIndexMap.empty()) {
11278     for (MachineFunction::VariableDbgInfo &VI :
11279          MF->getInStackSlotVariableDbgInfo()) {
11280       auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot());
11281       if (I != ArgCopyElisionFrameIndexMap.end())
11282         VI.updateStackSlot(I->second);
11283     }
11284   }
11285 
11286   // Finally, if the target has anything special to do, allow it to do so.
11287   emitFunctionEntryCode();
11288 }
11289 
11290 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
11291 /// ensure constants are generated when needed.  Remember the virtual registers
11292 /// that need to be added to the Machine PHI nodes as input.  We cannot just
11293 /// directly add them, because expansion might result in multiple MBB's for one
11294 /// BB.  As such, the start of the BB might correspond to a different MBB than
11295 /// the end.
11296 void
11297 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
11298   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11299 
11300   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
11301 
11302   // Check PHI nodes in successors that expect a value to be available from this
11303   // block.
11304   for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
11305     if (!isa<PHINode>(SuccBB->begin())) continue;
11306     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
11307 
11308     // If this terminator has multiple identical successors (common for
11309     // switches), only handle each succ once.
11310     if (!SuccsHandled.insert(SuccMBB).second)
11311       continue;
11312 
11313     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
11314 
11315     // At this point we know that there is a 1-1 correspondence between LLVM PHI
11316     // nodes and Machine PHI nodes, but the incoming operands have not been
11317     // emitted yet.
11318     for (const PHINode &PN : SuccBB->phis()) {
11319       // Ignore dead phi's.
11320       if (PN.use_empty())
11321         continue;
11322 
11323       // Skip empty types
11324       if (PN.getType()->isEmptyTy())
11325         continue;
11326 
11327       unsigned Reg;
11328       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
11329 
11330       if (const auto *C = dyn_cast<Constant>(PHIOp)) {
11331         unsigned &RegOut = ConstantsOut[C];
11332         if (RegOut == 0) {
11333           RegOut = FuncInfo.CreateRegs(C);
11334           // We need to zero/sign extend ConstantInt phi operands to match
11335           // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
11336           ISD::NodeType ExtendType = ISD::ANY_EXTEND;
11337           if (auto *CI = dyn_cast<ConstantInt>(C))
11338             ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
11339                                                     : ISD::ZERO_EXTEND;
11340           CopyValueToVirtualRegister(C, RegOut, ExtendType);
11341         }
11342         Reg = RegOut;
11343       } else {
11344         DenseMap<const Value *, Register>::iterator I =
11345           FuncInfo.ValueMap.find(PHIOp);
11346         if (I != FuncInfo.ValueMap.end())
11347           Reg = I->second;
11348         else {
11349           assert(isa<AllocaInst>(PHIOp) &&
11350                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
11351                  "Didn't codegen value into a register!??");
11352           Reg = FuncInfo.CreateRegs(PHIOp);
11353           CopyValueToVirtualRegister(PHIOp, Reg);
11354         }
11355       }
11356 
11357       // Remember that this register needs to added to the machine PHI node as
11358       // the input for this MBB.
11359       SmallVector<EVT, 4> ValueVTs;
11360       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
11361       for (EVT VT : ValueVTs) {
11362         const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
11363         for (unsigned i = 0; i != NumRegisters; ++i)
11364           FuncInfo.PHINodesToUpdate.push_back(
11365               std::make_pair(&*MBBI++, Reg + i));
11366         Reg += NumRegisters;
11367       }
11368     }
11369   }
11370 
11371   ConstantsOut.clear();
11372 }
11373 
11374 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
11375   MachineFunction::iterator I(MBB);
11376   if (++I == FuncInfo.MF->end())
11377     return nullptr;
11378   return &*I;
11379 }
11380 
11381 /// During lowering new call nodes can be created (such as memset, etc.).
11382 /// Those will become new roots of the current DAG, but complications arise
11383 /// when they are tail calls. In such cases, the call lowering will update
11384 /// the root, but the builder still needs to know that a tail call has been
11385 /// lowered in order to avoid generating an additional return.
11386 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
11387   // If the node is null, we do have a tail call.
11388   if (MaybeTC.getNode() != nullptr)
11389     DAG.setRoot(MaybeTC);
11390   else
11391     HasTailCall = true;
11392 }
11393 
11394 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
11395                                         MachineBasicBlock *SwitchMBB,
11396                                         MachineBasicBlock *DefaultMBB) {
11397   MachineFunction *CurMF = FuncInfo.MF;
11398   MachineBasicBlock *NextMBB = nullptr;
11399   MachineFunction::iterator BBI(W.MBB);
11400   if (++BBI != FuncInfo.MF->end())
11401     NextMBB = &*BBI;
11402 
11403   unsigned Size = W.LastCluster - W.FirstCluster + 1;
11404 
11405   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11406 
11407   if (Size == 2 && W.MBB == SwitchMBB) {
11408     // If any two of the cases has the same destination, and if one value
11409     // is the same as the other, but has one bit unset that the other has set,
11410     // use bit manipulation to do two compares at once.  For example:
11411     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
11412     // TODO: This could be extended to merge any 2 cases in switches with 3
11413     // cases.
11414     // TODO: Handle cases where W.CaseBB != SwitchBB.
11415     CaseCluster &Small = *W.FirstCluster;
11416     CaseCluster &Big = *W.LastCluster;
11417 
11418     if (Small.Low == Small.High && Big.Low == Big.High &&
11419         Small.MBB == Big.MBB) {
11420       const APInt &SmallValue = Small.Low->getValue();
11421       const APInt &BigValue = Big.Low->getValue();
11422 
11423       // Check that there is only one bit different.
11424       APInt CommonBit = BigValue ^ SmallValue;
11425       if (CommonBit.isPowerOf2()) {
11426         SDValue CondLHS = getValue(Cond);
11427         EVT VT = CondLHS.getValueType();
11428         SDLoc DL = getCurSDLoc();
11429 
11430         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
11431                                  DAG.getConstant(CommonBit, DL, VT));
11432         SDValue Cond = DAG.getSetCC(
11433             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
11434             ISD::SETEQ);
11435 
11436         // Update successor info.
11437         // Both Small and Big will jump to Small.BB, so we sum up the
11438         // probabilities.
11439         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
11440         if (BPI)
11441           addSuccessorWithProb(
11442               SwitchMBB, DefaultMBB,
11443               // The default destination is the first successor in IR.
11444               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
11445         else
11446           addSuccessorWithProb(SwitchMBB, DefaultMBB);
11447 
11448         // Insert the true branch.
11449         SDValue BrCond =
11450             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
11451                         DAG.getBasicBlock(Small.MBB));
11452         // Insert the false branch.
11453         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
11454                              DAG.getBasicBlock(DefaultMBB));
11455 
11456         DAG.setRoot(BrCond);
11457         return;
11458       }
11459     }
11460   }
11461 
11462   if (TM.getOptLevel() != CodeGenOptLevel::None) {
11463     // Here, we order cases by probability so the most likely case will be
11464     // checked first. However, two clusters can have the same probability in
11465     // which case their relative ordering is non-deterministic. So we use Low
11466     // as a tie-breaker as clusters are guaranteed to never overlap.
11467     llvm::sort(W.FirstCluster, W.LastCluster + 1,
11468                [](const CaseCluster &a, const CaseCluster &b) {
11469       return a.Prob != b.Prob ?
11470              a.Prob > b.Prob :
11471              a.Low->getValue().slt(b.Low->getValue());
11472     });
11473 
11474     // Rearrange the case blocks so that the last one falls through if possible
11475     // without changing the order of probabilities.
11476     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
11477       --I;
11478       if (I->Prob > W.LastCluster->Prob)
11479         break;
11480       if (I->Kind == CC_Range && I->MBB == NextMBB) {
11481         std::swap(*I, *W.LastCluster);
11482         break;
11483       }
11484     }
11485   }
11486 
11487   // Compute total probability.
11488   BranchProbability DefaultProb = W.DefaultProb;
11489   BranchProbability UnhandledProbs = DefaultProb;
11490   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
11491     UnhandledProbs += I->Prob;
11492 
11493   MachineBasicBlock *CurMBB = W.MBB;
11494   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
11495     bool FallthroughUnreachable = false;
11496     MachineBasicBlock *Fallthrough;
11497     if (I == W.LastCluster) {
11498       // For the last cluster, fall through to the default destination.
11499       Fallthrough = DefaultMBB;
11500       FallthroughUnreachable = isa<UnreachableInst>(
11501           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
11502     } else {
11503       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
11504       CurMF->insert(BBI, Fallthrough);
11505       // Put Cond in a virtual register to make it available from the new blocks.
11506       ExportFromCurrentBlock(Cond);
11507     }
11508     UnhandledProbs -= I->Prob;
11509 
11510     switch (I->Kind) {
11511       case CC_JumpTable: {
11512         // FIXME: Optimize away range check based on pivot comparisons.
11513         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
11514         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
11515 
11516         // The jump block hasn't been inserted yet; insert it here.
11517         MachineBasicBlock *JumpMBB = JT->MBB;
11518         CurMF->insert(BBI, JumpMBB);
11519 
11520         auto JumpProb = I->Prob;
11521         auto FallthroughProb = UnhandledProbs;
11522 
11523         // If the default statement is a target of the jump table, we evenly
11524         // distribute the default probability to successors of CurMBB. Also
11525         // update the probability on the edge from JumpMBB to Fallthrough.
11526         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
11527                                               SE = JumpMBB->succ_end();
11528              SI != SE; ++SI) {
11529           if (*SI == DefaultMBB) {
11530             JumpProb += DefaultProb / 2;
11531             FallthroughProb -= DefaultProb / 2;
11532             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
11533             JumpMBB->normalizeSuccProbs();
11534             break;
11535           }
11536         }
11537 
11538         // If the default clause is unreachable, propagate that knowledge into
11539         // JTH->FallthroughUnreachable which will use it to suppress the range
11540         // check.
11541         //
11542         // However, don't do this if we're doing branch target enforcement,
11543         // because a table branch _without_ a range check can be a tempting JOP
11544         // gadget - out-of-bounds inputs that are impossible in correct
11545         // execution become possible again if an attacker can influence the
11546         // control flow. So if an attacker doesn't already have a BTI bypass
11547         // available, we don't want them to be able to get one out of this
11548         // table branch.
11549         if (FallthroughUnreachable) {
11550           Function &CurFunc = CurMF->getFunction();
11551           bool HasBranchTargetEnforcement = false;
11552           if (CurFunc.hasFnAttribute("branch-target-enforcement")) {
11553             HasBranchTargetEnforcement =
11554                 CurFunc.getFnAttribute("branch-target-enforcement")
11555                     .getValueAsBool();
11556           } else {
11557             HasBranchTargetEnforcement =
11558                 CurMF->getMMI().getModule()->getModuleFlag(
11559                     "branch-target-enforcement");
11560           }
11561           if (!HasBranchTargetEnforcement)
11562             JTH->FallthroughUnreachable = true;
11563         }
11564 
11565         if (!JTH->FallthroughUnreachable)
11566           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
11567         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
11568         CurMBB->normalizeSuccProbs();
11569 
11570         // The jump table header will be inserted in our current block, do the
11571         // range check, and fall through to our fallthrough block.
11572         JTH->HeaderBB = CurMBB;
11573         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
11574 
11575         // If we're in the right place, emit the jump table header right now.
11576         if (CurMBB == SwitchMBB) {
11577           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
11578           JTH->Emitted = true;
11579         }
11580         break;
11581       }
11582       case CC_BitTests: {
11583         // FIXME: Optimize away range check based on pivot comparisons.
11584         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
11585 
11586         // The bit test blocks haven't been inserted yet; insert them here.
11587         for (BitTestCase &BTC : BTB->Cases)
11588           CurMF->insert(BBI, BTC.ThisBB);
11589 
11590         // Fill in fields of the BitTestBlock.
11591         BTB->Parent = CurMBB;
11592         BTB->Default = Fallthrough;
11593 
11594         BTB->DefaultProb = UnhandledProbs;
11595         // If the cases in bit test don't form a contiguous range, we evenly
11596         // distribute the probability on the edge to Fallthrough to two
11597         // successors of CurMBB.
11598         if (!BTB->ContiguousRange) {
11599           BTB->Prob += DefaultProb / 2;
11600           BTB->DefaultProb -= DefaultProb / 2;
11601         }
11602 
11603         if (FallthroughUnreachable)
11604           BTB->FallthroughUnreachable = true;
11605 
11606         // If we're in the right place, emit the bit test header right now.
11607         if (CurMBB == SwitchMBB) {
11608           visitBitTestHeader(*BTB, SwitchMBB);
11609           BTB->Emitted = true;
11610         }
11611         break;
11612       }
11613       case CC_Range: {
11614         const Value *RHS, *LHS, *MHS;
11615         ISD::CondCode CC;
11616         if (I->Low == I->High) {
11617           // Check Cond == I->Low.
11618           CC = ISD::SETEQ;
11619           LHS = Cond;
11620           RHS=I->Low;
11621           MHS = nullptr;
11622         } else {
11623           // Check I->Low <= Cond <= I->High.
11624           CC = ISD::SETLE;
11625           LHS = I->Low;
11626           MHS = Cond;
11627           RHS = I->High;
11628         }
11629 
11630         // If Fallthrough is unreachable, fold away the comparison.
11631         if (FallthroughUnreachable)
11632           CC = ISD::SETTRUE;
11633 
11634         // The false probability is the sum of all unhandled cases.
11635         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
11636                      getCurSDLoc(), I->Prob, UnhandledProbs);
11637 
11638         if (CurMBB == SwitchMBB)
11639           visitSwitchCase(CB, SwitchMBB);
11640         else
11641           SL->SwitchCases.push_back(CB);
11642 
11643         break;
11644       }
11645     }
11646     CurMBB = Fallthrough;
11647   }
11648 }
11649 
11650 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
11651                                         const SwitchWorkListItem &W,
11652                                         Value *Cond,
11653                                         MachineBasicBlock *SwitchMBB) {
11654   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
11655          "Clusters not sorted?");
11656   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
11657 
11658   auto [LastLeft, FirstRight, LeftProb, RightProb] =
11659       SL->computeSplitWorkItemInfo(W);
11660 
11661   // Use the first element on the right as pivot since we will make less-than
11662   // comparisons against it.
11663   CaseClusterIt PivotCluster = FirstRight;
11664   assert(PivotCluster > W.FirstCluster);
11665   assert(PivotCluster <= W.LastCluster);
11666 
11667   CaseClusterIt FirstLeft = W.FirstCluster;
11668   CaseClusterIt LastRight = W.LastCluster;
11669 
11670   const ConstantInt *Pivot = PivotCluster->Low;
11671 
11672   // New blocks will be inserted immediately after the current one.
11673   MachineFunction::iterator BBI(W.MBB);
11674   ++BBI;
11675 
11676   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
11677   // we can branch to its destination directly if it's squeezed exactly in
11678   // between the known lower bound and Pivot - 1.
11679   MachineBasicBlock *LeftMBB;
11680   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
11681       FirstLeft->Low == W.GE &&
11682       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
11683     LeftMBB = FirstLeft->MBB;
11684   } else {
11685     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11686     FuncInfo.MF->insert(BBI, LeftMBB);
11687     WorkList.push_back(
11688         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
11689     // Put Cond in a virtual register to make it available from the new blocks.
11690     ExportFromCurrentBlock(Cond);
11691   }
11692 
11693   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
11694   // single cluster, RHS.Low == Pivot, and we can branch to its destination
11695   // directly if RHS.High equals the current upper bound.
11696   MachineBasicBlock *RightMBB;
11697   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
11698       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
11699     RightMBB = FirstRight->MBB;
11700   } else {
11701     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11702     FuncInfo.MF->insert(BBI, RightMBB);
11703     WorkList.push_back(
11704         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
11705     // Put Cond in a virtual register to make it available from the new blocks.
11706     ExportFromCurrentBlock(Cond);
11707   }
11708 
11709   // Create the CaseBlock record that will be used to lower the branch.
11710   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
11711                getCurSDLoc(), LeftProb, RightProb);
11712 
11713   if (W.MBB == SwitchMBB)
11714     visitSwitchCase(CB, SwitchMBB);
11715   else
11716     SL->SwitchCases.push_back(CB);
11717 }
11718 
11719 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
11720 // from the swith statement.
11721 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
11722                                             BranchProbability PeeledCaseProb) {
11723   if (PeeledCaseProb == BranchProbability::getOne())
11724     return BranchProbability::getZero();
11725   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
11726 
11727   uint32_t Numerator = CaseProb.getNumerator();
11728   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
11729   return BranchProbability(Numerator, std::max(Numerator, Denominator));
11730 }
11731 
11732 // Try to peel the top probability case if it exceeds the threshold.
11733 // Return current MachineBasicBlock for the switch statement if the peeling
11734 // does not occur.
11735 // If the peeling is performed, return the newly created MachineBasicBlock
11736 // for the peeled switch statement. Also update Clusters to remove the peeled
11737 // case. PeeledCaseProb is the BranchProbability for the peeled case.
11738 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
11739     const SwitchInst &SI, CaseClusterVector &Clusters,
11740     BranchProbability &PeeledCaseProb) {
11741   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11742   // Don't perform if there is only one cluster or optimizing for size.
11743   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
11744       TM.getOptLevel() == CodeGenOptLevel::None ||
11745       SwitchMBB->getParent()->getFunction().hasMinSize())
11746     return SwitchMBB;
11747 
11748   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
11749   unsigned PeeledCaseIndex = 0;
11750   bool SwitchPeeled = false;
11751   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
11752     CaseCluster &CC = Clusters[Index];
11753     if (CC.Prob < TopCaseProb)
11754       continue;
11755     TopCaseProb = CC.Prob;
11756     PeeledCaseIndex = Index;
11757     SwitchPeeled = true;
11758   }
11759   if (!SwitchPeeled)
11760     return SwitchMBB;
11761 
11762   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
11763                     << TopCaseProb << "\n");
11764 
11765   // Record the MBB for the peeled switch statement.
11766   MachineFunction::iterator BBI(SwitchMBB);
11767   ++BBI;
11768   MachineBasicBlock *PeeledSwitchMBB =
11769       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
11770   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
11771 
11772   ExportFromCurrentBlock(SI.getCondition());
11773   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
11774   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
11775                           nullptr,   nullptr,      TopCaseProb.getCompl()};
11776   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
11777 
11778   Clusters.erase(PeeledCaseIt);
11779   for (CaseCluster &CC : Clusters) {
11780     LLVM_DEBUG(
11781         dbgs() << "Scale the probablity for one cluster, before scaling: "
11782                << CC.Prob << "\n");
11783     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
11784     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
11785   }
11786   PeeledCaseProb = TopCaseProb;
11787   return PeeledSwitchMBB;
11788 }
11789 
11790 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
11791   // Extract cases from the switch.
11792   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11793   CaseClusterVector Clusters;
11794   Clusters.reserve(SI.getNumCases());
11795   for (auto I : SI.cases()) {
11796     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
11797     const ConstantInt *CaseVal = I.getCaseValue();
11798     BranchProbability Prob =
11799         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
11800             : BranchProbability(1, SI.getNumCases() + 1);
11801     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
11802   }
11803 
11804   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
11805 
11806   // Cluster adjacent cases with the same destination. We do this at all
11807   // optimization levels because it's cheap to do and will make codegen faster
11808   // if there are many clusters.
11809   sortAndRangeify(Clusters);
11810 
11811   // The branch probablity of the peeled case.
11812   BranchProbability PeeledCaseProb = BranchProbability::getZero();
11813   MachineBasicBlock *PeeledSwitchMBB =
11814       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
11815 
11816   // If there is only the default destination, jump there directly.
11817   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11818   if (Clusters.empty()) {
11819     assert(PeeledSwitchMBB == SwitchMBB);
11820     SwitchMBB->addSuccessor(DefaultMBB);
11821     if (DefaultMBB != NextBlock(SwitchMBB)) {
11822       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
11823                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
11824     }
11825     return;
11826   }
11827 
11828   SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(),
11829                      DAG.getBFI());
11830   SL->findBitTestClusters(Clusters, &SI);
11831 
11832   LLVM_DEBUG({
11833     dbgs() << "Case clusters: ";
11834     for (const CaseCluster &C : Clusters) {
11835       if (C.Kind == CC_JumpTable)
11836         dbgs() << "JT:";
11837       if (C.Kind == CC_BitTests)
11838         dbgs() << "BT:";
11839 
11840       C.Low->getValue().print(dbgs(), true);
11841       if (C.Low != C.High) {
11842         dbgs() << '-';
11843         C.High->getValue().print(dbgs(), true);
11844       }
11845       dbgs() << ' ';
11846     }
11847     dbgs() << '\n';
11848   });
11849 
11850   assert(!Clusters.empty());
11851   SwitchWorkList WorkList;
11852   CaseClusterIt First = Clusters.begin();
11853   CaseClusterIt Last = Clusters.end() - 1;
11854   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
11855   // Scale the branchprobability for DefaultMBB if the peel occurs and
11856   // DefaultMBB is not replaced.
11857   if (PeeledCaseProb != BranchProbability::getZero() &&
11858       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
11859     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
11860   WorkList.push_back(
11861       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
11862 
11863   while (!WorkList.empty()) {
11864     SwitchWorkListItem W = WorkList.pop_back_val();
11865     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
11866 
11867     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None &&
11868         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
11869       // For optimized builds, lower large range as a balanced binary tree.
11870       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
11871       continue;
11872     }
11873 
11874     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
11875   }
11876 }
11877 
11878 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
11879   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11880   auto DL = getCurSDLoc();
11881   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11882   setValue(&I, DAG.getStepVector(DL, ResultVT));
11883 }
11884 
11885 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
11886   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11887   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11888 
11889   SDLoc DL = getCurSDLoc();
11890   SDValue V = getValue(I.getOperand(0));
11891   assert(VT == V.getValueType() && "Malformed vector.reverse!");
11892 
11893   if (VT.isScalableVector()) {
11894     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
11895     return;
11896   }
11897 
11898   // Use VECTOR_SHUFFLE for the fixed-length vector
11899   // to maintain existing behavior.
11900   SmallVector<int, 8> Mask;
11901   unsigned NumElts = VT.getVectorMinNumElements();
11902   for (unsigned i = 0; i != NumElts; ++i)
11903     Mask.push_back(NumElts - 1 - i);
11904 
11905   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
11906 }
11907 
11908 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) {
11909   auto DL = getCurSDLoc();
11910   SDValue InVec = getValue(I.getOperand(0));
11911   EVT OutVT =
11912       InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
11913 
11914   unsigned OutNumElts = OutVT.getVectorMinNumElements();
11915 
11916   // ISD Node needs the input vectors split into two equal parts
11917   SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
11918                            DAG.getVectorIdxConstant(0, DL));
11919   SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
11920                            DAG.getVectorIdxConstant(OutNumElts, DL));
11921 
11922   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
11923   // legalisation and combines.
11924   if (OutVT.isFixedLengthVector()) {
11925     SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
11926                                         createStrideMask(0, 2, OutNumElts));
11927     SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
11928                                        createStrideMask(1, 2, OutNumElts));
11929     SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc());
11930     setValue(&I, Res);
11931     return;
11932   }
11933 
11934   SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL,
11935                             DAG.getVTList(OutVT, OutVT), Lo, Hi);
11936   setValue(&I, Res);
11937 }
11938 
11939 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) {
11940   auto DL = getCurSDLoc();
11941   EVT InVT = getValue(I.getOperand(0)).getValueType();
11942   SDValue InVec0 = getValue(I.getOperand(0));
11943   SDValue InVec1 = getValue(I.getOperand(1));
11944   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11945   EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11946 
11947   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
11948   // legalisation and combines.
11949   if (OutVT.isFixedLengthVector()) {
11950     unsigned NumElts = InVT.getVectorMinNumElements();
11951     SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1);
11952     setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT),
11953                                       createInterleaveMask(NumElts, 2)));
11954     return;
11955   }
11956 
11957   SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL,
11958                             DAG.getVTList(InVT, InVT), InVec0, InVec1);
11959   Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0),
11960                     Res.getValue(1));
11961   setValue(&I, Res);
11962 }
11963 
11964 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
11965   SmallVector<EVT, 4> ValueVTs;
11966   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
11967                   ValueVTs);
11968   unsigned NumValues = ValueVTs.size();
11969   if (NumValues == 0) return;
11970 
11971   SmallVector<SDValue, 4> Values(NumValues);
11972   SDValue Op = getValue(I.getOperand(0));
11973 
11974   for (unsigned i = 0; i != NumValues; ++i)
11975     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
11976                             SDValue(Op.getNode(), Op.getResNo() + i));
11977 
11978   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
11979                            DAG.getVTList(ValueVTs), Values));
11980 }
11981 
11982 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
11983   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11984   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11985 
11986   SDLoc DL = getCurSDLoc();
11987   SDValue V1 = getValue(I.getOperand(0));
11988   SDValue V2 = getValue(I.getOperand(1));
11989   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
11990 
11991   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
11992   if (VT.isScalableVector()) {
11993     MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
11994     setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
11995                              DAG.getConstant(Imm, DL, IdxVT)));
11996     return;
11997   }
11998 
11999   unsigned NumElts = VT.getVectorNumElements();
12000 
12001   uint64_t Idx = (NumElts + Imm) % NumElts;
12002 
12003   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
12004   SmallVector<int, 8> Mask;
12005   for (unsigned i = 0; i < NumElts; ++i)
12006     Mask.push_back(Idx + i);
12007   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
12008 }
12009 
12010 // Consider the following MIR after SelectionDAG, which produces output in
12011 // phyregs in the first case or virtregs in the second case.
12012 //
12013 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx
12014 // %5:gr32 = COPY $ebx
12015 // %6:gr32 = COPY $edx
12016 // %1:gr32 = COPY %6:gr32
12017 // %0:gr32 = COPY %5:gr32
12018 //
12019 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32
12020 // %1:gr32 = COPY %6:gr32
12021 // %0:gr32 = COPY %5:gr32
12022 //
12023 // Given %0, we'd like to return $ebx in the first case and %5 in the second.
12024 // Given %1, we'd like to return $edx in the first case and %6 in the second.
12025 //
12026 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap
12027 // to a single virtreg (such as %0). The remaining outputs monotonically
12028 // increase in virtreg number from there. If a callbr has no outputs, then it
12029 // should not have a corresponding callbr landingpad; in fact, the callbr
12030 // landingpad would not even be able to refer to such a callbr.
12031 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) {
12032   MachineInstr *MI = MRI.def_begin(Reg)->getParent();
12033   // There is definitely at least one copy.
12034   assert(MI->getOpcode() == TargetOpcode::COPY &&
12035          "start of copy chain MUST be COPY");
12036   Reg = MI->getOperand(1).getReg();
12037   MI = MRI.def_begin(Reg)->getParent();
12038   // There may be an optional second copy.
12039   if (MI->getOpcode() == TargetOpcode::COPY) {
12040     assert(Reg.isVirtual() && "expected COPY of virtual register");
12041     Reg = MI->getOperand(1).getReg();
12042     assert(Reg.isPhysical() && "expected COPY of physical register");
12043     MI = MRI.def_begin(Reg)->getParent();
12044   }
12045   // The start of the chain must be an INLINEASM_BR.
12046   assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR &&
12047          "end of copy chain MUST be INLINEASM_BR");
12048   return Reg;
12049 }
12050 
12051 // We must do this walk rather than the simpler
12052 //   setValue(&I, getCopyFromRegs(CBR, CBR->getType()));
12053 // otherwise we will end up with copies of virtregs only valid along direct
12054 // edges.
12055 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) {
12056   SmallVector<EVT, 8> ResultVTs;
12057   SmallVector<SDValue, 8> ResultValues;
12058   const auto *CBR =
12059       cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator());
12060 
12061   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12062   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
12063   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
12064 
12065   unsigned InitialDef = FuncInfo.ValueMap[CBR];
12066   SDValue Chain = DAG.getRoot();
12067 
12068   // Re-parse the asm constraints string.
12069   TargetLowering::AsmOperandInfoVector TargetConstraints =
12070       TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR);
12071   for (auto &T : TargetConstraints) {
12072     SDISelAsmOperandInfo OpInfo(T);
12073     if (OpInfo.Type != InlineAsm::isOutput)
12074       continue;
12075 
12076     // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the
12077     // individual constraint.
12078     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
12079 
12080     switch (OpInfo.ConstraintType) {
12081     case TargetLowering::C_Register:
12082     case TargetLowering::C_RegisterClass: {
12083       // Fill in OpInfo.AssignedRegs.Regs.
12084       getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo);
12085 
12086       // getRegistersForValue may produce 1 to many registers based on whether
12087       // the OpInfo.ConstraintVT is legal on the target or not.
12088       for (size_t i = 0, e = OpInfo.AssignedRegs.Regs.size(); i != e; ++i) {
12089         Register OriginalDef = FollowCopyChain(MRI, InitialDef++);
12090         if (Register::isPhysicalRegister(OriginalDef))
12091           FuncInfo.MBB->addLiveIn(OriginalDef);
12092         // Update the assigned registers to use the original defs.
12093         OpInfo.AssignedRegs.Regs[i] = OriginalDef;
12094       }
12095 
12096       SDValue V = OpInfo.AssignedRegs.getCopyFromRegs(
12097           DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR);
12098       ResultValues.push_back(V);
12099       ResultVTs.push_back(OpInfo.ConstraintVT);
12100       break;
12101     }
12102     case TargetLowering::C_Other: {
12103       SDValue Flag;
12104       SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
12105                                                   OpInfo, DAG);
12106       ++InitialDef;
12107       ResultValues.push_back(V);
12108       ResultVTs.push_back(OpInfo.ConstraintVT);
12109       break;
12110     }
12111     default:
12112       break;
12113     }
12114   }
12115   SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12116                           DAG.getVTList(ResultVTs), ResultValues);
12117   setValue(&I, V);
12118 }
12119