xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 943f3e52a0532d1d2b5c743635e1aed15033154b)
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                                       std::optional<CallingConv::ID> CC);
157 
158 /// getCopyFromParts - Create a value that contains the specified legal parts
159 /// combined into the value they represent.  If the parts combine to a type
160 /// larger than ValueVT then AssertOp can be used to specify whether the extra
161 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
162 /// (ISD::AssertSext).
163 static SDValue
164 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts,
165                  unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V,
166                  std::optional<CallingConv::ID> CC = std::nullopt,
167                  std::optional<ISD::NodeType> AssertOp = std::nullopt) {
168   // Let the target assemble the parts if it wants to
169   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
170   if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
171                                                    PartVT, ValueVT, CC))
172     return Val;
173 
174   if (ValueVT.isVector())
175     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
176                                   CC);
177 
178   assert(NumParts > 0 && "No parts to assemble!");
179   SDValue Val = Parts[0];
180 
181   if (NumParts > 1) {
182     // Assemble the value from multiple parts.
183     if (ValueVT.isInteger()) {
184       unsigned PartBits = PartVT.getSizeInBits();
185       unsigned ValueBits = ValueVT.getSizeInBits();
186 
187       // Assemble the power of 2 part.
188       unsigned RoundParts = llvm::bit_floor(NumParts);
189       unsigned RoundBits = PartBits * RoundParts;
190       EVT RoundVT = RoundBits == ValueBits ?
191         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
192       SDValue Lo, Hi;
193 
194       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
195 
196       if (RoundParts > 2) {
197         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
198                               PartVT, HalfVT, V);
199         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
200                               RoundParts / 2, PartVT, HalfVT, V);
201       } else {
202         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
203         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
204       }
205 
206       if (DAG.getDataLayout().isBigEndian())
207         std::swap(Lo, Hi);
208 
209       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
210 
211       if (RoundParts < NumParts) {
212         // Assemble the trailing non-power-of-2 part.
213         unsigned OddParts = NumParts - RoundParts;
214         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
215         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
216                               OddVT, V, CC);
217 
218         // Combine the round and odd parts.
219         Lo = Val;
220         if (DAG.getDataLayout().isBigEndian())
221           std::swap(Lo, Hi);
222         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
223         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
224         Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
225                          DAG.getConstant(Lo.getValueSizeInBits(), DL,
226                                          TLI.getShiftAmountTy(
227                                              TotalVT, DAG.getDataLayout())));
228         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
229         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
230       }
231     } else if (PartVT.isFloatingPoint()) {
232       // FP split into multiple FP parts (for ppcf128)
233       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
234              "Unexpected split");
235       SDValue Lo, Hi;
236       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
237       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
238       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
239         std::swap(Lo, Hi);
240       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
241     } else {
242       // FP split into integer parts (soft fp)
243       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
244              !PartVT.isVector() && "Unexpected split");
245       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
246       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
247     }
248   }
249 
250   // There is now one part, held in Val.  Correct it to match ValueVT.
251   // PartEVT is the type of the register class that holds the value.
252   // ValueVT is the type of the inline asm operation.
253   EVT PartEVT = Val.getValueType();
254 
255   if (PartEVT == ValueVT)
256     return Val;
257 
258   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
259       ValueVT.bitsLT(PartEVT)) {
260     // For an FP value in an integer part, we need to truncate to the right
261     // width first.
262     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
263     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
264   }
265 
266   // Handle types that have the same size.
267   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
268     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
269 
270   // Handle types with different sizes.
271   if (PartEVT.isInteger() && ValueVT.isInteger()) {
272     if (ValueVT.bitsLT(PartEVT)) {
273       // For a truncate, see if we have any information to
274       // indicate whether the truncated bits will always be
275       // zero or sign-extension.
276       if (AssertOp)
277         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
278                           DAG.getValueType(ValueVT));
279       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
280     }
281     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
282   }
283 
284   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
285     // FP_ROUND's are always exact here.
286     if (ValueVT.bitsLT(Val.getValueType()))
287       return DAG.getNode(
288           ISD::FP_ROUND, DL, ValueVT, Val,
289           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
290 
291     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
292   }
293 
294   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
295   // then truncating.
296   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
297       ValueVT.bitsLT(PartEVT)) {
298     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
299     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
300   }
301 
302   report_fatal_error("Unknown mismatch in getCopyFromParts!");
303 }
304 
305 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
306                                               const Twine &ErrMsg) {
307   const Instruction *I = dyn_cast_or_null<Instruction>(V);
308   if (!V)
309     return Ctx.emitError(ErrMsg);
310 
311   const char *AsmError = ", possible invalid constraint for vector type";
312   if (const CallInst *CI = dyn_cast<CallInst>(I))
313     if (CI->isInlineAsm())
314       return Ctx.emitError(I, ErrMsg + AsmError);
315 
316   return Ctx.emitError(I, ErrMsg);
317 }
318 
319 /// getCopyFromPartsVector - Create a value that contains the specified legal
320 /// parts combined into the value they represent.  If the parts combine to a
321 /// type larger than ValueVT then AssertOp can be used to specify whether the
322 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
323 /// ValueVT (ISD::AssertSext).
324 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
325                                       const SDValue *Parts, unsigned NumParts,
326                                       MVT PartVT, EVT ValueVT, const Value *V,
327                                       std::optional<CallingConv::ID> CallConv) {
328   assert(ValueVT.isVector() && "Not a vector value");
329   assert(NumParts > 0 && "No parts to assemble!");
330   const bool IsABIRegCopy = CallConv.has_value();
331 
332   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
333   SDValue Val = Parts[0];
334 
335   // Handle a multi-element vector.
336   if (NumParts > 1) {
337     EVT IntermediateVT;
338     MVT RegisterVT;
339     unsigned NumIntermediates;
340     unsigned NumRegs;
341 
342     if (IsABIRegCopy) {
343       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
344           *DAG.getContext(), *CallConv, ValueVT, IntermediateVT,
345           NumIntermediates, RegisterVT);
346     } else {
347       NumRegs =
348           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
349                                      NumIntermediates, RegisterVT);
350     }
351 
352     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
353     NumParts = NumRegs; // Silence a compiler warning.
354     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
355     assert(RegisterVT.getSizeInBits() ==
356            Parts[0].getSimpleValueType().getSizeInBits() &&
357            "Part type sizes don't match!");
358 
359     // Assemble the parts into intermediate operands.
360     SmallVector<SDValue, 8> Ops(NumIntermediates);
361     if (NumIntermediates == NumParts) {
362       // If the register was not expanded, truncate or copy the value,
363       // as appropriate.
364       for (unsigned i = 0; i != NumParts; ++i)
365         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
366                                   PartVT, IntermediateVT, V, CallConv);
367     } else if (NumParts > 0) {
368       // If the intermediate type was expanded, build the intermediate
369       // operands from the parts.
370       assert(NumParts % NumIntermediates == 0 &&
371              "Must expand into a divisible number of parts!");
372       unsigned Factor = NumParts / NumIntermediates;
373       for (unsigned i = 0; i != NumIntermediates; ++i)
374         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
375                                   PartVT, IntermediateVT, V, CallConv);
376     }
377 
378     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
379     // intermediate operands.
380     EVT BuiltVectorTy =
381         IntermediateVT.isVector()
382             ? EVT::getVectorVT(
383                   *DAG.getContext(), IntermediateVT.getScalarType(),
384                   IntermediateVT.getVectorElementCount() * NumParts)
385             : EVT::getVectorVT(*DAG.getContext(),
386                                IntermediateVT.getScalarType(),
387                                NumIntermediates);
388     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
389                                                 : ISD::BUILD_VECTOR,
390                       DL, BuiltVectorTy, Ops);
391   }
392 
393   // There is now one part, held in Val.  Correct it to match ValueVT.
394   EVT PartEVT = Val.getValueType();
395 
396   if (PartEVT == ValueVT)
397     return Val;
398 
399   if (PartEVT.isVector()) {
400     // Vector/Vector bitcast.
401     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
402       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
403 
404     // If the parts vector has more elements than the value vector, then we
405     // have a vector widening case (e.g. <2 x float> -> <4 x float>).
406     // Extract the elements we want.
407     if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
408       assert((PartEVT.getVectorElementCount().getKnownMinValue() >
409               ValueVT.getVectorElementCount().getKnownMinValue()) &&
410              (PartEVT.getVectorElementCount().isScalable() ==
411               ValueVT.getVectorElementCount().isScalable()) &&
412              "Cannot narrow, it would be a lossy transformation");
413       PartEVT =
414           EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(),
415                            ValueVT.getVectorElementCount());
416       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val,
417                         DAG.getVectorIdxConstant(0, DL));
418       if (PartEVT == ValueVT)
419         return Val;
420       if (PartEVT.isInteger() && ValueVT.isFloatingPoint())
421         return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
422 
423       // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>).
424       if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
425         return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
426     }
427 
428     // Promoted vector extract
429     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
430   }
431 
432   // Trivial bitcast if the types are the same size and the destination
433   // vector type is legal.
434   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
435       TLI.isTypeLegal(ValueVT))
436     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
437 
438   if (ValueVT.getVectorNumElements() != 1) {
439      // Certain ABIs require that vectors are passed as integers. For vectors
440      // are the same size, this is an obvious bitcast.
441      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
442        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
443      } else if (ValueVT.bitsLT(PartEVT)) {
444        const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
445        EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
446        // Drop the extra bits.
447        Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
448        return DAG.getBitcast(ValueVT, Val);
449      }
450 
451      diagnosePossiblyInvalidConstraint(
452          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
453      return DAG.getUNDEF(ValueVT);
454   }
455 
456   // Handle cases such as i8 -> <1 x i1>
457   EVT ValueSVT = ValueVT.getVectorElementType();
458   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
459     unsigned ValueSize = ValueSVT.getSizeInBits();
460     if (ValueSize == PartEVT.getSizeInBits()) {
461       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
462     } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) {
463       // It's possible a scalar floating point type gets softened to integer and
464       // then promoted to a larger integer. If PartEVT is the larger integer
465       // we need to truncate it and then bitcast to the FP type.
466       assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types");
467       EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
468       Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
469       Val = DAG.getBitcast(ValueSVT, Val);
470     } else {
471       Val = ValueVT.isFloatingPoint()
472                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
473                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
474     }
475   }
476 
477   return DAG.getBuildVector(ValueVT, DL, Val);
478 }
479 
480 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
481                                  SDValue Val, SDValue *Parts, unsigned NumParts,
482                                  MVT PartVT, const Value *V,
483                                  std::optional<CallingConv::ID> CallConv);
484 
485 /// getCopyToParts - Create a series of nodes that contain the specified value
486 /// split into legal parts.  If the parts contain more bits than Val, then, for
487 /// integers, ExtendKind can be used to specify how to generate the extra bits.
488 static void
489 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
490                unsigned NumParts, MVT PartVT, const Value *V,
491                std::optional<CallingConv::ID> CallConv = std::nullopt,
492                ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
493   // Let the target split the parts if it wants to
494   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
495   if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
496                                       CallConv))
497     return;
498   EVT ValueVT = Val.getValueType();
499 
500   // Handle the vector case separately.
501   if (ValueVT.isVector())
502     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
503                                 CallConv);
504 
505   unsigned OrigNumParts = NumParts;
506   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
507          "Copying to an illegal type!");
508 
509   if (NumParts == 0)
510     return;
511 
512   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
513   EVT PartEVT = PartVT;
514   if (PartEVT == ValueVT) {
515     assert(NumParts == 1 && "No-op copy with multiple parts!");
516     Parts[0] = Val;
517     return;
518   }
519 
520   unsigned PartBits = PartVT.getSizeInBits();
521   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
522     // If the parts cover more bits than the value has, promote the value.
523     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
524       assert(NumParts == 1 && "Do not know what to promote to!");
525       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
526     } else {
527       if (ValueVT.isFloatingPoint()) {
528         // FP values need to be bitcast, then extended if they are being put
529         // into a larger container.
530         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
531         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
532       }
533       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
534              ValueVT.isInteger() &&
535              "Unknown mismatch!");
536       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
537       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
538       if (PartVT == MVT::x86mmx)
539         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
540     }
541   } else if (PartBits == ValueVT.getSizeInBits()) {
542     // Different types of the same size.
543     assert(NumParts == 1 && PartEVT != ValueVT);
544     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
545   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
546     // If the parts cover less bits than value has, truncate the value.
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(ISD::TRUNCATE, DL, ValueVT, Val);
552     if (PartVT == MVT::x86mmx)
553       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
554   }
555 
556   // The value may have changed - recompute ValueVT.
557   ValueVT = Val.getValueType();
558   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
559          "Failed to tile the value with PartVT!");
560 
561   if (NumParts == 1) {
562     if (PartEVT != ValueVT) {
563       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
564                                         "scalar-to-vector conversion failed");
565       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
566     }
567 
568     Parts[0] = Val;
569     return;
570   }
571 
572   // Expand the value into multiple parts.
573   if (NumParts & (NumParts - 1)) {
574     // The number of parts is not a power of 2.  Split off and copy the tail.
575     assert(PartVT.isInteger() && ValueVT.isInteger() &&
576            "Do not know what to expand to!");
577     unsigned RoundParts = llvm::bit_floor(NumParts);
578     unsigned RoundBits = RoundParts * PartBits;
579     unsigned OddParts = NumParts - RoundParts;
580     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
581       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL));
582 
583     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
584                    CallConv);
585 
586     if (DAG.getDataLayout().isBigEndian())
587       // The odd parts were reversed by getCopyToParts - unreverse them.
588       std::reverse(Parts + RoundParts, Parts + NumParts);
589 
590     NumParts = RoundParts;
591     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
592     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
593   }
594 
595   // The number of parts is a power of 2.  Repeatedly bisect the value using
596   // EXTRACT_ELEMENT.
597   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
598                          EVT::getIntegerVT(*DAG.getContext(),
599                                            ValueVT.getSizeInBits()),
600                          Val);
601 
602   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
603     for (unsigned i = 0; i < NumParts; i += StepSize) {
604       unsigned ThisBits = StepSize * PartBits / 2;
605       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
606       SDValue &Part0 = Parts[i];
607       SDValue &Part1 = Parts[i+StepSize/2];
608 
609       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
610                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
611       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
612                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
613 
614       if (ThisBits == PartBits && ThisVT != PartVT) {
615         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
616         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
617       }
618     }
619   }
620 
621   if (DAG.getDataLayout().isBigEndian())
622     std::reverse(Parts, Parts + OrigNumParts);
623 }
624 
625 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val,
626                                      const SDLoc &DL, EVT PartVT) {
627   if (!PartVT.isVector())
628     return SDValue();
629 
630   EVT ValueVT = Val.getValueType();
631   EVT PartEVT = PartVT.getVectorElementType();
632   EVT ValueEVT = ValueVT.getVectorElementType();
633   ElementCount PartNumElts = PartVT.getVectorElementCount();
634   ElementCount ValueNumElts = ValueVT.getVectorElementCount();
635 
636   // We only support widening vectors with equivalent element types and
637   // fixed/scalable properties. If a target needs to widen a fixed-length type
638   // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
639   if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
640       PartNumElts.isScalable() != ValueNumElts.isScalable())
641     return SDValue();
642 
643   // Have a try for bf16 because some targets share its ABI with fp16.
644   if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) {
645     assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
646            "Cannot widen to illegal type");
647     Val = DAG.getNode(ISD::BITCAST, DL,
648                       ValueVT.changeVectorElementType(MVT::f16), Val);
649   } else if (PartEVT != ValueEVT) {
650     return SDValue();
651   }
652 
653   // Widening a scalable vector to another scalable vector is done by inserting
654   // the vector into a larger undef one.
655   if (PartNumElts.isScalable())
656     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
657                        Val, DAG.getVectorIdxConstant(0, DL));
658 
659   // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
660   // undef elements.
661   SmallVector<SDValue, 16> Ops;
662   DAG.ExtractVectorElements(Val, Ops);
663   SDValue EltUndef = DAG.getUNDEF(PartEVT);
664   Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
665 
666   // FIXME: Use CONCAT for 2x -> 4x.
667   return DAG.getBuildVector(PartVT, DL, Ops);
668 }
669 
670 /// getCopyToPartsVector - Create a series of nodes that contain the specified
671 /// value split into legal parts.
672 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
673                                  SDValue Val, SDValue *Parts, unsigned NumParts,
674                                  MVT PartVT, const Value *V,
675                                  std::optional<CallingConv::ID> CallConv) {
676   EVT ValueVT = Val.getValueType();
677   assert(ValueVT.isVector() && "Not a vector");
678   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
679   const bool IsABIRegCopy = CallConv.has_value();
680 
681   if (NumParts == 1) {
682     EVT PartEVT = PartVT;
683     if (PartEVT == ValueVT) {
684       // Nothing to do.
685     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
686       // Bitconvert vector->vector case.
687       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
688     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
689       Val = Widened;
690     } else if (PartVT.isVector() &&
691                PartEVT.getVectorElementType().bitsGE(
692                    ValueVT.getVectorElementType()) &&
693                PartEVT.getVectorElementCount() ==
694                    ValueVT.getVectorElementCount()) {
695 
696       // Promoted vector extract
697       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
698     } else if (PartEVT.isVector() &&
699                PartEVT.getVectorElementType() !=
700                    ValueVT.getVectorElementType() &&
701                TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
702                    TargetLowering::TypeWidenVector) {
703       // Combination of widening and promotion.
704       EVT WidenVT =
705           EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(),
706                            PartVT.getVectorElementCount());
707       SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
708       Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
709     } else {
710       // Don't extract an integer from a float vector. This can happen if the
711       // FP type gets softened to integer and then promoted. The promotion
712       // prevents it from being picked up by the earlier bitcast case.
713       if (ValueVT.getVectorElementCount().isScalar() &&
714           (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) {
715         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
716                           DAG.getVectorIdxConstant(0, DL));
717       } else {
718         uint64_t ValueSize = ValueVT.getFixedSizeInBits();
719         assert(PartVT.getFixedSizeInBits() > ValueSize &&
720                "lossy conversion of vector to scalar type");
721         EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
722         Val = DAG.getBitcast(IntermediateType, Val);
723         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
724       }
725     }
726 
727     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
728     Parts[0] = Val;
729     return;
730   }
731 
732   // Handle a multi-element vector.
733   EVT IntermediateVT;
734   MVT RegisterVT;
735   unsigned NumIntermediates;
736   unsigned NumRegs;
737   if (IsABIRegCopy) {
738     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
739         *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates,
740         RegisterVT);
741   } else {
742     NumRegs =
743         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
744                                    NumIntermediates, RegisterVT);
745   }
746 
747   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
748   NumParts = NumRegs; // Silence a compiler warning.
749   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
750 
751   assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
752          "Mixing scalable and fixed vectors when copying in parts");
753 
754   std::optional<ElementCount> DestEltCnt;
755 
756   if (IntermediateVT.isVector())
757     DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
758   else
759     DestEltCnt = ElementCount::getFixed(NumIntermediates);
760 
761   EVT BuiltVectorTy = EVT::getVectorVT(
762       *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt);
763 
764   if (ValueVT == BuiltVectorTy) {
765     // Nothing to do.
766   } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
767     // Bitconvert vector->vector case.
768     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
769   } else {
770     if (BuiltVectorTy.getVectorElementType().bitsGT(
771             ValueVT.getVectorElementType())) {
772       // Integer promotion.
773       ValueVT = EVT::getVectorVT(*DAG.getContext(),
774                                  BuiltVectorTy.getVectorElementType(),
775                                  ValueVT.getVectorElementCount());
776       Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
777     }
778 
779     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
780       Val = Widened;
781     }
782   }
783 
784   assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
785 
786   // Split the vector into intermediate operands.
787   SmallVector<SDValue, 8> Ops(NumIntermediates);
788   for (unsigned i = 0; i != NumIntermediates; ++i) {
789     if (IntermediateVT.isVector()) {
790       // This does something sensible for scalable vectors - see the
791       // definition of EXTRACT_SUBVECTOR for further details.
792       unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
793       Ops[i] =
794           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
795                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
796     } else {
797       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
798                            DAG.getVectorIdxConstant(i, DL));
799     }
800   }
801 
802   // Split the intermediate operands into legal parts.
803   if (NumParts == NumIntermediates) {
804     // If the register was not expanded, promote or copy the value,
805     // as appropriate.
806     for (unsigned i = 0; i != NumParts; ++i)
807       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
808   } else if (NumParts > 0) {
809     // If the intermediate type was expanded, split each the value into
810     // legal parts.
811     assert(NumIntermediates != 0 && "division by zero");
812     assert(NumParts % NumIntermediates == 0 &&
813            "Must expand into a divisible number of parts!");
814     unsigned Factor = NumParts / NumIntermediates;
815     for (unsigned i = 0; i != NumIntermediates; ++i)
816       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
817                      CallConv);
818   }
819 }
820 
821 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
822                            EVT valuevt, std::optional<CallingConv::ID> CC)
823     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
824       RegCount(1, regs.size()), CallConv(CC) {}
825 
826 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
827                            const DataLayout &DL, unsigned Reg, Type *Ty,
828                            std::optional<CallingConv::ID> CC) {
829   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
830 
831   CallConv = CC;
832 
833   for (EVT ValueVT : ValueVTs) {
834     unsigned NumRegs =
835         isABIMangled()
836             ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT)
837             : TLI.getNumRegisters(Context, ValueVT);
838     MVT RegisterVT =
839         isABIMangled()
840             ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT)
841             : TLI.getRegisterType(Context, ValueVT);
842     for (unsigned i = 0; i != NumRegs; ++i)
843       Regs.push_back(Reg + i);
844     RegVTs.push_back(RegisterVT);
845     RegCount.push_back(NumRegs);
846     Reg += NumRegs;
847   }
848 }
849 
850 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
851                                       FunctionLoweringInfo &FuncInfo,
852                                       const SDLoc &dl, SDValue &Chain,
853                                       SDValue *Glue, const Value *V) const {
854   // A Value with type {} or [0 x %t] needs no registers.
855   if (ValueVTs.empty())
856     return SDValue();
857 
858   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
859 
860   // Assemble the legal parts into the final values.
861   SmallVector<SDValue, 4> Values(ValueVTs.size());
862   SmallVector<SDValue, 8> Parts;
863   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
864     // Copy the legal parts from the registers.
865     EVT ValueVT = ValueVTs[Value];
866     unsigned NumRegs = RegCount[Value];
867     MVT RegisterVT = isABIMangled()
868                          ? TLI.getRegisterTypeForCallingConv(
869                                *DAG.getContext(), *CallConv, RegVTs[Value])
870                          : RegVTs[Value];
871 
872     Parts.resize(NumRegs);
873     for (unsigned i = 0; i != NumRegs; ++i) {
874       SDValue P;
875       if (!Glue) {
876         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
877       } else {
878         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue);
879         *Glue = P.getValue(2);
880       }
881 
882       Chain = P.getValue(1);
883       Parts[i] = P;
884 
885       // If the source register was virtual and if we know something about it,
886       // add an assert node.
887       if (!Register::isVirtualRegister(Regs[Part + i]) ||
888           !RegisterVT.isInteger())
889         continue;
890 
891       const FunctionLoweringInfo::LiveOutInfo *LOI =
892         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
893       if (!LOI)
894         continue;
895 
896       unsigned RegSize = RegisterVT.getScalarSizeInBits();
897       unsigned NumSignBits = LOI->NumSignBits;
898       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
899 
900       if (NumZeroBits == RegSize) {
901         // The current value is a zero.
902         // Explicitly express that as it would be easier for
903         // optimizations to kick in.
904         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
905         continue;
906       }
907 
908       // FIXME: We capture more information than the dag can represent.  For
909       // now, just use the tightest assertzext/assertsext possible.
910       bool isSExt;
911       EVT FromVT(MVT::Other);
912       if (NumZeroBits) {
913         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
914         isSExt = false;
915       } else if (NumSignBits > 1) {
916         FromVT =
917             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
918         isSExt = true;
919       } else {
920         continue;
921       }
922       // Add an assertion node.
923       assert(FromVT != MVT::Other);
924       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
925                              RegisterVT, P, DAG.getValueType(FromVT));
926     }
927 
928     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
929                                      RegisterVT, ValueVT, V, CallConv);
930     Part += NumRegs;
931     Parts.clear();
932   }
933 
934   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
935 }
936 
937 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
938                                  const SDLoc &dl, SDValue &Chain, SDValue *Glue,
939                                  const Value *V,
940                                  ISD::NodeType PreferredExtendType) const {
941   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
942   ISD::NodeType ExtendKind = PreferredExtendType;
943 
944   // Get the list of the values's legal parts.
945   unsigned NumRegs = Regs.size();
946   SmallVector<SDValue, 8> Parts(NumRegs);
947   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
948     unsigned NumParts = RegCount[Value];
949 
950     MVT RegisterVT = isABIMangled()
951                          ? TLI.getRegisterTypeForCallingConv(
952                                *DAG.getContext(), *CallConv, RegVTs[Value])
953                          : RegVTs[Value];
954 
955     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
956       ExtendKind = ISD::ZERO_EXTEND;
957 
958     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
959                    NumParts, RegisterVT, V, CallConv, ExtendKind);
960     Part += NumParts;
961   }
962 
963   // Copy the parts into the registers.
964   SmallVector<SDValue, 8> Chains(NumRegs);
965   for (unsigned i = 0; i != NumRegs; ++i) {
966     SDValue Part;
967     if (!Glue) {
968       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
969     } else {
970       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue);
971       *Glue = Part.getValue(1);
972     }
973 
974     Chains[i] = Part.getValue(0);
975   }
976 
977   if (NumRegs == 1 || Glue)
978     // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is
979     // flagged to it. That is the CopyToReg nodes and the user are considered
980     // a single scheduling unit. If we create a TokenFactor and return it as
981     // chain, then the TokenFactor is both a predecessor (operand) of the
982     // user as well as a successor (the TF operands are flagged to the user).
983     // c1, f1 = CopyToReg
984     // c2, f2 = CopyToReg
985     // c3     = TokenFactor c1, c2
986     // ...
987     //        = op c3, ..., f2
988     Chain = Chains[NumRegs-1];
989   else
990     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
991 }
992 
993 void RegsForValue::AddInlineAsmOperands(InlineAsm::Kind Code, bool HasMatching,
994                                         unsigned MatchingIdx, const SDLoc &dl,
995                                         SelectionDAG &DAG,
996                                         std::vector<SDValue> &Ops) const {
997   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
998 
999   InlineAsm::Flag Flag(Code, Regs.size());
1000   if (HasMatching)
1001     Flag.setMatchingOp(MatchingIdx);
1002   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
1003     // Put the register class of the virtual registers in the flag word.  That
1004     // way, later passes can recompute register class constraints for inline
1005     // assembly as well as normal instructions.
1006     // Don't do this for tied operands that can use the regclass information
1007     // from the def.
1008     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1009     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
1010     Flag.setRegClass(RC->getID());
1011   }
1012 
1013   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
1014   Ops.push_back(Res);
1015 
1016   if (Code == InlineAsm::Kind::Clobber) {
1017     // Clobbers should always have a 1:1 mapping with registers, and may
1018     // reference registers that have illegal (e.g. vector) types. Hence, we
1019     // shouldn't try to apply any sort of splitting logic to them.
1020     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
1021            "No 1:1 mapping from clobbers to regs?");
1022     Register SP = TLI.getStackPointerRegisterToSaveRestore();
1023     (void)SP;
1024     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
1025       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
1026       assert(
1027           (Regs[I] != SP ||
1028            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
1029           "If we clobbered the stack pointer, MFI should know about it.");
1030     }
1031     return;
1032   }
1033 
1034   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1035     MVT RegisterVT = RegVTs[Value];
1036     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
1037                                            RegisterVT);
1038     for (unsigned i = 0; i != NumRegs; ++i) {
1039       assert(Reg < Regs.size() && "Mismatch in # registers expected");
1040       unsigned TheReg = Regs[Reg++];
1041       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1042     }
1043   }
1044 }
1045 
1046 SmallVector<std::pair<unsigned, TypeSize>, 4>
1047 RegsForValue::getRegsAndSizes() const {
1048   SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec;
1049   unsigned I = 0;
1050   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1051     unsigned RegCount = std::get<0>(CountAndVT);
1052     MVT RegisterVT = std::get<1>(CountAndVT);
1053     TypeSize RegisterSize = RegisterVT.getSizeInBits();
1054     for (unsigned E = I + RegCount; I != E; ++I)
1055       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1056   }
1057   return OutVec;
1058 }
1059 
1060 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1061                                AssumptionCache *ac,
1062                                const TargetLibraryInfo *li) {
1063   AA = aa;
1064   AC = ac;
1065   GFI = gfi;
1066   LibInfo = li;
1067   Context = DAG.getContext();
1068   LPadToCallSiteMap.clear();
1069   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1070   AssignmentTrackingEnabled = isAssignmentTrackingEnabled(
1071       *DAG.getMachineFunction().getFunction().getParent());
1072 }
1073 
1074 void SelectionDAGBuilder::clear() {
1075   NodeMap.clear();
1076   UnusedArgNodeMap.clear();
1077   PendingLoads.clear();
1078   PendingExports.clear();
1079   PendingConstrainedFP.clear();
1080   PendingConstrainedFPStrict.clear();
1081   CurInst = nullptr;
1082   HasTailCall = false;
1083   SDNodeOrder = LowestSDNodeOrder;
1084   StatepointLowering.clear();
1085 }
1086 
1087 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1088   DanglingDebugInfoMap.clear();
1089 }
1090 
1091 // Update DAG root to include dependencies on Pending chains.
1092 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1093   SDValue Root = DAG.getRoot();
1094 
1095   if (Pending.empty())
1096     return Root;
1097 
1098   // Add current root to PendingChains, unless we already indirectly
1099   // depend on it.
1100   if (Root.getOpcode() != ISD::EntryToken) {
1101     unsigned i = 0, e = Pending.size();
1102     for (; i != e; ++i) {
1103       assert(Pending[i].getNode()->getNumOperands() > 1);
1104       if (Pending[i].getNode()->getOperand(0) == Root)
1105         break;  // Don't add the root if we already indirectly depend on it.
1106     }
1107 
1108     if (i == e)
1109       Pending.push_back(Root);
1110   }
1111 
1112   if (Pending.size() == 1)
1113     Root = Pending[0];
1114   else
1115     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1116 
1117   DAG.setRoot(Root);
1118   Pending.clear();
1119   return Root;
1120 }
1121 
1122 SDValue SelectionDAGBuilder::getMemoryRoot() {
1123   return updateRoot(PendingLoads);
1124 }
1125 
1126 SDValue SelectionDAGBuilder::getRoot() {
1127   // Chain up all pending constrained intrinsics together with all
1128   // pending loads, by simply appending them to PendingLoads and
1129   // then calling getMemoryRoot().
1130   PendingLoads.reserve(PendingLoads.size() +
1131                        PendingConstrainedFP.size() +
1132                        PendingConstrainedFPStrict.size());
1133   PendingLoads.append(PendingConstrainedFP.begin(),
1134                       PendingConstrainedFP.end());
1135   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1136                       PendingConstrainedFPStrict.end());
1137   PendingConstrainedFP.clear();
1138   PendingConstrainedFPStrict.clear();
1139   return getMemoryRoot();
1140 }
1141 
1142 SDValue SelectionDAGBuilder::getControlRoot() {
1143   // We need to emit pending fpexcept.strict constrained intrinsics,
1144   // so append them to the PendingExports list.
1145   PendingExports.append(PendingConstrainedFPStrict.begin(),
1146                         PendingConstrainedFPStrict.end());
1147   PendingConstrainedFPStrict.clear();
1148   return updateRoot(PendingExports);
1149 }
1150 
1151 void SelectionDAGBuilder::visitDbgInfo(const Instruction &I) {
1152   // Add SDDbgValue nodes for any var locs here. Do so before updating
1153   // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1154   if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) {
1155     // Add SDDbgValue nodes for any var locs here. Do so before updating
1156     // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1157     for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I);
1158          It != End; ++It) {
1159       auto *Var = FnVarLocs->getDILocalVariable(It->VariableID);
1160       dropDanglingDebugInfo(Var, It->Expr);
1161       if (It->Values.isKillLocation(It->Expr)) {
1162         handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder);
1163         continue;
1164       }
1165       SmallVector<Value *> Values(It->Values.location_ops());
1166       if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder,
1167                             It->Values.hasArgList())) {
1168         SmallVector<Value *, 4> Vals;
1169         for (Value *V : It->Values.location_ops())
1170           Vals.push_back(V);
1171         addDanglingDebugInfo(Vals,
1172                              FnVarLocs->getDILocalVariable(It->VariableID),
1173                              It->Expr, Vals.size() > 1, It->DL, SDNodeOrder);
1174       }
1175     }
1176   }
1177 
1178   // Is there is any debug-info attached to this instruction, in the form of
1179   // DPValue non-instruction debug-info records.
1180   for (DPValue &DPV : I.getDbgValueRange()) {
1181     DILocalVariable *Variable = DPV.getVariable();
1182     DIExpression *Expression = DPV.getExpression();
1183     dropDanglingDebugInfo(Variable, Expression);
1184 
1185     // A DPValue with no locations is a kill location.
1186     SmallVector<Value *, 4> Values(DPV.location_ops());
1187     if (Values.empty()) {
1188       handleKillDebugValue(Variable, Expression, DPV.getDebugLoc(),
1189                            SDNodeOrder);
1190       continue;
1191     }
1192 
1193     // A DPValue with an undef or absent location is also a kill location.
1194     if (llvm::any_of(Values,
1195                      [](Value *V) { return !V || isa<UndefValue>(V); })) {
1196       handleKillDebugValue(Variable, Expression, DPV.getDebugLoc(),
1197                            SDNodeOrder);
1198       continue;
1199     }
1200 
1201     bool IsVariadic = DPV.hasArgList();
1202     if (!handleDebugValue(Values, Variable, Expression, DPV.getDebugLoc(),
1203                           SDNodeOrder, IsVariadic)) {
1204       addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
1205                            DPV.getDebugLoc(), SDNodeOrder);
1206     }
1207   }
1208 }
1209 
1210 void SelectionDAGBuilder::visit(const Instruction &I) {
1211   visitDbgInfo(I);
1212 
1213   // Set up outgoing PHI node register values before emitting the terminator.
1214   if (I.isTerminator()) {
1215     HandlePHINodesInSuccessorBlocks(I.getParent());
1216   }
1217 
1218   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1219   if (!isa<DbgInfoIntrinsic>(I))
1220     ++SDNodeOrder;
1221 
1222   CurInst = &I;
1223 
1224   // Set inserted listener only if required.
1225   bool NodeInserted = false;
1226   std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener;
1227   MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections);
1228   if (PCSectionsMD) {
1229     InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>(
1230         DAG, [&](SDNode *) { NodeInserted = true; });
1231   }
1232 
1233   visit(I.getOpcode(), I);
1234 
1235   if (!I.isTerminator() && !HasTailCall &&
1236       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1237     CopyToExportRegsIfNeeded(&I);
1238 
1239   // Handle metadata.
1240   if (PCSectionsMD) {
1241     auto It = NodeMap.find(&I);
1242     if (It != NodeMap.end()) {
1243       DAG.addPCSections(It->second.getNode(), PCSectionsMD);
1244     } else if (NodeInserted) {
1245       // This should not happen; if it does, don't let it go unnoticed so we can
1246       // fix it. Relevant visit*() function is probably missing a setValue().
1247       errs() << "warning: loosing !pcsections metadata ["
1248              << I.getModule()->getName() << "]\n";
1249       LLVM_DEBUG(I.dump());
1250       assert(false);
1251     }
1252   }
1253 
1254   CurInst = nullptr;
1255 }
1256 
1257 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1258   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1259 }
1260 
1261 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1262   // Note: this doesn't use InstVisitor, because it has to work with
1263   // ConstantExpr's in addition to instructions.
1264   switch (Opcode) {
1265   default: llvm_unreachable("Unknown instruction type encountered!");
1266     // Build the switch statement using the Instruction.def file.
1267 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1268     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1269 #include "llvm/IR/Instruction.def"
1270   }
1271 }
1272 
1273 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG,
1274                                             DILocalVariable *Variable,
1275                                             DebugLoc DL, unsigned Order,
1276                                             SmallVectorImpl<Value *> &Values,
1277                                             DIExpression *Expression) {
1278   // For variadic dbg_values we will now insert an undef.
1279   // FIXME: We can potentially recover these!
1280   SmallVector<SDDbgOperand, 2> Locs;
1281   for (const Value *V : Values) {
1282     auto *Undef = UndefValue::get(V->getType());
1283     Locs.push_back(SDDbgOperand::fromConst(Undef));
1284   }
1285   SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {},
1286                                         /*IsIndirect=*/false, DL, Order,
1287                                         /*IsVariadic=*/true);
1288   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1289   return true;
1290 }
1291 
1292 void SelectionDAGBuilder::addDanglingDebugInfo(SmallVectorImpl<Value *> &Values,
1293                                                DILocalVariable *Var,
1294                                                DIExpression *Expr,
1295                                                bool IsVariadic, DebugLoc DL,
1296                                                unsigned Order) {
1297   if (IsVariadic) {
1298     handleDanglingVariadicDebugInfo(DAG, Var, DL, Order, Values, Expr);
1299     return;
1300   }
1301   // TODO: Dangling debug info will eventually either be resolved or produce
1302   // an Undef DBG_VALUE. However in the resolution case, a gap may appear
1303   // between the original dbg.value location and its resolved DBG_VALUE,
1304   // which we should ideally fill with an extra Undef DBG_VALUE.
1305   assert(Values.size() == 1);
1306   DanglingDebugInfoMap[Values[0]].emplace_back(Var, Expr, DL, Order);
1307 }
1308 
1309 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1310                                                 const DIExpression *Expr) {
1311   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1312     DIVariable *DanglingVariable = DDI.getVariable();
1313     DIExpression *DanglingExpr = DDI.getExpression();
1314     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1315       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for "
1316                         << printDDI(nullptr, DDI) << "\n");
1317       return true;
1318     }
1319     return false;
1320   };
1321 
1322   for (auto &DDIMI : DanglingDebugInfoMap) {
1323     DanglingDebugInfoVector &DDIV = DDIMI.second;
1324 
1325     // If debug info is to be dropped, run it through final checks to see
1326     // whether it can be salvaged.
1327     for (auto &DDI : DDIV)
1328       if (isMatchingDbgValue(DDI))
1329         salvageUnresolvedDbgValue(DDIMI.first, DDI);
1330 
1331     erase_if(DDIV, isMatchingDbgValue);
1332   }
1333 }
1334 
1335 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1336 // generate the debug data structures now that we've seen its definition.
1337 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1338                                                    SDValue Val) {
1339   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1340   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1341     return;
1342 
1343   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1344   for (auto &DDI : DDIV) {
1345     DebugLoc DL = DDI.getDebugLoc();
1346     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1347     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1348     DILocalVariable *Variable = DDI.getVariable();
1349     DIExpression *Expr = DDI.getExpression();
1350     assert(Variable->isValidLocationForIntrinsic(DL) &&
1351            "Expected inlined-at fields to agree");
1352     SDDbgValue *SDV;
1353     if (Val.getNode()) {
1354       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1355       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1356       // we couldn't resolve it directly when examining the DbgValue intrinsic
1357       // in the first place we should not be more successful here). Unless we
1358       // have some test case that prove this to be correct we should avoid
1359       // calling EmitFuncArgumentDbgValue here.
1360       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL,
1361                                     FuncArgumentDbgValueKind::Value, Val)) {
1362         LLVM_DEBUG(dbgs() << "Resolve dangling debug info for "
1363                           << printDDI(V, DDI) << "\n");
1364         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1365         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1366         // inserted after the definition of Val when emitting the instructions
1367         // after ISel. An alternative could be to teach
1368         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1369         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1370                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1371                    << ValSDNodeOrder << "\n");
1372         SDV = getDbgValue(Val, Variable, Expr, DL,
1373                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1374         DAG.AddDbgValue(SDV, false);
1375       } else
1376         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for "
1377                           << printDDI(V, DDI)
1378                           << " in EmitFuncArgumentDbgValue\n");
1379     } else {
1380       LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(V, DDI)
1381                         << "\n");
1382       auto Undef = UndefValue::get(V->getType());
1383       auto SDV =
1384           DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder);
1385       DAG.AddDbgValue(SDV, false);
1386     }
1387   }
1388   DDIV.clear();
1389 }
1390 
1391 void SelectionDAGBuilder::salvageUnresolvedDbgValue(const Value *V,
1392                                                     DanglingDebugInfo &DDI) {
1393   // TODO: For the variadic implementation, instead of only checking the fail
1394   // state of `handleDebugValue`, we need know specifically which values were
1395   // invalid, so that we attempt to salvage only those values when processing
1396   // a DIArgList.
1397   const Value *OrigV = V;
1398   DILocalVariable *Var = DDI.getVariable();
1399   DIExpression *Expr = DDI.getExpression();
1400   DebugLoc DL = DDI.getDebugLoc();
1401   unsigned SDOrder = DDI.getSDNodeOrder();
1402 
1403   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1404   // that DW_OP_stack_value is desired.
1405   bool StackValue = true;
1406 
1407   // Can this Value can be encoded without any further work?
1408   if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false))
1409     return;
1410 
1411   // Attempt to salvage back through as many instructions as possible. Bail if
1412   // a non-instruction is seen, such as a constant expression or global
1413   // variable. FIXME: Further work could recover those too.
1414   while (isa<Instruction>(V)) {
1415     const Instruction &VAsInst = *cast<const Instruction>(V);
1416     // Temporary "0", awaiting real implementation.
1417     SmallVector<uint64_t, 16> Ops;
1418     SmallVector<Value *, 4> AdditionalValues;
1419     V = salvageDebugInfoImpl(const_cast<Instruction &>(VAsInst),
1420                              Expr->getNumLocationOperands(), Ops,
1421                              AdditionalValues);
1422     // If we cannot salvage any further, and haven't yet found a suitable debug
1423     // expression, bail out.
1424     if (!V)
1425       break;
1426 
1427     // TODO: If AdditionalValues isn't empty, then the salvage can only be
1428     // represented with a DBG_VALUE_LIST, so we give up. When we have support
1429     // here for variadic dbg_values, remove that condition.
1430     if (!AdditionalValues.empty())
1431       break;
1432 
1433     // New value and expr now represent this debuginfo.
1434     Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue);
1435 
1436     // Some kind of simplification occurred: check whether the operand of the
1437     // salvaged debug expression can be encoded in this DAG.
1438     if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) {
1439       LLVM_DEBUG(
1440           dbgs() << "Salvaged debug location info for:\n  " << *Var << "\n"
1441                  << *OrigV << "\nBy stripping back to:\n  " << *V << "\n");
1442       return;
1443     }
1444   }
1445 
1446   // This was the final opportunity to salvage this debug information, and it
1447   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1448   // any earlier variable location.
1449   assert(OrigV && "V shouldn't be null");
1450   auto *Undef = UndefValue::get(OrigV->getType());
1451   auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1452   DAG.AddDbgValue(SDV, false);
1453   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  "
1454                     << printDDI(OrigV, DDI) << "\n");
1455 }
1456 
1457 void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var,
1458                                                DIExpression *Expr,
1459                                                DebugLoc DbgLoc,
1460                                                unsigned Order) {
1461   Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context));
1462   DIExpression *NewExpr =
1463       const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr));
1464   handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order,
1465                    /*IsVariadic*/ false);
1466 }
1467 
1468 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1469                                            DILocalVariable *Var,
1470                                            DIExpression *Expr, DebugLoc DbgLoc,
1471                                            unsigned Order, bool IsVariadic) {
1472   if (Values.empty())
1473     return true;
1474   SmallVector<SDDbgOperand> LocationOps;
1475   SmallVector<SDNode *> Dependencies;
1476   for (const Value *V : Values) {
1477     // Constant value.
1478     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1479         isa<ConstantPointerNull>(V)) {
1480       LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1481       continue;
1482     }
1483 
1484     // Look through IntToPtr constants.
1485     if (auto *CE = dyn_cast<ConstantExpr>(V))
1486       if (CE->getOpcode() == Instruction::IntToPtr) {
1487         LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0)));
1488         continue;
1489       }
1490 
1491     // If the Value is a frame index, we can create a FrameIndex debug value
1492     // without relying on the DAG at all.
1493     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1494       auto SI = FuncInfo.StaticAllocaMap.find(AI);
1495       if (SI != FuncInfo.StaticAllocaMap.end()) {
1496         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1497         continue;
1498       }
1499     }
1500 
1501     // Do not use getValue() in here; we don't want to generate code at
1502     // this point if it hasn't been done yet.
1503     SDValue N = NodeMap[V];
1504     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1505       N = UnusedArgNodeMap[V];
1506     if (N.getNode()) {
1507       // Only emit func arg dbg value for non-variadic dbg.values for now.
1508       if (!IsVariadic &&
1509           EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc,
1510                                    FuncArgumentDbgValueKind::Value, N))
1511         return true;
1512       if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1513         // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1514         // describe stack slot locations.
1515         //
1516         // Consider "int x = 0; int *px = &x;". There are two kinds of
1517         // interesting debug values here after optimization:
1518         //
1519         //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
1520         //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1521         //
1522         // Both describe the direct values of their associated variables.
1523         Dependencies.push_back(N.getNode());
1524         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1525         continue;
1526       }
1527       LocationOps.emplace_back(
1528           SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1529       continue;
1530     }
1531 
1532     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1533     // Special rules apply for the first dbg.values of parameter variables in a
1534     // function. Identify them by the fact they reference Argument Values, that
1535     // they're parameters, and they are parameters of the current function. We
1536     // need to let them dangle until they get an SDNode.
1537     bool IsParamOfFunc =
1538         isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt();
1539     if (IsParamOfFunc)
1540       return false;
1541 
1542     // The value is not used in this block yet (or it would have an SDNode).
1543     // We still want the value to appear for the user if possible -- if it has
1544     // an associated VReg, we can refer to that instead.
1545     auto VMI = FuncInfo.ValueMap.find(V);
1546     if (VMI != FuncInfo.ValueMap.end()) {
1547       unsigned Reg = VMI->second;
1548       // If this is a PHI node, it may be split up into several MI PHI nodes
1549       // (in FunctionLoweringInfo::set).
1550       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1551                        V->getType(), std::nullopt);
1552       if (RFV.occupiesMultipleRegs()) {
1553         // FIXME: We could potentially support variadic dbg_values here.
1554         if (IsVariadic)
1555           return false;
1556         unsigned Offset = 0;
1557         unsigned BitsToDescribe = 0;
1558         if (auto VarSize = Var->getSizeInBits())
1559           BitsToDescribe = *VarSize;
1560         if (auto Fragment = Expr->getFragmentInfo())
1561           BitsToDescribe = Fragment->SizeInBits;
1562         for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1563           // Bail out if all bits are described already.
1564           if (Offset >= BitsToDescribe)
1565             break;
1566           // TODO: handle scalable vectors.
1567           unsigned RegisterSize = RegAndSize.second;
1568           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1569                                       ? BitsToDescribe - Offset
1570                                       : RegisterSize;
1571           auto FragmentExpr = DIExpression::createFragmentExpression(
1572               Expr, Offset, FragmentSize);
1573           if (!FragmentExpr)
1574             continue;
1575           SDDbgValue *SDV = DAG.getVRegDbgValue(
1576               Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, SDNodeOrder);
1577           DAG.AddDbgValue(SDV, false);
1578           Offset += RegisterSize;
1579         }
1580         return true;
1581       }
1582       // We can use simple vreg locations for variadic dbg_values as well.
1583       LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1584       continue;
1585     }
1586     // We failed to create a SDDbgOperand for V.
1587     return false;
1588   }
1589 
1590   // We have created a SDDbgOperand for each Value in Values.
1591   // Should use Order instead of SDNodeOrder?
1592   assert(!LocationOps.empty());
1593   SDDbgValue *SDV = DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1594                                         /*IsIndirect=*/false, DbgLoc,
1595                                         SDNodeOrder, IsVariadic);
1596   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1597   return true;
1598 }
1599 
1600 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1601   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1602   for (auto &Pair : DanglingDebugInfoMap)
1603     for (auto &DDI : Pair.second)
1604       salvageUnresolvedDbgValue(const_cast<Value *>(Pair.first), DDI);
1605   clearDanglingDebugInfo();
1606 }
1607 
1608 /// getCopyFromRegs - If there was virtual register allocated for the value V
1609 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1610 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1611   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1612   SDValue Result;
1613 
1614   if (It != FuncInfo.ValueMap.end()) {
1615     Register InReg = It->second;
1616 
1617     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1618                      DAG.getDataLayout(), InReg, Ty,
1619                      std::nullopt); // This is not an ABI copy.
1620     SDValue Chain = DAG.getEntryNode();
1621     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1622                                  V);
1623     resolveDanglingDebugInfo(V, Result);
1624   }
1625 
1626   return Result;
1627 }
1628 
1629 /// getValue - Return an SDValue for the given Value.
1630 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1631   // If we already have an SDValue for this value, use it. It's important
1632   // to do this first, so that we don't create a CopyFromReg if we already
1633   // have a regular SDValue.
1634   SDValue &N = NodeMap[V];
1635   if (N.getNode()) return N;
1636 
1637   // If there's a virtual register allocated and initialized for this
1638   // value, use it.
1639   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1640     return copyFromReg;
1641 
1642   // Otherwise create a new SDValue and remember it.
1643   SDValue Val = getValueImpl(V);
1644   NodeMap[V] = Val;
1645   resolveDanglingDebugInfo(V, Val);
1646   return Val;
1647 }
1648 
1649 /// getNonRegisterValue - Return an SDValue for the given Value, but
1650 /// don't look in FuncInfo.ValueMap for a virtual register.
1651 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1652   // If we already have an SDValue for this value, use it.
1653   SDValue &N = NodeMap[V];
1654   if (N.getNode()) {
1655     if (isIntOrFPConstant(N)) {
1656       // Remove the debug location from the node as the node is about to be used
1657       // in a location which may differ from the original debug location.  This
1658       // is relevant to Constant and ConstantFP nodes because they can appear
1659       // as constant expressions inside PHI nodes.
1660       N->setDebugLoc(DebugLoc());
1661     }
1662     return N;
1663   }
1664 
1665   // Otherwise create a new SDValue and remember it.
1666   SDValue Val = getValueImpl(V);
1667   NodeMap[V] = Val;
1668   resolveDanglingDebugInfo(V, Val);
1669   return Val;
1670 }
1671 
1672 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1673 /// Create an SDValue for the given value.
1674 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1675   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1676 
1677   if (const Constant *C = dyn_cast<Constant>(V)) {
1678     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1679 
1680     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1681       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1682 
1683     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1684       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1685 
1686     if (isa<ConstantPointerNull>(C)) {
1687       unsigned AS = V->getType()->getPointerAddressSpace();
1688       return DAG.getConstant(0, getCurSDLoc(),
1689                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1690     }
1691 
1692     if (match(C, m_VScale()))
1693       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1694 
1695     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1696       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1697 
1698     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1699       return DAG.getUNDEF(VT);
1700 
1701     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1702       visit(CE->getOpcode(), *CE);
1703       SDValue N1 = NodeMap[V];
1704       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1705       return N1;
1706     }
1707 
1708     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1709       SmallVector<SDValue, 4> Constants;
1710       for (const Use &U : C->operands()) {
1711         SDNode *Val = getValue(U).getNode();
1712         // If the operand is an empty aggregate, there are no values.
1713         if (!Val) continue;
1714         // Add each leaf value from the operand to the Constants list
1715         // to form a flattened list of all the values.
1716         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1717           Constants.push_back(SDValue(Val, i));
1718       }
1719 
1720       return DAG.getMergeValues(Constants, getCurSDLoc());
1721     }
1722 
1723     if (const ConstantDataSequential *CDS =
1724           dyn_cast<ConstantDataSequential>(C)) {
1725       SmallVector<SDValue, 4> Ops;
1726       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1727         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1728         // Add each leaf value from the operand to the Constants list
1729         // to form a flattened list of all the values.
1730         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1731           Ops.push_back(SDValue(Val, i));
1732       }
1733 
1734       if (isa<ArrayType>(CDS->getType()))
1735         return DAG.getMergeValues(Ops, getCurSDLoc());
1736       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1737     }
1738 
1739     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1740       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1741              "Unknown struct or array constant!");
1742 
1743       SmallVector<EVT, 4> ValueVTs;
1744       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1745       unsigned NumElts = ValueVTs.size();
1746       if (NumElts == 0)
1747         return SDValue(); // empty struct
1748       SmallVector<SDValue, 4> Constants(NumElts);
1749       for (unsigned i = 0; i != NumElts; ++i) {
1750         EVT EltVT = ValueVTs[i];
1751         if (isa<UndefValue>(C))
1752           Constants[i] = DAG.getUNDEF(EltVT);
1753         else if (EltVT.isFloatingPoint())
1754           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1755         else
1756           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1757       }
1758 
1759       return DAG.getMergeValues(Constants, getCurSDLoc());
1760     }
1761 
1762     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1763       return DAG.getBlockAddress(BA, VT);
1764 
1765     if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1766       return getValue(Equiv->getGlobalValue());
1767 
1768     if (const auto *NC = dyn_cast<NoCFIValue>(C))
1769       return getValue(NC->getGlobalValue());
1770 
1771     if (VT == MVT::aarch64svcount) {
1772       assert(C->isNullValue() && "Can only zero this target type!");
1773       return DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT,
1774                          DAG.getConstant(0, getCurSDLoc(), MVT::nxv16i1));
1775     }
1776 
1777     VectorType *VecTy = cast<VectorType>(V->getType());
1778 
1779     // Now that we know the number and type of the elements, get that number of
1780     // elements into the Ops array based on what kind of constant it is.
1781     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1782       SmallVector<SDValue, 16> Ops;
1783       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1784       for (unsigned i = 0; i != NumElements; ++i)
1785         Ops.push_back(getValue(CV->getOperand(i)));
1786 
1787       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1788     }
1789 
1790     if (isa<ConstantAggregateZero>(C)) {
1791       EVT EltVT =
1792           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1793 
1794       SDValue Op;
1795       if (EltVT.isFloatingPoint())
1796         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1797       else
1798         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1799 
1800       return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op);
1801     }
1802 
1803     llvm_unreachable("Unknown vector constant");
1804   }
1805 
1806   // If this is a static alloca, generate it as the frameindex instead of
1807   // computation.
1808   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1809     DenseMap<const AllocaInst*, int>::iterator SI =
1810       FuncInfo.StaticAllocaMap.find(AI);
1811     if (SI != FuncInfo.StaticAllocaMap.end())
1812       return DAG.getFrameIndex(
1813           SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType()));
1814   }
1815 
1816   // If this is an instruction which fast-isel has deferred, select it now.
1817   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1818     Register InReg = FuncInfo.InitializeRegForValue(Inst);
1819 
1820     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1821                      Inst->getType(), std::nullopt);
1822     SDValue Chain = DAG.getEntryNode();
1823     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1824   }
1825 
1826   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V))
1827     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1828 
1829   if (const auto *BB = dyn_cast<BasicBlock>(V))
1830     return DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
1831 
1832   llvm_unreachable("Can't get register for value!");
1833 }
1834 
1835 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1836   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1837   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1838   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1839   bool IsSEH = isAsynchronousEHPersonality(Pers);
1840   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1841   if (!IsSEH)
1842     CatchPadMBB->setIsEHScopeEntry();
1843   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1844   if (IsMSVCCXX || IsCoreCLR)
1845     CatchPadMBB->setIsEHFuncletEntry();
1846 }
1847 
1848 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1849   // Update machine-CFG edge.
1850   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1851   FuncInfo.MBB->addSuccessor(TargetMBB);
1852   TargetMBB->setIsEHCatchretTarget(true);
1853   DAG.getMachineFunction().setHasEHCatchret(true);
1854 
1855   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1856   bool IsSEH = isAsynchronousEHPersonality(Pers);
1857   if (IsSEH) {
1858     // If this is not a fall-through branch or optimizations are switched off,
1859     // emit the branch.
1860     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1861         TM.getOptLevel() == CodeGenOptLevel::None)
1862       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1863                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1864     return;
1865   }
1866 
1867   // Figure out the funclet membership for the catchret's successor.
1868   // This will be used by the FuncletLayout pass to determine how to order the
1869   // BB's.
1870   // A 'catchret' returns to the outer scope's color.
1871   Value *ParentPad = I.getCatchSwitchParentPad();
1872   const BasicBlock *SuccessorColor;
1873   if (isa<ConstantTokenNone>(ParentPad))
1874     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1875   else
1876     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1877   assert(SuccessorColor && "No parent funclet for catchret!");
1878   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1879   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1880 
1881   // Create the terminator node.
1882   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1883                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1884                             DAG.getBasicBlock(SuccessorColorMBB));
1885   DAG.setRoot(Ret);
1886 }
1887 
1888 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1889   // Don't emit any special code for the cleanuppad instruction. It just marks
1890   // the start of an EH scope/funclet.
1891   FuncInfo.MBB->setIsEHScopeEntry();
1892   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1893   if (Pers != EHPersonality::Wasm_CXX) {
1894     FuncInfo.MBB->setIsEHFuncletEntry();
1895     FuncInfo.MBB->setIsCleanupFuncletEntry();
1896   }
1897 }
1898 
1899 // In wasm EH, even though a catchpad may not catch an exception if a tag does
1900 // not match, it is OK to add only the first unwind destination catchpad to the
1901 // successors, because there will be at least one invoke instruction within the
1902 // catch scope that points to the next unwind destination, if one exists, so
1903 // CFGSort cannot mess up with BB sorting order.
1904 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
1905 // call within them, and catchpads only consisting of 'catch (...)' have a
1906 // '__cxa_end_catch' call within them, both of which generate invokes in case
1907 // the next unwind destination exists, i.e., the next unwind destination is not
1908 // the caller.)
1909 //
1910 // Having at most one EH pad successor is also simpler and helps later
1911 // transformations.
1912 //
1913 // For example,
1914 // current:
1915 //   invoke void @foo to ... unwind label %catch.dispatch
1916 // catch.dispatch:
1917 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
1918 // catch.start:
1919 //   ...
1920 //   ... in this BB or some other child BB dominated by this BB there will be an
1921 //   invoke that points to 'next' BB as an unwind destination
1922 //
1923 // next: ; We don't need to add this to 'current' BB's successor
1924 //   ...
1925 static void findWasmUnwindDestinations(
1926     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1927     BranchProbability Prob,
1928     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1929         &UnwindDests) {
1930   while (EHPadBB) {
1931     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1932     if (isa<CleanupPadInst>(Pad)) {
1933       // Stop on cleanup pads.
1934       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1935       UnwindDests.back().first->setIsEHScopeEntry();
1936       break;
1937     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1938       // Add the catchpad handlers to the possible destinations. We don't
1939       // continue to the unwind destination of the catchswitch for wasm.
1940       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1941         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1942         UnwindDests.back().first->setIsEHScopeEntry();
1943       }
1944       break;
1945     } else {
1946       continue;
1947     }
1948   }
1949 }
1950 
1951 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1952 /// many places it could ultimately go. In the IR, we have a single unwind
1953 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1954 /// This function skips over imaginary basic blocks that hold catchswitch
1955 /// instructions, and finds all the "real" machine
1956 /// basic block destinations. As those destinations may not be successors of
1957 /// EHPadBB, here we also calculate the edge probability to those destinations.
1958 /// The passed-in Prob is the edge probability to EHPadBB.
1959 static void findUnwindDestinations(
1960     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1961     BranchProbability Prob,
1962     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1963         &UnwindDests) {
1964   EHPersonality Personality =
1965     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1966   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1967   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1968   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1969   bool IsSEH = isAsynchronousEHPersonality(Personality);
1970 
1971   if (IsWasmCXX) {
1972     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1973     assert(UnwindDests.size() <= 1 &&
1974            "There should be at most one unwind destination for wasm");
1975     return;
1976   }
1977 
1978   while (EHPadBB) {
1979     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1980     BasicBlock *NewEHPadBB = nullptr;
1981     if (isa<LandingPadInst>(Pad)) {
1982       // Stop on landingpads. They are not funclets.
1983       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1984       break;
1985     } else if (isa<CleanupPadInst>(Pad)) {
1986       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1987       // personalities.
1988       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1989       UnwindDests.back().first->setIsEHScopeEntry();
1990       UnwindDests.back().first->setIsEHFuncletEntry();
1991       break;
1992     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1993       // Add the catchpad handlers to the possible destinations.
1994       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1995         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1996         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1997         if (IsMSVCCXX || IsCoreCLR)
1998           UnwindDests.back().first->setIsEHFuncletEntry();
1999         if (!IsSEH)
2000           UnwindDests.back().first->setIsEHScopeEntry();
2001       }
2002       NewEHPadBB = CatchSwitch->getUnwindDest();
2003     } else {
2004       continue;
2005     }
2006 
2007     BranchProbabilityInfo *BPI = FuncInfo.BPI;
2008     if (BPI && NewEHPadBB)
2009       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
2010     EHPadBB = NewEHPadBB;
2011   }
2012 }
2013 
2014 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
2015   // Update successor info.
2016   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2017   auto UnwindDest = I.getUnwindDest();
2018   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2019   BranchProbability UnwindDestProb =
2020       (BPI && UnwindDest)
2021           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
2022           : BranchProbability::getZero();
2023   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
2024   for (auto &UnwindDest : UnwindDests) {
2025     UnwindDest.first->setIsEHPad();
2026     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
2027   }
2028   FuncInfo.MBB->normalizeSuccProbs();
2029 
2030   // Create the terminator node.
2031   SDValue Ret =
2032       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
2033   DAG.setRoot(Ret);
2034 }
2035 
2036 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
2037   report_fatal_error("visitCatchSwitch not yet implemented!");
2038 }
2039 
2040 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
2041   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2042   auto &DL = DAG.getDataLayout();
2043   SDValue Chain = getControlRoot();
2044   SmallVector<ISD::OutputArg, 8> Outs;
2045   SmallVector<SDValue, 8> OutVals;
2046 
2047   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
2048   // lower
2049   //
2050   //   %val = call <ty> @llvm.experimental.deoptimize()
2051   //   ret <ty> %val
2052   //
2053   // differently.
2054   if (I.getParent()->getTerminatingDeoptimizeCall()) {
2055     LowerDeoptimizingReturn();
2056     return;
2057   }
2058 
2059   if (!FuncInfo.CanLowerReturn) {
2060     unsigned DemoteReg = FuncInfo.DemoteRegister;
2061     const Function *F = I.getParent()->getParent();
2062 
2063     // Emit a store of the return value through the virtual register.
2064     // Leave Outs empty so that LowerReturn won't try to load return
2065     // registers the usual way.
2066     SmallVector<EVT, 1> PtrValueVTs;
2067     ComputeValueVTs(TLI, DL,
2068                     PointerType::get(F->getContext(),
2069                                      DAG.getDataLayout().getAllocaAddrSpace()),
2070                     PtrValueVTs);
2071 
2072     SDValue RetPtr =
2073         DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]);
2074     SDValue RetOp = getValue(I.getOperand(0));
2075 
2076     SmallVector<EVT, 4> ValueVTs, MemVTs;
2077     SmallVector<uint64_t, 4> Offsets;
2078     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
2079                     &Offsets, 0);
2080     unsigned NumValues = ValueVTs.size();
2081 
2082     SmallVector<SDValue, 4> Chains(NumValues);
2083     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
2084     for (unsigned i = 0; i != NumValues; ++i) {
2085       // An aggregate return value cannot wrap around the address space, so
2086       // offsets to its parts don't wrap either.
2087       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
2088                                            TypeSize::getFixed(Offsets[i]));
2089 
2090       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
2091       if (MemVTs[i] != ValueVTs[i])
2092         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
2093       Chains[i] = DAG.getStore(
2094           Chain, getCurSDLoc(), Val,
2095           // FIXME: better loc info would be nice.
2096           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
2097           commonAlignment(BaseAlign, Offsets[i]));
2098     }
2099 
2100     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
2101                         MVT::Other, Chains);
2102   } else if (I.getNumOperands() != 0) {
2103     SmallVector<EVT, 4> ValueVTs;
2104     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
2105     unsigned NumValues = ValueVTs.size();
2106     if (NumValues) {
2107       SDValue RetOp = getValue(I.getOperand(0));
2108 
2109       const Function *F = I.getParent()->getParent();
2110 
2111       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
2112           I.getOperand(0)->getType(), F->getCallingConv(),
2113           /*IsVarArg*/ false, DL);
2114 
2115       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
2116       if (F->getAttributes().hasRetAttr(Attribute::SExt))
2117         ExtendKind = ISD::SIGN_EXTEND;
2118       else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
2119         ExtendKind = ISD::ZERO_EXTEND;
2120 
2121       LLVMContext &Context = F->getContext();
2122       bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
2123 
2124       for (unsigned j = 0; j != NumValues; ++j) {
2125         EVT VT = ValueVTs[j];
2126 
2127         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2128           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
2129 
2130         CallingConv::ID CC = F->getCallingConv();
2131 
2132         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
2133         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2134         SmallVector<SDValue, 4> Parts(NumParts);
2135         getCopyToParts(DAG, getCurSDLoc(),
2136                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2137                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
2138 
2139         // 'inreg' on function refers to return value
2140         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2141         if (RetInReg)
2142           Flags.setInReg();
2143 
2144         if (I.getOperand(0)->getType()->isPointerTy()) {
2145           Flags.setPointer();
2146           Flags.setPointerAddrSpace(
2147               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2148         }
2149 
2150         if (NeedsRegBlock) {
2151           Flags.setInConsecutiveRegs();
2152           if (j == NumValues - 1)
2153             Flags.setInConsecutiveRegsLast();
2154         }
2155 
2156         // Propagate extension type if any
2157         if (ExtendKind == ISD::SIGN_EXTEND)
2158           Flags.setSExt();
2159         else if (ExtendKind == ISD::ZERO_EXTEND)
2160           Flags.setZExt();
2161 
2162         for (unsigned i = 0; i < NumParts; ++i) {
2163           Outs.push_back(ISD::OutputArg(Flags,
2164                                         Parts[i].getValueType().getSimpleVT(),
2165                                         VT, /*isfixed=*/true, 0, 0));
2166           OutVals.push_back(Parts[i]);
2167         }
2168       }
2169     }
2170   }
2171 
2172   // Push in swifterror virtual register as the last element of Outs. This makes
2173   // sure swifterror virtual register will be returned in the swifterror
2174   // physical register.
2175   const Function *F = I.getParent()->getParent();
2176   if (TLI.supportSwiftError() &&
2177       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2178     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2179     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2180     Flags.setSwiftError();
2181     Outs.push_back(ISD::OutputArg(
2182         Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
2183         /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
2184     // Create SDNode for the swifterror virtual register.
2185     OutVals.push_back(
2186         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2187                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2188                         EVT(TLI.getPointerTy(DL))));
2189   }
2190 
2191   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2192   CallingConv::ID CallConv =
2193     DAG.getMachineFunction().getFunction().getCallingConv();
2194   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2195       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2196 
2197   // Verify that the target's LowerReturn behaved as expected.
2198   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2199          "LowerReturn didn't return a valid chain!");
2200 
2201   // Update the DAG with the new chain value resulting from return lowering.
2202   DAG.setRoot(Chain);
2203 }
2204 
2205 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2206 /// created for it, emit nodes to copy the value into the virtual
2207 /// registers.
2208 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2209   // Skip empty types
2210   if (V->getType()->isEmptyTy())
2211     return;
2212 
2213   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2214   if (VMI != FuncInfo.ValueMap.end()) {
2215     assert((!V->use_empty() || isa<CallBrInst>(V)) &&
2216            "Unused value assigned virtual registers!");
2217     CopyValueToVirtualRegister(V, VMI->second);
2218   }
2219 }
2220 
2221 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2222 /// the current basic block, add it to ValueMap now so that we'll get a
2223 /// CopyTo/FromReg.
2224 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2225   // No need to export constants.
2226   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2227 
2228   // Already exported?
2229   if (FuncInfo.isExportedInst(V)) return;
2230 
2231   Register Reg = FuncInfo.InitializeRegForValue(V);
2232   CopyValueToVirtualRegister(V, Reg);
2233 }
2234 
2235 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2236                                                      const BasicBlock *FromBB) {
2237   // The operands of the setcc have to be in this block.  We don't know
2238   // how to export them from some other block.
2239   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2240     // Can export from current BB.
2241     if (VI->getParent() == FromBB)
2242       return true;
2243 
2244     // Is already exported, noop.
2245     return FuncInfo.isExportedInst(V);
2246   }
2247 
2248   // If this is an argument, we can export it if the BB is the entry block or
2249   // if it is already exported.
2250   if (isa<Argument>(V)) {
2251     if (FromBB->isEntryBlock())
2252       return true;
2253 
2254     // Otherwise, can only export this if it is already exported.
2255     return FuncInfo.isExportedInst(V);
2256   }
2257 
2258   // Otherwise, constants can always be exported.
2259   return true;
2260 }
2261 
2262 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2263 BranchProbability
2264 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2265                                         const MachineBasicBlock *Dst) const {
2266   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2267   const BasicBlock *SrcBB = Src->getBasicBlock();
2268   const BasicBlock *DstBB = Dst->getBasicBlock();
2269   if (!BPI) {
2270     // If BPI is not available, set the default probability as 1 / N, where N is
2271     // the number of successors.
2272     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2273     return BranchProbability(1, SuccSize);
2274   }
2275   return BPI->getEdgeProbability(SrcBB, DstBB);
2276 }
2277 
2278 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2279                                                MachineBasicBlock *Dst,
2280                                                BranchProbability Prob) {
2281   if (!FuncInfo.BPI)
2282     Src->addSuccessorWithoutProb(Dst);
2283   else {
2284     if (Prob.isUnknown())
2285       Prob = getEdgeProbability(Src, Dst);
2286     Src->addSuccessor(Dst, Prob);
2287   }
2288 }
2289 
2290 static bool InBlock(const Value *V, const BasicBlock *BB) {
2291   if (const Instruction *I = dyn_cast<Instruction>(V))
2292     return I->getParent() == BB;
2293   return true;
2294 }
2295 
2296 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2297 /// This function emits a branch and is used at the leaves of an OR or an
2298 /// AND operator tree.
2299 void
2300 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2301                                                   MachineBasicBlock *TBB,
2302                                                   MachineBasicBlock *FBB,
2303                                                   MachineBasicBlock *CurBB,
2304                                                   MachineBasicBlock *SwitchBB,
2305                                                   BranchProbability TProb,
2306                                                   BranchProbability FProb,
2307                                                   bool InvertCond) {
2308   const BasicBlock *BB = CurBB->getBasicBlock();
2309 
2310   // If the leaf of the tree is a comparison, merge the condition into
2311   // the caseblock.
2312   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2313     // The operands of the cmp have to be in this block.  We don't know
2314     // how to export them from some other block.  If this is the first block
2315     // of the sequence, no exporting is needed.
2316     if (CurBB == SwitchBB ||
2317         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2318          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2319       ISD::CondCode Condition;
2320       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2321         ICmpInst::Predicate Pred =
2322             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2323         Condition = getICmpCondCode(Pred);
2324       } else {
2325         const FCmpInst *FC = cast<FCmpInst>(Cond);
2326         FCmpInst::Predicate Pred =
2327             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2328         Condition = getFCmpCondCode(Pred);
2329         if (TM.Options.NoNaNsFPMath)
2330           Condition = getFCmpCodeWithoutNaN(Condition);
2331       }
2332 
2333       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2334                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2335       SL->SwitchCases.push_back(CB);
2336       return;
2337     }
2338   }
2339 
2340   // Create a CaseBlock record representing this branch.
2341   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2342   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2343                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2344   SL->SwitchCases.push_back(CB);
2345 }
2346 
2347 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2348                                                MachineBasicBlock *TBB,
2349                                                MachineBasicBlock *FBB,
2350                                                MachineBasicBlock *CurBB,
2351                                                MachineBasicBlock *SwitchBB,
2352                                                Instruction::BinaryOps Opc,
2353                                                BranchProbability TProb,
2354                                                BranchProbability FProb,
2355                                                bool InvertCond) {
2356   // Skip over not part of the tree and remember to invert op and operands at
2357   // next level.
2358   Value *NotCond;
2359   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2360       InBlock(NotCond, CurBB->getBasicBlock())) {
2361     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2362                          !InvertCond);
2363     return;
2364   }
2365 
2366   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2367   const Value *BOpOp0, *BOpOp1;
2368   // Compute the effective opcode for Cond, taking into account whether it needs
2369   // to be inverted, e.g.
2370   //   and (not (or A, B)), C
2371   // gets lowered as
2372   //   and (and (not A, not B), C)
2373   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2374   if (BOp) {
2375     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2376                ? Instruction::And
2377                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2378                       ? Instruction::Or
2379                       : (Instruction::BinaryOps)0);
2380     if (InvertCond) {
2381       if (BOpc == Instruction::And)
2382         BOpc = Instruction::Or;
2383       else if (BOpc == Instruction::Or)
2384         BOpc = Instruction::And;
2385     }
2386   }
2387 
2388   // If this node is not part of the or/and tree, emit it as a branch.
2389   // Note that all nodes in the tree should have same opcode.
2390   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2391   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2392       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2393       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2394     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2395                                  TProb, FProb, InvertCond);
2396     return;
2397   }
2398 
2399   //  Create TmpBB after CurBB.
2400   MachineFunction::iterator BBI(CurBB);
2401   MachineFunction &MF = DAG.getMachineFunction();
2402   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2403   CurBB->getParent()->insert(++BBI, TmpBB);
2404 
2405   if (Opc == Instruction::Or) {
2406     // Codegen X | Y as:
2407     // BB1:
2408     //   jmp_if_X TBB
2409     //   jmp TmpBB
2410     // TmpBB:
2411     //   jmp_if_Y TBB
2412     //   jmp FBB
2413     //
2414 
2415     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2416     // The requirement is that
2417     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2418     //     = TrueProb for original BB.
2419     // Assuming the original probabilities are A and B, one choice is to set
2420     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2421     // A/(1+B) and 2B/(1+B). This choice assumes that
2422     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2423     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2424     // TmpBB, but the math is more complicated.
2425 
2426     auto NewTrueProb = TProb / 2;
2427     auto NewFalseProb = TProb / 2 + FProb;
2428     // Emit the LHS condition.
2429     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2430                          NewFalseProb, InvertCond);
2431 
2432     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2433     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2434     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2435     // Emit the RHS condition into TmpBB.
2436     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2437                          Probs[1], InvertCond);
2438   } else {
2439     assert(Opc == Instruction::And && "Unknown merge op!");
2440     // Codegen X & Y as:
2441     // BB1:
2442     //   jmp_if_X TmpBB
2443     //   jmp FBB
2444     // TmpBB:
2445     //   jmp_if_Y TBB
2446     //   jmp FBB
2447     //
2448     //  This requires creation of TmpBB after CurBB.
2449 
2450     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2451     // The requirement is that
2452     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2453     //     = FalseProb for original BB.
2454     // Assuming the original probabilities are A and B, one choice is to set
2455     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2456     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2457     // TrueProb for BB1 * FalseProb for TmpBB.
2458 
2459     auto NewTrueProb = TProb + FProb / 2;
2460     auto NewFalseProb = FProb / 2;
2461     // Emit the LHS condition.
2462     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2463                          NewFalseProb, InvertCond);
2464 
2465     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2466     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2467     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2468     // Emit the RHS condition into TmpBB.
2469     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2470                          Probs[1], InvertCond);
2471   }
2472 }
2473 
2474 /// If the set of cases should be emitted as a series of branches, return true.
2475 /// If we should emit this as a bunch of and/or'd together conditions, return
2476 /// false.
2477 bool
2478 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2479   if (Cases.size() != 2) return true;
2480 
2481   // If this is two comparisons of the same values or'd or and'd together, they
2482   // will get folded into a single comparison, so don't emit two blocks.
2483   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2484        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2485       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2486        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2487     return false;
2488   }
2489 
2490   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2491   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2492   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2493       Cases[0].CC == Cases[1].CC &&
2494       isa<Constant>(Cases[0].CmpRHS) &&
2495       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2496     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2497       return false;
2498     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2499       return false;
2500   }
2501 
2502   return true;
2503 }
2504 
2505 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2506   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2507 
2508   // Update machine-CFG edges.
2509   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2510 
2511   if (I.isUnconditional()) {
2512     // Update machine-CFG edges.
2513     BrMBB->addSuccessor(Succ0MBB);
2514 
2515     // If this is not a fall-through branch or optimizations are switched off,
2516     // emit the branch.
2517     if (Succ0MBB != NextBlock(BrMBB) ||
2518         TM.getOptLevel() == CodeGenOptLevel::None) {
2519       auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
2520                             getControlRoot(), DAG.getBasicBlock(Succ0MBB));
2521       setValue(&I, Br);
2522       DAG.setRoot(Br);
2523     }
2524 
2525     return;
2526   }
2527 
2528   // If this condition is one of the special cases we handle, do special stuff
2529   // now.
2530   const Value *CondVal = I.getCondition();
2531   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2532 
2533   // If this is a series of conditions that are or'd or and'd together, emit
2534   // this as a sequence of branches instead of setcc's with and/or operations.
2535   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2536   // unpredictable branches, and vector extracts because those jumps are likely
2537   // expensive for any target), this should improve performance.
2538   // For example, instead of something like:
2539   //     cmp A, B
2540   //     C = seteq
2541   //     cmp D, E
2542   //     F = setle
2543   //     or C, F
2544   //     jnz foo
2545   // Emit:
2546   //     cmp A, B
2547   //     je foo
2548   //     cmp D, E
2549   //     jle foo
2550   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2551   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2552       BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2553     Value *Vec;
2554     const Value *BOp0, *BOp1;
2555     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2556     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2557       Opcode = Instruction::And;
2558     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2559       Opcode = Instruction::Or;
2560 
2561     if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2562                     match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
2563       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2564                            getEdgeProbability(BrMBB, Succ0MBB),
2565                            getEdgeProbability(BrMBB, Succ1MBB),
2566                            /*InvertCond=*/false);
2567       // If the compares in later blocks need to use values not currently
2568       // exported from this block, export them now.  This block should always
2569       // be the first entry.
2570       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2571 
2572       // Allow some cases to be rejected.
2573       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2574         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2575           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2576           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2577         }
2578 
2579         // Emit the branch for this block.
2580         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2581         SL->SwitchCases.erase(SL->SwitchCases.begin());
2582         return;
2583       }
2584 
2585       // Okay, we decided not to do this, remove any inserted MBB's and clear
2586       // SwitchCases.
2587       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2588         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2589 
2590       SL->SwitchCases.clear();
2591     }
2592   }
2593 
2594   // Create a CaseBlock record representing this branch.
2595   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2596                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2597 
2598   // Use visitSwitchCase to actually insert the fast branch sequence for this
2599   // cond branch.
2600   visitSwitchCase(CB, BrMBB);
2601 }
2602 
2603 /// visitSwitchCase - Emits the necessary code to represent a single node in
2604 /// the binary search tree resulting from lowering a switch instruction.
2605 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2606                                           MachineBasicBlock *SwitchBB) {
2607   SDValue Cond;
2608   SDValue CondLHS = getValue(CB.CmpLHS);
2609   SDLoc dl = CB.DL;
2610 
2611   if (CB.CC == ISD::SETTRUE) {
2612     // Branch or fall through to TrueBB.
2613     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2614     SwitchBB->normalizeSuccProbs();
2615     if (CB.TrueBB != NextBlock(SwitchBB)) {
2616       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2617                               DAG.getBasicBlock(CB.TrueBB)));
2618     }
2619     return;
2620   }
2621 
2622   auto &TLI = DAG.getTargetLoweringInfo();
2623   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2624 
2625   // Build the setcc now.
2626   if (!CB.CmpMHS) {
2627     // Fold "(X == true)" to X and "(X == false)" to !X to
2628     // handle common cases produced by branch lowering.
2629     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2630         CB.CC == ISD::SETEQ)
2631       Cond = CondLHS;
2632     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2633              CB.CC == ISD::SETEQ) {
2634       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2635       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2636     } else {
2637       SDValue CondRHS = getValue(CB.CmpRHS);
2638 
2639       // If a pointer's DAG type is larger than its memory type then the DAG
2640       // values are zero-extended. This breaks signed comparisons so truncate
2641       // back to the underlying type before doing the compare.
2642       if (CondLHS.getValueType() != MemVT) {
2643         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2644         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2645       }
2646       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2647     }
2648   } else {
2649     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2650 
2651     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2652     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2653 
2654     SDValue CmpOp = getValue(CB.CmpMHS);
2655     EVT VT = CmpOp.getValueType();
2656 
2657     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2658       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2659                           ISD::SETLE);
2660     } else {
2661       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2662                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2663       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2664                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2665     }
2666   }
2667 
2668   // Update successor info
2669   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2670   // TrueBB and FalseBB are always different unless the incoming IR is
2671   // degenerate. This only happens when running llc on weird IR.
2672   if (CB.TrueBB != CB.FalseBB)
2673     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2674   SwitchBB->normalizeSuccProbs();
2675 
2676   // If the lhs block is the next block, invert the condition so that we can
2677   // fall through to the lhs instead of the rhs block.
2678   if (CB.TrueBB == NextBlock(SwitchBB)) {
2679     std::swap(CB.TrueBB, CB.FalseBB);
2680     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2681     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2682   }
2683 
2684   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2685                                MVT::Other, getControlRoot(), Cond,
2686                                DAG.getBasicBlock(CB.TrueBB));
2687 
2688   setValue(CurInst, BrCond);
2689 
2690   // Insert the false branch. Do this even if it's a fall through branch,
2691   // this makes it easier to do DAG optimizations which require inverting
2692   // the branch condition.
2693   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2694                        DAG.getBasicBlock(CB.FalseBB));
2695 
2696   DAG.setRoot(BrCond);
2697 }
2698 
2699 /// visitJumpTable - Emit JumpTable node in the current MBB
2700 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2701   // Emit the code for the jump table
2702   assert(JT.SL && "Should set SDLoc for SelectionDAG!");
2703   assert(JT.Reg != -1U && "Should lower JT Header first!");
2704   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2705   SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy);
2706   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2707   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other,
2708                                     Index.getValue(1), Table, Index);
2709   DAG.setRoot(BrJumpTable);
2710 }
2711 
2712 /// visitJumpTableHeader - This function emits necessary code to produce index
2713 /// in the JumpTable from switch case.
2714 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2715                                                JumpTableHeader &JTH,
2716                                                MachineBasicBlock *SwitchBB) {
2717   assert(JT.SL && "Should set SDLoc for SelectionDAG!");
2718   const SDLoc &dl = *JT.SL;
2719 
2720   // Subtract the lowest switch case value from the value being switched on.
2721   SDValue SwitchOp = getValue(JTH.SValue);
2722   EVT VT = SwitchOp.getValueType();
2723   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2724                             DAG.getConstant(JTH.First, dl, VT));
2725 
2726   // The SDNode we just created, which holds the value being switched on minus
2727   // the smallest case value, needs to be copied to a virtual register so it
2728   // can be used as an index into the jump table in a subsequent basic block.
2729   // This value may be smaller or larger than the target's pointer type, and
2730   // therefore require extension or truncating.
2731   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2732   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2733 
2734   unsigned JumpTableReg =
2735       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2736   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2737                                     JumpTableReg, SwitchOp);
2738   JT.Reg = JumpTableReg;
2739 
2740   if (!JTH.FallthroughUnreachable) {
2741     // Emit the range check for the jump table, and branch to the default block
2742     // for the switch statement if the value being switched on exceeds the
2743     // largest case in the switch.
2744     SDValue CMP = DAG.getSetCC(
2745         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2746                                    Sub.getValueType()),
2747         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2748 
2749     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2750                                  MVT::Other, CopyTo, CMP,
2751                                  DAG.getBasicBlock(JT.Default));
2752 
2753     // Avoid emitting unnecessary branches to the next block.
2754     if (JT.MBB != NextBlock(SwitchBB))
2755       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2756                            DAG.getBasicBlock(JT.MBB));
2757 
2758     DAG.setRoot(BrCond);
2759   } else {
2760     // Avoid emitting unnecessary branches to the next block.
2761     if (JT.MBB != NextBlock(SwitchBB))
2762       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2763                               DAG.getBasicBlock(JT.MBB)));
2764     else
2765       DAG.setRoot(CopyTo);
2766   }
2767 }
2768 
2769 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2770 /// variable if there exists one.
2771 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2772                                  SDValue &Chain) {
2773   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2774   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2775   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2776   MachineFunction &MF = DAG.getMachineFunction();
2777   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2778   MachineSDNode *Node =
2779       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2780   if (Global) {
2781     MachinePointerInfo MPInfo(Global);
2782     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2783                  MachineMemOperand::MODereferenceable;
2784     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2785         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2786     DAG.setNodeMemRefs(Node, {MemRef});
2787   }
2788   if (PtrTy != PtrMemTy)
2789     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2790   return SDValue(Node, 0);
2791 }
2792 
2793 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2794 /// tail spliced into a stack protector check success bb.
2795 ///
2796 /// For a high level explanation of how this fits into the stack protector
2797 /// generation see the comment on the declaration of class
2798 /// StackProtectorDescriptor.
2799 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2800                                                   MachineBasicBlock *ParentBB) {
2801 
2802   // First create the loads to the guard/stack slot for the comparison.
2803   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2804   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2805   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2806 
2807   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2808   int FI = MFI.getStackProtectorIndex();
2809 
2810   SDValue Guard;
2811   SDLoc dl = getCurSDLoc();
2812   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2813   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2814   Align Align =
2815       DAG.getDataLayout().getPrefTypeAlign(PointerType::get(M.getContext(), 0));
2816 
2817   // Generate code to load the content of the guard slot.
2818   SDValue GuardVal = DAG.getLoad(
2819       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2820       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2821       MachineMemOperand::MOVolatile);
2822 
2823   if (TLI.useStackGuardXorFP())
2824     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2825 
2826   // Retrieve guard check function, nullptr if instrumentation is inlined.
2827   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2828     // The target provides a guard check function to validate the guard value.
2829     // Generate a call to that function with the content of the guard slot as
2830     // argument.
2831     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2832     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2833 
2834     TargetLowering::ArgListTy Args;
2835     TargetLowering::ArgListEntry Entry;
2836     Entry.Node = GuardVal;
2837     Entry.Ty = FnTy->getParamType(0);
2838     if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
2839       Entry.IsInReg = true;
2840     Args.push_back(Entry);
2841 
2842     TargetLowering::CallLoweringInfo CLI(DAG);
2843     CLI.setDebugLoc(getCurSDLoc())
2844         .setChain(DAG.getEntryNode())
2845         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2846                    getValue(GuardCheckFn), std::move(Args));
2847 
2848     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2849     DAG.setRoot(Result.second);
2850     return;
2851   }
2852 
2853   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2854   // Otherwise, emit a volatile load to retrieve the stack guard value.
2855   SDValue Chain = DAG.getEntryNode();
2856   if (TLI.useLoadStackGuardNode()) {
2857     Guard = getLoadStackGuard(DAG, dl, Chain);
2858   } else {
2859     const Value *IRGuard = TLI.getSDagStackGuard(M);
2860     SDValue GuardPtr = getValue(IRGuard);
2861 
2862     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2863                         MachinePointerInfo(IRGuard, 0), Align,
2864                         MachineMemOperand::MOVolatile);
2865   }
2866 
2867   // Perform the comparison via a getsetcc.
2868   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2869                                                         *DAG.getContext(),
2870                                                         Guard.getValueType()),
2871                              Guard, GuardVal, ISD::SETNE);
2872 
2873   // If the guard/stackslot do not equal, branch to failure MBB.
2874   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2875                                MVT::Other, GuardVal.getOperand(0),
2876                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2877   // Otherwise branch to success MBB.
2878   SDValue Br = DAG.getNode(ISD::BR, dl,
2879                            MVT::Other, BrCond,
2880                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2881 
2882   DAG.setRoot(Br);
2883 }
2884 
2885 /// Codegen the failure basic block for a stack protector check.
2886 ///
2887 /// A failure stack protector machine basic block consists simply of a call to
2888 /// __stack_chk_fail().
2889 ///
2890 /// For a high level explanation of how this fits into the stack protector
2891 /// generation see the comment on the declaration of class
2892 /// StackProtectorDescriptor.
2893 void
2894 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2895   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2896   TargetLowering::MakeLibCallOptions CallOptions;
2897   CallOptions.setDiscardResult(true);
2898   SDValue Chain =
2899       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2900                       std::nullopt, CallOptions, getCurSDLoc())
2901           .second;
2902   // On PS4/PS5, the "return address" must still be within the calling
2903   // function, even if it's at the very end, so emit an explicit TRAP here.
2904   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2905   if (TM.getTargetTriple().isPS())
2906     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2907   // WebAssembly needs an unreachable instruction after a non-returning call,
2908   // because the function return type can be different from __stack_chk_fail's
2909   // return type (void).
2910   if (TM.getTargetTriple().isWasm())
2911     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2912 
2913   DAG.setRoot(Chain);
2914 }
2915 
2916 /// visitBitTestHeader - This function emits necessary code to produce value
2917 /// suitable for "bit tests"
2918 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2919                                              MachineBasicBlock *SwitchBB) {
2920   SDLoc dl = getCurSDLoc();
2921 
2922   // Subtract the minimum value.
2923   SDValue SwitchOp = getValue(B.SValue);
2924   EVT VT = SwitchOp.getValueType();
2925   SDValue RangeSub =
2926       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2927 
2928   // Determine the type of the test operands.
2929   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2930   bool UsePtrType = false;
2931   if (!TLI.isTypeLegal(VT)) {
2932     UsePtrType = true;
2933   } else {
2934     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2935       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2936         // Switch table case range are encoded into series of masks.
2937         // Just use pointer type, it's guaranteed to fit.
2938         UsePtrType = true;
2939         break;
2940       }
2941   }
2942   SDValue Sub = RangeSub;
2943   if (UsePtrType) {
2944     VT = TLI.getPointerTy(DAG.getDataLayout());
2945     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2946   }
2947 
2948   B.RegVT = VT.getSimpleVT();
2949   B.Reg = FuncInfo.CreateReg(B.RegVT);
2950   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2951 
2952   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2953 
2954   if (!B.FallthroughUnreachable)
2955     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2956   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2957   SwitchBB->normalizeSuccProbs();
2958 
2959   SDValue Root = CopyTo;
2960   if (!B.FallthroughUnreachable) {
2961     // Conditional branch to the default block.
2962     SDValue RangeCmp = DAG.getSetCC(dl,
2963         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2964                                RangeSub.getValueType()),
2965         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2966         ISD::SETUGT);
2967 
2968     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2969                        DAG.getBasicBlock(B.Default));
2970   }
2971 
2972   // Avoid emitting unnecessary branches to the next block.
2973   if (MBB != NextBlock(SwitchBB))
2974     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2975 
2976   DAG.setRoot(Root);
2977 }
2978 
2979 /// visitBitTestCase - this function produces one "bit test"
2980 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2981                                            MachineBasicBlock* NextMBB,
2982                                            BranchProbability BranchProbToNext,
2983                                            unsigned Reg,
2984                                            BitTestCase &B,
2985                                            MachineBasicBlock *SwitchBB) {
2986   SDLoc dl = getCurSDLoc();
2987   MVT VT = BB.RegVT;
2988   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2989   SDValue Cmp;
2990   unsigned PopCount = llvm::popcount(B.Mask);
2991   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2992   if (PopCount == 1) {
2993     // Testing for a single bit; just compare the shift count with what it
2994     // would need to be to shift a 1 bit in that position.
2995     Cmp = DAG.getSetCC(
2996         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2997         ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT),
2998         ISD::SETEQ);
2999   } else if (PopCount == BB.Range) {
3000     // There is only one zero bit in the range, test for it directly.
3001     Cmp = DAG.getSetCC(
3002         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3003         ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE);
3004   } else {
3005     // Make desired shift
3006     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
3007                                     DAG.getConstant(1, dl, VT), ShiftOp);
3008 
3009     // Emit bit tests and jumps
3010     SDValue AndOp = DAG.getNode(ISD::AND, dl,
3011                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
3012     Cmp = DAG.getSetCC(
3013         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3014         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
3015   }
3016 
3017   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
3018   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
3019   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
3020   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
3021   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
3022   // one as they are relative probabilities (and thus work more like weights),
3023   // and hence we need to normalize them to let the sum of them become one.
3024   SwitchBB->normalizeSuccProbs();
3025 
3026   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
3027                               MVT::Other, getControlRoot(),
3028                               Cmp, DAG.getBasicBlock(B.TargetBB));
3029 
3030   // Avoid emitting unnecessary branches to the next block.
3031   if (NextMBB != NextBlock(SwitchBB))
3032     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
3033                         DAG.getBasicBlock(NextMBB));
3034 
3035   DAG.setRoot(BrAnd);
3036 }
3037 
3038 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
3039   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
3040 
3041   // Retrieve successors. Look through artificial IR level blocks like
3042   // catchswitch for successors.
3043   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
3044   const BasicBlock *EHPadBB = I.getSuccessor(1);
3045   MachineBasicBlock *EHPadMBB = FuncInfo.MBBMap[EHPadBB];
3046 
3047   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3048   // have to do anything here to lower funclet bundles.
3049   assert(!I.hasOperandBundlesOtherThan(
3050              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
3051               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
3052               LLVMContext::OB_cfguardtarget,
3053               LLVMContext::OB_clang_arc_attachedcall}) &&
3054          "Cannot lower invokes with arbitrary operand bundles yet!");
3055 
3056   const Value *Callee(I.getCalledOperand());
3057   const Function *Fn = dyn_cast<Function>(Callee);
3058   if (isa<InlineAsm>(Callee))
3059     visitInlineAsm(I, EHPadBB);
3060   else if (Fn && Fn->isIntrinsic()) {
3061     switch (Fn->getIntrinsicID()) {
3062     default:
3063       llvm_unreachable("Cannot invoke this intrinsic");
3064     case Intrinsic::donothing:
3065       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
3066     case Intrinsic::seh_try_begin:
3067     case Intrinsic::seh_scope_begin:
3068     case Intrinsic::seh_try_end:
3069     case Intrinsic::seh_scope_end:
3070       if (EHPadMBB)
3071           // a block referenced by EH table
3072           // so dtor-funclet not removed by opts
3073           EHPadMBB->setMachineBlockAddressTaken();
3074       break;
3075     case Intrinsic::experimental_patchpoint_void:
3076     case Intrinsic::experimental_patchpoint_i64:
3077       visitPatchpoint(I, EHPadBB);
3078       break;
3079     case Intrinsic::experimental_gc_statepoint:
3080       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
3081       break;
3082     case Intrinsic::wasm_rethrow: {
3083       // This is usually done in visitTargetIntrinsic, but this intrinsic is
3084       // special because it can be invoked, so we manually lower it to a DAG
3085       // node here.
3086       SmallVector<SDValue, 8> Ops;
3087       Ops.push_back(getRoot()); // inchain
3088       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3089       Ops.push_back(
3090           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
3091                                 TLI.getPointerTy(DAG.getDataLayout())));
3092       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3093       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3094       break;
3095     }
3096     }
3097   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
3098     // Currently we do not lower any intrinsic calls with deopt operand bundles.
3099     // Eventually we will support lowering the @llvm.experimental.deoptimize
3100     // intrinsic, and right now there are no plans to support other intrinsics
3101     // with deopt state.
3102     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
3103   } else {
3104     LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
3105   }
3106 
3107   // If the value of the invoke is used outside of its defining block, make it
3108   // available as a virtual register.
3109   // We already took care of the exported value for the statepoint instruction
3110   // during call to the LowerStatepoint.
3111   if (!isa<GCStatepointInst>(I)) {
3112     CopyToExportRegsIfNeeded(&I);
3113   }
3114 
3115   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
3116   BranchProbabilityInfo *BPI = FuncInfo.BPI;
3117   BranchProbability EHPadBBProb =
3118       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3119           : BranchProbability::getZero();
3120   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
3121 
3122   // Update successor info.
3123   addSuccessorWithProb(InvokeMBB, Return);
3124   for (auto &UnwindDest : UnwindDests) {
3125     UnwindDest.first->setIsEHPad();
3126     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3127   }
3128   InvokeMBB->normalizeSuccProbs();
3129 
3130   // Drop into normal successor.
3131   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
3132                           DAG.getBasicBlock(Return)));
3133 }
3134 
3135 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3136   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3137 
3138   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3139   // have to do anything here to lower funclet bundles.
3140   assert(!I.hasOperandBundlesOtherThan(
3141              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
3142          "Cannot lower callbrs with arbitrary operand bundles yet!");
3143 
3144   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
3145   visitInlineAsm(I);
3146   CopyToExportRegsIfNeeded(&I);
3147 
3148   // Retrieve successors.
3149   SmallPtrSet<BasicBlock *, 8> Dests;
3150   Dests.insert(I.getDefaultDest());
3151   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
3152 
3153   // Update successor info.
3154   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3155   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
3156     BasicBlock *Dest = I.getIndirectDest(i);
3157     MachineBasicBlock *Target = FuncInfo.MBBMap[Dest];
3158     Target->setIsInlineAsmBrIndirectTarget();
3159     Target->setMachineBlockAddressTaken();
3160     Target->setLabelMustBeEmitted();
3161     // Don't add duplicate machine successors.
3162     if (Dests.insert(Dest).second)
3163       addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3164   }
3165   CallBrMBB->normalizeSuccProbs();
3166 
3167   // Drop into default successor.
3168   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3169                           MVT::Other, getControlRoot(),
3170                           DAG.getBasicBlock(Return)));
3171 }
3172 
3173 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3174   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3175 }
3176 
3177 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3178   assert(FuncInfo.MBB->isEHPad() &&
3179          "Call to landingpad not in landing pad!");
3180 
3181   // If there aren't registers to copy the values into (e.g., during SjLj
3182   // exceptions), then don't bother to create these DAG nodes.
3183   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3184   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3185   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3186       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3187     return;
3188 
3189   // If landingpad's return type is token type, we don't create DAG nodes
3190   // for its exception pointer and selector value. The extraction of exception
3191   // pointer or selector value from token type landingpads is not currently
3192   // supported.
3193   if (LP.getType()->isTokenTy())
3194     return;
3195 
3196   SmallVector<EVT, 2> ValueVTs;
3197   SDLoc dl = getCurSDLoc();
3198   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3199   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3200 
3201   // Get the two live-in registers as SDValues. The physregs have already been
3202   // copied into virtual registers.
3203   SDValue Ops[2];
3204   if (FuncInfo.ExceptionPointerVirtReg) {
3205     Ops[0] = DAG.getZExtOrTrunc(
3206         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3207                            FuncInfo.ExceptionPointerVirtReg,
3208                            TLI.getPointerTy(DAG.getDataLayout())),
3209         dl, ValueVTs[0]);
3210   } else {
3211     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3212   }
3213   Ops[1] = DAG.getZExtOrTrunc(
3214       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3215                          FuncInfo.ExceptionSelectorVirtReg,
3216                          TLI.getPointerTy(DAG.getDataLayout())),
3217       dl, ValueVTs[1]);
3218 
3219   // Merge into one.
3220   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3221                             DAG.getVTList(ValueVTs), Ops);
3222   setValue(&LP, Res);
3223 }
3224 
3225 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3226                                            MachineBasicBlock *Last) {
3227   // Update JTCases.
3228   for (JumpTableBlock &JTB : SL->JTCases)
3229     if (JTB.first.HeaderBB == First)
3230       JTB.first.HeaderBB = Last;
3231 
3232   // Update BitTestCases.
3233   for (BitTestBlock &BTB : SL->BitTestCases)
3234     if (BTB.Parent == First)
3235       BTB.Parent = Last;
3236 }
3237 
3238 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3239   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3240 
3241   // Update machine-CFG edges with unique successors.
3242   SmallSet<BasicBlock*, 32> Done;
3243   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3244     BasicBlock *BB = I.getSuccessor(i);
3245     bool Inserted = Done.insert(BB).second;
3246     if (!Inserted)
3247         continue;
3248 
3249     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
3250     addSuccessorWithProb(IndirectBrMBB, Succ);
3251   }
3252   IndirectBrMBB->normalizeSuccProbs();
3253 
3254   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3255                           MVT::Other, getControlRoot(),
3256                           getValue(I.getAddress())));
3257 }
3258 
3259 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3260   if (!DAG.getTarget().Options.TrapUnreachable)
3261     return;
3262 
3263   // We may be able to ignore unreachable behind a noreturn call.
3264   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
3265     if (const CallInst *Call = dyn_cast_or_null<CallInst>(I.getPrevNode())) {
3266       if (Call->doesNotReturn())
3267         return;
3268     }
3269   }
3270 
3271   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3272 }
3273 
3274 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3275   SDNodeFlags Flags;
3276   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3277     Flags.copyFMF(*FPOp);
3278 
3279   SDValue Op = getValue(I.getOperand(0));
3280   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3281                                     Op, Flags);
3282   setValue(&I, UnNodeValue);
3283 }
3284 
3285 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3286   SDNodeFlags Flags;
3287   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3288     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3289     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3290   }
3291   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3292     Flags.setExact(ExactOp->isExact());
3293   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3294     Flags.copyFMF(*FPOp);
3295 
3296   SDValue Op1 = getValue(I.getOperand(0));
3297   SDValue Op2 = getValue(I.getOperand(1));
3298   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3299                                      Op1, Op2, Flags);
3300   setValue(&I, BinNodeValue);
3301 }
3302 
3303 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3304   SDValue Op1 = getValue(I.getOperand(0));
3305   SDValue Op2 = getValue(I.getOperand(1));
3306 
3307   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3308       Op1.getValueType(), DAG.getDataLayout());
3309 
3310   // Coerce the shift amount to the right type if we can. This exposes the
3311   // truncate or zext to optimization early.
3312   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3313     assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) &&
3314            "Unexpected shift type");
3315     Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3316   }
3317 
3318   bool nuw = false;
3319   bool nsw = false;
3320   bool exact = false;
3321 
3322   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3323 
3324     if (const OverflowingBinaryOperator *OFBinOp =
3325             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3326       nuw = OFBinOp->hasNoUnsignedWrap();
3327       nsw = OFBinOp->hasNoSignedWrap();
3328     }
3329     if (const PossiblyExactOperator *ExactOp =
3330             dyn_cast<const PossiblyExactOperator>(&I))
3331       exact = ExactOp->isExact();
3332   }
3333   SDNodeFlags Flags;
3334   Flags.setExact(exact);
3335   Flags.setNoSignedWrap(nsw);
3336   Flags.setNoUnsignedWrap(nuw);
3337   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3338                             Flags);
3339   setValue(&I, Res);
3340 }
3341 
3342 void SelectionDAGBuilder::visitSDiv(const User &I) {
3343   SDValue Op1 = getValue(I.getOperand(0));
3344   SDValue Op2 = getValue(I.getOperand(1));
3345 
3346   SDNodeFlags Flags;
3347   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3348                  cast<PossiblyExactOperator>(&I)->isExact());
3349   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3350                            Op2, Flags));
3351 }
3352 
3353 void SelectionDAGBuilder::visitICmp(const User &I) {
3354   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3355   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3356     predicate = IC->getPredicate();
3357   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3358     predicate = ICmpInst::Predicate(IC->getPredicate());
3359   SDValue Op1 = getValue(I.getOperand(0));
3360   SDValue Op2 = getValue(I.getOperand(1));
3361   ISD::CondCode Opcode = getICmpCondCode(predicate);
3362 
3363   auto &TLI = DAG.getTargetLoweringInfo();
3364   EVT MemVT =
3365       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3366 
3367   // If a pointer's DAG type is larger than its memory type then the DAG values
3368   // are zero-extended. This breaks signed comparisons so truncate back to the
3369   // underlying type before doing the compare.
3370   if (Op1.getValueType() != MemVT) {
3371     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3372     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3373   }
3374 
3375   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3376                                                         I.getType());
3377   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3378 }
3379 
3380 void SelectionDAGBuilder::visitFCmp(const User &I) {
3381   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3382   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3383     predicate = FC->getPredicate();
3384   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3385     predicate = FCmpInst::Predicate(FC->getPredicate());
3386   SDValue Op1 = getValue(I.getOperand(0));
3387   SDValue Op2 = getValue(I.getOperand(1));
3388 
3389   ISD::CondCode Condition = getFCmpCondCode(predicate);
3390   auto *FPMO = cast<FPMathOperator>(&I);
3391   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3392     Condition = getFCmpCodeWithoutNaN(Condition);
3393 
3394   SDNodeFlags Flags;
3395   Flags.copyFMF(*FPMO);
3396   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3397 
3398   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3399                                                         I.getType());
3400   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3401 }
3402 
3403 // Check if the condition of the select has one use or two users that are both
3404 // selects with the same condition.
3405 static bool hasOnlySelectUsers(const Value *Cond) {
3406   return llvm::all_of(Cond->users(), [](const Value *V) {
3407     return isa<SelectInst>(V);
3408   });
3409 }
3410 
3411 void SelectionDAGBuilder::visitSelect(const User &I) {
3412   SmallVector<EVT, 4> ValueVTs;
3413   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3414                   ValueVTs);
3415   unsigned NumValues = ValueVTs.size();
3416   if (NumValues == 0) return;
3417 
3418   SmallVector<SDValue, 4> Values(NumValues);
3419   SDValue Cond     = getValue(I.getOperand(0));
3420   SDValue LHSVal   = getValue(I.getOperand(1));
3421   SDValue RHSVal   = getValue(I.getOperand(2));
3422   SmallVector<SDValue, 1> BaseOps(1, Cond);
3423   ISD::NodeType OpCode =
3424       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3425 
3426   bool IsUnaryAbs = false;
3427   bool Negate = false;
3428 
3429   SDNodeFlags Flags;
3430   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3431     Flags.copyFMF(*FPOp);
3432 
3433   Flags.setUnpredictable(
3434       cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable));
3435 
3436   // Min/max matching is only viable if all output VTs are the same.
3437   if (all_equal(ValueVTs)) {
3438     EVT VT = ValueVTs[0];
3439     LLVMContext &Ctx = *DAG.getContext();
3440     auto &TLI = DAG.getTargetLoweringInfo();
3441 
3442     // We care about the legality of the operation after it has been type
3443     // legalized.
3444     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3445       VT = TLI.getTypeToTransformTo(Ctx, VT);
3446 
3447     // If the vselect is legal, assume we want to leave this as a vector setcc +
3448     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3449     // min/max is legal on the scalar type.
3450     bool UseScalarMinMax = VT.isVector() &&
3451       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3452 
3453     // ValueTracking's select pattern matching does not account for -0.0,
3454     // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that
3455     // -0.0 is less than +0.0.
3456     Value *LHS, *RHS;
3457     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3458     ISD::NodeType Opc = ISD::DELETED_NODE;
3459     switch (SPR.Flavor) {
3460     case SPF_UMAX:    Opc = ISD::UMAX; break;
3461     case SPF_UMIN:    Opc = ISD::UMIN; break;
3462     case SPF_SMAX:    Opc = ISD::SMAX; break;
3463     case SPF_SMIN:    Opc = ISD::SMIN; break;
3464     case SPF_FMINNUM:
3465       switch (SPR.NaNBehavior) {
3466       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3467       case SPNB_RETURNS_NAN: break;
3468       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3469       case SPNB_RETURNS_ANY:
3470         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) ||
3471             (UseScalarMinMax &&
3472              TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType())))
3473           Opc = ISD::FMINNUM;
3474         break;
3475       }
3476       break;
3477     case SPF_FMAXNUM:
3478       switch (SPR.NaNBehavior) {
3479       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3480       case SPNB_RETURNS_NAN: break;
3481       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3482       case SPNB_RETURNS_ANY:
3483         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) ||
3484             (UseScalarMinMax &&
3485              TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType())))
3486           Opc = ISD::FMAXNUM;
3487         break;
3488       }
3489       break;
3490     case SPF_NABS:
3491       Negate = true;
3492       [[fallthrough]];
3493     case SPF_ABS:
3494       IsUnaryAbs = true;
3495       Opc = ISD::ABS;
3496       break;
3497     default: break;
3498     }
3499 
3500     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3501         (TLI.isOperationLegalOrCustomOrPromote(Opc, VT) ||
3502          (UseScalarMinMax &&
3503           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3504         // If the underlying comparison instruction is used by any other
3505         // instruction, the consumed instructions won't be destroyed, so it is
3506         // not profitable to convert to a min/max.
3507         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3508       OpCode = Opc;
3509       LHSVal = getValue(LHS);
3510       RHSVal = getValue(RHS);
3511       BaseOps.clear();
3512     }
3513 
3514     if (IsUnaryAbs) {
3515       OpCode = Opc;
3516       LHSVal = getValue(LHS);
3517       BaseOps.clear();
3518     }
3519   }
3520 
3521   if (IsUnaryAbs) {
3522     for (unsigned i = 0; i != NumValues; ++i) {
3523       SDLoc dl = getCurSDLoc();
3524       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3525       Values[i] =
3526           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3527       if (Negate)
3528         Values[i] = DAG.getNegative(Values[i], dl, VT);
3529     }
3530   } else {
3531     for (unsigned i = 0; i != NumValues; ++i) {
3532       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3533       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3534       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3535       Values[i] = DAG.getNode(
3536           OpCode, getCurSDLoc(),
3537           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3538     }
3539   }
3540 
3541   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3542                            DAG.getVTList(ValueVTs), Values));
3543 }
3544 
3545 void SelectionDAGBuilder::visitTrunc(const User &I) {
3546   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3547   SDValue N = getValue(I.getOperand(0));
3548   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3549                                                         I.getType());
3550   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3551 }
3552 
3553 void SelectionDAGBuilder::visitZExt(const User &I) {
3554   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3555   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3556   SDValue N = getValue(I.getOperand(0));
3557   auto &TLI = DAG.getTargetLoweringInfo();
3558   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3559 
3560   SDNodeFlags Flags;
3561   if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
3562     Flags.setNonNeg(PNI->hasNonNeg());
3563 
3564   // Eagerly use nonneg information to canonicalize towards sign_extend if
3565   // that is the target's preference.
3566   // TODO: Let the target do this later.
3567   if (Flags.hasNonNeg() &&
3568       TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) {
3569     setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3570     return;
3571   }
3572 
3573   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags));
3574 }
3575 
3576 void SelectionDAGBuilder::visitSExt(const User &I) {
3577   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3578   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3579   SDValue N = getValue(I.getOperand(0));
3580   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3581                                                         I.getType());
3582   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3583 }
3584 
3585 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3586   // FPTrunc is never a no-op cast, no need to check
3587   SDValue N = getValue(I.getOperand(0));
3588   SDLoc dl = getCurSDLoc();
3589   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3590   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3591   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3592                            DAG.getTargetConstant(
3593                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3594 }
3595 
3596 void SelectionDAGBuilder::visitFPExt(const User &I) {
3597   // FPExt is never a no-op cast, no need to check
3598   SDValue N = getValue(I.getOperand(0));
3599   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3600                                                         I.getType());
3601   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3602 }
3603 
3604 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3605   // FPToUI is never a no-op cast, no need to check
3606   SDValue N = getValue(I.getOperand(0));
3607   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3608                                                         I.getType());
3609   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3610 }
3611 
3612 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3613   // FPToSI is never a no-op cast, no need to check
3614   SDValue N = getValue(I.getOperand(0));
3615   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3616                                                         I.getType());
3617   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3618 }
3619 
3620 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3621   // UIToFP is never a no-op cast, no need to check
3622   SDValue N = getValue(I.getOperand(0));
3623   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3624                                                         I.getType());
3625   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3626 }
3627 
3628 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3629   // SIToFP is never a no-op cast, no need to check
3630   SDValue N = getValue(I.getOperand(0));
3631   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3632                                                         I.getType());
3633   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3634 }
3635 
3636 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3637   // What to do depends on the size of the integer and the size of the pointer.
3638   // We can either truncate, zero extend, or no-op, accordingly.
3639   SDValue N = getValue(I.getOperand(0));
3640   auto &TLI = DAG.getTargetLoweringInfo();
3641   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3642                                                         I.getType());
3643   EVT PtrMemVT =
3644       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3645   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3646   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3647   setValue(&I, N);
3648 }
3649 
3650 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3651   // What to do depends on the size of the integer and the size of the pointer.
3652   // We can either truncate, zero extend, or no-op, accordingly.
3653   SDValue N = getValue(I.getOperand(0));
3654   auto &TLI = DAG.getTargetLoweringInfo();
3655   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3656   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3657   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3658   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3659   setValue(&I, N);
3660 }
3661 
3662 void SelectionDAGBuilder::visitBitCast(const User &I) {
3663   SDValue N = getValue(I.getOperand(0));
3664   SDLoc dl = getCurSDLoc();
3665   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3666                                                         I.getType());
3667 
3668   // BitCast assures us that source and destination are the same size so this is
3669   // either a BITCAST or a no-op.
3670   if (DestVT != N.getValueType())
3671     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3672                              DestVT, N)); // convert types.
3673   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3674   // might fold any kind of constant expression to an integer constant and that
3675   // is not what we are looking for. Only recognize a bitcast of a genuine
3676   // constant integer as an opaque constant.
3677   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3678     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3679                                  /*isOpaque*/true));
3680   else
3681     setValue(&I, N);            // noop cast.
3682 }
3683 
3684 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3685   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3686   const Value *SV = I.getOperand(0);
3687   SDValue N = getValue(SV);
3688   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3689 
3690   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3691   unsigned DestAS = I.getType()->getPointerAddressSpace();
3692 
3693   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3694     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3695 
3696   setValue(&I, N);
3697 }
3698 
3699 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3700   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3701   SDValue InVec = getValue(I.getOperand(0));
3702   SDValue InVal = getValue(I.getOperand(1));
3703   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3704                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3705   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3706                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3707                            InVec, InVal, InIdx));
3708 }
3709 
3710 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3711   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3712   SDValue InVec = getValue(I.getOperand(0));
3713   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3714                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3715   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3716                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3717                            InVec, InIdx));
3718 }
3719 
3720 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3721   SDValue Src1 = getValue(I.getOperand(0));
3722   SDValue Src2 = getValue(I.getOperand(1));
3723   ArrayRef<int> Mask;
3724   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3725     Mask = SVI->getShuffleMask();
3726   else
3727     Mask = cast<ConstantExpr>(I).getShuffleMask();
3728   SDLoc DL = getCurSDLoc();
3729   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3730   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3731   EVT SrcVT = Src1.getValueType();
3732 
3733   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3734       VT.isScalableVector()) {
3735     // Canonical splat form of first element of first input vector.
3736     SDValue FirstElt =
3737         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3738                     DAG.getVectorIdxConstant(0, DL));
3739     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3740     return;
3741   }
3742 
3743   // For now, we only handle splats for scalable vectors.
3744   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3745   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3746   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3747 
3748   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3749   unsigned MaskNumElts = Mask.size();
3750 
3751   if (SrcNumElts == MaskNumElts) {
3752     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3753     return;
3754   }
3755 
3756   // Normalize the shuffle vector since mask and vector length don't match.
3757   if (SrcNumElts < MaskNumElts) {
3758     // Mask is longer than the source vectors. We can use concatenate vector to
3759     // make the mask and vectors lengths match.
3760 
3761     if (MaskNumElts % SrcNumElts == 0) {
3762       // Mask length is a multiple of the source vector length.
3763       // Check if the shuffle is some kind of concatenation of the input
3764       // vectors.
3765       unsigned NumConcat = MaskNumElts / SrcNumElts;
3766       bool IsConcat = true;
3767       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3768       for (unsigned i = 0; i != MaskNumElts; ++i) {
3769         int Idx = Mask[i];
3770         if (Idx < 0)
3771           continue;
3772         // Ensure the indices in each SrcVT sized piece are sequential and that
3773         // the same source is used for the whole piece.
3774         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3775             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3776              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3777           IsConcat = false;
3778           break;
3779         }
3780         // Remember which source this index came from.
3781         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3782       }
3783 
3784       // The shuffle is concatenating multiple vectors together. Just emit
3785       // a CONCAT_VECTORS operation.
3786       if (IsConcat) {
3787         SmallVector<SDValue, 8> ConcatOps;
3788         for (auto Src : ConcatSrcs) {
3789           if (Src < 0)
3790             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3791           else if (Src == 0)
3792             ConcatOps.push_back(Src1);
3793           else
3794             ConcatOps.push_back(Src2);
3795         }
3796         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3797         return;
3798       }
3799     }
3800 
3801     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3802     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3803     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3804                                     PaddedMaskNumElts);
3805 
3806     // Pad both vectors with undefs to make them the same length as the mask.
3807     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3808 
3809     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3810     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3811     MOps1[0] = Src1;
3812     MOps2[0] = Src2;
3813 
3814     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3815     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3816 
3817     // Readjust mask for new input vector length.
3818     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3819     for (unsigned i = 0; i != MaskNumElts; ++i) {
3820       int Idx = Mask[i];
3821       if (Idx >= (int)SrcNumElts)
3822         Idx -= SrcNumElts - PaddedMaskNumElts;
3823       MappedOps[i] = Idx;
3824     }
3825 
3826     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3827 
3828     // If the concatenated vector was padded, extract a subvector with the
3829     // correct number of elements.
3830     if (MaskNumElts != PaddedMaskNumElts)
3831       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3832                            DAG.getVectorIdxConstant(0, DL));
3833 
3834     setValue(&I, Result);
3835     return;
3836   }
3837 
3838   if (SrcNumElts > MaskNumElts) {
3839     // Analyze the access pattern of the vector to see if we can extract
3840     // two subvectors and do the shuffle.
3841     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3842     bool CanExtract = true;
3843     for (int Idx : Mask) {
3844       unsigned Input = 0;
3845       if (Idx < 0)
3846         continue;
3847 
3848       if (Idx >= (int)SrcNumElts) {
3849         Input = 1;
3850         Idx -= SrcNumElts;
3851       }
3852 
3853       // If all the indices come from the same MaskNumElts sized portion of
3854       // the sources we can use extract. Also make sure the extract wouldn't
3855       // extract past the end of the source.
3856       int NewStartIdx = alignDown(Idx, MaskNumElts);
3857       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3858           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3859         CanExtract = false;
3860       // Make sure we always update StartIdx as we use it to track if all
3861       // elements are undef.
3862       StartIdx[Input] = NewStartIdx;
3863     }
3864 
3865     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3866       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3867       return;
3868     }
3869     if (CanExtract) {
3870       // Extract appropriate subvector and generate a vector shuffle
3871       for (unsigned Input = 0; Input < 2; ++Input) {
3872         SDValue &Src = Input == 0 ? Src1 : Src2;
3873         if (StartIdx[Input] < 0)
3874           Src = DAG.getUNDEF(VT);
3875         else {
3876           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3877                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3878         }
3879       }
3880 
3881       // Calculate new mask.
3882       SmallVector<int, 8> MappedOps(Mask);
3883       for (int &Idx : MappedOps) {
3884         if (Idx >= (int)SrcNumElts)
3885           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3886         else if (Idx >= 0)
3887           Idx -= StartIdx[0];
3888       }
3889 
3890       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3891       return;
3892     }
3893   }
3894 
3895   // We can't use either concat vectors or extract subvectors so fall back to
3896   // replacing the shuffle with extract and build vector.
3897   // to insert and build vector.
3898   EVT EltVT = VT.getVectorElementType();
3899   SmallVector<SDValue,8> Ops;
3900   for (int Idx : Mask) {
3901     SDValue Res;
3902 
3903     if (Idx < 0) {
3904       Res = DAG.getUNDEF(EltVT);
3905     } else {
3906       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3907       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3908 
3909       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3910                         DAG.getVectorIdxConstant(Idx, DL));
3911     }
3912 
3913     Ops.push_back(Res);
3914   }
3915 
3916   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3917 }
3918 
3919 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
3920   ArrayRef<unsigned> Indices = I.getIndices();
3921   const Value *Op0 = I.getOperand(0);
3922   const Value *Op1 = I.getOperand(1);
3923   Type *AggTy = I.getType();
3924   Type *ValTy = Op1->getType();
3925   bool IntoUndef = isa<UndefValue>(Op0);
3926   bool FromUndef = isa<UndefValue>(Op1);
3927 
3928   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3929 
3930   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3931   SmallVector<EVT, 4> AggValueVTs;
3932   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3933   SmallVector<EVT, 4> ValValueVTs;
3934   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3935 
3936   unsigned NumAggValues = AggValueVTs.size();
3937   unsigned NumValValues = ValValueVTs.size();
3938   SmallVector<SDValue, 4> Values(NumAggValues);
3939 
3940   // Ignore an insertvalue that produces an empty object
3941   if (!NumAggValues) {
3942     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3943     return;
3944   }
3945 
3946   SDValue Agg = getValue(Op0);
3947   unsigned i = 0;
3948   // Copy the beginning value(s) from the original aggregate.
3949   for (; i != LinearIndex; ++i)
3950     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3951                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3952   // Copy values from the inserted value(s).
3953   if (NumValValues) {
3954     SDValue Val = getValue(Op1);
3955     for (; i != LinearIndex + NumValValues; ++i)
3956       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3957                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3958   }
3959   // Copy remaining value(s) from the original aggregate.
3960   for (; i != NumAggValues; ++i)
3961     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3962                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3963 
3964   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3965                            DAG.getVTList(AggValueVTs), Values));
3966 }
3967 
3968 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
3969   ArrayRef<unsigned> Indices = I.getIndices();
3970   const Value *Op0 = I.getOperand(0);
3971   Type *AggTy = Op0->getType();
3972   Type *ValTy = I.getType();
3973   bool OutOfUndef = isa<UndefValue>(Op0);
3974 
3975   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3976 
3977   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3978   SmallVector<EVT, 4> ValValueVTs;
3979   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3980 
3981   unsigned NumValValues = ValValueVTs.size();
3982 
3983   // Ignore a extractvalue that produces an empty object
3984   if (!NumValValues) {
3985     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3986     return;
3987   }
3988 
3989   SmallVector<SDValue, 4> Values(NumValValues);
3990 
3991   SDValue Agg = getValue(Op0);
3992   // Copy out the selected value(s).
3993   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3994     Values[i - LinearIndex] =
3995       OutOfUndef ?
3996         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3997         SDValue(Agg.getNode(), Agg.getResNo() + i);
3998 
3999   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
4000                            DAG.getVTList(ValValueVTs), Values));
4001 }
4002 
4003 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
4004   Value *Op0 = I.getOperand(0);
4005   // Note that the pointer operand may be a vector of pointers. Take the scalar
4006   // element which holds a pointer.
4007   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
4008   SDValue N = getValue(Op0);
4009   SDLoc dl = getCurSDLoc();
4010   auto &TLI = DAG.getTargetLoweringInfo();
4011 
4012   // Normalize Vector GEP - all scalar operands should be converted to the
4013   // splat vector.
4014   bool IsVectorGEP = I.getType()->isVectorTy();
4015   ElementCount VectorElementCount =
4016       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
4017                   : ElementCount::getFixed(0);
4018 
4019   if (IsVectorGEP && !N.getValueType().isVector()) {
4020     LLVMContext &Context = *DAG.getContext();
4021     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
4022     N = DAG.getSplat(VT, dl, N);
4023   }
4024 
4025   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
4026        GTI != E; ++GTI) {
4027     const Value *Idx = GTI.getOperand();
4028     if (StructType *StTy = GTI.getStructTypeOrNull()) {
4029       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
4030       if (Field) {
4031         // N = N + Offset
4032         uint64_t Offset =
4033             DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
4034 
4035         // In an inbounds GEP with an offset that is nonnegative even when
4036         // interpreted as signed, assume there is no unsigned overflow.
4037         SDNodeFlags Flags;
4038         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
4039           Flags.setNoUnsignedWrap(true);
4040 
4041         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
4042                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
4043       }
4044     } else {
4045       // IdxSize is the width of the arithmetic according to IR semantics.
4046       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
4047       // (and fix up the result later).
4048       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
4049       MVT IdxTy = MVT::getIntegerVT(IdxSize);
4050       TypeSize ElementSize =
4051           DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType());
4052       // We intentionally mask away the high bits here; ElementSize may not
4053       // fit in IdxTy.
4054       APInt ElementMul(IdxSize, ElementSize.getKnownMinValue());
4055       bool ElementScalable = ElementSize.isScalable();
4056 
4057       // If this is a scalar constant or a splat vector of constants,
4058       // handle it quickly.
4059       const auto *C = dyn_cast<Constant>(Idx);
4060       if (C && isa<VectorType>(C->getType()))
4061         C = C->getSplatValue();
4062 
4063       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
4064       if (CI && CI->isZero())
4065         continue;
4066       if (CI && !ElementScalable) {
4067         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
4068         LLVMContext &Context = *DAG.getContext();
4069         SDValue OffsVal;
4070         if (IsVectorGEP)
4071           OffsVal = DAG.getConstant(
4072               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
4073         else
4074           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
4075 
4076         // In an inbounds GEP with an offset that is nonnegative even when
4077         // interpreted as signed, assume there is no unsigned overflow.
4078         SDNodeFlags Flags;
4079         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
4080           Flags.setNoUnsignedWrap(true);
4081 
4082         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
4083 
4084         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
4085         continue;
4086       }
4087 
4088       // N = N + Idx * ElementMul;
4089       SDValue IdxN = getValue(Idx);
4090 
4091       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
4092         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
4093                                   VectorElementCount);
4094         IdxN = DAG.getSplat(VT, dl, IdxN);
4095       }
4096 
4097       // If the index is smaller or larger than intptr_t, truncate or extend
4098       // it.
4099       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
4100 
4101       if (ElementScalable) {
4102         EVT VScaleTy = N.getValueType().getScalarType();
4103         SDValue VScale = DAG.getNode(
4104             ISD::VSCALE, dl, VScaleTy,
4105             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
4106         if (IsVectorGEP)
4107           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
4108         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
4109       } else {
4110         // If this is a multiply by a power of two, turn it into a shl
4111         // immediately.  This is a very common case.
4112         if (ElementMul != 1) {
4113           if (ElementMul.isPowerOf2()) {
4114             unsigned Amt = ElementMul.logBase2();
4115             IdxN = DAG.getNode(ISD::SHL, dl,
4116                                N.getValueType(), IdxN,
4117                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
4118           } else {
4119             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
4120                                             IdxN.getValueType());
4121             IdxN = DAG.getNode(ISD::MUL, dl,
4122                                N.getValueType(), IdxN, Scale);
4123           }
4124         }
4125       }
4126 
4127       N = DAG.getNode(ISD::ADD, dl,
4128                       N.getValueType(), N, IdxN);
4129     }
4130   }
4131 
4132   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4133   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4134   if (IsVectorGEP) {
4135     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4136     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4137   }
4138 
4139   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4140     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4141 
4142   setValue(&I, N);
4143 }
4144 
4145 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4146   // If this is a fixed sized alloca in the entry block of the function,
4147   // allocate it statically on the stack.
4148   if (FuncInfo.StaticAllocaMap.count(&I))
4149     return;   // getValue will auto-populate this.
4150 
4151   SDLoc dl = getCurSDLoc();
4152   Type *Ty = I.getAllocatedType();
4153   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4154   auto &DL = DAG.getDataLayout();
4155   TypeSize TySize = DL.getTypeAllocSize(Ty);
4156   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4157 
4158   SDValue AllocSize = getValue(I.getArraySize());
4159 
4160   EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace());
4161   if (AllocSize.getValueType() != IntPtr)
4162     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4163 
4164   if (TySize.isScalable())
4165     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4166                             DAG.getVScale(dl, IntPtr,
4167                                           APInt(IntPtr.getScalarSizeInBits(),
4168                                                 TySize.getKnownMinValue())));
4169   else {
4170     SDValue TySizeValue =
4171         DAG.getConstant(TySize.getFixedValue(), dl, MVT::getIntegerVT(64));
4172     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4173                             DAG.getZExtOrTrunc(TySizeValue, dl, IntPtr));
4174   }
4175 
4176   // Handle alignment.  If the requested alignment is less than or equal to
4177   // the stack alignment, ignore it.  If the size is greater than or equal to
4178   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4179   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4180   if (*Alignment <= StackAlign)
4181     Alignment = std::nullopt;
4182 
4183   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4184   // Round the size of the allocation up to the stack alignment size
4185   // by add SA-1 to the size. This doesn't overflow because we're computing
4186   // an address inside an alloca.
4187   SDNodeFlags Flags;
4188   Flags.setNoUnsignedWrap(true);
4189   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4190                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4191 
4192   // Mask out the low bits for alignment purposes.
4193   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4194                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
4195 
4196   SDValue Ops[] = {
4197       getRoot(), AllocSize,
4198       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4199   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4200   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4201   setValue(&I, DSA);
4202   DAG.setRoot(DSA.getValue(1));
4203 
4204   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4205 }
4206 
4207 static const MDNode *getRangeMetadata(const Instruction &I) {
4208   // If !noundef is not present, then !range violation results in a poison
4209   // value rather than immediate undefined behavior. In theory, transferring
4210   // these annotations to SDAG is fine, but in practice there are key SDAG
4211   // transforms that are known not to be poison-safe, such as folding logical
4212   // and/or to bitwise and/or. For now, only transfer !range if !noundef is
4213   // also present.
4214   if (!I.hasMetadata(LLVMContext::MD_noundef))
4215     return nullptr;
4216   return I.getMetadata(LLVMContext::MD_range);
4217 }
4218 
4219 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4220   if (I.isAtomic())
4221     return visitAtomicLoad(I);
4222 
4223   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4224   const Value *SV = I.getOperand(0);
4225   if (TLI.supportSwiftError()) {
4226     // Swifterror values can come from either a function parameter with
4227     // swifterror attribute or an alloca with swifterror attribute.
4228     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4229       if (Arg->hasSwiftErrorAttr())
4230         return visitLoadFromSwiftError(I);
4231     }
4232 
4233     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4234       if (Alloca->isSwiftError())
4235         return visitLoadFromSwiftError(I);
4236     }
4237   }
4238 
4239   SDValue Ptr = getValue(SV);
4240 
4241   Type *Ty = I.getType();
4242   SmallVector<EVT, 4> ValueVTs, MemVTs;
4243   SmallVector<TypeSize, 4> Offsets;
4244   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets, 0);
4245   unsigned NumValues = ValueVTs.size();
4246   if (NumValues == 0)
4247     return;
4248 
4249   Align Alignment = I.getAlign();
4250   AAMDNodes AAInfo = I.getAAMetadata();
4251   const MDNode *Ranges = getRangeMetadata(I);
4252   bool isVolatile = I.isVolatile();
4253   MachineMemOperand::Flags MMOFlags =
4254       TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4255 
4256   SDValue Root;
4257   bool ConstantMemory = false;
4258   if (isVolatile)
4259     // Serialize volatile loads with other side effects.
4260     Root = getRoot();
4261   else if (NumValues > MaxParallelChains)
4262     Root = getMemoryRoot();
4263   else if (AA &&
4264            AA->pointsToConstantMemory(MemoryLocation(
4265                SV,
4266                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4267                AAInfo))) {
4268     // Do not serialize (non-volatile) loads of constant memory with anything.
4269     Root = DAG.getEntryNode();
4270     ConstantMemory = true;
4271     MMOFlags |= MachineMemOperand::MOInvariant;
4272   } else {
4273     // Do not serialize non-volatile loads against each other.
4274     Root = DAG.getRoot();
4275   }
4276 
4277   SDLoc dl = getCurSDLoc();
4278 
4279   if (isVolatile)
4280     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4281 
4282   SmallVector<SDValue, 4> Values(NumValues);
4283   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4284 
4285   unsigned ChainI = 0;
4286   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4287     // Serializing loads here may result in excessive register pressure, and
4288     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4289     // could recover a bit by hoisting nodes upward in the chain by recognizing
4290     // they are side-effect free or do not alias. The optimizer should really
4291     // avoid this case by converting large object/array copies to llvm.memcpy
4292     // (MaxParallelChains should always remain as failsafe).
4293     if (ChainI == MaxParallelChains) {
4294       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4295       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4296                                   ArrayRef(Chains.data(), ChainI));
4297       Root = Chain;
4298       ChainI = 0;
4299     }
4300 
4301     // TODO: MachinePointerInfo only supports a fixed length offset.
4302     MachinePointerInfo PtrInfo =
4303         !Offsets[i].isScalable() || Offsets[i].isZero()
4304             ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue())
4305             : MachinePointerInfo();
4306 
4307     SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4308     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment,
4309                             MMOFlags, AAInfo, Ranges);
4310     Chains[ChainI] = L.getValue(1);
4311 
4312     if (MemVTs[i] != ValueVTs[i])
4313       L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]);
4314 
4315     Values[i] = L;
4316   }
4317 
4318   if (!ConstantMemory) {
4319     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4320                                 ArrayRef(Chains.data(), ChainI));
4321     if (isVolatile)
4322       DAG.setRoot(Chain);
4323     else
4324       PendingLoads.push_back(Chain);
4325   }
4326 
4327   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4328                            DAG.getVTList(ValueVTs), Values));
4329 }
4330 
4331 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4332   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4333          "call visitStoreToSwiftError when backend supports swifterror");
4334 
4335   SmallVector<EVT, 4> ValueVTs;
4336   SmallVector<uint64_t, 4> Offsets;
4337   const Value *SrcV = I.getOperand(0);
4338   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4339                   SrcV->getType(), ValueVTs, &Offsets, 0);
4340   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4341          "expect a single EVT for swifterror");
4342 
4343   SDValue Src = getValue(SrcV);
4344   // Create a virtual register, then update the virtual register.
4345   Register VReg =
4346       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4347   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4348   // Chain can be getRoot or getControlRoot.
4349   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4350                                       SDValue(Src.getNode(), Src.getResNo()));
4351   DAG.setRoot(CopyNode);
4352 }
4353 
4354 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4355   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4356          "call visitLoadFromSwiftError when backend supports swifterror");
4357 
4358   assert(!I.isVolatile() &&
4359          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4360          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4361          "Support volatile, non temporal, invariant for load_from_swift_error");
4362 
4363   const Value *SV = I.getOperand(0);
4364   Type *Ty = I.getType();
4365   assert(
4366       (!AA ||
4367        !AA->pointsToConstantMemory(MemoryLocation(
4368            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4369            I.getAAMetadata()))) &&
4370       "load_from_swift_error should not be constant memory");
4371 
4372   SmallVector<EVT, 4> ValueVTs;
4373   SmallVector<uint64_t, 4> Offsets;
4374   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4375                   ValueVTs, &Offsets, 0);
4376   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4377          "expect a single EVT for swifterror");
4378 
4379   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4380   SDValue L = DAG.getCopyFromReg(
4381       getRoot(), getCurSDLoc(),
4382       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4383 
4384   setValue(&I, L);
4385 }
4386 
4387 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4388   if (I.isAtomic())
4389     return visitAtomicStore(I);
4390 
4391   const Value *SrcV = I.getOperand(0);
4392   const Value *PtrV = I.getOperand(1);
4393 
4394   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4395   if (TLI.supportSwiftError()) {
4396     // Swifterror values can come from either a function parameter with
4397     // swifterror attribute or an alloca with swifterror attribute.
4398     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4399       if (Arg->hasSwiftErrorAttr())
4400         return visitStoreToSwiftError(I);
4401     }
4402 
4403     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4404       if (Alloca->isSwiftError())
4405         return visitStoreToSwiftError(I);
4406     }
4407   }
4408 
4409   SmallVector<EVT, 4> ValueVTs, MemVTs;
4410   SmallVector<TypeSize, 4> Offsets;
4411   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4412                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets, 0);
4413   unsigned NumValues = ValueVTs.size();
4414   if (NumValues == 0)
4415     return;
4416 
4417   // Get the lowered operands. Note that we do this after
4418   // checking if NumResults is zero, because with zero results
4419   // the operands won't have values in the map.
4420   SDValue Src = getValue(SrcV);
4421   SDValue Ptr = getValue(PtrV);
4422 
4423   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4424   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4425   SDLoc dl = getCurSDLoc();
4426   Align Alignment = I.getAlign();
4427   AAMDNodes AAInfo = I.getAAMetadata();
4428 
4429   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4430 
4431   unsigned ChainI = 0;
4432   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4433     // See visitLoad comments.
4434     if (ChainI == MaxParallelChains) {
4435       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4436                                   ArrayRef(Chains.data(), ChainI));
4437       Root = Chain;
4438       ChainI = 0;
4439     }
4440 
4441     // TODO: MachinePointerInfo only supports a fixed length offset.
4442     MachinePointerInfo PtrInfo =
4443         !Offsets[i].isScalable() || Offsets[i].isZero()
4444             ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue())
4445             : MachinePointerInfo();
4446 
4447     SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4448     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4449     if (MemVTs[i] != ValueVTs[i])
4450       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4451     SDValue St =
4452         DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags, AAInfo);
4453     Chains[ChainI] = St;
4454   }
4455 
4456   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4457                                   ArrayRef(Chains.data(), ChainI));
4458   setValue(&I, StoreNode);
4459   DAG.setRoot(StoreNode);
4460 }
4461 
4462 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4463                                            bool IsCompressing) {
4464   SDLoc sdl = getCurSDLoc();
4465 
4466   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4467                                MaybeAlign &Alignment) {
4468     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4469     Src0 = I.getArgOperand(0);
4470     Ptr = I.getArgOperand(1);
4471     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
4472     Mask = I.getArgOperand(3);
4473   };
4474   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4475                                     MaybeAlign &Alignment) {
4476     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4477     Src0 = I.getArgOperand(0);
4478     Ptr = I.getArgOperand(1);
4479     Mask = I.getArgOperand(2);
4480     Alignment = std::nullopt;
4481   };
4482 
4483   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4484   MaybeAlign Alignment;
4485   if (IsCompressing)
4486     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4487   else
4488     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4489 
4490   SDValue Ptr = getValue(PtrOperand);
4491   SDValue Src0 = getValue(Src0Operand);
4492   SDValue Mask = getValue(MaskOperand);
4493   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4494 
4495   EVT VT = Src0.getValueType();
4496   if (!Alignment)
4497     Alignment = DAG.getEVTAlign(VT);
4498 
4499   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4500       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4501       MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata());
4502   SDValue StoreNode =
4503       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4504                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4505   DAG.setRoot(StoreNode);
4506   setValue(&I, StoreNode);
4507 }
4508 
4509 // Get a uniform base for the Gather/Scatter intrinsic.
4510 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4511 // We try to represent it as a base pointer + vector of indices.
4512 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4513 // The first operand of the GEP may be a single pointer or a vector of pointers
4514 // Example:
4515 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4516 //  or
4517 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4518 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4519 //
4520 // When the first GEP operand is a single pointer - it is the uniform base we
4521 // are looking for. If first operand of the GEP is a splat vector - we
4522 // extract the splat value and use it as a uniform base.
4523 // In all other cases the function returns 'false'.
4524 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4525                            ISD::MemIndexType &IndexType, SDValue &Scale,
4526                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB,
4527                            uint64_t ElemSize) {
4528   SelectionDAG& DAG = SDB->DAG;
4529   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4530   const DataLayout &DL = DAG.getDataLayout();
4531 
4532   assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4533 
4534   // Handle splat constant pointer.
4535   if (auto *C = dyn_cast<Constant>(Ptr)) {
4536     C = C->getSplatValue();
4537     if (!C)
4538       return false;
4539 
4540     Base = SDB->getValue(C);
4541 
4542     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4543     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4544     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4545     IndexType = ISD::SIGNED_SCALED;
4546     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4547     return true;
4548   }
4549 
4550   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4551   if (!GEP || GEP->getParent() != CurBB)
4552     return false;
4553 
4554   if (GEP->getNumOperands() != 2)
4555     return false;
4556 
4557   const Value *BasePtr = GEP->getPointerOperand();
4558   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4559 
4560   // Make sure the base is scalar and the index is a vector.
4561   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4562     return false;
4563 
4564   TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
4565   if (ScaleVal.isScalable())
4566     return false;
4567 
4568   // Target may not support the required addressing mode.
4569   if (ScaleVal != 1 &&
4570       !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize))
4571     return false;
4572 
4573   Base = SDB->getValue(BasePtr);
4574   Index = SDB->getValue(IndexVal);
4575   IndexType = ISD::SIGNED_SCALED;
4576 
4577   Scale =
4578       DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4579   return true;
4580 }
4581 
4582 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4583   SDLoc sdl = getCurSDLoc();
4584 
4585   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4586   const Value *Ptr = I.getArgOperand(1);
4587   SDValue Src0 = getValue(I.getArgOperand(0));
4588   SDValue Mask = getValue(I.getArgOperand(3));
4589   EVT VT = Src0.getValueType();
4590   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4591                         ->getMaybeAlignValue()
4592                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4593   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4594 
4595   SDValue Base;
4596   SDValue Index;
4597   ISD::MemIndexType IndexType;
4598   SDValue Scale;
4599   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4600                                     I.getParent(), VT.getScalarStoreSize());
4601 
4602   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4603   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4604       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4605       // TODO: Make MachineMemOperands aware of scalable
4606       // vectors.
4607       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata());
4608   if (!UniformBase) {
4609     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4610     Index = getValue(Ptr);
4611     IndexType = ISD::SIGNED_SCALED;
4612     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4613   }
4614 
4615   EVT IdxVT = Index.getValueType();
4616   EVT EltTy = IdxVT.getVectorElementType();
4617   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4618     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4619     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4620   }
4621 
4622   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4623   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4624                                          Ops, MMO, IndexType, false);
4625   DAG.setRoot(Scatter);
4626   setValue(&I, Scatter);
4627 }
4628 
4629 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4630   SDLoc sdl = getCurSDLoc();
4631 
4632   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4633                               MaybeAlign &Alignment) {
4634     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4635     Ptr = I.getArgOperand(0);
4636     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4637     Mask = I.getArgOperand(2);
4638     Src0 = I.getArgOperand(3);
4639   };
4640   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4641                                  MaybeAlign &Alignment) {
4642     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4643     Ptr = I.getArgOperand(0);
4644     Alignment = std::nullopt;
4645     Mask = I.getArgOperand(1);
4646     Src0 = I.getArgOperand(2);
4647   };
4648 
4649   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4650   MaybeAlign Alignment;
4651   if (IsExpanding)
4652     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4653   else
4654     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4655 
4656   SDValue Ptr = getValue(PtrOperand);
4657   SDValue Src0 = getValue(Src0Operand);
4658   SDValue Mask = getValue(MaskOperand);
4659   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4660 
4661   EVT VT = Src0.getValueType();
4662   if (!Alignment)
4663     Alignment = DAG.getEVTAlign(VT);
4664 
4665   AAMDNodes AAInfo = I.getAAMetadata();
4666   const MDNode *Ranges = getRangeMetadata(I);
4667 
4668   // Do not serialize masked loads of constant memory with anything.
4669   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
4670   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4671 
4672   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4673 
4674   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4675       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4676       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
4677 
4678   SDValue Load =
4679       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4680                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4681   if (AddToChain)
4682     PendingLoads.push_back(Load.getValue(1));
4683   setValue(&I, Load);
4684 }
4685 
4686 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4687   SDLoc sdl = getCurSDLoc();
4688 
4689   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4690   const Value *Ptr = I.getArgOperand(0);
4691   SDValue Src0 = getValue(I.getArgOperand(3));
4692   SDValue Mask = getValue(I.getArgOperand(2));
4693 
4694   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4695   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4696   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4697                         ->getMaybeAlignValue()
4698                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4699 
4700   const MDNode *Ranges = getRangeMetadata(I);
4701 
4702   SDValue Root = DAG.getRoot();
4703   SDValue Base;
4704   SDValue Index;
4705   ISD::MemIndexType IndexType;
4706   SDValue Scale;
4707   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4708                                     I.getParent(), VT.getScalarStoreSize());
4709   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4710   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4711       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4712       // TODO: Make MachineMemOperands aware of scalable
4713       // vectors.
4714       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
4715 
4716   if (!UniformBase) {
4717     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4718     Index = getValue(Ptr);
4719     IndexType = ISD::SIGNED_SCALED;
4720     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4721   }
4722 
4723   EVT IdxVT = Index.getValueType();
4724   EVT EltTy = IdxVT.getVectorElementType();
4725   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4726     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4727     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4728   }
4729 
4730   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4731   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4732                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
4733 
4734   PendingLoads.push_back(Gather.getValue(1));
4735   setValue(&I, Gather);
4736 }
4737 
4738 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4739   SDLoc dl = getCurSDLoc();
4740   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4741   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4742   SyncScope::ID SSID = I.getSyncScopeID();
4743 
4744   SDValue InChain = getRoot();
4745 
4746   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4747   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4748 
4749   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4750   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4751 
4752   MachineFunction &MF = DAG.getMachineFunction();
4753   MachineMemOperand *MMO = MF.getMachineMemOperand(
4754       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4755       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4756       FailureOrdering);
4757 
4758   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4759                                    dl, MemVT, VTs, InChain,
4760                                    getValue(I.getPointerOperand()),
4761                                    getValue(I.getCompareOperand()),
4762                                    getValue(I.getNewValOperand()), MMO);
4763 
4764   SDValue OutChain = L.getValue(2);
4765 
4766   setValue(&I, L);
4767   DAG.setRoot(OutChain);
4768 }
4769 
4770 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4771   SDLoc dl = getCurSDLoc();
4772   ISD::NodeType NT;
4773   switch (I.getOperation()) {
4774   default: llvm_unreachable("Unknown atomicrmw operation");
4775   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4776   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4777   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4778   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4779   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4780   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4781   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4782   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4783   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4784   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4785   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4786   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4787   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4788   case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break;
4789   case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break;
4790   case AtomicRMWInst::UIncWrap:
4791     NT = ISD::ATOMIC_LOAD_UINC_WRAP;
4792     break;
4793   case AtomicRMWInst::UDecWrap:
4794     NT = ISD::ATOMIC_LOAD_UDEC_WRAP;
4795     break;
4796   }
4797   AtomicOrdering Ordering = I.getOrdering();
4798   SyncScope::ID SSID = I.getSyncScopeID();
4799 
4800   SDValue InChain = getRoot();
4801 
4802   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4803   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4804   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4805 
4806   MachineFunction &MF = DAG.getMachineFunction();
4807   MachineMemOperand *MMO = MF.getMachineMemOperand(
4808       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4809       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4810 
4811   SDValue L =
4812     DAG.getAtomic(NT, dl, MemVT, InChain,
4813                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4814                   MMO);
4815 
4816   SDValue OutChain = L.getValue(1);
4817 
4818   setValue(&I, L);
4819   DAG.setRoot(OutChain);
4820 }
4821 
4822 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4823   SDLoc dl = getCurSDLoc();
4824   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4825   SDValue Ops[3];
4826   Ops[0] = getRoot();
4827   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4828                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4829   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4830                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4831   SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
4832   setValue(&I, N);
4833   DAG.setRoot(N);
4834 }
4835 
4836 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4837   SDLoc dl = getCurSDLoc();
4838   AtomicOrdering Order = I.getOrdering();
4839   SyncScope::ID SSID = I.getSyncScopeID();
4840 
4841   SDValue InChain = getRoot();
4842 
4843   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4844   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4845   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4846 
4847   if (!TLI.supportsUnalignedAtomics() &&
4848       I.getAlign().value() < MemVT.getSizeInBits() / 8)
4849     report_fatal_error("Cannot generate unaligned atomic load");
4850 
4851   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4852 
4853   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4854       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4855       I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4856 
4857   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4858 
4859   SDValue Ptr = getValue(I.getPointerOperand());
4860   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4861                             Ptr, MMO);
4862 
4863   SDValue OutChain = L.getValue(1);
4864   if (MemVT != VT)
4865     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4866 
4867   setValue(&I, L);
4868   DAG.setRoot(OutChain);
4869 }
4870 
4871 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4872   SDLoc dl = getCurSDLoc();
4873 
4874   AtomicOrdering Ordering = I.getOrdering();
4875   SyncScope::ID SSID = I.getSyncScopeID();
4876 
4877   SDValue InChain = getRoot();
4878 
4879   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4880   EVT MemVT =
4881       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4882 
4883   if (!TLI.supportsUnalignedAtomics() &&
4884       I.getAlign().value() < MemVT.getSizeInBits() / 8)
4885     report_fatal_error("Cannot generate unaligned atomic store");
4886 
4887   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4888 
4889   MachineFunction &MF = DAG.getMachineFunction();
4890   MachineMemOperand *MMO = MF.getMachineMemOperand(
4891       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4892       I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4893 
4894   SDValue Val = getValue(I.getValueOperand());
4895   if (Val.getValueType() != MemVT)
4896     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4897   SDValue Ptr = getValue(I.getPointerOperand());
4898 
4899   SDValue OutChain =
4900       DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO);
4901 
4902   setValue(&I, OutChain);
4903   DAG.setRoot(OutChain);
4904 }
4905 
4906 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4907 /// node.
4908 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4909                                                unsigned Intrinsic) {
4910   // Ignore the callsite's attributes. A specific call site may be marked with
4911   // readnone, but the lowering code will expect the chain based on the
4912   // definition.
4913   const Function *F = I.getCalledFunction();
4914   bool HasChain = !F->doesNotAccessMemory();
4915   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4916 
4917   // Build the operand list.
4918   SmallVector<SDValue, 8> Ops;
4919   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4920     if (OnlyLoad) {
4921       // We don't need to serialize loads against other loads.
4922       Ops.push_back(DAG.getRoot());
4923     } else {
4924       Ops.push_back(getRoot());
4925     }
4926   }
4927 
4928   // Info is set by getTgtMemIntrinsic
4929   TargetLowering::IntrinsicInfo Info;
4930   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4931   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4932                                                DAG.getMachineFunction(),
4933                                                Intrinsic);
4934 
4935   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4936   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4937       Info.opc == ISD::INTRINSIC_W_CHAIN)
4938     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4939                                         TLI.getPointerTy(DAG.getDataLayout())));
4940 
4941   // Add all operands of the call to the operand list.
4942   for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
4943     const Value *Arg = I.getArgOperand(i);
4944     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4945       Ops.push_back(getValue(Arg));
4946       continue;
4947     }
4948 
4949     // Use TargetConstant instead of a regular constant for immarg.
4950     EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
4951     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4952       assert(CI->getBitWidth() <= 64 &&
4953              "large intrinsic immediates not handled");
4954       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4955     } else {
4956       Ops.push_back(
4957           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4958     }
4959   }
4960 
4961   SmallVector<EVT, 4> ValueVTs;
4962   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4963 
4964   if (HasChain)
4965     ValueVTs.push_back(MVT::Other);
4966 
4967   SDVTList VTs = DAG.getVTList(ValueVTs);
4968 
4969   // Propagate fast-math-flags from IR to node(s).
4970   SDNodeFlags Flags;
4971   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
4972     Flags.copyFMF(*FPMO);
4973   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
4974 
4975   // Create the node.
4976   SDValue Result;
4977   // In some cases, custom collection of operands from CallInst I may be needed.
4978   TLI.CollectTargetIntrinsicOperands(I, Ops, DAG);
4979   if (IsTgtIntrinsic) {
4980     // This is target intrinsic that touches memory
4981     //
4982     // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic
4983     //       didn't yield anything useful.
4984     MachinePointerInfo MPI;
4985     if (Info.ptrVal)
4986       MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
4987     else if (Info.fallbackAddressSpace)
4988       MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
4989     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops,
4990                                      Info.memVT, MPI, Info.align, Info.flags,
4991                                      Info.size, I.getAAMetadata());
4992   } else if (!HasChain) {
4993     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4994   } else if (!I.getType()->isVoidTy()) {
4995     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4996   } else {
4997     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4998   }
4999 
5000   if (HasChain) {
5001     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
5002     if (OnlyLoad)
5003       PendingLoads.push_back(Chain);
5004     else
5005       DAG.setRoot(Chain);
5006   }
5007 
5008   if (!I.getType()->isVoidTy()) {
5009     if (!isa<VectorType>(I.getType()))
5010       Result = lowerRangeToAssertZExt(DAG, I, Result);
5011 
5012     MaybeAlign Alignment = I.getRetAlign();
5013 
5014     // Insert `assertalign` node if there's an alignment.
5015     if (InsertAssertAlign && Alignment) {
5016       Result =
5017           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
5018     }
5019 
5020     setValue(&I, Result);
5021   }
5022 }
5023 
5024 /// GetSignificand - Get the significand and build it into a floating-point
5025 /// number with exponent of 1:
5026 ///
5027 ///   Op = (Op & 0x007fffff) | 0x3f800000;
5028 ///
5029 /// where Op is the hexadecimal representation of floating point value.
5030 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
5031   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5032                            DAG.getConstant(0x007fffff, dl, MVT::i32));
5033   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
5034                            DAG.getConstant(0x3f800000, dl, MVT::i32));
5035   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
5036 }
5037 
5038 /// GetExponent - Get the exponent:
5039 ///
5040 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
5041 ///
5042 /// where Op is the hexadecimal representation of floating point value.
5043 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
5044                            const TargetLowering &TLI, const SDLoc &dl) {
5045   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5046                            DAG.getConstant(0x7f800000, dl, MVT::i32));
5047   SDValue t1 = DAG.getNode(
5048       ISD::SRL, dl, MVT::i32, t0,
5049       DAG.getConstant(23, dl,
5050                       TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout())));
5051   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
5052                            DAG.getConstant(127, dl, MVT::i32));
5053   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
5054 }
5055 
5056 /// getF32Constant - Get 32-bit floating point constant.
5057 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
5058                               const SDLoc &dl) {
5059   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
5060                            MVT::f32);
5061 }
5062 
5063 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
5064                                        SelectionDAG &DAG) {
5065   // TODO: What fast-math-flags should be set on the floating-point nodes?
5066 
5067   //   IntegerPartOfX = ((int32_t)(t0);
5068   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
5069 
5070   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
5071   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
5072   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
5073 
5074   //   IntegerPartOfX <<= 23;
5075   IntegerPartOfX =
5076       DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
5077                   DAG.getConstant(23, dl,
5078                                   DAG.getTargetLoweringInfo().getShiftAmountTy(
5079                                       MVT::i32, DAG.getDataLayout())));
5080 
5081   SDValue TwoToFractionalPartOfX;
5082   if (LimitFloatPrecision <= 6) {
5083     // For floating-point precision of 6:
5084     //
5085     //   TwoToFractionalPartOfX =
5086     //     0.997535578f +
5087     //       (0.735607626f + 0.252464424f * x) * x;
5088     //
5089     // error 0.0144103317, which is 6 bits
5090     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5091                              getF32Constant(DAG, 0x3e814304, dl));
5092     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5093                              getF32Constant(DAG, 0x3f3c50c8, dl));
5094     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5095     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5096                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
5097   } else if (LimitFloatPrecision <= 12) {
5098     // For floating-point precision of 12:
5099     //
5100     //   TwoToFractionalPartOfX =
5101     //     0.999892986f +
5102     //       (0.696457318f +
5103     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
5104     //
5105     // error 0.000107046256, which is 13 to 14 bits
5106     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5107                              getF32Constant(DAG, 0x3da235e3, dl));
5108     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5109                              getF32Constant(DAG, 0x3e65b8f3, dl));
5110     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5111     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5112                              getF32Constant(DAG, 0x3f324b07, dl));
5113     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5114     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5115                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
5116   } else { // LimitFloatPrecision <= 18
5117     // For floating-point precision of 18:
5118     //
5119     //   TwoToFractionalPartOfX =
5120     //     0.999999982f +
5121     //       (0.693148872f +
5122     //         (0.240227044f +
5123     //           (0.554906021e-1f +
5124     //             (0.961591928e-2f +
5125     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5126     // error 2.47208000*10^(-7), which is better than 18 bits
5127     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5128                              getF32Constant(DAG, 0x3924b03e, dl));
5129     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5130                              getF32Constant(DAG, 0x3ab24b87, dl));
5131     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5132     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5133                              getF32Constant(DAG, 0x3c1d8c17, dl));
5134     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5135     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5136                              getF32Constant(DAG, 0x3d634a1d, dl));
5137     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5138     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5139                              getF32Constant(DAG, 0x3e75fe14, dl));
5140     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5141     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5142                               getF32Constant(DAG, 0x3f317234, dl));
5143     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5144     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5145                                          getF32Constant(DAG, 0x3f800000, dl));
5146   }
5147 
5148   // Add the exponent into the result in integer domain.
5149   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5150   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5151                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5152 }
5153 
5154 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5155 /// limited-precision mode.
5156 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5157                          const TargetLowering &TLI, SDNodeFlags Flags) {
5158   if (Op.getValueType() == MVT::f32 &&
5159       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5160 
5161     // Put the exponent in the right bit position for later addition to the
5162     // final result:
5163     //
5164     // t0 = Op * log2(e)
5165 
5166     // TODO: What fast-math-flags should be set here?
5167     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5168                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5169     return getLimitedPrecisionExp2(t0, dl, DAG);
5170   }
5171 
5172   // No special expansion.
5173   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5174 }
5175 
5176 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5177 /// limited-precision mode.
5178 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5179                          const TargetLowering &TLI, SDNodeFlags Flags) {
5180   // TODO: What fast-math-flags should be set on the floating-point nodes?
5181 
5182   if (Op.getValueType() == MVT::f32 &&
5183       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5184     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5185 
5186     // Scale the exponent by log(2).
5187     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5188     SDValue LogOfExponent =
5189         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5190                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5191 
5192     // Get the significand and build it into a floating-point number with
5193     // exponent of 1.
5194     SDValue X = GetSignificand(DAG, Op1, dl);
5195 
5196     SDValue LogOfMantissa;
5197     if (LimitFloatPrecision <= 6) {
5198       // For floating-point precision of 6:
5199       //
5200       //   LogofMantissa =
5201       //     -1.1609546f +
5202       //       (1.4034025f - 0.23903021f * x) * x;
5203       //
5204       // error 0.0034276066, which is better than 8 bits
5205       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5206                                getF32Constant(DAG, 0xbe74c456, dl));
5207       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5208                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5209       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5210       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5211                                   getF32Constant(DAG, 0x3f949a29, dl));
5212     } else if (LimitFloatPrecision <= 12) {
5213       // For floating-point precision of 12:
5214       //
5215       //   LogOfMantissa =
5216       //     -1.7417939f +
5217       //       (2.8212026f +
5218       //         (-1.4699568f +
5219       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5220       //
5221       // error 0.000061011436, which is 14 bits
5222       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5223                                getF32Constant(DAG, 0xbd67b6d6, dl));
5224       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5225                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5226       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5227       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5228                                getF32Constant(DAG, 0x3fbc278b, dl));
5229       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5230       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5231                                getF32Constant(DAG, 0x40348e95, dl));
5232       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5233       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5234                                   getF32Constant(DAG, 0x3fdef31a, dl));
5235     } else { // LimitFloatPrecision <= 18
5236       // For floating-point precision of 18:
5237       //
5238       //   LogOfMantissa =
5239       //     -2.1072184f +
5240       //       (4.2372794f +
5241       //         (-3.7029485f +
5242       //           (2.2781945f +
5243       //             (-0.87823314f +
5244       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5245       //
5246       // error 0.0000023660568, which is better than 18 bits
5247       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5248                                getF32Constant(DAG, 0xbc91e5ac, dl));
5249       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5250                                getF32Constant(DAG, 0x3e4350aa, dl));
5251       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5252       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5253                                getF32Constant(DAG, 0x3f60d3e3, dl));
5254       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5255       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5256                                getF32Constant(DAG, 0x4011cdf0, dl));
5257       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5258       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5259                                getF32Constant(DAG, 0x406cfd1c, dl));
5260       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5261       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5262                                getF32Constant(DAG, 0x408797cb, dl));
5263       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5264       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5265                                   getF32Constant(DAG, 0x4006dcab, dl));
5266     }
5267 
5268     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5269   }
5270 
5271   // No special expansion.
5272   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5273 }
5274 
5275 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5276 /// limited-precision mode.
5277 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5278                           const TargetLowering &TLI, SDNodeFlags Flags) {
5279   // TODO: What fast-math-flags should be set on the floating-point nodes?
5280 
5281   if (Op.getValueType() == MVT::f32 &&
5282       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5283     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5284 
5285     // Get the exponent.
5286     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5287 
5288     // Get the significand and build it into a floating-point number with
5289     // exponent of 1.
5290     SDValue X = GetSignificand(DAG, Op1, dl);
5291 
5292     // Different possible minimax approximations of significand in
5293     // floating-point for various degrees of accuracy over [1,2].
5294     SDValue Log2ofMantissa;
5295     if (LimitFloatPrecision <= 6) {
5296       // For floating-point precision of 6:
5297       //
5298       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5299       //
5300       // error 0.0049451742, which is more than 7 bits
5301       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5302                                getF32Constant(DAG, 0xbeb08fe0, dl));
5303       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5304                                getF32Constant(DAG, 0x40019463, dl));
5305       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5306       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5307                                    getF32Constant(DAG, 0x3fd6633d, dl));
5308     } else if (LimitFloatPrecision <= 12) {
5309       // For floating-point precision of 12:
5310       //
5311       //   Log2ofMantissa =
5312       //     -2.51285454f +
5313       //       (4.07009056f +
5314       //         (-2.12067489f +
5315       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5316       //
5317       // error 0.0000876136000, which is better than 13 bits
5318       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5319                                getF32Constant(DAG, 0xbda7262e, dl));
5320       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5321                                getF32Constant(DAG, 0x3f25280b, dl));
5322       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5323       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5324                                getF32Constant(DAG, 0x4007b923, dl));
5325       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5326       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5327                                getF32Constant(DAG, 0x40823e2f, dl));
5328       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5329       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5330                                    getF32Constant(DAG, 0x4020d29c, dl));
5331     } else { // LimitFloatPrecision <= 18
5332       // For floating-point precision of 18:
5333       //
5334       //   Log2ofMantissa =
5335       //     -3.0400495f +
5336       //       (6.1129976f +
5337       //         (-5.3420409f +
5338       //           (3.2865683f +
5339       //             (-1.2669343f +
5340       //               (0.27515199f -
5341       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5342       //
5343       // error 0.0000018516, which is better than 18 bits
5344       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5345                                getF32Constant(DAG, 0xbcd2769e, dl));
5346       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5347                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5348       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5349       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5350                                getF32Constant(DAG, 0x3fa22ae7, dl));
5351       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5352       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5353                                getF32Constant(DAG, 0x40525723, dl));
5354       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5355       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5356                                getF32Constant(DAG, 0x40aaf200, dl));
5357       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5358       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5359                                getF32Constant(DAG, 0x40c39dad, dl));
5360       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5361       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5362                                    getF32Constant(DAG, 0x4042902c, dl));
5363     }
5364 
5365     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5366   }
5367 
5368   // No special expansion.
5369   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5370 }
5371 
5372 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5373 /// limited-precision mode.
5374 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5375                            const TargetLowering &TLI, SDNodeFlags Flags) {
5376   // TODO: What fast-math-flags should be set on the floating-point nodes?
5377 
5378   if (Op.getValueType() == MVT::f32 &&
5379       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5380     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5381 
5382     // Scale the exponent by log10(2) [0.30102999f].
5383     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5384     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5385                                         getF32Constant(DAG, 0x3e9a209a, dl));
5386 
5387     // Get the significand and build it into a floating-point number with
5388     // exponent of 1.
5389     SDValue X = GetSignificand(DAG, Op1, dl);
5390 
5391     SDValue Log10ofMantissa;
5392     if (LimitFloatPrecision <= 6) {
5393       // For floating-point precision of 6:
5394       //
5395       //   Log10ofMantissa =
5396       //     -0.50419619f +
5397       //       (0.60948995f - 0.10380950f * x) * x;
5398       //
5399       // error 0.0014886165, which is 6 bits
5400       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5401                                getF32Constant(DAG, 0xbdd49a13, dl));
5402       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5403                                getF32Constant(DAG, 0x3f1c0789, dl));
5404       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5405       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5406                                     getF32Constant(DAG, 0x3f011300, dl));
5407     } else if (LimitFloatPrecision <= 12) {
5408       // For floating-point precision of 12:
5409       //
5410       //   Log10ofMantissa =
5411       //     -0.64831180f +
5412       //       (0.91751397f +
5413       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5414       //
5415       // error 0.00019228036, which is better than 12 bits
5416       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5417                                getF32Constant(DAG, 0x3d431f31, dl));
5418       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5419                                getF32Constant(DAG, 0x3ea21fb2, dl));
5420       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5421       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5422                                getF32Constant(DAG, 0x3f6ae232, dl));
5423       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5424       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5425                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5426     } else { // LimitFloatPrecision <= 18
5427       // For floating-point precision of 18:
5428       //
5429       //   Log10ofMantissa =
5430       //     -0.84299375f +
5431       //       (1.5327582f +
5432       //         (-1.0688956f +
5433       //           (0.49102474f +
5434       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5435       //
5436       // error 0.0000037995730, which is better than 18 bits
5437       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5438                                getF32Constant(DAG, 0x3c5d51ce, dl));
5439       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5440                                getF32Constant(DAG, 0x3e00685a, dl));
5441       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5442       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5443                                getF32Constant(DAG, 0x3efb6798, dl));
5444       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5445       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5446                                getF32Constant(DAG, 0x3f88d192, dl));
5447       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5448       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5449                                getF32Constant(DAG, 0x3fc4316c, dl));
5450       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5451       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5452                                     getF32Constant(DAG, 0x3f57ce70, dl));
5453     }
5454 
5455     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5456   }
5457 
5458   // No special expansion.
5459   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5460 }
5461 
5462 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5463 /// limited-precision mode.
5464 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5465                           const TargetLowering &TLI, SDNodeFlags Flags) {
5466   if (Op.getValueType() == MVT::f32 &&
5467       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5468     return getLimitedPrecisionExp2(Op, dl, DAG);
5469 
5470   // No special expansion.
5471   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5472 }
5473 
5474 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5475 /// limited-precision mode with x == 10.0f.
5476 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5477                          SelectionDAG &DAG, const TargetLowering &TLI,
5478                          SDNodeFlags Flags) {
5479   bool IsExp10 = false;
5480   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5481       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5482     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5483       APFloat Ten(10.0f);
5484       IsExp10 = LHSC->isExactlyValue(Ten);
5485     }
5486   }
5487 
5488   // TODO: What fast-math-flags should be set on the FMUL node?
5489   if (IsExp10) {
5490     // Put the exponent in the right bit position for later addition to the
5491     // final result:
5492     //
5493     //   #define LOG2OF10 3.3219281f
5494     //   t0 = Op * LOG2OF10;
5495     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5496                              getF32Constant(DAG, 0x40549a78, dl));
5497     return getLimitedPrecisionExp2(t0, dl, DAG);
5498   }
5499 
5500   // No special expansion.
5501   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5502 }
5503 
5504 /// ExpandPowI - Expand a llvm.powi intrinsic.
5505 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5506                           SelectionDAG &DAG) {
5507   // If RHS is a constant, we can expand this out to a multiplication tree if
5508   // it's beneficial on the target, otherwise we end up lowering to a call to
5509   // __powidf2 (for example).
5510   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5511     unsigned Val = RHSC->getSExtValue();
5512 
5513     // powi(x, 0) -> 1.0
5514     if (Val == 0)
5515       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5516 
5517     if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI(
5518             Val, DAG.shouldOptForSize())) {
5519       // Get the exponent as a positive value.
5520       if ((int)Val < 0)
5521         Val = -Val;
5522       // We use the simple binary decomposition method to generate the multiply
5523       // sequence.  There are more optimal ways to do this (for example,
5524       // powi(x,15) generates one more multiply than it should), but this has
5525       // the benefit of being both really simple and much better than a libcall.
5526       SDValue Res; // Logically starts equal to 1.0
5527       SDValue CurSquare = LHS;
5528       // TODO: Intrinsics should have fast-math-flags that propagate to these
5529       // nodes.
5530       while (Val) {
5531         if (Val & 1) {
5532           if (Res.getNode())
5533             Res =
5534                 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
5535           else
5536             Res = CurSquare; // 1.0*CurSquare.
5537         }
5538 
5539         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5540                                 CurSquare, CurSquare);
5541         Val >>= 1;
5542       }
5543 
5544       // If the original was negative, invert the result, producing 1/(x*x*x).
5545       if (RHSC->getSExtValue() < 0)
5546         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5547                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5548       return Res;
5549     }
5550   }
5551 
5552   // Otherwise, expand to a libcall.
5553   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5554 }
5555 
5556 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5557                             SDValue LHS, SDValue RHS, SDValue Scale,
5558                             SelectionDAG &DAG, const TargetLowering &TLI) {
5559   EVT VT = LHS.getValueType();
5560   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5561   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5562   LLVMContext &Ctx = *DAG.getContext();
5563 
5564   // If the type is legal but the operation isn't, this node might survive all
5565   // the way to operation legalization. If we end up there and we do not have
5566   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5567   // node.
5568 
5569   // Coax the legalizer into expanding the node during type legalization instead
5570   // by bumping the size by one bit. This will force it to Promote, enabling the
5571   // early expansion and avoiding the need to expand later.
5572 
5573   // We don't have to do this if Scale is 0; that can always be expanded, unless
5574   // it's a saturating signed operation. Those can experience true integer
5575   // division overflow, a case which we must avoid.
5576 
5577   // FIXME: We wouldn't have to do this (or any of the early
5578   // expansion/promotion) if it was possible to expand a libcall of an
5579   // illegal type during operation legalization. But it's not, so things
5580   // get a bit hacky.
5581   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5582   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5583       (TLI.isTypeLegal(VT) ||
5584        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5585     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5586         Opcode, VT, ScaleInt);
5587     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5588       EVT PromVT;
5589       if (VT.isScalarInteger())
5590         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5591       else if (VT.isVector()) {
5592         PromVT = VT.getVectorElementType();
5593         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5594         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5595       } else
5596         llvm_unreachable("Wrong VT for DIVFIX?");
5597       LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT);
5598       RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT);
5599       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5600       // For saturating operations, we need to shift up the LHS to get the
5601       // proper saturation width, and then shift down again afterwards.
5602       if (Saturating)
5603         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5604                           DAG.getConstant(1, DL, ShiftTy));
5605       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5606       if (Saturating)
5607         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5608                           DAG.getConstant(1, DL, ShiftTy));
5609       return DAG.getZExtOrTrunc(Res, DL, VT);
5610     }
5611   }
5612 
5613   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5614 }
5615 
5616 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5617 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5618 static void
5619 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5620                      const SDValue &N) {
5621   switch (N.getOpcode()) {
5622   case ISD::CopyFromReg: {
5623     SDValue Op = N.getOperand(1);
5624     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5625                       Op.getValueType().getSizeInBits());
5626     return;
5627   }
5628   case ISD::BITCAST:
5629   case ISD::AssertZext:
5630   case ISD::AssertSext:
5631   case ISD::TRUNCATE:
5632     getUnderlyingArgRegs(Regs, N.getOperand(0));
5633     return;
5634   case ISD::BUILD_PAIR:
5635   case ISD::BUILD_VECTOR:
5636   case ISD::CONCAT_VECTORS:
5637     for (SDValue Op : N->op_values())
5638       getUnderlyingArgRegs(Regs, Op);
5639     return;
5640   default:
5641     return;
5642   }
5643 }
5644 
5645 /// If the DbgValueInst is a dbg_value of a function argument, create the
5646 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5647 /// instruction selection, they will be inserted to the entry BB.
5648 /// We don't currently support this for variadic dbg_values, as they shouldn't
5649 /// appear for function arguments or in the prologue.
5650 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5651     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5652     DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
5653   const Argument *Arg = dyn_cast<Argument>(V);
5654   if (!Arg)
5655     return false;
5656 
5657   MachineFunction &MF = DAG.getMachineFunction();
5658   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5659 
5660   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
5661   // we've been asked to pursue.
5662   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
5663                               bool Indirect) {
5664     if (Reg.isVirtual() && MF.useDebugInstrRef()) {
5665       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
5666       // pointing at the VReg, which will be patched up later.
5667       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
5668       SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg(
5669           /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
5670           /* isKill */ false, /* isDead */ false,
5671           /* isUndef */ false, /* isEarlyClobber */ false,
5672           /* SubReg */ 0, /* isDebug */ true)});
5673 
5674       auto *NewDIExpr = FragExpr;
5675       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
5676       // the DIExpression.
5677       if (Indirect)
5678         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
5679       SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0});
5680       NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops);
5681       return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr);
5682     } else {
5683       // Create a completely standard DBG_VALUE.
5684       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
5685       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
5686     }
5687   };
5688 
5689   if (Kind == FuncArgumentDbgValueKind::Value) {
5690     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5691     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5692     // the entry block.
5693     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5694     if (!IsInEntryBlock)
5695       return false;
5696 
5697     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5698     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5699     // variable that also is a param.
5700     //
5701     // Although, if we are at the top of the entry block already, we can still
5702     // emit using ArgDbgValue. This might catch some situations when the
5703     // dbg.value refers to an argument that isn't used in the entry block, so
5704     // any CopyToReg node would be optimized out and the only way to express
5705     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5706     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5707     // we should only emit as ArgDbgValue if the Variable is an argument to the
5708     // current function, and the dbg.value intrinsic is found in the entry
5709     // block.
5710     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5711         !DL->getInlinedAt();
5712     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5713     if (!IsInPrologue && !VariableIsFunctionInputArg)
5714       return false;
5715 
5716     // Here we assume that a function argument on IR level only can be used to
5717     // describe one input parameter on source level. If we for example have
5718     // source code like this
5719     //
5720     //    struct A { long x, y; };
5721     //    void foo(struct A a, long b) {
5722     //      ...
5723     //      b = a.x;
5724     //      ...
5725     //    }
5726     //
5727     // and IR like this
5728     //
5729     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5730     //  entry:
5731     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5732     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5733     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5734     //    ...
5735     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5736     //    ...
5737     //
5738     // then the last dbg.value is describing a parameter "b" using a value that
5739     // is an argument. But since we already has used %a1 to describe a parameter
5740     // we should not handle that last dbg.value here (that would result in an
5741     // incorrect hoisting of the DBG_VALUE to the function entry).
5742     // Notice that we allow one dbg.value per IR level argument, to accommodate
5743     // for the situation with fragments above.
5744     if (VariableIsFunctionInputArg) {
5745       unsigned ArgNo = Arg->getArgNo();
5746       if (ArgNo >= FuncInfo.DescribedArgs.size())
5747         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5748       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5749         return false;
5750       FuncInfo.DescribedArgs.set(ArgNo);
5751     }
5752   }
5753 
5754   bool IsIndirect = false;
5755   std::optional<MachineOperand> Op;
5756   // Some arguments' frame index is recorded during argument lowering.
5757   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5758   if (FI != std::numeric_limits<int>::max())
5759     Op = MachineOperand::CreateFI(FI);
5760 
5761   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
5762   if (!Op && N.getNode()) {
5763     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5764     Register Reg;
5765     if (ArgRegsAndSizes.size() == 1)
5766       Reg = ArgRegsAndSizes.front().first;
5767 
5768     if (Reg && Reg.isVirtual()) {
5769       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5770       Register PR = RegInfo.getLiveInPhysReg(Reg);
5771       if (PR)
5772         Reg = PR;
5773     }
5774     if (Reg) {
5775       Op = MachineOperand::CreateReg(Reg, false);
5776       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
5777     }
5778   }
5779 
5780   if (!Op && N.getNode()) {
5781     // Check if frame index is available.
5782     SDValue LCandidate = peekThroughBitcasts(N);
5783     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5784       if (FrameIndexSDNode *FINode =
5785           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5786         Op = MachineOperand::CreateFI(FINode->getIndex());
5787   }
5788 
5789   if (!Op) {
5790     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5791     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
5792                                          SplitRegs) {
5793       unsigned Offset = 0;
5794       for (const auto &RegAndSize : SplitRegs) {
5795         // If the expression is already a fragment, the current register
5796         // offset+size might extend beyond the fragment. In this case, only
5797         // the register bits that are inside the fragment are relevant.
5798         int RegFragmentSizeInBits = RegAndSize.second;
5799         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5800           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5801           // The register is entirely outside the expression fragment,
5802           // so is irrelevant for debug info.
5803           if (Offset >= ExprFragmentSizeInBits)
5804             break;
5805           // The register is partially outside the expression fragment, only
5806           // the low bits within the fragment are relevant for debug info.
5807           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5808             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5809           }
5810         }
5811 
5812         auto FragmentExpr = DIExpression::createFragmentExpression(
5813             Expr, Offset, RegFragmentSizeInBits);
5814         Offset += RegAndSize.second;
5815         // If a valid fragment expression cannot be created, the variable's
5816         // correct value cannot be determined and so it is set as Undef.
5817         if (!FragmentExpr) {
5818           SDDbgValue *SDV = DAG.getConstantDbgValue(
5819               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5820           DAG.AddDbgValue(SDV, false);
5821           continue;
5822         }
5823         MachineInstr *NewMI =
5824             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr,
5825                              Kind != FuncArgumentDbgValueKind::Value);
5826         FuncInfo.ArgDbgValues.push_back(NewMI);
5827       }
5828     };
5829 
5830     // Check if ValueMap has reg number.
5831     DenseMap<const Value *, Register>::const_iterator
5832       VMI = FuncInfo.ValueMap.find(V);
5833     if (VMI != FuncInfo.ValueMap.end()) {
5834       const auto &TLI = DAG.getTargetLoweringInfo();
5835       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5836                        V->getType(), std::nullopt);
5837       if (RFV.occupiesMultipleRegs()) {
5838         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5839         return true;
5840       }
5841 
5842       Op = MachineOperand::CreateReg(VMI->second, false);
5843       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
5844     } else if (ArgRegsAndSizes.size() > 1) {
5845       // This was split due to the calling convention, and no virtual register
5846       // mapping exists for the value.
5847       splitMultiRegDbgValue(ArgRegsAndSizes);
5848       return true;
5849     }
5850   }
5851 
5852   if (!Op)
5853     return false;
5854 
5855   assert(Variable->isValidLocationForIntrinsic(DL) &&
5856          "Expected inlined-at fields to agree");
5857   MachineInstr *NewMI = nullptr;
5858 
5859   if (Op->isReg())
5860     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
5861   else
5862     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
5863                     Variable, Expr);
5864 
5865   // Otherwise, use ArgDbgValues.
5866   FuncInfo.ArgDbgValues.push_back(NewMI);
5867   return true;
5868 }
5869 
5870 /// Return the appropriate SDDbgValue based on N.
5871 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5872                                              DILocalVariable *Variable,
5873                                              DIExpression *Expr,
5874                                              const DebugLoc &dl,
5875                                              unsigned DbgSDNodeOrder) {
5876   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5877     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5878     // stack slot locations.
5879     //
5880     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5881     // debug values here after optimization:
5882     //
5883     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5884     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5885     //
5886     // Both describe the direct values of their associated variables.
5887     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5888                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5889   }
5890   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5891                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5892 }
5893 
5894 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5895   switch (Intrinsic) {
5896   case Intrinsic::smul_fix:
5897     return ISD::SMULFIX;
5898   case Intrinsic::umul_fix:
5899     return ISD::UMULFIX;
5900   case Intrinsic::smul_fix_sat:
5901     return ISD::SMULFIXSAT;
5902   case Intrinsic::umul_fix_sat:
5903     return ISD::UMULFIXSAT;
5904   case Intrinsic::sdiv_fix:
5905     return ISD::SDIVFIX;
5906   case Intrinsic::udiv_fix:
5907     return ISD::UDIVFIX;
5908   case Intrinsic::sdiv_fix_sat:
5909     return ISD::SDIVFIXSAT;
5910   case Intrinsic::udiv_fix_sat:
5911     return ISD::UDIVFIXSAT;
5912   default:
5913     llvm_unreachable("Unhandled fixed point intrinsic");
5914   }
5915 }
5916 
5917 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5918                                            const char *FunctionName) {
5919   assert(FunctionName && "FunctionName must not be nullptr");
5920   SDValue Callee = DAG.getExternalSymbol(
5921       FunctionName,
5922       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5923   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
5924 }
5925 
5926 /// Given a @llvm.call.preallocated.setup, return the corresponding
5927 /// preallocated call.
5928 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
5929   assert(cast<CallBase>(PreallocatedSetup)
5930                  ->getCalledFunction()
5931                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
5932          "expected call_preallocated_setup Value");
5933   for (const auto *U : PreallocatedSetup->users()) {
5934     auto *UseCall = cast<CallBase>(U);
5935     const Function *Fn = UseCall->getCalledFunction();
5936     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
5937       return UseCall;
5938     }
5939   }
5940   llvm_unreachable("expected corresponding call to preallocated setup/arg");
5941 }
5942 
5943 /// If DI is a debug value with an EntryValue expression, lower it using the
5944 /// corresponding physical register of the associated Argument value
5945 /// (guaranteed to exist by the verifier).
5946 bool SelectionDAGBuilder::visitEntryValueDbgValue(const DbgValueInst &DI) {
5947   DILocalVariable *Variable = DI.getVariable();
5948   DIExpression *Expr = DI.getExpression();
5949   if (!Expr->isEntryValue() || !hasSingleElement(DI.getValues()))
5950     return false;
5951 
5952   // These properties are guaranteed by the verifier.
5953   Argument *Arg = cast<Argument>(DI.getValue(0));
5954   assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync));
5955 
5956   auto ArgIt = FuncInfo.ValueMap.find(Arg);
5957   if (ArgIt == FuncInfo.ValueMap.end()) {
5958     LLVM_DEBUG(
5959         dbgs() << "Dropping dbg.value: expression is entry_value but "
5960                   "couldn't find an associated register for the Argument\n");
5961     return true;
5962   }
5963   Register ArgVReg = ArgIt->getSecond();
5964 
5965   for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
5966     if (ArgVReg == VirtReg || ArgVReg == PhysReg) {
5967       SDDbgValue *SDV =
5968           DAG.getVRegDbgValue(Variable, Expr, PhysReg, false /*IsIndidrect*/,
5969                               DI.getDebugLoc(), SDNodeOrder);
5970       DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/);
5971       return true;
5972     }
5973   LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but "
5974                        "couldn't find a physical register\n");
5975   return true;
5976 }
5977 
5978 /// Lower the call to the specified intrinsic function.
5979 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5980                                              unsigned Intrinsic) {
5981   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5982   SDLoc sdl = getCurSDLoc();
5983   DebugLoc dl = getCurDebugLoc();
5984   SDValue Res;
5985 
5986   SDNodeFlags Flags;
5987   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
5988     Flags.copyFMF(*FPOp);
5989 
5990   switch (Intrinsic) {
5991   default:
5992     // By default, turn this into a target intrinsic node.
5993     visitTargetIntrinsic(I, Intrinsic);
5994     return;
5995   case Intrinsic::vscale: {
5996     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5997     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
5998     return;
5999   }
6000   case Intrinsic::vastart:  visitVAStart(I); return;
6001   case Intrinsic::vaend:    visitVAEnd(I); return;
6002   case Intrinsic::vacopy:   visitVACopy(I); return;
6003   case Intrinsic::returnaddress:
6004     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
6005                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6006                              getValue(I.getArgOperand(0))));
6007     return;
6008   case Intrinsic::addressofreturnaddress:
6009     setValue(&I,
6010              DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
6011                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6012     return;
6013   case Intrinsic::sponentry:
6014     setValue(&I,
6015              DAG.getNode(ISD::SPONENTRY, sdl,
6016                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6017     return;
6018   case Intrinsic::frameaddress:
6019     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
6020                              TLI.getFrameIndexTy(DAG.getDataLayout()),
6021                              getValue(I.getArgOperand(0))));
6022     return;
6023   case Intrinsic::read_volatile_register:
6024   case Intrinsic::read_register: {
6025     Value *Reg = I.getArgOperand(0);
6026     SDValue Chain = getRoot();
6027     SDValue RegName =
6028         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6029     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6030     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
6031       DAG.getVTList(VT, MVT::Other), Chain, RegName);
6032     setValue(&I, Res);
6033     DAG.setRoot(Res.getValue(1));
6034     return;
6035   }
6036   case Intrinsic::write_register: {
6037     Value *Reg = I.getArgOperand(0);
6038     Value *RegValue = I.getArgOperand(1);
6039     SDValue Chain = getRoot();
6040     SDValue RegName =
6041         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6042     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
6043                             RegName, getValue(RegValue)));
6044     return;
6045   }
6046   case Intrinsic::memcpy: {
6047     const auto &MCI = cast<MemCpyInst>(I);
6048     SDValue Op1 = getValue(I.getArgOperand(0));
6049     SDValue Op2 = getValue(I.getArgOperand(1));
6050     SDValue Op3 = getValue(I.getArgOperand(2));
6051     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
6052     Align DstAlign = MCI.getDestAlign().valueOrOne();
6053     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6054     Align Alignment = std::min(DstAlign, SrcAlign);
6055     bool isVol = MCI.isVolatile();
6056     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6057     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6058     // node.
6059     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6060     SDValue MC = DAG.getMemcpy(
6061         Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6062         /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)),
6063         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
6064     updateDAGForMaybeTailCall(MC);
6065     return;
6066   }
6067   case Intrinsic::memcpy_inline: {
6068     const auto &MCI = cast<MemCpyInlineInst>(I);
6069     SDValue Dst = getValue(I.getArgOperand(0));
6070     SDValue Src = getValue(I.getArgOperand(1));
6071     SDValue Size = getValue(I.getArgOperand(2));
6072     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
6073     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
6074     Align DstAlign = MCI.getDestAlign().valueOrOne();
6075     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6076     Align Alignment = std::min(DstAlign, SrcAlign);
6077     bool isVol = MCI.isVolatile();
6078     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6079     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6080     // node.
6081     SDValue MC = DAG.getMemcpy(
6082         getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
6083         /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)),
6084         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
6085     updateDAGForMaybeTailCall(MC);
6086     return;
6087   }
6088   case Intrinsic::memset: {
6089     const auto &MSI = cast<MemSetInst>(I);
6090     SDValue Op1 = getValue(I.getArgOperand(0));
6091     SDValue Op2 = getValue(I.getArgOperand(1));
6092     SDValue Op3 = getValue(I.getArgOperand(2));
6093     // @llvm.memset defines 0 and 1 to both mean no alignment.
6094     Align Alignment = MSI.getDestAlign().valueOrOne();
6095     bool isVol = MSI.isVolatile();
6096     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6097     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6098     SDValue MS = DAG.getMemset(
6099         Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false,
6100         isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
6101     updateDAGForMaybeTailCall(MS);
6102     return;
6103   }
6104   case Intrinsic::memset_inline: {
6105     const auto &MSII = cast<MemSetInlineInst>(I);
6106     SDValue Dst = getValue(I.getArgOperand(0));
6107     SDValue Value = getValue(I.getArgOperand(1));
6108     SDValue Size = getValue(I.getArgOperand(2));
6109     assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size");
6110     // @llvm.memset defines 0 and 1 to both mean no alignment.
6111     Align DstAlign = MSII.getDestAlign().valueOrOne();
6112     bool isVol = MSII.isVolatile();
6113     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6114     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6115     SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol,
6116                                /* AlwaysInline */ true, isTC,
6117                                MachinePointerInfo(I.getArgOperand(0)),
6118                                I.getAAMetadata());
6119     updateDAGForMaybeTailCall(MC);
6120     return;
6121   }
6122   case Intrinsic::memmove: {
6123     const auto &MMI = cast<MemMoveInst>(I);
6124     SDValue Op1 = getValue(I.getArgOperand(0));
6125     SDValue Op2 = getValue(I.getArgOperand(1));
6126     SDValue Op3 = getValue(I.getArgOperand(2));
6127     // @llvm.memmove defines 0 and 1 to both mean no alignment.
6128     Align DstAlign = MMI.getDestAlign().valueOrOne();
6129     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
6130     Align Alignment = std::min(DstAlign, SrcAlign);
6131     bool isVol = MMI.isVolatile();
6132     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6133     // FIXME: Support passing different dest/src alignments to the memmove DAG
6134     // node.
6135     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6136     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6137                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
6138                                 MachinePointerInfo(I.getArgOperand(1)),
6139                                 I.getAAMetadata(), AA);
6140     updateDAGForMaybeTailCall(MM);
6141     return;
6142   }
6143   case Intrinsic::memcpy_element_unordered_atomic: {
6144     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
6145     SDValue Dst = getValue(MI.getRawDest());
6146     SDValue Src = getValue(MI.getRawSource());
6147     SDValue Length = getValue(MI.getLength());
6148 
6149     Type *LengthTy = MI.getLength()->getType();
6150     unsigned ElemSz = MI.getElementSizeInBytes();
6151     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6152     SDValue MC =
6153         DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6154                             isTC, MachinePointerInfo(MI.getRawDest()),
6155                             MachinePointerInfo(MI.getRawSource()));
6156     updateDAGForMaybeTailCall(MC);
6157     return;
6158   }
6159   case Intrinsic::memmove_element_unordered_atomic: {
6160     auto &MI = cast<AtomicMemMoveInst>(I);
6161     SDValue Dst = getValue(MI.getRawDest());
6162     SDValue Src = getValue(MI.getRawSource());
6163     SDValue Length = getValue(MI.getLength());
6164 
6165     Type *LengthTy = MI.getLength()->getType();
6166     unsigned ElemSz = MI.getElementSizeInBytes();
6167     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6168     SDValue MC =
6169         DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6170                              isTC, MachinePointerInfo(MI.getRawDest()),
6171                              MachinePointerInfo(MI.getRawSource()));
6172     updateDAGForMaybeTailCall(MC);
6173     return;
6174   }
6175   case Intrinsic::memset_element_unordered_atomic: {
6176     auto &MI = cast<AtomicMemSetInst>(I);
6177     SDValue Dst = getValue(MI.getRawDest());
6178     SDValue Val = getValue(MI.getValue());
6179     SDValue Length = getValue(MI.getLength());
6180 
6181     Type *LengthTy = MI.getLength()->getType();
6182     unsigned ElemSz = MI.getElementSizeInBytes();
6183     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6184     SDValue MC =
6185         DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
6186                             isTC, MachinePointerInfo(MI.getRawDest()));
6187     updateDAGForMaybeTailCall(MC);
6188     return;
6189   }
6190   case Intrinsic::call_preallocated_setup: {
6191     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
6192     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6193     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
6194                               getRoot(), SrcValue);
6195     setValue(&I, Res);
6196     DAG.setRoot(Res);
6197     return;
6198   }
6199   case Intrinsic::call_preallocated_arg: {
6200     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6201     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6202     SDValue Ops[3];
6203     Ops[0] = getRoot();
6204     Ops[1] = SrcValue;
6205     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6206                                    MVT::i32); // arg index
6207     SDValue Res = DAG.getNode(
6208         ISD::PREALLOCATED_ARG, sdl,
6209         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6210     setValue(&I, Res);
6211     DAG.setRoot(Res.getValue(1));
6212     return;
6213   }
6214   case Intrinsic::dbg_declare: {
6215     const auto &DI = cast<DbgDeclareInst>(I);
6216     // Debug intrinsics are handled separately in assignment tracking mode.
6217     // Some intrinsics are handled right after Argument lowering.
6218     if (AssignmentTrackingEnabled ||
6219         FuncInfo.PreprocessedDbgDeclares.count(&DI))
6220       return;
6221     // Assume dbg.declare can not currently use DIArgList, i.e.
6222     // it is non-variadic.
6223     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6224     DILocalVariable *Variable = DI.getVariable();
6225     DIExpression *Expression = DI.getExpression();
6226     dropDanglingDebugInfo(Variable, Expression);
6227     assert(Variable && "Missing variable");
6228     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
6229                       << "\n");
6230     // Check if address has undef value.
6231     const Value *Address = DI.getVariableLocationOp(0);
6232     if (!Address || isa<UndefValue>(Address) ||
6233         (Address->use_empty() && !isa<Argument>(Address))) {
6234       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6235                         << " (bad/undef/unused-arg address)\n");
6236       return;
6237     }
6238 
6239     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
6240 
6241     SDValue &N = NodeMap[Address];
6242     if (!N.getNode() && isa<Argument>(Address))
6243       // Check unused arguments map.
6244       N = UnusedArgNodeMap[Address];
6245     SDDbgValue *SDV;
6246     if (N.getNode()) {
6247       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
6248         Address = BCI->getOperand(0);
6249       // Parameters are handled specially.
6250       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
6251       if (isParameter && FINode) {
6252         // Byval parameter. We have a frame index at this point.
6253         SDV =
6254             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
6255                                       /*IsIndirect*/ true, dl, SDNodeOrder);
6256       } else if (isa<Argument>(Address)) {
6257         // Address is an argument, so try to emit its dbg value using
6258         // virtual register info from the FuncInfo.ValueMap.
6259         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl,
6260                                  FuncArgumentDbgValueKind::Declare, N);
6261         return;
6262       } else {
6263         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
6264                               true, dl, SDNodeOrder);
6265       }
6266       DAG.AddDbgValue(SDV, isParameter);
6267     } else {
6268       // If Address is an argument then try to emit its dbg value using
6269       // virtual register info from the FuncInfo.ValueMap.
6270       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl,
6271                                     FuncArgumentDbgValueKind::Declare, N)) {
6272         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6273                           << " (could not emit func-arg dbg_value)\n");
6274       }
6275     }
6276     return;
6277   }
6278   case Intrinsic::dbg_label: {
6279     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6280     DILabel *Label = DI.getLabel();
6281     assert(Label && "Missing label");
6282 
6283     SDDbgLabel *SDV;
6284     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6285     DAG.AddDbgLabel(SDV);
6286     return;
6287   }
6288   case Intrinsic::dbg_assign: {
6289     // Debug intrinsics are handled seperately in assignment tracking mode.
6290     if (AssignmentTrackingEnabled)
6291       return;
6292     // If assignment tracking hasn't been enabled then fall through and treat
6293     // the dbg.assign as a dbg.value.
6294     [[fallthrough]];
6295   }
6296   case Intrinsic::dbg_value: {
6297     // Debug intrinsics are handled seperately in assignment tracking mode.
6298     if (AssignmentTrackingEnabled)
6299       return;
6300     const DbgValueInst &DI = cast<DbgValueInst>(I);
6301     assert(DI.getVariable() && "Missing variable");
6302 
6303     DILocalVariable *Variable = DI.getVariable();
6304     DIExpression *Expression = DI.getExpression();
6305     dropDanglingDebugInfo(Variable, Expression);
6306 
6307     if (visitEntryValueDbgValue(DI))
6308       return;
6309 
6310     if (DI.isKillLocation()) {
6311       handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder);
6312       return;
6313     }
6314 
6315     SmallVector<Value *, 4> Values(DI.getValues());
6316     if (Values.empty())
6317       return;
6318 
6319     bool IsVariadic = DI.hasArgList();
6320     if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(),
6321                           SDNodeOrder, IsVariadic))
6322       addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
6323                            DI.getDebugLoc(), SDNodeOrder);
6324     return;
6325   }
6326 
6327   case Intrinsic::eh_typeid_for: {
6328     // Find the type id for the given typeinfo.
6329     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6330     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6331     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6332     setValue(&I, Res);
6333     return;
6334   }
6335 
6336   case Intrinsic::eh_return_i32:
6337   case Intrinsic::eh_return_i64:
6338     DAG.getMachineFunction().setCallsEHReturn(true);
6339     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6340                             MVT::Other,
6341                             getControlRoot(),
6342                             getValue(I.getArgOperand(0)),
6343                             getValue(I.getArgOperand(1))));
6344     return;
6345   case Intrinsic::eh_unwind_init:
6346     DAG.getMachineFunction().setCallsUnwindInit(true);
6347     return;
6348   case Intrinsic::eh_dwarf_cfa:
6349     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6350                              TLI.getPointerTy(DAG.getDataLayout()),
6351                              getValue(I.getArgOperand(0))));
6352     return;
6353   case Intrinsic::eh_sjlj_callsite: {
6354     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6355     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
6356     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6357 
6358     MMI.setCurrentCallSite(CI->getZExtValue());
6359     return;
6360   }
6361   case Intrinsic::eh_sjlj_functioncontext: {
6362     // Get and store the index of the function context.
6363     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6364     AllocaInst *FnCtx =
6365       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6366     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6367     MFI.setFunctionContextIndex(FI);
6368     return;
6369   }
6370   case Intrinsic::eh_sjlj_setjmp: {
6371     SDValue Ops[2];
6372     Ops[0] = getRoot();
6373     Ops[1] = getValue(I.getArgOperand(0));
6374     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6375                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6376     setValue(&I, Op.getValue(0));
6377     DAG.setRoot(Op.getValue(1));
6378     return;
6379   }
6380   case Intrinsic::eh_sjlj_longjmp:
6381     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6382                             getRoot(), getValue(I.getArgOperand(0))));
6383     return;
6384   case Intrinsic::eh_sjlj_setup_dispatch:
6385     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6386                             getRoot()));
6387     return;
6388   case Intrinsic::masked_gather:
6389     visitMaskedGather(I);
6390     return;
6391   case Intrinsic::masked_load:
6392     visitMaskedLoad(I);
6393     return;
6394   case Intrinsic::masked_scatter:
6395     visitMaskedScatter(I);
6396     return;
6397   case Intrinsic::masked_store:
6398     visitMaskedStore(I);
6399     return;
6400   case Intrinsic::masked_expandload:
6401     visitMaskedLoad(I, true /* IsExpanding */);
6402     return;
6403   case Intrinsic::masked_compressstore:
6404     visitMaskedStore(I, true /* IsCompressing */);
6405     return;
6406   case Intrinsic::powi:
6407     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6408                             getValue(I.getArgOperand(1)), DAG));
6409     return;
6410   case Intrinsic::log:
6411     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6412     return;
6413   case Intrinsic::log2:
6414     setValue(&I,
6415              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6416     return;
6417   case Intrinsic::log10:
6418     setValue(&I,
6419              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6420     return;
6421   case Intrinsic::exp:
6422     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6423     return;
6424   case Intrinsic::exp2:
6425     setValue(&I,
6426              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6427     return;
6428   case Intrinsic::pow:
6429     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6430                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6431     return;
6432   case Intrinsic::sqrt:
6433   case Intrinsic::fabs:
6434   case Intrinsic::sin:
6435   case Intrinsic::cos:
6436   case Intrinsic::exp10:
6437   case Intrinsic::floor:
6438   case Intrinsic::ceil:
6439   case Intrinsic::trunc:
6440   case Intrinsic::rint:
6441   case Intrinsic::nearbyint:
6442   case Intrinsic::round:
6443   case Intrinsic::roundeven:
6444   case Intrinsic::canonicalize: {
6445     unsigned Opcode;
6446     switch (Intrinsic) {
6447     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6448     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6449     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6450     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6451     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6452     case Intrinsic::exp10:     Opcode = ISD::FEXP10;     break;
6453     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6454     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6455     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6456     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6457     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6458     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6459     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6460     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6461     }
6462 
6463     setValue(&I, DAG.getNode(Opcode, sdl,
6464                              getValue(I.getArgOperand(0)).getValueType(),
6465                              getValue(I.getArgOperand(0)), Flags));
6466     return;
6467   }
6468   case Intrinsic::lround:
6469   case Intrinsic::llround:
6470   case Intrinsic::lrint:
6471   case Intrinsic::llrint: {
6472     unsigned Opcode;
6473     switch (Intrinsic) {
6474     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6475     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6476     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6477     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6478     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6479     }
6480 
6481     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6482     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6483                              getValue(I.getArgOperand(0))));
6484     return;
6485   }
6486   case Intrinsic::minnum:
6487     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6488                              getValue(I.getArgOperand(0)).getValueType(),
6489                              getValue(I.getArgOperand(0)),
6490                              getValue(I.getArgOperand(1)), Flags));
6491     return;
6492   case Intrinsic::maxnum:
6493     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6494                              getValue(I.getArgOperand(0)).getValueType(),
6495                              getValue(I.getArgOperand(0)),
6496                              getValue(I.getArgOperand(1)), Flags));
6497     return;
6498   case Intrinsic::minimum:
6499     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6500                              getValue(I.getArgOperand(0)).getValueType(),
6501                              getValue(I.getArgOperand(0)),
6502                              getValue(I.getArgOperand(1)), Flags));
6503     return;
6504   case Intrinsic::maximum:
6505     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6506                              getValue(I.getArgOperand(0)).getValueType(),
6507                              getValue(I.getArgOperand(0)),
6508                              getValue(I.getArgOperand(1)), Flags));
6509     return;
6510   case Intrinsic::copysign:
6511     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6512                              getValue(I.getArgOperand(0)).getValueType(),
6513                              getValue(I.getArgOperand(0)),
6514                              getValue(I.getArgOperand(1)), Flags));
6515     return;
6516   case Intrinsic::ldexp:
6517     setValue(&I, DAG.getNode(ISD::FLDEXP, sdl,
6518                              getValue(I.getArgOperand(0)).getValueType(),
6519                              getValue(I.getArgOperand(0)),
6520                              getValue(I.getArgOperand(1)), Flags));
6521     return;
6522   case Intrinsic::frexp: {
6523     SmallVector<EVT, 2> ValueVTs;
6524     ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
6525     SDVTList VTs = DAG.getVTList(ValueVTs);
6526     setValue(&I,
6527              DAG.getNode(ISD::FFREXP, sdl, VTs, getValue(I.getArgOperand(0))));
6528     return;
6529   }
6530   case Intrinsic::arithmetic_fence: {
6531     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6532                              getValue(I.getArgOperand(0)).getValueType(),
6533                              getValue(I.getArgOperand(0)), Flags));
6534     return;
6535   }
6536   case Intrinsic::fma:
6537     setValue(&I, DAG.getNode(
6538                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6539                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6540                      getValue(I.getArgOperand(2)), Flags));
6541     return;
6542 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6543   case Intrinsic::INTRINSIC:
6544 #include "llvm/IR/ConstrainedOps.def"
6545     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6546     return;
6547 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6548 #include "llvm/IR/VPIntrinsics.def"
6549     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6550     return;
6551   case Intrinsic::fptrunc_round: {
6552     // Get the last argument, the metadata and convert it to an integer in the
6553     // call
6554     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
6555     std::optional<RoundingMode> RoundMode =
6556         convertStrToRoundingMode(cast<MDString>(MD)->getString());
6557 
6558     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6559 
6560     // Propagate fast-math-flags from IR to node(s).
6561     SDNodeFlags Flags;
6562     Flags.copyFMF(*cast<FPMathOperator>(&I));
6563     SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
6564 
6565     SDValue Result;
6566     Result = DAG.getNode(
6567         ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
6568         DAG.getTargetConstant((int)*RoundMode, sdl,
6569                               TLI.getPointerTy(DAG.getDataLayout())));
6570     setValue(&I, Result);
6571 
6572     return;
6573   }
6574   case Intrinsic::fmuladd: {
6575     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6576     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6577         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6578       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6579                                getValue(I.getArgOperand(0)).getValueType(),
6580                                getValue(I.getArgOperand(0)),
6581                                getValue(I.getArgOperand(1)),
6582                                getValue(I.getArgOperand(2)), Flags));
6583     } else {
6584       // TODO: Intrinsic calls should have fast-math-flags.
6585       SDValue Mul = DAG.getNode(
6586           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6587           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6588       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6589                                 getValue(I.getArgOperand(0)).getValueType(),
6590                                 Mul, getValue(I.getArgOperand(2)), Flags);
6591       setValue(&I, Add);
6592     }
6593     return;
6594   }
6595   case Intrinsic::convert_to_fp16:
6596     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6597                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6598                                          getValue(I.getArgOperand(0)),
6599                                          DAG.getTargetConstant(0, sdl,
6600                                                                MVT::i32))));
6601     return;
6602   case Intrinsic::convert_from_fp16:
6603     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6604                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6605                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6606                                          getValue(I.getArgOperand(0)))));
6607     return;
6608   case Intrinsic::fptosi_sat: {
6609     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6610     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
6611                              getValue(I.getArgOperand(0)),
6612                              DAG.getValueType(VT.getScalarType())));
6613     return;
6614   }
6615   case Intrinsic::fptoui_sat: {
6616     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6617     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
6618                              getValue(I.getArgOperand(0)),
6619                              DAG.getValueType(VT.getScalarType())));
6620     return;
6621   }
6622   case Intrinsic::set_rounding:
6623     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6624                       {getRoot(), getValue(I.getArgOperand(0))});
6625     setValue(&I, Res);
6626     DAG.setRoot(Res.getValue(0));
6627     return;
6628   case Intrinsic::is_fpclass: {
6629     const DataLayout DLayout = DAG.getDataLayout();
6630     EVT DestVT = TLI.getValueType(DLayout, I.getType());
6631     EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
6632     FPClassTest Test = static_cast<FPClassTest>(
6633         cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
6634     MachineFunction &MF = DAG.getMachineFunction();
6635     const Function &F = MF.getFunction();
6636     SDValue Op = getValue(I.getArgOperand(0));
6637     SDNodeFlags Flags;
6638     Flags.setNoFPExcept(
6639         !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
6640     // If ISD::IS_FPCLASS should be expanded, do it right now, because the
6641     // expansion can use illegal types. Making expansion early allows
6642     // legalizing these types prior to selection.
6643     if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) {
6644       SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
6645       setValue(&I, Result);
6646       return;
6647     }
6648 
6649     SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
6650     SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
6651     setValue(&I, V);
6652     return;
6653   }
6654   case Intrinsic::get_fpenv: {
6655     const DataLayout DLayout = DAG.getDataLayout();
6656     EVT EnvVT = TLI.getValueType(DLayout, I.getType());
6657     Align TempAlign = DAG.getEVTAlign(EnvVT);
6658     SDValue Chain = getRoot();
6659     // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node
6660     // and temporary storage in stack.
6661     if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) {
6662       Res = DAG.getNode(
6663           ISD::GET_FPENV, sdl,
6664           DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
6665                         MVT::Other),
6666           Chain);
6667     } else {
6668       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
6669       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
6670       auto MPI =
6671           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
6672       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6673           MPI, MachineMemOperand::MOStore, MemoryLocation::UnknownSize,
6674           TempAlign);
6675       Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
6676       Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI);
6677     }
6678     setValue(&I, Res);
6679     DAG.setRoot(Res.getValue(1));
6680     return;
6681   }
6682   case Intrinsic::set_fpenv: {
6683     const DataLayout DLayout = DAG.getDataLayout();
6684     SDValue Env = getValue(I.getArgOperand(0));
6685     EVT EnvVT = Env.getValueType();
6686     Align TempAlign = DAG.getEVTAlign(EnvVT);
6687     SDValue Chain = getRoot();
6688     // If SET_FPENV is custom or legal, use it. Otherwise use loading
6689     // environment from memory.
6690     if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) {
6691       Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env);
6692     } else {
6693       // Allocate space in stack, copy environment bits into it and use this
6694       // memory in SET_FPENV_MEM.
6695       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
6696       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
6697       auto MPI =
6698           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
6699       Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign,
6700                            MachineMemOperand::MOStore);
6701       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6702           MPI, MachineMemOperand::MOLoad, MemoryLocation::UnknownSize,
6703           TempAlign);
6704       Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
6705     }
6706     DAG.setRoot(Chain);
6707     return;
6708   }
6709   case Intrinsic::reset_fpenv:
6710     DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot()));
6711     return;
6712   case Intrinsic::get_fpmode:
6713     Res = DAG.getNode(
6714         ISD::GET_FPMODE, sdl,
6715         DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
6716                       MVT::Other),
6717         DAG.getRoot());
6718     setValue(&I, Res);
6719     DAG.setRoot(Res.getValue(1));
6720     return;
6721   case Intrinsic::set_fpmode:
6722     Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()},
6723                       getValue(I.getArgOperand(0)));
6724     DAG.setRoot(Res);
6725     return;
6726   case Intrinsic::reset_fpmode: {
6727     Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot());
6728     DAG.setRoot(Res);
6729     return;
6730   }
6731   case Intrinsic::pcmarker: {
6732     SDValue Tmp = getValue(I.getArgOperand(0));
6733     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6734     return;
6735   }
6736   case Intrinsic::readcyclecounter: {
6737     SDValue Op = getRoot();
6738     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6739                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6740     setValue(&I, Res);
6741     DAG.setRoot(Res.getValue(1));
6742     return;
6743   }
6744   case Intrinsic::bitreverse:
6745     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6746                              getValue(I.getArgOperand(0)).getValueType(),
6747                              getValue(I.getArgOperand(0))));
6748     return;
6749   case Intrinsic::bswap:
6750     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6751                              getValue(I.getArgOperand(0)).getValueType(),
6752                              getValue(I.getArgOperand(0))));
6753     return;
6754   case Intrinsic::cttz: {
6755     SDValue Arg = getValue(I.getArgOperand(0));
6756     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6757     EVT Ty = Arg.getValueType();
6758     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6759                              sdl, Ty, Arg));
6760     return;
6761   }
6762   case Intrinsic::ctlz: {
6763     SDValue Arg = getValue(I.getArgOperand(0));
6764     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6765     EVT Ty = Arg.getValueType();
6766     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6767                              sdl, Ty, Arg));
6768     return;
6769   }
6770   case Intrinsic::ctpop: {
6771     SDValue Arg = getValue(I.getArgOperand(0));
6772     EVT Ty = Arg.getValueType();
6773     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6774     return;
6775   }
6776   case Intrinsic::fshl:
6777   case Intrinsic::fshr: {
6778     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6779     SDValue X = getValue(I.getArgOperand(0));
6780     SDValue Y = getValue(I.getArgOperand(1));
6781     SDValue Z = getValue(I.getArgOperand(2));
6782     EVT VT = X.getValueType();
6783 
6784     if (X == Y) {
6785       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6786       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6787     } else {
6788       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6789       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6790     }
6791     return;
6792   }
6793   case Intrinsic::sadd_sat: {
6794     SDValue Op1 = getValue(I.getArgOperand(0));
6795     SDValue Op2 = getValue(I.getArgOperand(1));
6796     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6797     return;
6798   }
6799   case Intrinsic::uadd_sat: {
6800     SDValue Op1 = getValue(I.getArgOperand(0));
6801     SDValue Op2 = getValue(I.getArgOperand(1));
6802     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6803     return;
6804   }
6805   case Intrinsic::ssub_sat: {
6806     SDValue Op1 = getValue(I.getArgOperand(0));
6807     SDValue Op2 = getValue(I.getArgOperand(1));
6808     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6809     return;
6810   }
6811   case Intrinsic::usub_sat: {
6812     SDValue Op1 = getValue(I.getArgOperand(0));
6813     SDValue Op2 = getValue(I.getArgOperand(1));
6814     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6815     return;
6816   }
6817   case Intrinsic::sshl_sat: {
6818     SDValue Op1 = getValue(I.getArgOperand(0));
6819     SDValue Op2 = getValue(I.getArgOperand(1));
6820     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6821     return;
6822   }
6823   case Intrinsic::ushl_sat: {
6824     SDValue Op1 = getValue(I.getArgOperand(0));
6825     SDValue Op2 = getValue(I.getArgOperand(1));
6826     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6827     return;
6828   }
6829   case Intrinsic::smul_fix:
6830   case Intrinsic::umul_fix:
6831   case Intrinsic::smul_fix_sat:
6832   case Intrinsic::umul_fix_sat: {
6833     SDValue Op1 = getValue(I.getArgOperand(0));
6834     SDValue Op2 = getValue(I.getArgOperand(1));
6835     SDValue Op3 = getValue(I.getArgOperand(2));
6836     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6837                              Op1.getValueType(), Op1, Op2, Op3));
6838     return;
6839   }
6840   case Intrinsic::sdiv_fix:
6841   case Intrinsic::udiv_fix:
6842   case Intrinsic::sdiv_fix_sat:
6843   case Intrinsic::udiv_fix_sat: {
6844     SDValue Op1 = getValue(I.getArgOperand(0));
6845     SDValue Op2 = getValue(I.getArgOperand(1));
6846     SDValue Op3 = getValue(I.getArgOperand(2));
6847     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6848                               Op1, Op2, Op3, DAG, TLI));
6849     return;
6850   }
6851   case Intrinsic::smax: {
6852     SDValue Op1 = getValue(I.getArgOperand(0));
6853     SDValue Op2 = getValue(I.getArgOperand(1));
6854     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
6855     return;
6856   }
6857   case Intrinsic::smin: {
6858     SDValue Op1 = getValue(I.getArgOperand(0));
6859     SDValue Op2 = getValue(I.getArgOperand(1));
6860     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
6861     return;
6862   }
6863   case Intrinsic::umax: {
6864     SDValue Op1 = getValue(I.getArgOperand(0));
6865     SDValue Op2 = getValue(I.getArgOperand(1));
6866     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
6867     return;
6868   }
6869   case Intrinsic::umin: {
6870     SDValue Op1 = getValue(I.getArgOperand(0));
6871     SDValue Op2 = getValue(I.getArgOperand(1));
6872     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
6873     return;
6874   }
6875   case Intrinsic::abs: {
6876     // TODO: Preserve "int min is poison" arg in SDAG?
6877     SDValue Op1 = getValue(I.getArgOperand(0));
6878     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
6879     return;
6880   }
6881   case Intrinsic::stacksave: {
6882     SDValue Op = getRoot();
6883     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6884     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6885     setValue(&I, Res);
6886     DAG.setRoot(Res.getValue(1));
6887     return;
6888   }
6889   case Intrinsic::stackrestore:
6890     Res = getValue(I.getArgOperand(0));
6891     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6892     return;
6893   case Intrinsic::get_dynamic_area_offset: {
6894     SDValue Op = getRoot();
6895     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6896     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6897     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6898     // target.
6899     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
6900       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6901                          " intrinsic!");
6902     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6903                       Op);
6904     DAG.setRoot(Op);
6905     setValue(&I, Res);
6906     return;
6907   }
6908   case Intrinsic::stackguard: {
6909     MachineFunction &MF = DAG.getMachineFunction();
6910     const Module &M = *MF.getFunction().getParent();
6911     SDValue Chain = getRoot();
6912     if (TLI.useLoadStackGuardNode()) {
6913       Res = getLoadStackGuard(DAG, sdl, Chain);
6914     } else {
6915       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6916       const Value *Global = TLI.getSDagStackGuard(M);
6917       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
6918       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6919                         MachinePointerInfo(Global, 0), Align,
6920                         MachineMemOperand::MOVolatile);
6921     }
6922     if (TLI.useStackGuardXorFP())
6923       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6924     DAG.setRoot(Chain);
6925     setValue(&I, Res);
6926     return;
6927   }
6928   case Intrinsic::stackprotector: {
6929     // Emit code into the DAG to store the stack guard onto the stack.
6930     MachineFunction &MF = DAG.getMachineFunction();
6931     MachineFrameInfo &MFI = MF.getFrameInfo();
6932     SDValue Src, Chain = getRoot();
6933 
6934     if (TLI.useLoadStackGuardNode())
6935       Src = getLoadStackGuard(DAG, sdl, Chain);
6936     else
6937       Src = getValue(I.getArgOperand(0));   // The guard's value.
6938 
6939     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6940 
6941     int FI = FuncInfo.StaticAllocaMap[Slot];
6942     MFI.setStackProtectorIndex(FI);
6943     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6944 
6945     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6946 
6947     // Store the stack protector onto the stack.
6948     Res = DAG.getStore(
6949         Chain, sdl, Src, FIN,
6950         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
6951         MaybeAlign(), MachineMemOperand::MOVolatile);
6952     setValue(&I, Res);
6953     DAG.setRoot(Res);
6954     return;
6955   }
6956   case Intrinsic::objectsize:
6957     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6958 
6959   case Intrinsic::is_constant:
6960     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6961 
6962   case Intrinsic::annotation:
6963   case Intrinsic::ptr_annotation:
6964   case Intrinsic::launder_invariant_group:
6965   case Intrinsic::strip_invariant_group:
6966     // Drop the intrinsic, but forward the value
6967     setValue(&I, getValue(I.getOperand(0)));
6968     return;
6969 
6970   case Intrinsic::assume:
6971   case Intrinsic::experimental_noalias_scope_decl:
6972   case Intrinsic::var_annotation:
6973   case Intrinsic::sideeffect:
6974     // Discard annotate attributes, noalias scope declarations, assumptions, and
6975     // artificial side-effects.
6976     return;
6977 
6978   case Intrinsic::codeview_annotation: {
6979     // Emit a label associated with this metadata.
6980     MachineFunction &MF = DAG.getMachineFunction();
6981     MCSymbol *Label =
6982         MF.getMMI().getContext().createTempSymbol("annotation", true);
6983     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6984     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6985     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6986     DAG.setRoot(Res);
6987     return;
6988   }
6989 
6990   case Intrinsic::init_trampoline: {
6991     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6992 
6993     SDValue Ops[6];
6994     Ops[0] = getRoot();
6995     Ops[1] = getValue(I.getArgOperand(0));
6996     Ops[2] = getValue(I.getArgOperand(1));
6997     Ops[3] = getValue(I.getArgOperand(2));
6998     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6999     Ops[5] = DAG.getSrcValue(F);
7000 
7001     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
7002 
7003     DAG.setRoot(Res);
7004     return;
7005   }
7006   case Intrinsic::adjust_trampoline:
7007     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
7008                              TLI.getPointerTy(DAG.getDataLayout()),
7009                              getValue(I.getArgOperand(0))));
7010     return;
7011   case Intrinsic::gcroot: {
7012     assert(DAG.getMachineFunction().getFunction().hasGC() &&
7013            "only valid in functions with gc specified, enforced by Verifier");
7014     assert(GFI && "implied by previous");
7015     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
7016     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
7017 
7018     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
7019     GFI->addStackRoot(FI->getIndex(), TypeMap);
7020     return;
7021   }
7022   case Intrinsic::gcread:
7023   case Intrinsic::gcwrite:
7024     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
7025   case Intrinsic::get_rounding:
7026     Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot());
7027     setValue(&I, Res);
7028     DAG.setRoot(Res.getValue(1));
7029     return;
7030 
7031   case Intrinsic::expect:
7032     // Just replace __builtin_expect(exp, c) with EXP.
7033     setValue(&I, getValue(I.getArgOperand(0)));
7034     return;
7035 
7036   case Intrinsic::ubsantrap:
7037   case Intrinsic::debugtrap:
7038   case Intrinsic::trap: {
7039     StringRef TrapFuncName =
7040         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
7041     if (TrapFuncName.empty()) {
7042       switch (Intrinsic) {
7043       case Intrinsic::trap:
7044         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
7045         break;
7046       case Intrinsic::debugtrap:
7047         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
7048         break;
7049       case Intrinsic::ubsantrap:
7050         DAG.setRoot(DAG.getNode(
7051             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
7052             DAG.getTargetConstant(
7053                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
7054                 MVT::i32)));
7055         break;
7056       default: llvm_unreachable("unknown trap intrinsic");
7057       }
7058       return;
7059     }
7060     TargetLowering::ArgListTy Args;
7061     if (Intrinsic == Intrinsic::ubsantrap) {
7062       Args.push_back(TargetLoweringBase::ArgListEntry());
7063       Args[0].Val = I.getArgOperand(0);
7064       Args[0].Node = getValue(Args[0].Val);
7065       Args[0].Ty = Args[0].Val->getType();
7066     }
7067 
7068     TargetLowering::CallLoweringInfo CLI(DAG);
7069     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
7070         CallingConv::C, I.getType(),
7071         DAG.getExternalSymbol(TrapFuncName.data(),
7072                               TLI.getPointerTy(DAG.getDataLayout())),
7073         std::move(Args));
7074 
7075     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7076     DAG.setRoot(Result.second);
7077     return;
7078   }
7079 
7080   case Intrinsic::uadd_with_overflow:
7081   case Intrinsic::sadd_with_overflow:
7082   case Intrinsic::usub_with_overflow:
7083   case Intrinsic::ssub_with_overflow:
7084   case Intrinsic::umul_with_overflow:
7085   case Intrinsic::smul_with_overflow: {
7086     ISD::NodeType Op;
7087     switch (Intrinsic) {
7088     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7089     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
7090     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
7091     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
7092     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
7093     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
7094     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
7095     }
7096     SDValue Op1 = getValue(I.getArgOperand(0));
7097     SDValue Op2 = getValue(I.getArgOperand(1));
7098 
7099     EVT ResultVT = Op1.getValueType();
7100     EVT OverflowVT = MVT::i1;
7101     if (ResultVT.isVector())
7102       OverflowVT = EVT::getVectorVT(
7103           *Context, OverflowVT, ResultVT.getVectorElementCount());
7104 
7105     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
7106     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
7107     return;
7108   }
7109   case Intrinsic::prefetch: {
7110     SDValue Ops[5];
7111     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7112     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
7113     Ops[0] = DAG.getRoot();
7114     Ops[1] = getValue(I.getArgOperand(0));
7115     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
7116                                    MVT::i32);
7117     Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl,
7118                                    MVT::i32);
7119     Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl,
7120                                    MVT::i32);
7121     SDValue Result = DAG.getMemIntrinsicNode(
7122         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
7123         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
7124         /* align */ std::nullopt, Flags);
7125 
7126     // Chain the prefetch in parallell with any pending loads, to stay out of
7127     // the way of later optimizations.
7128     PendingLoads.push_back(Result);
7129     Result = getRoot();
7130     DAG.setRoot(Result);
7131     return;
7132   }
7133   case Intrinsic::lifetime_start:
7134   case Intrinsic::lifetime_end: {
7135     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
7136     // Stack coloring is not enabled in O0, discard region information.
7137     if (TM.getOptLevel() == CodeGenOptLevel::None)
7138       return;
7139 
7140     const int64_t ObjectSize =
7141         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
7142     Value *const ObjectPtr = I.getArgOperand(1);
7143     SmallVector<const Value *, 4> Allocas;
7144     getUnderlyingObjects(ObjectPtr, Allocas);
7145 
7146     for (const Value *Alloca : Allocas) {
7147       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
7148 
7149       // Could not find an Alloca.
7150       if (!LifetimeObject)
7151         continue;
7152 
7153       // First check that the Alloca is static, otherwise it won't have a
7154       // valid frame index.
7155       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
7156       if (SI == FuncInfo.StaticAllocaMap.end())
7157         return;
7158 
7159       const int FrameIndex = SI->second;
7160       int64_t Offset;
7161       if (GetPointerBaseWithConstantOffset(
7162               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
7163         Offset = -1; // Cannot determine offset from alloca to lifetime object.
7164       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
7165                                 Offset);
7166       DAG.setRoot(Res);
7167     }
7168     return;
7169   }
7170   case Intrinsic::pseudoprobe: {
7171     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
7172     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7173     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
7174     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
7175     DAG.setRoot(Res);
7176     return;
7177   }
7178   case Intrinsic::invariant_start:
7179     // Discard region information.
7180     setValue(&I,
7181              DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
7182     return;
7183   case Intrinsic::invariant_end:
7184     // Discard region information.
7185     return;
7186   case Intrinsic::clear_cache:
7187     /// FunctionName may be null.
7188     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
7189       lowerCallToExternalSymbol(I, FunctionName);
7190     return;
7191   case Intrinsic::donothing:
7192   case Intrinsic::seh_try_begin:
7193   case Intrinsic::seh_scope_begin:
7194   case Intrinsic::seh_try_end:
7195   case Intrinsic::seh_scope_end:
7196     // ignore
7197     return;
7198   case Intrinsic::experimental_stackmap:
7199     visitStackmap(I);
7200     return;
7201   case Intrinsic::experimental_patchpoint_void:
7202   case Intrinsic::experimental_patchpoint_i64:
7203     visitPatchpoint(I);
7204     return;
7205   case Intrinsic::experimental_gc_statepoint:
7206     LowerStatepoint(cast<GCStatepointInst>(I));
7207     return;
7208   case Intrinsic::experimental_gc_result:
7209     visitGCResult(cast<GCResultInst>(I));
7210     return;
7211   case Intrinsic::experimental_gc_relocate:
7212     visitGCRelocate(cast<GCRelocateInst>(I));
7213     return;
7214   case Intrinsic::instrprof_cover:
7215     llvm_unreachable("instrprof failed to lower a cover");
7216   case Intrinsic::instrprof_increment:
7217     llvm_unreachable("instrprof failed to lower an increment");
7218   case Intrinsic::instrprof_timestamp:
7219     llvm_unreachable("instrprof failed to lower a timestamp");
7220   case Intrinsic::instrprof_value_profile:
7221     llvm_unreachable("instrprof failed to lower a value profiling call");
7222   case Intrinsic::instrprof_mcdc_parameters:
7223     llvm_unreachable("instrprof failed to lower mcdc parameters");
7224   case Intrinsic::instrprof_mcdc_tvbitmap_update:
7225     llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update");
7226   case Intrinsic::instrprof_mcdc_condbitmap_update:
7227     llvm_unreachable("instrprof failed to lower an mcdc condbitmap update");
7228   case Intrinsic::localescape: {
7229     MachineFunction &MF = DAG.getMachineFunction();
7230     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
7231 
7232     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
7233     // is the same on all targets.
7234     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
7235       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
7236       if (isa<ConstantPointerNull>(Arg))
7237         continue; // Skip null pointers. They represent a hole in index space.
7238       AllocaInst *Slot = cast<AllocaInst>(Arg);
7239       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
7240              "can only escape static allocas");
7241       int FI = FuncInfo.StaticAllocaMap[Slot];
7242       MCSymbol *FrameAllocSym =
7243           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7244               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
7245       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
7246               TII->get(TargetOpcode::LOCAL_ESCAPE))
7247           .addSym(FrameAllocSym)
7248           .addFrameIndex(FI);
7249     }
7250 
7251     return;
7252   }
7253 
7254   case Intrinsic::localrecover: {
7255     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
7256     MachineFunction &MF = DAG.getMachineFunction();
7257 
7258     // Get the symbol that defines the frame offset.
7259     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
7260     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
7261     unsigned IdxVal =
7262         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
7263     MCSymbol *FrameAllocSym =
7264         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7265             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
7266 
7267     Value *FP = I.getArgOperand(1);
7268     SDValue FPVal = getValue(FP);
7269     EVT PtrVT = FPVal.getValueType();
7270 
7271     // Create a MCSymbol for the label to avoid any target lowering
7272     // that would make this PC relative.
7273     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
7274     SDValue OffsetVal =
7275         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
7276 
7277     // Add the offset to the FP.
7278     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
7279     setValue(&I, Add);
7280 
7281     return;
7282   }
7283 
7284   case Intrinsic::eh_exceptionpointer:
7285   case Intrinsic::eh_exceptioncode: {
7286     // Get the exception pointer vreg, copy from it, and resize it to fit.
7287     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
7288     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
7289     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
7290     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
7291     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
7292     if (Intrinsic == Intrinsic::eh_exceptioncode)
7293       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
7294     setValue(&I, N);
7295     return;
7296   }
7297   case Intrinsic::xray_customevent: {
7298     // Here we want to make sure that the intrinsic behaves as if it has a
7299     // specific calling convention.
7300     const auto &Triple = DAG.getTarget().getTargetTriple();
7301     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7302       return;
7303 
7304     SmallVector<SDValue, 8> Ops;
7305 
7306     // We want to say that we always want the arguments in registers.
7307     SDValue LogEntryVal = getValue(I.getArgOperand(0));
7308     SDValue StrSizeVal = getValue(I.getArgOperand(1));
7309     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7310     SDValue Chain = getRoot();
7311     Ops.push_back(LogEntryVal);
7312     Ops.push_back(StrSizeVal);
7313     Ops.push_back(Chain);
7314 
7315     // We need to enforce the calling convention for the callsite, so that
7316     // argument ordering is enforced correctly, and that register allocation can
7317     // see that some registers may be assumed clobbered and have to preserve
7318     // them across calls to the intrinsic.
7319     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
7320                                            sdl, NodeTys, Ops);
7321     SDValue patchableNode = SDValue(MN, 0);
7322     DAG.setRoot(patchableNode);
7323     setValue(&I, patchableNode);
7324     return;
7325   }
7326   case Intrinsic::xray_typedevent: {
7327     // Here we want to make sure that the intrinsic behaves as if it has a
7328     // specific calling convention.
7329     const auto &Triple = DAG.getTarget().getTargetTriple();
7330     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7331       return;
7332 
7333     SmallVector<SDValue, 8> Ops;
7334 
7335     // We want to say that we always want the arguments in registers.
7336     // It's unclear to me how manipulating the selection DAG here forces callers
7337     // to provide arguments in registers instead of on the stack.
7338     SDValue LogTypeId = getValue(I.getArgOperand(0));
7339     SDValue LogEntryVal = getValue(I.getArgOperand(1));
7340     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7341     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7342     SDValue Chain = getRoot();
7343     Ops.push_back(LogTypeId);
7344     Ops.push_back(LogEntryVal);
7345     Ops.push_back(StrSizeVal);
7346     Ops.push_back(Chain);
7347 
7348     // We need to enforce the calling convention for the callsite, so that
7349     // argument ordering is enforced correctly, and that register allocation can
7350     // see that some registers may be assumed clobbered and have to preserve
7351     // them across calls to the intrinsic.
7352     MachineSDNode *MN = DAG.getMachineNode(
7353         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7354     SDValue patchableNode = SDValue(MN, 0);
7355     DAG.setRoot(patchableNode);
7356     setValue(&I, patchableNode);
7357     return;
7358   }
7359   case Intrinsic::experimental_deoptimize:
7360     LowerDeoptimizeCall(&I);
7361     return;
7362   case Intrinsic::experimental_stepvector:
7363     visitStepVector(I);
7364     return;
7365   case Intrinsic::vector_reduce_fadd:
7366   case Intrinsic::vector_reduce_fmul:
7367   case Intrinsic::vector_reduce_add:
7368   case Intrinsic::vector_reduce_mul:
7369   case Intrinsic::vector_reduce_and:
7370   case Intrinsic::vector_reduce_or:
7371   case Intrinsic::vector_reduce_xor:
7372   case Intrinsic::vector_reduce_smax:
7373   case Intrinsic::vector_reduce_smin:
7374   case Intrinsic::vector_reduce_umax:
7375   case Intrinsic::vector_reduce_umin:
7376   case Intrinsic::vector_reduce_fmax:
7377   case Intrinsic::vector_reduce_fmin:
7378   case Intrinsic::vector_reduce_fmaximum:
7379   case Intrinsic::vector_reduce_fminimum:
7380     visitVectorReduce(I, Intrinsic);
7381     return;
7382 
7383   case Intrinsic::icall_branch_funnel: {
7384     SmallVector<SDValue, 16> Ops;
7385     Ops.push_back(getValue(I.getArgOperand(0)));
7386 
7387     int64_t Offset;
7388     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7389         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7390     if (!Base)
7391       report_fatal_error(
7392           "llvm.icall.branch.funnel operand must be a GlobalValue");
7393     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7394 
7395     struct BranchFunnelTarget {
7396       int64_t Offset;
7397       SDValue Target;
7398     };
7399     SmallVector<BranchFunnelTarget, 8> Targets;
7400 
7401     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7402       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7403           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7404       if (ElemBase != Base)
7405         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7406                            "to the same GlobalValue");
7407 
7408       SDValue Val = getValue(I.getArgOperand(Op + 1));
7409       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7410       if (!GA)
7411         report_fatal_error(
7412             "llvm.icall.branch.funnel operand must be a GlobalValue");
7413       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7414                                      GA->getGlobal(), sdl, Val.getValueType(),
7415                                      GA->getOffset())});
7416     }
7417     llvm::sort(Targets,
7418                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7419                  return T1.Offset < T2.Offset;
7420                });
7421 
7422     for (auto &T : Targets) {
7423       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7424       Ops.push_back(T.Target);
7425     }
7426 
7427     Ops.push_back(DAG.getRoot()); // Chain
7428     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7429                                  MVT::Other, Ops),
7430               0);
7431     DAG.setRoot(N);
7432     setValue(&I, N);
7433     HasTailCall = true;
7434     return;
7435   }
7436 
7437   case Intrinsic::wasm_landingpad_index:
7438     // Information this intrinsic contained has been transferred to
7439     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7440     // delete it now.
7441     return;
7442 
7443   case Intrinsic::aarch64_settag:
7444   case Intrinsic::aarch64_settag_zero: {
7445     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7446     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7447     SDValue Val = TSI.EmitTargetCodeForSetTag(
7448         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7449         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7450         ZeroMemory);
7451     DAG.setRoot(Val);
7452     setValue(&I, Val);
7453     return;
7454   }
7455   case Intrinsic::amdgcn_cs_chain: {
7456     assert(I.arg_size() == 5 && "Additional args not supported yet");
7457     assert(cast<ConstantInt>(I.getOperand(4))->isZero() &&
7458            "Non-zero flags not supported yet");
7459 
7460     // At this point we don't care if it's amdgpu_cs_chain or
7461     // amdgpu_cs_chain_preserve.
7462     CallingConv::ID CC = CallingConv::AMDGPU_CS_Chain;
7463 
7464     Type *RetTy = I.getType();
7465     assert(RetTy->isVoidTy() && "Should not return");
7466 
7467     SDValue Callee = getValue(I.getOperand(0));
7468 
7469     // We only have 2 actual args: one for the SGPRs and one for the VGPRs.
7470     // We'll also tack the value of the EXEC mask at the end.
7471     TargetLowering::ArgListTy Args;
7472     Args.reserve(3);
7473 
7474     for (unsigned Idx : {2, 3, 1}) {
7475       TargetLowering::ArgListEntry Arg;
7476       Arg.Node = getValue(I.getOperand(Idx));
7477       Arg.Ty = I.getOperand(Idx)->getType();
7478       Arg.setAttributes(&I, Idx);
7479       Args.push_back(Arg);
7480     }
7481 
7482     assert(Args[0].IsInReg && "SGPR args should be marked inreg");
7483     assert(!Args[1].IsInReg && "VGPR args should not be marked inreg");
7484     Args[2].IsInReg = true; // EXEC should be inreg
7485 
7486     TargetLowering::CallLoweringInfo CLI(DAG);
7487     CLI.setDebugLoc(getCurSDLoc())
7488         .setChain(getRoot())
7489         .setCallee(CC, RetTy, Callee, std::move(Args))
7490         .setNoReturn(true)
7491         .setTailCall(true)
7492         .setConvergent(I.isConvergent());
7493     CLI.CB = &I;
7494     std::pair<SDValue, SDValue> Result =
7495         lowerInvokable(CLI, /*EHPadBB*/ nullptr);
7496     (void)Result;
7497     assert(!Result.first.getNode() && !Result.second.getNode() &&
7498            "Should've lowered as tail call");
7499 
7500     HasTailCall = true;
7501     return;
7502   }
7503   case Intrinsic::ptrmask: {
7504     SDValue Ptr = getValue(I.getOperand(0));
7505     SDValue Mask = getValue(I.getOperand(1));
7506 
7507     EVT PtrVT = Ptr.getValueType();
7508     assert(PtrVT == Mask.getValueType() &&
7509            "Pointers with different index type are not supported by SDAG");
7510     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask));
7511     return;
7512   }
7513   case Intrinsic::threadlocal_address: {
7514     setValue(&I, getValue(I.getOperand(0)));
7515     return;
7516   }
7517   case Intrinsic::get_active_lane_mask: {
7518     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7519     SDValue Index = getValue(I.getOperand(0));
7520     EVT ElementVT = Index.getValueType();
7521 
7522     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
7523       visitTargetIntrinsic(I, Intrinsic);
7524       return;
7525     }
7526 
7527     SDValue TripCount = getValue(I.getOperand(1));
7528     EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT,
7529                                  CCVT.getVectorElementCount());
7530 
7531     SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
7532     SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
7533     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
7534     SDValue VectorInduction = DAG.getNode(
7535         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
7536     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
7537                                  VectorTripCount, ISD::CondCode::SETULT);
7538     setValue(&I, SetCC);
7539     return;
7540   }
7541   case Intrinsic::experimental_get_vector_length: {
7542     assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 &&
7543            "Expected positive VF");
7544     unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue();
7545     bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne();
7546 
7547     SDValue Count = getValue(I.getOperand(0));
7548     EVT CountVT = Count.getValueType();
7549 
7550     if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) {
7551       visitTargetIntrinsic(I, Intrinsic);
7552       return;
7553     }
7554 
7555     // Expand to a umin between the trip count and the maximum elements the type
7556     // can hold.
7557     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7558 
7559     // Extend the trip count to at least the result VT.
7560     if (CountVT.bitsLT(VT)) {
7561       Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count);
7562       CountVT = VT;
7563     }
7564 
7565     SDValue MaxEVL = DAG.getElementCount(sdl, CountVT,
7566                                          ElementCount::get(VF, IsScalable));
7567 
7568     SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL);
7569     // Clip to the result type if needed.
7570     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin);
7571 
7572     setValue(&I, Trunc);
7573     return;
7574   }
7575   case Intrinsic::experimental_cttz_elts: {
7576     auto DL = getCurSDLoc();
7577     SDValue Op = getValue(I.getOperand(0));
7578     EVT OpVT = Op.getValueType();
7579 
7580     if (!TLI.shouldExpandCttzElements(OpVT)) {
7581       visitTargetIntrinsic(I, Intrinsic);
7582       return;
7583     }
7584 
7585     if (OpVT.getScalarType() != MVT::i1) {
7586       // Compare the input vector elements to zero & use to count trailing zeros
7587       SDValue AllZero = DAG.getConstant(0, DL, OpVT);
7588       OpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
7589                               OpVT.getVectorElementCount());
7590       Op = DAG.getSetCC(DL, OpVT, Op, AllZero, ISD::SETNE);
7591     }
7592 
7593     // Find the smallest "sensible" element type to use for the expansion.
7594     ConstantRange CR(
7595         APInt(64, OpVT.getVectorElementCount().getKnownMinValue()));
7596     if (OpVT.isScalableVT())
7597       CR = CR.umul_sat(getVScaleRange(I.getCaller(), 64));
7598 
7599     // If the zero-is-poison flag is set, we can assume the upper limit
7600     // of the result is VF-1.
7601     if (!cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero())
7602       CR = CR.subtract(APInt(64, 1));
7603 
7604     unsigned EltWidth = I.getType()->getScalarSizeInBits();
7605     EltWidth = std::min(EltWidth, (unsigned)CR.getActiveBits());
7606     EltWidth = std::max(llvm::bit_ceil(EltWidth), (unsigned)8);
7607 
7608     MVT NewEltTy = MVT::getIntegerVT(EltWidth);
7609 
7610     // Create the new vector type & get the vector length
7611     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), NewEltTy,
7612                                  OpVT.getVectorElementCount());
7613 
7614     SDValue VL =
7615         DAG.getElementCount(DL, NewEltTy, OpVT.getVectorElementCount());
7616 
7617     SDValue StepVec = DAG.getStepVector(DL, NewVT);
7618     SDValue SplatVL = DAG.getSplat(NewVT, DL, VL);
7619     SDValue StepVL = DAG.getNode(ISD::SUB, DL, NewVT, SplatVL, StepVec);
7620     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, Op);
7621     SDValue And = DAG.getNode(ISD::AND, DL, NewVT, StepVL, Ext);
7622     SDValue Max = DAG.getNode(ISD::VECREDUCE_UMAX, DL, NewEltTy, And);
7623     SDValue Sub = DAG.getNode(ISD::SUB, DL, NewEltTy, VL, Max);
7624 
7625     EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7626     SDValue Ret = DAG.getZExtOrTrunc(Sub, DL, RetTy);
7627 
7628     setValue(&I, Ret);
7629     return;
7630   }
7631   case Intrinsic::vector_insert: {
7632     SDValue Vec = getValue(I.getOperand(0));
7633     SDValue SubVec = getValue(I.getOperand(1));
7634     SDValue Index = getValue(I.getOperand(2));
7635 
7636     // The intrinsic's index type is i64, but the SDNode requires an index type
7637     // suitable for the target. Convert the index as required.
7638     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7639     if (Index.getValueType() != VectorIdxTy)
7640       Index = DAG.getVectorIdxConstant(
7641           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7642 
7643     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7644     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
7645                              Index));
7646     return;
7647   }
7648   case Intrinsic::vector_extract: {
7649     SDValue Vec = getValue(I.getOperand(0));
7650     SDValue Index = getValue(I.getOperand(1));
7651     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7652 
7653     // The intrinsic's index type is i64, but the SDNode requires an index type
7654     // suitable for the target. Convert the index as required.
7655     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7656     if (Index.getValueType() != VectorIdxTy)
7657       Index = DAG.getVectorIdxConstant(
7658           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7659 
7660     setValue(&I,
7661              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
7662     return;
7663   }
7664   case Intrinsic::experimental_vector_reverse:
7665     visitVectorReverse(I);
7666     return;
7667   case Intrinsic::experimental_vector_splice:
7668     visitVectorSplice(I);
7669     return;
7670   case Intrinsic::callbr_landingpad:
7671     visitCallBrLandingPad(I);
7672     return;
7673   case Intrinsic::experimental_vector_interleave2:
7674     visitVectorInterleave(I);
7675     return;
7676   case Intrinsic::experimental_vector_deinterleave2:
7677     visitVectorDeinterleave(I);
7678     return;
7679   }
7680 }
7681 
7682 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7683     const ConstrainedFPIntrinsic &FPI) {
7684   SDLoc sdl = getCurSDLoc();
7685 
7686   // We do not need to serialize constrained FP intrinsics against
7687   // each other or against (nonvolatile) loads, so they can be
7688   // chained like loads.
7689   SDValue Chain = DAG.getRoot();
7690   SmallVector<SDValue, 4> Opers;
7691   Opers.push_back(Chain);
7692   if (FPI.isUnaryOp()) {
7693     Opers.push_back(getValue(FPI.getArgOperand(0)));
7694   } else if (FPI.isTernaryOp()) {
7695     Opers.push_back(getValue(FPI.getArgOperand(0)));
7696     Opers.push_back(getValue(FPI.getArgOperand(1)));
7697     Opers.push_back(getValue(FPI.getArgOperand(2)));
7698   } else {
7699     Opers.push_back(getValue(FPI.getArgOperand(0)));
7700     Opers.push_back(getValue(FPI.getArgOperand(1)));
7701   }
7702 
7703   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
7704     assert(Result.getNode()->getNumValues() == 2);
7705 
7706     // Push node to the appropriate list so that future instructions can be
7707     // chained up correctly.
7708     SDValue OutChain = Result.getValue(1);
7709     switch (EB) {
7710     case fp::ExceptionBehavior::ebIgnore:
7711       // The only reason why ebIgnore nodes still need to be chained is that
7712       // they might depend on the current rounding mode, and therefore must
7713       // not be moved across instruction that may change that mode.
7714       [[fallthrough]];
7715     case fp::ExceptionBehavior::ebMayTrap:
7716       // These must not be moved across calls or instructions that may change
7717       // floating-point exception masks.
7718       PendingConstrainedFP.push_back(OutChain);
7719       break;
7720     case fp::ExceptionBehavior::ebStrict:
7721       // These must not be moved across calls or instructions that may change
7722       // floating-point exception masks or read floating-point exception flags.
7723       // In addition, they cannot be optimized out even if unused.
7724       PendingConstrainedFPStrict.push_back(OutChain);
7725       break;
7726     }
7727   };
7728 
7729   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7730   EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
7731   SDVTList VTs = DAG.getVTList(VT, MVT::Other);
7732   fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
7733 
7734   SDNodeFlags Flags;
7735   if (EB == fp::ExceptionBehavior::ebIgnore)
7736     Flags.setNoFPExcept(true);
7737 
7738   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
7739     Flags.copyFMF(*FPOp);
7740 
7741   unsigned Opcode;
7742   switch (FPI.getIntrinsicID()) {
7743   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7744 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7745   case Intrinsic::INTRINSIC:                                                   \
7746     Opcode = ISD::STRICT_##DAGN;                                               \
7747     break;
7748 #include "llvm/IR/ConstrainedOps.def"
7749   case Intrinsic::experimental_constrained_fmuladd: {
7750     Opcode = ISD::STRICT_FMA;
7751     // Break fmuladd into fmul and fadd.
7752     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7753         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
7754       Opers.pop_back();
7755       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
7756       pushOutChain(Mul, EB);
7757       Opcode = ISD::STRICT_FADD;
7758       Opers.clear();
7759       Opers.push_back(Mul.getValue(1));
7760       Opers.push_back(Mul.getValue(0));
7761       Opers.push_back(getValue(FPI.getArgOperand(2)));
7762     }
7763     break;
7764   }
7765   }
7766 
7767   // A few strict DAG nodes carry additional operands that are not
7768   // set up by the default code above.
7769   switch (Opcode) {
7770   default: break;
7771   case ISD::STRICT_FP_ROUND:
7772     Opers.push_back(
7773         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7774     break;
7775   case ISD::STRICT_FSETCC:
7776   case ISD::STRICT_FSETCCS: {
7777     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7778     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
7779     if (TM.Options.NoNaNsFPMath)
7780       Condition = getFCmpCodeWithoutNaN(Condition);
7781     Opers.push_back(DAG.getCondCode(Condition));
7782     break;
7783   }
7784   }
7785 
7786   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7787   pushOutChain(Result, EB);
7788 
7789   SDValue FPResult = Result.getValue(0);
7790   setValue(&FPI, FPResult);
7791 }
7792 
7793 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
7794   std::optional<unsigned> ResOPC;
7795   switch (VPIntrin.getIntrinsicID()) {
7796   case Intrinsic::vp_ctlz: {
7797     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
7798     ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ;
7799     break;
7800   }
7801   case Intrinsic::vp_cttz: {
7802     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
7803     ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ;
7804     break;
7805   }
7806 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD)                                    \
7807   case Intrinsic::VPID:                                                        \
7808     ResOPC = ISD::VPSD;                                                        \
7809     break;
7810 #include "llvm/IR/VPIntrinsics.def"
7811   }
7812 
7813   if (!ResOPC)
7814     llvm_unreachable(
7815         "Inconsistency: no SDNode available for this VPIntrinsic!");
7816 
7817   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
7818       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
7819     if (VPIntrin.getFastMathFlags().allowReassoc())
7820       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
7821                                                 : ISD::VP_REDUCE_FMUL;
7822   }
7823 
7824   return *ResOPC;
7825 }
7826 
7827 void SelectionDAGBuilder::visitVPLoad(
7828     const VPIntrinsic &VPIntrin, EVT VT,
7829     const SmallVectorImpl<SDValue> &OpValues) {
7830   SDLoc DL = getCurSDLoc();
7831   Value *PtrOperand = VPIntrin.getArgOperand(0);
7832   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7833   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7834   const MDNode *Ranges = getRangeMetadata(VPIntrin);
7835   SDValue LD;
7836   // Do not serialize variable-length loads of constant memory with
7837   // anything.
7838   if (!Alignment)
7839     Alignment = DAG.getEVTAlign(VT);
7840   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7841   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7842   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7843   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7844       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7845       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7846   LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
7847                      MMO, false /*IsExpanding */);
7848   if (AddToChain)
7849     PendingLoads.push_back(LD.getValue(1));
7850   setValue(&VPIntrin, LD);
7851 }
7852 
7853 void SelectionDAGBuilder::visitVPGather(
7854     const VPIntrinsic &VPIntrin, EVT VT,
7855     const SmallVectorImpl<SDValue> &OpValues) {
7856   SDLoc DL = getCurSDLoc();
7857   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7858   Value *PtrOperand = VPIntrin.getArgOperand(0);
7859   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7860   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7861   const MDNode *Ranges = getRangeMetadata(VPIntrin);
7862   SDValue LD;
7863   if (!Alignment)
7864     Alignment = DAG.getEVTAlign(VT.getScalarType());
7865   unsigned AS =
7866     PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7867   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7868      MachinePointerInfo(AS), MachineMemOperand::MOLoad,
7869      MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7870   SDValue Base, Index, Scale;
7871   ISD::MemIndexType IndexType;
7872   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7873                                     this, VPIntrin.getParent(),
7874                                     VT.getScalarStoreSize());
7875   if (!UniformBase) {
7876     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7877     Index = getValue(PtrOperand);
7878     IndexType = ISD::SIGNED_SCALED;
7879     Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7880   }
7881   EVT IdxVT = Index.getValueType();
7882   EVT EltTy = IdxVT.getVectorElementType();
7883   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7884     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7885     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7886   }
7887   LD = DAG.getGatherVP(
7888       DAG.getVTList(VT, MVT::Other), VT, DL,
7889       {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
7890       IndexType);
7891   PendingLoads.push_back(LD.getValue(1));
7892   setValue(&VPIntrin, LD);
7893 }
7894 
7895 void SelectionDAGBuilder::visitVPStore(
7896     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
7897   SDLoc DL = getCurSDLoc();
7898   Value *PtrOperand = VPIntrin.getArgOperand(1);
7899   EVT VT = OpValues[0].getValueType();
7900   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7901   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7902   SDValue ST;
7903   if (!Alignment)
7904     Alignment = DAG.getEVTAlign(VT);
7905   SDValue Ptr = OpValues[1];
7906   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
7907   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7908       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7909       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7910   ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
7911                       OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
7912                       /* IsTruncating */ false, /*IsCompressing*/ false);
7913   DAG.setRoot(ST);
7914   setValue(&VPIntrin, ST);
7915 }
7916 
7917 void SelectionDAGBuilder::visitVPScatter(
7918     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
7919   SDLoc DL = getCurSDLoc();
7920   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7921   Value *PtrOperand = VPIntrin.getArgOperand(1);
7922   EVT VT = OpValues[0].getValueType();
7923   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7924   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7925   SDValue ST;
7926   if (!Alignment)
7927     Alignment = DAG.getEVTAlign(VT.getScalarType());
7928   unsigned AS =
7929       PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7930   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7931       MachinePointerInfo(AS), MachineMemOperand::MOStore,
7932       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7933   SDValue Base, Index, Scale;
7934   ISD::MemIndexType IndexType;
7935   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7936                                     this, VPIntrin.getParent(),
7937                                     VT.getScalarStoreSize());
7938   if (!UniformBase) {
7939     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7940     Index = getValue(PtrOperand);
7941     IndexType = ISD::SIGNED_SCALED;
7942     Scale =
7943       DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7944   }
7945   EVT IdxVT = Index.getValueType();
7946   EVT EltTy = IdxVT.getVectorElementType();
7947   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7948     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7949     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7950   }
7951   ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
7952                         {getMemoryRoot(), OpValues[0], Base, Index, Scale,
7953                          OpValues[2], OpValues[3]},
7954                         MMO, IndexType);
7955   DAG.setRoot(ST);
7956   setValue(&VPIntrin, ST);
7957 }
7958 
7959 void SelectionDAGBuilder::visitVPStridedLoad(
7960     const VPIntrinsic &VPIntrin, EVT VT,
7961     const SmallVectorImpl<SDValue> &OpValues) {
7962   SDLoc DL = getCurSDLoc();
7963   Value *PtrOperand = VPIntrin.getArgOperand(0);
7964   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7965   if (!Alignment)
7966     Alignment = DAG.getEVTAlign(VT.getScalarType());
7967   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7968   const MDNode *Ranges = getRangeMetadata(VPIntrin);
7969   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7970   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7971   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7972   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7973       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7974       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7975 
7976   SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
7977                                     OpValues[2], OpValues[3], MMO,
7978                                     false /*IsExpanding*/);
7979 
7980   if (AddToChain)
7981     PendingLoads.push_back(LD.getValue(1));
7982   setValue(&VPIntrin, LD);
7983 }
7984 
7985 void SelectionDAGBuilder::visitVPStridedStore(
7986     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
7987   SDLoc DL = getCurSDLoc();
7988   Value *PtrOperand = VPIntrin.getArgOperand(1);
7989   EVT VT = OpValues[0].getValueType();
7990   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7991   if (!Alignment)
7992     Alignment = DAG.getEVTAlign(VT.getScalarType());
7993   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7994   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7995       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7996       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7997 
7998   SDValue ST = DAG.getStridedStoreVP(
7999       getMemoryRoot(), DL, OpValues[0], OpValues[1],
8000       DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3],
8001       OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
8002       /*IsCompressing*/ false);
8003 
8004   DAG.setRoot(ST);
8005   setValue(&VPIntrin, ST);
8006 }
8007 
8008 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) {
8009   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8010   SDLoc DL = getCurSDLoc();
8011 
8012   ISD::CondCode Condition;
8013   CmpInst::Predicate CondCode = VPIntrin.getPredicate();
8014   bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy();
8015   if (IsFP) {
8016     // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan)
8017     // flags, but calls that don't return floating-point types can't be
8018     // FPMathOperators, like vp.fcmp. This affects constrained fcmp too.
8019     Condition = getFCmpCondCode(CondCode);
8020     if (TM.Options.NoNaNsFPMath)
8021       Condition = getFCmpCodeWithoutNaN(Condition);
8022   } else {
8023     Condition = getICmpCondCode(CondCode);
8024   }
8025 
8026   SDValue Op1 = getValue(VPIntrin.getOperand(0));
8027   SDValue Op2 = getValue(VPIntrin.getOperand(1));
8028   // #2 is the condition code
8029   SDValue MaskOp = getValue(VPIntrin.getOperand(3));
8030   SDValue EVL = getValue(VPIntrin.getOperand(4));
8031   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8032   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8033          "Unexpected target EVL type");
8034   EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL);
8035 
8036   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8037                                                         VPIntrin.getType());
8038   setValue(&VPIntrin,
8039            DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL));
8040 }
8041 
8042 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
8043     const VPIntrinsic &VPIntrin) {
8044   SDLoc DL = getCurSDLoc();
8045   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
8046 
8047   auto IID = VPIntrin.getIntrinsicID();
8048 
8049   if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin))
8050     return visitVPCmp(*CmpI);
8051 
8052   SmallVector<EVT, 4> ValueVTs;
8053   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8054   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
8055   SDVTList VTs = DAG.getVTList(ValueVTs);
8056 
8057   auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
8058 
8059   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8060   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8061          "Unexpected target EVL type");
8062 
8063   // Request operands.
8064   SmallVector<SDValue, 7> OpValues;
8065   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
8066     auto Op = getValue(VPIntrin.getArgOperand(I));
8067     if (I == EVLParamPos)
8068       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
8069     OpValues.push_back(Op);
8070   }
8071 
8072   switch (Opcode) {
8073   default: {
8074     SDNodeFlags SDFlags;
8075     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8076       SDFlags.copyFMF(*FPMO);
8077     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
8078     setValue(&VPIntrin, Result);
8079     break;
8080   }
8081   case ISD::VP_LOAD:
8082     visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
8083     break;
8084   case ISD::VP_GATHER:
8085     visitVPGather(VPIntrin, ValueVTs[0], OpValues);
8086     break;
8087   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
8088     visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
8089     break;
8090   case ISD::VP_STORE:
8091     visitVPStore(VPIntrin, OpValues);
8092     break;
8093   case ISD::VP_SCATTER:
8094     visitVPScatter(VPIntrin, OpValues);
8095     break;
8096   case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
8097     visitVPStridedStore(VPIntrin, OpValues);
8098     break;
8099   case ISD::VP_FMULADD: {
8100     assert(OpValues.size() == 5 && "Unexpected number of operands");
8101     SDNodeFlags SDFlags;
8102     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8103       SDFlags.copyFMF(*FPMO);
8104     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
8105         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) {
8106       setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags));
8107     } else {
8108       SDValue Mul = DAG.getNode(
8109           ISD::VP_FMUL, DL, VTs,
8110           {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags);
8111       SDValue Add =
8112           DAG.getNode(ISD::VP_FADD, DL, VTs,
8113                       {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags);
8114       setValue(&VPIntrin, Add);
8115     }
8116     break;
8117   }
8118   case ISD::VP_IS_FPCLASS: {
8119     const DataLayout DLayout = DAG.getDataLayout();
8120     EVT DestVT = TLI.getValueType(DLayout, VPIntrin.getType());
8121     auto Constant = cast<ConstantSDNode>(OpValues[1])->getZExtValue();
8122     SDValue Check = DAG.getTargetConstant(Constant, DL, MVT::i32);
8123     SDValue V = DAG.getNode(ISD::VP_IS_FPCLASS, DL, DestVT,
8124                             {OpValues[0], Check, OpValues[2], OpValues[3]});
8125     setValue(&VPIntrin, V);
8126     return;
8127   }
8128   case ISD::VP_INTTOPTR: {
8129     SDValue N = OpValues[0];
8130     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType());
8131     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType());
8132     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8133                                OpValues[2]);
8134     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8135                              OpValues[2]);
8136     setValue(&VPIntrin, N);
8137     break;
8138   }
8139   case ISD::VP_PTRTOINT: {
8140     SDValue N = OpValues[0];
8141     EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8142                                                           VPIntrin.getType());
8143     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(),
8144                                        VPIntrin.getOperand(0)->getType());
8145     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8146                                OpValues[2]);
8147     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8148                              OpValues[2]);
8149     setValue(&VPIntrin, N);
8150     break;
8151   }
8152   case ISD::VP_ABS:
8153   case ISD::VP_CTLZ:
8154   case ISD::VP_CTLZ_ZERO_UNDEF:
8155   case ISD::VP_CTTZ:
8156   case ISD::VP_CTTZ_ZERO_UNDEF: {
8157     SDValue Result =
8158         DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]});
8159     setValue(&VPIntrin, Result);
8160     break;
8161   }
8162   }
8163 }
8164 
8165 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
8166                                           const BasicBlock *EHPadBB,
8167                                           MCSymbol *&BeginLabel) {
8168   MachineFunction &MF = DAG.getMachineFunction();
8169   MachineModuleInfo &MMI = MF.getMMI();
8170 
8171   // Insert a label before the invoke call to mark the try range.  This can be
8172   // used to detect deletion of the invoke via the MachineModuleInfo.
8173   BeginLabel = MMI.getContext().createTempSymbol();
8174 
8175   // For SjLj, keep track of which landing pads go with which invokes
8176   // so as to maintain the ordering of pads in the LSDA.
8177   unsigned CallSiteIndex = MMI.getCurrentCallSite();
8178   if (CallSiteIndex) {
8179     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
8180     LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
8181 
8182     // Now that the call site is handled, stop tracking it.
8183     MMI.setCurrentCallSite(0);
8184   }
8185 
8186   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
8187 }
8188 
8189 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
8190                                         const BasicBlock *EHPadBB,
8191                                         MCSymbol *BeginLabel) {
8192   assert(BeginLabel && "BeginLabel should've been set");
8193 
8194   MachineFunction &MF = DAG.getMachineFunction();
8195   MachineModuleInfo &MMI = MF.getMMI();
8196 
8197   // Insert a label at the end of the invoke call to mark the try range.  This
8198   // can be used to detect deletion of the invoke via the MachineModuleInfo.
8199   MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
8200   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
8201 
8202   // Inform MachineModuleInfo of range.
8203   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
8204   // There is a platform (e.g. wasm) that uses funclet style IR but does not
8205   // actually use outlined funclets and their LSDA info style.
8206   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
8207     assert(II && "II should've been set");
8208     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
8209     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
8210   } else if (!isScopedEHPersonality(Pers)) {
8211     assert(EHPadBB);
8212     MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
8213   }
8214 
8215   return Chain;
8216 }
8217 
8218 std::pair<SDValue, SDValue>
8219 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
8220                                     const BasicBlock *EHPadBB) {
8221   MCSymbol *BeginLabel = nullptr;
8222 
8223   if (EHPadBB) {
8224     // Both PendingLoads and PendingExports must be flushed here;
8225     // this call might not return.
8226     (void)getRoot();
8227     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
8228     CLI.setChain(getRoot());
8229   }
8230 
8231   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8232   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
8233 
8234   assert((CLI.IsTailCall || Result.second.getNode()) &&
8235          "Non-null chain expected with non-tail call!");
8236   assert((Result.second.getNode() || !Result.first.getNode()) &&
8237          "Null value expected with tail call!");
8238 
8239   if (!Result.second.getNode()) {
8240     // As a special case, a null chain means that a tail call has been emitted
8241     // and the DAG root is already updated.
8242     HasTailCall = true;
8243 
8244     // Since there's no actual continuation from this block, nothing can be
8245     // relying on us setting vregs for them.
8246     PendingExports.clear();
8247   } else {
8248     DAG.setRoot(Result.second);
8249   }
8250 
8251   if (EHPadBB) {
8252     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
8253                            BeginLabel));
8254   }
8255 
8256   return Result;
8257 }
8258 
8259 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
8260                                       bool isTailCall,
8261                                       bool isMustTailCall,
8262                                       const BasicBlock *EHPadBB) {
8263   auto &DL = DAG.getDataLayout();
8264   FunctionType *FTy = CB.getFunctionType();
8265   Type *RetTy = CB.getType();
8266 
8267   TargetLowering::ArgListTy Args;
8268   Args.reserve(CB.arg_size());
8269 
8270   const Value *SwiftErrorVal = nullptr;
8271   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8272 
8273   if (isTailCall) {
8274     // Avoid emitting tail calls in functions with the disable-tail-calls
8275     // attribute.
8276     auto *Caller = CB.getParent()->getParent();
8277     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
8278         "true" && !isMustTailCall)
8279       isTailCall = false;
8280 
8281     // We can't tail call inside a function with a swifterror argument. Lowering
8282     // does not support this yet. It would have to move into the swifterror
8283     // register before the call.
8284     if (TLI.supportSwiftError() &&
8285         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
8286       isTailCall = false;
8287   }
8288 
8289   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
8290     TargetLowering::ArgListEntry Entry;
8291     const Value *V = *I;
8292 
8293     // Skip empty types
8294     if (V->getType()->isEmptyTy())
8295       continue;
8296 
8297     SDValue ArgNode = getValue(V);
8298     Entry.Node = ArgNode; Entry.Ty = V->getType();
8299 
8300     Entry.setAttributes(&CB, I - CB.arg_begin());
8301 
8302     // Use swifterror virtual register as input to the call.
8303     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
8304       SwiftErrorVal = V;
8305       // We find the virtual register for the actual swifterror argument.
8306       // Instead of using the Value, we use the virtual register instead.
8307       Entry.Node =
8308           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
8309                           EVT(TLI.getPointerTy(DL)));
8310     }
8311 
8312     Args.push_back(Entry);
8313 
8314     // If we have an explicit sret argument that is an Instruction, (i.e., it
8315     // might point to function-local memory), we can't meaningfully tail-call.
8316     if (Entry.IsSRet && isa<Instruction>(V))
8317       isTailCall = false;
8318   }
8319 
8320   // If call site has a cfguardtarget operand bundle, create and add an
8321   // additional ArgListEntry.
8322   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
8323     TargetLowering::ArgListEntry Entry;
8324     Value *V = Bundle->Inputs[0];
8325     SDValue ArgNode = getValue(V);
8326     Entry.Node = ArgNode;
8327     Entry.Ty = V->getType();
8328     Entry.IsCFGuardTarget = true;
8329     Args.push_back(Entry);
8330   }
8331 
8332   // Check if target-independent constraints permit a tail call here.
8333   // Target-dependent constraints are checked within TLI->LowerCallTo.
8334   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
8335     isTailCall = false;
8336 
8337   // Disable tail calls if there is an swifterror argument. Targets have not
8338   // been updated to support tail calls.
8339   if (TLI.supportSwiftError() && SwiftErrorVal)
8340     isTailCall = false;
8341 
8342   ConstantInt *CFIType = nullptr;
8343   if (CB.isIndirectCall()) {
8344     if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
8345       if (!TLI.supportKCFIBundles())
8346         report_fatal_error(
8347             "Target doesn't support calls with kcfi operand bundles.");
8348       CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
8349       assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
8350     }
8351   }
8352 
8353   TargetLowering::CallLoweringInfo CLI(DAG);
8354   CLI.setDebugLoc(getCurSDLoc())
8355       .setChain(getRoot())
8356       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
8357       .setTailCall(isTailCall)
8358       .setConvergent(CB.isConvergent())
8359       .setIsPreallocated(
8360           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
8361       .setCFIType(CFIType);
8362   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8363 
8364   if (Result.first.getNode()) {
8365     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
8366     setValue(&CB, Result.first);
8367   }
8368 
8369   // The last element of CLI.InVals has the SDValue for swifterror return.
8370   // Here we copy it to a virtual register and update SwiftErrorMap for
8371   // book-keeping.
8372   if (SwiftErrorVal && TLI.supportSwiftError()) {
8373     // Get the last element of InVals.
8374     SDValue Src = CLI.InVals.back();
8375     Register VReg =
8376         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
8377     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
8378     DAG.setRoot(CopyNode);
8379   }
8380 }
8381 
8382 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
8383                              SelectionDAGBuilder &Builder) {
8384   // Check to see if this load can be trivially constant folded, e.g. if the
8385   // input is from a string literal.
8386   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
8387     // Cast pointer to the type we really want to load.
8388     Type *LoadTy =
8389         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
8390     if (LoadVT.isVector())
8391       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
8392 
8393     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
8394                                          PointerType::getUnqual(LoadTy));
8395 
8396     if (const Constant *LoadCst =
8397             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
8398                                          LoadTy, Builder.DAG.getDataLayout()))
8399       return Builder.getValue(LoadCst);
8400   }
8401 
8402   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
8403   // still constant memory, the input chain can be the entry node.
8404   SDValue Root;
8405   bool ConstantMemory = false;
8406 
8407   // Do not serialize (non-volatile) loads of constant memory with anything.
8408   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
8409     Root = Builder.DAG.getEntryNode();
8410     ConstantMemory = true;
8411   } else {
8412     // Do not serialize non-volatile loads against each other.
8413     Root = Builder.DAG.getRoot();
8414   }
8415 
8416   SDValue Ptr = Builder.getValue(PtrVal);
8417   SDValue LoadVal =
8418       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
8419                           MachinePointerInfo(PtrVal), Align(1));
8420 
8421   if (!ConstantMemory)
8422     Builder.PendingLoads.push_back(LoadVal.getValue(1));
8423   return LoadVal;
8424 }
8425 
8426 /// Record the value for an instruction that produces an integer result,
8427 /// converting the type where necessary.
8428 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
8429                                                   SDValue Value,
8430                                                   bool IsSigned) {
8431   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8432                                                     I.getType(), true);
8433   Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT);
8434   setValue(&I, Value);
8435 }
8436 
8437 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
8438 /// true and lower it. Otherwise return false, and it will be lowered like a
8439 /// normal call.
8440 /// The caller already checked that \p I calls the appropriate LibFunc with a
8441 /// correct prototype.
8442 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
8443   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
8444   const Value *Size = I.getArgOperand(2);
8445   const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
8446   if (CSize && CSize->getZExtValue() == 0) {
8447     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8448                                                           I.getType(), true);
8449     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
8450     return true;
8451   }
8452 
8453   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8454   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
8455       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
8456       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
8457   if (Res.first.getNode()) {
8458     processIntegerCallValue(I, Res.first, true);
8459     PendingLoads.push_back(Res.second);
8460     return true;
8461   }
8462 
8463   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
8464   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
8465   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
8466     return false;
8467 
8468   // If the target has a fast compare for the given size, it will return a
8469   // preferred load type for that size. Require that the load VT is legal and
8470   // that the target supports unaligned loads of that type. Otherwise, return
8471   // INVALID.
8472   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
8473     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8474     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
8475     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
8476       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
8477       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
8478       // TODO: Check alignment of src and dest ptrs.
8479       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
8480       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
8481       if (!TLI.isTypeLegal(LVT) ||
8482           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
8483           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
8484         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
8485     }
8486 
8487     return LVT;
8488   };
8489 
8490   // This turns into unaligned loads. We only do this if the target natively
8491   // supports the MVT we'll be loading or if it is small enough (<= 4) that
8492   // we'll only produce a small number of byte loads.
8493   MVT LoadVT;
8494   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
8495   switch (NumBitsToCompare) {
8496   default:
8497     return false;
8498   case 16:
8499     LoadVT = MVT::i16;
8500     break;
8501   case 32:
8502     LoadVT = MVT::i32;
8503     break;
8504   case 64:
8505   case 128:
8506   case 256:
8507     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
8508     break;
8509   }
8510 
8511   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
8512     return false;
8513 
8514   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
8515   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
8516 
8517   // Bitcast to a wide integer type if the loads are vectors.
8518   if (LoadVT.isVector()) {
8519     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
8520     LoadL = DAG.getBitcast(CmpVT, LoadL);
8521     LoadR = DAG.getBitcast(CmpVT, LoadR);
8522   }
8523 
8524   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
8525   processIntegerCallValue(I, Cmp, false);
8526   return true;
8527 }
8528 
8529 /// See if we can lower a memchr call into an optimized form. If so, return
8530 /// true and lower it. Otherwise return false, and it will be lowered like a
8531 /// normal call.
8532 /// The caller already checked that \p I calls the appropriate LibFunc with a
8533 /// correct prototype.
8534 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
8535   const Value *Src = I.getArgOperand(0);
8536   const Value *Char = I.getArgOperand(1);
8537   const Value *Length = I.getArgOperand(2);
8538 
8539   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8540   std::pair<SDValue, SDValue> Res =
8541     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
8542                                 getValue(Src), getValue(Char), getValue(Length),
8543                                 MachinePointerInfo(Src));
8544   if (Res.first.getNode()) {
8545     setValue(&I, Res.first);
8546     PendingLoads.push_back(Res.second);
8547     return true;
8548   }
8549 
8550   return false;
8551 }
8552 
8553 /// See if we can lower a mempcpy call into an optimized form. If so, return
8554 /// true and lower it. Otherwise return false, and it will be lowered like a
8555 /// normal call.
8556 /// The caller already checked that \p I calls the appropriate LibFunc with a
8557 /// correct prototype.
8558 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
8559   SDValue Dst = getValue(I.getArgOperand(0));
8560   SDValue Src = getValue(I.getArgOperand(1));
8561   SDValue Size = getValue(I.getArgOperand(2));
8562 
8563   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
8564   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
8565   // DAG::getMemcpy needs Alignment to be defined.
8566   Align Alignment = std::min(DstAlign, SrcAlign);
8567 
8568   SDLoc sdl = getCurSDLoc();
8569 
8570   // In the mempcpy context we need to pass in a false value for isTailCall
8571   // because the return pointer needs to be adjusted by the size of
8572   // the copied memory.
8573   SDValue Root = getMemoryRoot();
8574   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, false, false,
8575                              /*isTailCall=*/false,
8576                              MachinePointerInfo(I.getArgOperand(0)),
8577                              MachinePointerInfo(I.getArgOperand(1)),
8578                              I.getAAMetadata());
8579   assert(MC.getNode() != nullptr &&
8580          "** memcpy should not be lowered as TailCall in mempcpy context **");
8581   DAG.setRoot(MC);
8582 
8583   // Check if Size needs to be truncated or extended.
8584   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
8585 
8586   // Adjust return pointer to point just past the last dst byte.
8587   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
8588                                     Dst, Size);
8589   setValue(&I, DstPlusSize);
8590   return true;
8591 }
8592 
8593 /// See if we can lower a strcpy call into an optimized form.  If so, return
8594 /// true and lower it, otherwise return false and it will be lowered like a
8595 /// normal call.
8596 /// The caller already checked that \p I calls the appropriate LibFunc with a
8597 /// correct prototype.
8598 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
8599   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8600 
8601   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8602   std::pair<SDValue, SDValue> Res =
8603     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
8604                                 getValue(Arg0), getValue(Arg1),
8605                                 MachinePointerInfo(Arg0),
8606                                 MachinePointerInfo(Arg1), isStpcpy);
8607   if (Res.first.getNode()) {
8608     setValue(&I, Res.first);
8609     DAG.setRoot(Res.second);
8610     return true;
8611   }
8612 
8613   return false;
8614 }
8615 
8616 /// See if we can lower a strcmp call into an optimized form.  If so, return
8617 /// true and lower it, otherwise return false and it will be lowered like a
8618 /// normal call.
8619 /// The caller already checked that \p I calls the appropriate LibFunc with a
8620 /// correct prototype.
8621 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
8622   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8623 
8624   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8625   std::pair<SDValue, SDValue> Res =
8626     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
8627                                 getValue(Arg0), getValue(Arg1),
8628                                 MachinePointerInfo(Arg0),
8629                                 MachinePointerInfo(Arg1));
8630   if (Res.first.getNode()) {
8631     processIntegerCallValue(I, Res.first, true);
8632     PendingLoads.push_back(Res.second);
8633     return true;
8634   }
8635 
8636   return false;
8637 }
8638 
8639 /// See if we can lower a strlen call into an optimized form.  If so, return
8640 /// true and lower it, otherwise return false and it will be lowered like a
8641 /// normal call.
8642 /// The caller already checked that \p I calls the appropriate LibFunc with a
8643 /// correct prototype.
8644 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
8645   const Value *Arg0 = I.getArgOperand(0);
8646 
8647   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8648   std::pair<SDValue, SDValue> Res =
8649     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
8650                                 getValue(Arg0), MachinePointerInfo(Arg0));
8651   if (Res.first.getNode()) {
8652     processIntegerCallValue(I, Res.first, false);
8653     PendingLoads.push_back(Res.second);
8654     return true;
8655   }
8656 
8657   return false;
8658 }
8659 
8660 /// See if we can lower a strnlen call into an optimized form.  If so, return
8661 /// true and lower it, otherwise return false and it will be lowered like a
8662 /// normal call.
8663 /// The caller already checked that \p I calls the appropriate LibFunc with a
8664 /// correct prototype.
8665 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
8666   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8667 
8668   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8669   std::pair<SDValue, SDValue> Res =
8670     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
8671                                  getValue(Arg0), getValue(Arg1),
8672                                  MachinePointerInfo(Arg0));
8673   if (Res.first.getNode()) {
8674     processIntegerCallValue(I, Res.first, false);
8675     PendingLoads.push_back(Res.second);
8676     return true;
8677   }
8678 
8679   return false;
8680 }
8681 
8682 /// See if we can lower a unary floating-point operation into an SDNode with
8683 /// the specified Opcode.  If so, return true and lower it, otherwise return
8684 /// false and it will be lowered like a normal call.
8685 /// The caller already checked that \p I calls the appropriate LibFunc with a
8686 /// correct prototype.
8687 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
8688                                               unsigned Opcode) {
8689   // We already checked this call's prototype; verify it doesn't modify errno.
8690   if (!I.onlyReadsMemory())
8691     return false;
8692 
8693   SDNodeFlags Flags;
8694   Flags.copyFMF(cast<FPMathOperator>(I));
8695 
8696   SDValue Tmp = getValue(I.getArgOperand(0));
8697   setValue(&I,
8698            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
8699   return true;
8700 }
8701 
8702 /// See if we can lower a binary floating-point operation into an SDNode with
8703 /// the specified Opcode. If so, return true and lower it. Otherwise return
8704 /// false, and it will be lowered like a normal call.
8705 /// The caller already checked that \p I calls the appropriate LibFunc with a
8706 /// correct prototype.
8707 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
8708                                                unsigned Opcode) {
8709   // We already checked this call's prototype; verify it doesn't modify errno.
8710   if (!I.onlyReadsMemory())
8711     return false;
8712 
8713   SDNodeFlags Flags;
8714   Flags.copyFMF(cast<FPMathOperator>(I));
8715 
8716   SDValue Tmp0 = getValue(I.getArgOperand(0));
8717   SDValue Tmp1 = getValue(I.getArgOperand(1));
8718   EVT VT = Tmp0.getValueType();
8719   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
8720   return true;
8721 }
8722 
8723 void SelectionDAGBuilder::visitCall(const CallInst &I) {
8724   // Handle inline assembly differently.
8725   if (I.isInlineAsm()) {
8726     visitInlineAsm(I);
8727     return;
8728   }
8729 
8730   diagnoseDontCall(I);
8731 
8732   if (Function *F = I.getCalledFunction()) {
8733     if (F->isDeclaration()) {
8734       // Is this an LLVM intrinsic or a target-specific intrinsic?
8735       unsigned IID = F->getIntrinsicID();
8736       if (!IID)
8737         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
8738           IID = II->getIntrinsicID(F);
8739 
8740       if (IID) {
8741         visitIntrinsicCall(I, IID);
8742         return;
8743       }
8744     }
8745 
8746     // Check for well-known libc/libm calls.  If the function is internal, it
8747     // can't be a library call.  Don't do the check if marked as nobuiltin for
8748     // some reason or the call site requires strict floating point semantics.
8749     LibFunc Func;
8750     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
8751         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
8752         LibInfo->hasOptimizedCodeGen(Func)) {
8753       switch (Func) {
8754       default: break;
8755       case LibFunc_bcmp:
8756         if (visitMemCmpBCmpCall(I))
8757           return;
8758         break;
8759       case LibFunc_copysign:
8760       case LibFunc_copysignf:
8761       case LibFunc_copysignl:
8762         // We already checked this call's prototype; verify it doesn't modify
8763         // errno.
8764         if (I.onlyReadsMemory()) {
8765           SDValue LHS = getValue(I.getArgOperand(0));
8766           SDValue RHS = getValue(I.getArgOperand(1));
8767           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
8768                                    LHS.getValueType(), LHS, RHS));
8769           return;
8770         }
8771         break;
8772       case LibFunc_fabs:
8773       case LibFunc_fabsf:
8774       case LibFunc_fabsl:
8775         if (visitUnaryFloatCall(I, ISD::FABS))
8776           return;
8777         break;
8778       case LibFunc_fmin:
8779       case LibFunc_fminf:
8780       case LibFunc_fminl:
8781         if (visitBinaryFloatCall(I, ISD::FMINNUM))
8782           return;
8783         break;
8784       case LibFunc_fmax:
8785       case LibFunc_fmaxf:
8786       case LibFunc_fmaxl:
8787         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
8788           return;
8789         break;
8790       case LibFunc_sin:
8791       case LibFunc_sinf:
8792       case LibFunc_sinl:
8793         if (visitUnaryFloatCall(I, ISD::FSIN))
8794           return;
8795         break;
8796       case LibFunc_cos:
8797       case LibFunc_cosf:
8798       case LibFunc_cosl:
8799         if (visitUnaryFloatCall(I, ISD::FCOS))
8800           return;
8801         break;
8802       case LibFunc_sqrt:
8803       case LibFunc_sqrtf:
8804       case LibFunc_sqrtl:
8805       case LibFunc_sqrt_finite:
8806       case LibFunc_sqrtf_finite:
8807       case LibFunc_sqrtl_finite:
8808         if (visitUnaryFloatCall(I, ISD::FSQRT))
8809           return;
8810         break;
8811       case LibFunc_floor:
8812       case LibFunc_floorf:
8813       case LibFunc_floorl:
8814         if (visitUnaryFloatCall(I, ISD::FFLOOR))
8815           return;
8816         break;
8817       case LibFunc_nearbyint:
8818       case LibFunc_nearbyintf:
8819       case LibFunc_nearbyintl:
8820         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
8821           return;
8822         break;
8823       case LibFunc_ceil:
8824       case LibFunc_ceilf:
8825       case LibFunc_ceill:
8826         if (visitUnaryFloatCall(I, ISD::FCEIL))
8827           return;
8828         break;
8829       case LibFunc_rint:
8830       case LibFunc_rintf:
8831       case LibFunc_rintl:
8832         if (visitUnaryFloatCall(I, ISD::FRINT))
8833           return;
8834         break;
8835       case LibFunc_round:
8836       case LibFunc_roundf:
8837       case LibFunc_roundl:
8838         if (visitUnaryFloatCall(I, ISD::FROUND))
8839           return;
8840         break;
8841       case LibFunc_trunc:
8842       case LibFunc_truncf:
8843       case LibFunc_truncl:
8844         if (visitUnaryFloatCall(I, ISD::FTRUNC))
8845           return;
8846         break;
8847       case LibFunc_log2:
8848       case LibFunc_log2f:
8849       case LibFunc_log2l:
8850         if (visitUnaryFloatCall(I, ISD::FLOG2))
8851           return;
8852         break;
8853       case LibFunc_exp2:
8854       case LibFunc_exp2f:
8855       case LibFunc_exp2l:
8856         if (visitUnaryFloatCall(I, ISD::FEXP2))
8857           return;
8858         break;
8859       case LibFunc_exp10:
8860       case LibFunc_exp10f:
8861       case LibFunc_exp10l:
8862         if (visitUnaryFloatCall(I, ISD::FEXP10))
8863           return;
8864         break;
8865       case LibFunc_ldexp:
8866       case LibFunc_ldexpf:
8867       case LibFunc_ldexpl:
8868         if (visitBinaryFloatCall(I, ISD::FLDEXP))
8869           return;
8870         break;
8871       case LibFunc_memcmp:
8872         if (visitMemCmpBCmpCall(I))
8873           return;
8874         break;
8875       case LibFunc_mempcpy:
8876         if (visitMemPCpyCall(I))
8877           return;
8878         break;
8879       case LibFunc_memchr:
8880         if (visitMemChrCall(I))
8881           return;
8882         break;
8883       case LibFunc_strcpy:
8884         if (visitStrCpyCall(I, false))
8885           return;
8886         break;
8887       case LibFunc_stpcpy:
8888         if (visitStrCpyCall(I, true))
8889           return;
8890         break;
8891       case LibFunc_strcmp:
8892         if (visitStrCmpCall(I))
8893           return;
8894         break;
8895       case LibFunc_strlen:
8896         if (visitStrLenCall(I))
8897           return;
8898         break;
8899       case LibFunc_strnlen:
8900         if (visitStrNLenCall(I))
8901           return;
8902         break;
8903       }
8904     }
8905   }
8906 
8907   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
8908   // have to do anything here to lower funclet bundles.
8909   // CFGuardTarget bundles are lowered in LowerCallTo.
8910   assert(!I.hasOperandBundlesOtherThan(
8911              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
8912               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
8913               LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) &&
8914          "Cannot lower calls with arbitrary operand bundles!");
8915 
8916   SDValue Callee = getValue(I.getCalledOperand());
8917 
8918   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
8919     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
8920   else
8921     // Check if we can potentially perform a tail call. More detailed checking
8922     // is be done within LowerCallTo, after more information about the call is
8923     // known.
8924     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
8925 }
8926 
8927 namespace {
8928 
8929 /// AsmOperandInfo - This contains information for each constraint that we are
8930 /// lowering.
8931 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
8932 public:
8933   /// CallOperand - If this is the result output operand or a clobber
8934   /// this is null, otherwise it is the incoming operand to the CallInst.
8935   /// This gets modified as the asm is processed.
8936   SDValue CallOperand;
8937 
8938   /// AssignedRegs - If this is a register or register class operand, this
8939   /// contains the set of register corresponding to the operand.
8940   RegsForValue AssignedRegs;
8941 
8942   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
8943     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
8944   }
8945 
8946   /// Whether or not this operand accesses memory
8947   bool hasMemory(const TargetLowering &TLI) const {
8948     // Indirect operand accesses access memory.
8949     if (isIndirect)
8950       return true;
8951 
8952     for (const auto &Code : Codes)
8953       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
8954         return true;
8955 
8956     return false;
8957   }
8958 };
8959 
8960 
8961 } // end anonymous namespace
8962 
8963 /// Make sure that the output operand \p OpInfo and its corresponding input
8964 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
8965 /// out).
8966 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
8967                                SDISelAsmOperandInfo &MatchingOpInfo,
8968                                SelectionDAG &DAG) {
8969   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
8970     return;
8971 
8972   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
8973   const auto &TLI = DAG.getTargetLoweringInfo();
8974 
8975   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
8976       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
8977                                        OpInfo.ConstraintVT);
8978   std::pair<unsigned, const TargetRegisterClass *> InputRC =
8979       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
8980                                        MatchingOpInfo.ConstraintVT);
8981   if ((OpInfo.ConstraintVT.isInteger() !=
8982        MatchingOpInfo.ConstraintVT.isInteger()) ||
8983       (MatchRC.second != InputRC.second)) {
8984     // FIXME: error out in a more elegant fashion
8985     report_fatal_error("Unsupported asm: input constraint"
8986                        " with a matching output constraint of"
8987                        " incompatible type!");
8988   }
8989   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
8990 }
8991 
8992 /// Get a direct memory input to behave well as an indirect operand.
8993 /// This may introduce stores, hence the need for a \p Chain.
8994 /// \return The (possibly updated) chain.
8995 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
8996                                         SDISelAsmOperandInfo &OpInfo,
8997                                         SelectionDAG &DAG) {
8998   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8999 
9000   // If we don't have an indirect input, put it in the constpool if we can,
9001   // otherwise spill it to a stack slot.
9002   // TODO: This isn't quite right. We need to handle these according to
9003   // the addressing mode that the constraint wants. Also, this may take
9004   // an additional register for the computation and we don't want that
9005   // either.
9006 
9007   // If the operand is a float, integer, or vector constant, spill to a
9008   // constant pool entry to get its address.
9009   const Value *OpVal = OpInfo.CallOperandVal;
9010   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
9011       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
9012     OpInfo.CallOperand = DAG.getConstantPool(
9013         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
9014     return Chain;
9015   }
9016 
9017   // Otherwise, create a stack slot and emit a store to it before the asm.
9018   Type *Ty = OpVal->getType();
9019   auto &DL = DAG.getDataLayout();
9020   uint64_t TySize = DL.getTypeAllocSize(Ty);
9021   MachineFunction &MF = DAG.getMachineFunction();
9022   int SSFI = MF.getFrameInfo().CreateStackObject(
9023       TySize, DL.getPrefTypeAlign(Ty), false);
9024   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
9025   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
9026                             MachinePointerInfo::getFixedStack(MF, SSFI),
9027                             TLI.getMemValueType(DL, Ty));
9028   OpInfo.CallOperand = StackSlot;
9029 
9030   return Chain;
9031 }
9032 
9033 /// GetRegistersForValue - Assign registers (virtual or physical) for the
9034 /// specified operand.  We prefer to assign virtual registers, to allow the
9035 /// register allocator to handle the assignment process.  However, if the asm
9036 /// uses features that we can't model on machineinstrs, we have SDISel do the
9037 /// allocation.  This produces generally horrible, but correct, code.
9038 ///
9039 ///   OpInfo describes the operand
9040 ///   RefOpInfo describes the matching operand if any, the operand otherwise
9041 static std::optional<unsigned>
9042 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
9043                      SDISelAsmOperandInfo &OpInfo,
9044                      SDISelAsmOperandInfo &RefOpInfo) {
9045   LLVMContext &Context = *DAG.getContext();
9046   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9047 
9048   MachineFunction &MF = DAG.getMachineFunction();
9049   SmallVector<unsigned, 4> Regs;
9050   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9051 
9052   // No work to do for memory/address operands.
9053   if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9054       OpInfo.ConstraintType == TargetLowering::C_Address)
9055     return std::nullopt;
9056 
9057   // If this is a constraint for a single physreg, or a constraint for a
9058   // register class, find it.
9059   unsigned AssignedReg;
9060   const TargetRegisterClass *RC;
9061   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
9062       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
9063   // RC is unset only on failure. Return immediately.
9064   if (!RC)
9065     return std::nullopt;
9066 
9067   // Get the actual register value type.  This is important, because the user
9068   // may have asked for (e.g.) the AX register in i32 type.  We need to
9069   // remember that AX is actually i16 to get the right extension.
9070   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
9071 
9072   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
9073     // If this is an FP operand in an integer register (or visa versa), or more
9074     // generally if the operand value disagrees with the register class we plan
9075     // to stick it in, fix the operand type.
9076     //
9077     // If this is an input value, the bitcast to the new type is done now.
9078     // Bitcast for output value is done at the end of visitInlineAsm().
9079     if ((OpInfo.Type == InlineAsm::isOutput ||
9080          OpInfo.Type == InlineAsm::isInput) &&
9081         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
9082       // Try to convert to the first EVT that the reg class contains.  If the
9083       // types are identical size, use a bitcast to convert (e.g. two differing
9084       // vector types).  Note: output bitcast is done at the end of
9085       // visitInlineAsm().
9086       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
9087         // Exclude indirect inputs while they are unsupported because the code
9088         // to perform the load is missing and thus OpInfo.CallOperand still
9089         // refers to the input address rather than the pointed-to value.
9090         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
9091           OpInfo.CallOperand =
9092               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
9093         OpInfo.ConstraintVT = RegVT;
9094         // If the operand is an FP value and we want it in integer registers,
9095         // use the corresponding integer type. This turns an f64 value into
9096         // i64, which can be passed with two i32 values on a 32-bit machine.
9097       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
9098         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
9099         if (OpInfo.Type == InlineAsm::isInput)
9100           OpInfo.CallOperand =
9101               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
9102         OpInfo.ConstraintVT = VT;
9103       }
9104     }
9105   }
9106 
9107   // No need to allocate a matching input constraint since the constraint it's
9108   // matching to has already been allocated.
9109   if (OpInfo.isMatchingInputConstraint())
9110     return std::nullopt;
9111 
9112   EVT ValueVT = OpInfo.ConstraintVT;
9113   if (OpInfo.ConstraintVT == MVT::Other)
9114     ValueVT = RegVT;
9115 
9116   // Initialize NumRegs.
9117   unsigned NumRegs = 1;
9118   if (OpInfo.ConstraintVT != MVT::Other)
9119     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
9120 
9121   // If this is a constraint for a specific physical register, like {r17},
9122   // assign it now.
9123 
9124   // If this associated to a specific register, initialize iterator to correct
9125   // place. If virtual, make sure we have enough registers
9126 
9127   // Initialize iterator if necessary
9128   TargetRegisterClass::iterator I = RC->begin();
9129   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9130 
9131   // Do not check for single registers.
9132   if (AssignedReg) {
9133     I = std::find(I, RC->end(), AssignedReg);
9134     if (I == RC->end()) {
9135       // RC does not contain the selected register, which indicates a
9136       // mismatch between the register and the required type/bitwidth.
9137       return {AssignedReg};
9138     }
9139   }
9140 
9141   for (; NumRegs; --NumRegs, ++I) {
9142     assert(I != RC->end() && "Ran out of registers to allocate!");
9143     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
9144     Regs.push_back(R);
9145   }
9146 
9147   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
9148   return std::nullopt;
9149 }
9150 
9151 static unsigned
9152 findMatchingInlineAsmOperand(unsigned OperandNo,
9153                              const std::vector<SDValue> &AsmNodeOperands) {
9154   // Scan until we find the definition we already emitted of this operand.
9155   unsigned CurOp = InlineAsm::Op_FirstOperand;
9156   for (; OperandNo; --OperandNo) {
9157     // Advance to the next operand.
9158     unsigned OpFlag =
9159         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
9160     const InlineAsm::Flag F(OpFlag);
9161     assert(
9162         (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) &&
9163         "Skipped past definitions?");
9164     CurOp += F.getNumOperandRegisters() + 1;
9165   }
9166   return CurOp;
9167 }
9168 
9169 namespace {
9170 
9171 class ExtraFlags {
9172   unsigned Flags = 0;
9173 
9174 public:
9175   explicit ExtraFlags(const CallBase &Call) {
9176     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9177     if (IA->hasSideEffects())
9178       Flags |= InlineAsm::Extra_HasSideEffects;
9179     if (IA->isAlignStack())
9180       Flags |= InlineAsm::Extra_IsAlignStack;
9181     if (Call.isConvergent())
9182       Flags |= InlineAsm::Extra_IsConvergent;
9183     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
9184   }
9185 
9186   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
9187     // Ideally, we would only check against memory constraints.  However, the
9188     // meaning of an Other constraint can be target-specific and we can't easily
9189     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
9190     // for Other constraints as well.
9191     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9192         OpInfo.ConstraintType == TargetLowering::C_Other) {
9193       if (OpInfo.Type == InlineAsm::isInput)
9194         Flags |= InlineAsm::Extra_MayLoad;
9195       else if (OpInfo.Type == InlineAsm::isOutput)
9196         Flags |= InlineAsm::Extra_MayStore;
9197       else if (OpInfo.Type == InlineAsm::isClobber)
9198         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
9199     }
9200   }
9201 
9202   unsigned get() const { return Flags; }
9203 };
9204 
9205 } // end anonymous namespace
9206 
9207 static bool isFunction(SDValue Op) {
9208   if (Op && Op.getOpcode() == ISD::GlobalAddress) {
9209     if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
9210       auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
9211 
9212       // In normal "call dllimport func" instruction (non-inlineasm) it force
9213       // indirect access by specifing call opcode. And usually specially print
9214       // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
9215       // not do in this way now. (In fact, this is similar with "Data Access"
9216       // action). So here we ignore dllimport function.
9217       if (Fn && !Fn->hasDLLImportStorageClass())
9218         return true;
9219     }
9220   }
9221   return false;
9222 }
9223 
9224 /// visitInlineAsm - Handle a call to an InlineAsm object.
9225 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
9226                                          const BasicBlock *EHPadBB) {
9227   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9228 
9229   /// ConstraintOperands - Information about all of the constraints.
9230   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
9231 
9232   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9233   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
9234       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
9235 
9236   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
9237   // AsmDialect, MayLoad, MayStore).
9238   bool HasSideEffect = IA->hasSideEffects();
9239   ExtraFlags ExtraInfo(Call);
9240 
9241   for (auto &T : TargetConstraints) {
9242     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
9243     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
9244 
9245     if (OpInfo.CallOperandVal)
9246       OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
9247 
9248     if (!HasSideEffect)
9249       HasSideEffect = OpInfo.hasMemory(TLI);
9250 
9251     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
9252     // FIXME: Could we compute this on OpInfo rather than T?
9253 
9254     // Compute the constraint code and ConstraintType to use.
9255     TLI.ComputeConstraintToUse(T, SDValue());
9256 
9257     if (T.ConstraintType == TargetLowering::C_Immediate &&
9258         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
9259       // We've delayed emitting a diagnostic like the "n" constraint because
9260       // inlining could cause an integer showing up.
9261       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
9262                                           "' expects an integer constant "
9263                                           "expression");
9264 
9265     ExtraInfo.update(T);
9266   }
9267 
9268   // We won't need to flush pending loads if this asm doesn't touch
9269   // memory and is nonvolatile.
9270   SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
9271 
9272   bool EmitEHLabels = isa<InvokeInst>(Call);
9273   if (EmitEHLabels) {
9274     assert(EHPadBB && "InvokeInst must have an EHPadBB");
9275   }
9276   bool IsCallBr = isa<CallBrInst>(Call);
9277 
9278   if (IsCallBr || EmitEHLabels) {
9279     // If this is a callbr or invoke we need to flush pending exports since
9280     // inlineasm_br and invoke are terminators.
9281     // We need to do this before nodes are glued to the inlineasm_br node.
9282     Chain = getControlRoot();
9283   }
9284 
9285   MCSymbol *BeginLabel = nullptr;
9286   if (EmitEHLabels) {
9287     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
9288   }
9289 
9290   int OpNo = -1;
9291   SmallVector<StringRef> AsmStrs;
9292   IA->collectAsmStrs(AsmStrs);
9293 
9294   // Second pass over the constraints: compute which constraint option to use.
9295   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9296     if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
9297       OpNo++;
9298 
9299     // If this is an output operand with a matching input operand, look up the
9300     // matching input. If their types mismatch, e.g. one is an integer, the
9301     // other is floating point, or their sizes are different, flag it as an
9302     // error.
9303     if (OpInfo.hasMatchingInput()) {
9304       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
9305       patchMatchingInput(OpInfo, Input, DAG);
9306     }
9307 
9308     // Compute the constraint code and ConstraintType to use.
9309     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
9310 
9311     if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
9312          OpInfo.Type == InlineAsm::isClobber) ||
9313         OpInfo.ConstraintType == TargetLowering::C_Address)
9314       continue;
9315 
9316     // In Linux PIC model, there are 4 cases about value/label addressing:
9317     //
9318     // 1: Function call or Label jmp inside the module.
9319     // 2: Data access (such as global variable, static variable) inside module.
9320     // 3: Function call or Label jmp outside the module.
9321     // 4: Data access (such as global variable) outside the module.
9322     //
9323     // Due to current llvm inline asm architecture designed to not "recognize"
9324     // the asm code, there are quite troubles for us to treat mem addressing
9325     // differently for same value/adress used in different instuctions.
9326     // For example, in pic model, call a func may in plt way or direclty
9327     // pc-related, but lea/mov a function adress may use got.
9328     //
9329     // Here we try to "recognize" function call for the case 1 and case 3 in
9330     // inline asm. And try to adjust the constraint for them.
9331     //
9332     // TODO: Due to current inline asm didn't encourage to jmp to the outsider
9333     // label, so here we don't handle jmp function label now, but we need to
9334     // enhance it (especilly in PIC model) if we meet meaningful requirements.
9335     if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
9336         TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
9337         TM.getCodeModel() != CodeModel::Large) {
9338       OpInfo.isIndirect = false;
9339       OpInfo.ConstraintType = TargetLowering::C_Address;
9340     }
9341 
9342     // If this is a memory input, and if the operand is not indirect, do what we
9343     // need to provide an address for the memory input.
9344     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
9345         !OpInfo.isIndirect) {
9346       assert((OpInfo.isMultipleAlternative ||
9347               (OpInfo.Type == InlineAsm::isInput)) &&
9348              "Can only indirectify direct input operands!");
9349 
9350       // Memory operands really want the address of the value.
9351       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
9352 
9353       // There is no longer a Value* corresponding to this operand.
9354       OpInfo.CallOperandVal = nullptr;
9355 
9356       // It is now an indirect operand.
9357       OpInfo.isIndirect = true;
9358     }
9359 
9360   }
9361 
9362   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
9363   std::vector<SDValue> AsmNodeOperands;
9364   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
9365   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
9366       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
9367 
9368   // If we have a !srcloc metadata node associated with it, we want to attach
9369   // this to the ultimately generated inline asm machineinstr.  To do this, we
9370   // pass in the third operand as this (potentially null) inline asm MDNode.
9371   const MDNode *SrcLoc = Call.getMetadata("srcloc");
9372   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
9373 
9374   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
9375   // bits as operand 3.
9376   AsmNodeOperands.push_back(DAG.getTargetConstant(
9377       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9378 
9379   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
9380   // this, assign virtual and physical registers for inputs and otput.
9381   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9382     // Assign Registers.
9383     SDISelAsmOperandInfo &RefOpInfo =
9384         OpInfo.isMatchingInputConstraint()
9385             ? ConstraintOperands[OpInfo.getMatchedOperand()]
9386             : OpInfo;
9387     const auto RegError =
9388         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
9389     if (RegError) {
9390       const MachineFunction &MF = DAG.getMachineFunction();
9391       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9392       const char *RegName = TRI.getName(*RegError);
9393       emitInlineAsmError(Call, "register '" + Twine(RegName) +
9394                                    "' allocated for constraint '" +
9395                                    Twine(OpInfo.ConstraintCode) +
9396                                    "' does not match required type");
9397       return;
9398     }
9399 
9400     auto DetectWriteToReservedRegister = [&]() {
9401       const MachineFunction &MF = DAG.getMachineFunction();
9402       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9403       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
9404         if (Register::isPhysicalRegister(Reg) &&
9405             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
9406           const char *RegName = TRI.getName(Reg);
9407           emitInlineAsmError(Call, "write to reserved register '" +
9408                                        Twine(RegName) + "'");
9409           return true;
9410         }
9411       }
9412       return false;
9413     };
9414     assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
9415             (OpInfo.Type == InlineAsm::isInput &&
9416              !OpInfo.isMatchingInputConstraint())) &&
9417            "Only address as input operand is allowed.");
9418 
9419     switch (OpInfo.Type) {
9420     case InlineAsm::isOutput:
9421       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
9422         const InlineAsm::ConstraintCode ConstraintID =
9423             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9424         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
9425                "Failed to convert memory constraint code to constraint id.");
9426 
9427         // Add information to the INLINEASM node to know about this output.
9428         InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1);
9429         OpFlags.setMemConstraint(ConstraintID);
9430         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
9431                                                         MVT::i32));
9432         AsmNodeOperands.push_back(OpInfo.CallOperand);
9433       } else {
9434         // Otherwise, this outputs to a register (directly for C_Register /
9435         // C_RegisterClass, and a target-defined fashion for
9436         // C_Immediate/C_Other). Find a register that we can use.
9437         if (OpInfo.AssignedRegs.Regs.empty()) {
9438           emitInlineAsmError(
9439               Call, "couldn't allocate output register for constraint '" +
9440                         Twine(OpInfo.ConstraintCode) + "'");
9441           return;
9442         }
9443 
9444         if (DetectWriteToReservedRegister())
9445           return;
9446 
9447         // Add information to the INLINEASM node to know that this register is
9448         // set.
9449         OpInfo.AssignedRegs.AddInlineAsmOperands(
9450             OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber
9451                                   : InlineAsm::Kind::RegDef,
9452             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
9453       }
9454       break;
9455 
9456     case InlineAsm::isInput:
9457     case InlineAsm::isLabel: {
9458       SDValue InOperandVal = OpInfo.CallOperand;
9459 
9460       if (OpInfo.isMatchingInputConstraint()) {
9461         // If this is required to match an output register we have already set,
9462         // just use its register.
9463         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
9464                                                   AsmNodeOperands);
9465         InlineAsm::Flag Flag(
9466             cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue());
9467         if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) {
9468           if (OpInfo.isIndirect) {
9469             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
9470             emitInlineAsmError(Call, "inline asm not supported yet: "
9471                                      "don't know how to handle tied "
9472                                      "indirect register inputs");
9473             return;
9474           }
9475 
9476           SmallVector<unsigned, 4> Regs;
9477           MachineFunction &MF = DAG.getMachineFunction();
9478           MachineRegisterInfo &MRI = MF.getRegInfo();
9479           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9480           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
9481           Register TiedReg = R->getReg();
9482           MVT RegVT = R->getSimpleValueType(0);
9483           const TargetRegisterClass *RC =
9484               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
9485               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
9486                                       : TRI.getMinimalPhysRegClass(TiedReg);
9487           for (unsigned i = 0, e = Flag.getNumOperandRegisters(); i != e; ++i)
9488             Regs.push_back(MRI.createVirtualRegister(RC));
9489 
9490           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
9491 
9492           SDLoc dl = getCurSDLoc();
9493           // Use the produced MatchedRegs object to
9494           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call);
9495           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, true,
9496                                            OpInfo.getMatchedOperand(), dl, DAG,
9497                                            AsmNodeOperands);
9498           break;
9499         }
9500 
9501         assert(Flag.isMemKind() && "Unknown matching constraint!");
9502         assert(Flag.getNumOperandRegisters() == 1 &&
9503                "Unexpected number of operands");
9504         // Add information to the INLINEASM node to know about this input.
9505         // See InlineAsm.h isUseOperandTiedToDef.
9506         Flag.clearMemConstraint();
9507         Flag.setMatchingOp(OpInfo.getMatchedOperand());
9508         AsmNodeOperands.push_back(DAG.getTargetConstant(
9509             Flag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9510         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
9511         break;
9512       }
9513 
9514       // Treat indirect 'X' constraint as memory.
9515       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
9516           OpInfo.isIndirect)
9517         OpInfo.ConstraintType = TargetLowering::C_Memory;
9518 
9519       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
9520           OpInfo.ConstraintType == TargetLowering::C_Other) {
9521         std::vector<SDValue> Ops;
9522         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
9523                                           Ops, DAG);
9524         if (Ops.empty()) {
9525           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
9526             if (isa<ConstantSDNode>(InOperandVal)) {
9527               emitInlineAsmError(Call, "value out of range for constraint '" +
9528                                            Twine(OpInfo.ConstraintCode) + "'");
9529               return;
9530             }
9531 
9532           emitInlineAsmError(Call,
9533                              "invalid operand for inline asm constraint '" +
9534                                  Twine(OpInfo.ConstraintCode) + "'");
9535           return;
9536         }
9537 
9538         // Add information to the INLINEASM node to know about this input.
9539         InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size());
9540         AsmNodeOperands.push_back(DAG.getTargetConstant(
9541             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9542         llvm::append_range(AsmNodeOperands, Ops);
9543         break;
9544       }
9545 
9546       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
9547         assert((OpInfo.isIndirect ||
9548                 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
9549                "Operand must be indirect to be a mem!");
9550         assert(InOperandVal.getValueType() ==
9551                    TLI.getPointerTy(DAG.getDataLayout()) &&
9552                "Memory operands expect pointer values");
9553 
9554         const InlineAsm::ConstraintCode ConstraintID =
9555             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9556         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
9557                "Failed to convert memory constraint code to constraint id.");
9558 
9559         // Add information to the INLINEASM node to know about this input.
9560         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
9561         ResOpType.setMemConstraint(ConstraintID);
9562         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
9563                                                         getCurSDLoc(),
9564                                                         MVT::i32));
9565         AsmNodeOperands.push_back(InOperandVal);
9566         break;
9567       }
9568 
9569       if (OpInfo.ConstraintType == TargetLowering::C_Address) {
9570         const InlineAsm::ConstraintCode ConstraintID =
9571             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9572         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
9573                "Failed to convert memory constraint code to constraint id.");
9574 
9575         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
9576 
9577         SDValue AsmOp = InOperandVal;
9578         if (isFunction(InOperandVal)) {
9579           auto *GA = cast<GlobalAddressSDNode>(InOperandVal);
9580           ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1);
9581           AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(),
9582                                              InOperandVal.getValueType(),
9583                                              GA->getOffset());
9584         }
9585 
9586         // Add information to the INLINEASM node to know about this input.
9587         ResOpType.setMemConstraint(ConstraintID);
9588 
9589         AsmNodeOperands.push_back(
9590             DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32));
9591 
9592         AsmNodeOperands.push_back(AsmOp);
9593         break;
9594       }
9595 
9596       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
9597               OpInfo.ConstraintType == TargetLowering::C_Register) &&
9598              "Unknown constraint type!");
9599 
9600       // TODO: Support this.
9601       if (OpInfo.isIndirect) {
9602         emitInlineAsmError(
9603             Call, "Don't know how to handle indirect register inputs yet "
9604                   "for constraint '" +
9605                       Twine(OpInfo.ConstraintCode) + "'");
9606         return;
9607       }
9608 
9609       // Copy the input into the appropriate registers.
9610       if (OpInfo.AssignedRegs.Regs.empty()) {
9611         emitInlineAsmError(Call,
9612                            "couldn't allocate input reg for constraint '" +
9613                                Twine(OpInfo.ConstraintCode) + "'");
9614         return;
9615       }
9616 
9617       if (DetectWriteToReservedRegister())
9618         return;
9619 
9620       SDLoc dl = getCurSDLoc();
9621 
9622       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue,
9623                                         &Call);
9624 
9625       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, false,
9626                                                0, dl, DAG, AsmNodeOperands);
9627       break;
9628     }
9629     case InlineAsm::isClobber:
9630       // Add the clobbered value to the operand list, so that the register
9631       // allocator is aware that the physreg got clobbered.
9632       if (!OpInfo.AssignedRegs.Regs.empty())
9633         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::Clobber,
9634                                                  false, 0, getCurSDLoc(), DAG,
9635                                                  AsmNodeOperands);
9636       break;
9637     }
9638   }
9639 
9640   // Finish up input operands.  Set the input chain and add the flag last.
9641   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
9642   if (Glue.getNode()) AsmNodeOperands.push_back(Glue);
9643 
9644   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
9645   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
9646                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
9647   Glue = Chain.getValue(1);
9648 
9649   // Do additional work to generate outputs.
9650 
9651   SmallVector<EVT, 1> ResultVTs;
9652   SmallVector<SDValue, 1> ResultValues;
9653   SmallVector<SDValue, 8> OutChains;
9654 
9655   llvm::Type *CallResultType = Call.getType();
9656   ArrayRef<Type *> ResultTypes;
9657   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
9658     ResultTypes = StructResult->elements();
9659   else if (!CallResultType->isVoidTy())
9660     ResultTypes = ArrayRef(CallResultType);
9661 
9662   auto CurResultType = ResultTypes.begin();
9663   auto handleRegAssign = [&](SDValue V) {
9664     assert(CurResultType != ResultTypes.end() && "Unexpected value");
9665     assert((*CurResultType)->isSized() && "Unexpected unsized type");
9666     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
9667     ++CurResultType;
9668     // If the type of the inline asm call site return value is different but has
9669     // same size as the type of the asm output bitcast it.  One example of this
9670     // is for vectors with different width / number of elements.  This can
9671     // happen for register classes that can contain multiple different value
9672     // types.  The preg or vreg allocated may not have the same VT as was
9673     // expected.
9674     //
9675     // This can also happen for a return value that disagrees with the register
9676     // class it is put in, eg. a double in a general-purpose register on a
9677     // 32-bit machine.
9678     if (ResultVT != V.getValueType() &&
9679         ResultVT.getSizeInBits() == V.getValueSizeInBits())
9680       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
9681     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
9682              V.getValueType().isInteger()) {
9683       // If a result value was tied to an input value, the computed result
9684       // may have a wider width than the expected result.  Extract the
9685       // relevant portion.
9686       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
9687     }
9688     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
9689     ResultVTs.push_back(ResultVT);
9690     ResultValues.push_back(V);
9691   };
9692 
9693   // Deal with output operands.
9694   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9695     if (OpInfo.Type == InlineAsm::isOutput) {
9696       SDValue Val;
9697       // Skip trivial output operands.
9698       if (OpInfo.AssignedRegs.Regs.empty())
9699         continue;
9700 
9701       switch (OpInfo.ConstraintType) {
9702       case TargetLowering::C_Register:
9703       case TargetLowering::C_RegisterClass:
9704         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
9705                                                   Chain, &Glue, &Call);
9706         break;
9707       case TargetLowering::C_Immediate:
9708       case TargetLowering::C_Other:
9709         Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(),
9710                                               OpInfo, DAG);
9711         break;
9712       case TargetLowering::C_Memory:
9713         break; // Already handled.
9714       case TargetLowering::C_Address:
9715         break; // Silence warning.
9716       case TargetLowering::C_Unknown:
9717         assert(false && "Unexpected unknown constraint");
9718       }
9719 
9720       // Indirect output manifest as stores. Record output chains.
9721       if (OpInfo.isIndirect) {
9722         const Value *Ptr = OpInfo.CallOperandVal;
9723         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
9724         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
9725                                      MachinePointerInfo(Ptr));
9726         OutChains.push_back(Store);
9727       } else {
9728         // generate CopyFromRegs to associated registers.
9729         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
9730         if (Val.getOpcode() == ISD::MERGE_VALUES) {
9731           for (const SDValue &V : Val->op_values())
9732             handleRegAssign(V);
9733         } else
9734           handleRegAssign(Val);
9735       }
9736     }
9737   }
9738 
9739   // Set results.
9740   if (!ResultValues.empty()) {
9741     assert(CurResultType == ResultTypes.end() &&
9742            "Mismatch in number of ResultTypes");
9743     assert(ResultValues.size() == ResultTypes.size() &&
9744            "Mismatch in number of output operands in asm result");
9745 
9746     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
9747                             DAG.getVTList(ResultVTs), ResultValues);
9748     setValue(&Call, V);
9749   }
9750 
9751   // Collect store chains.
9752   if (!OutChains.empty())
9753     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
9754 
9755   if (EmitEHLabels) {
9756     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
9757   }
9758 
9759   // Only Update Root if inline assembly has a memory effect.
9760   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
9761       EmitEHLabels)
9762     DAG.setRoot(Chain);
9763 }
9764 
9765 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
9766                                              const Twine &Message) {
9767   LLVMContext &Ctx = *DAG.getContext();
9768   Ctx.emitError(&Call, Message);
9769 
9770   // Make sure we leave the DAG in a valid state
9771   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9772   SmallVector<EVT, 1> ValueVTs;
9773   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
9774 
9775   if (ValueVTs.empty())
9776     return;
9777 
9778   SmallVector<SDValue, 1> Ops;
9779   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
9780     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
9781 
9782   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
9783 }
9784 
9785 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
9786   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
9787                           MVT::Other, getRoot(),
9788                           getValue(I.getArgOperand(0)),
9789                           DAG.getSrcValue(I.getArgOperand(0))));
9790 }
9791 
9792 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
9793   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9794   const DataLayout &DL = DAG.getDataLayout();
9795   SDValue V = DAG.getVAArg(
9796       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
9797       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
9798       DL.getABITypeAlign(I.getType()).value());
9799   DAG.setRoot(V.getValue(1));
9800 
9801   if (I.getType()->isPointerTy())
9802     V = DAG.getPtrExtOrTrunc(
9803         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
9804   setValue(&I, V);
9805 }
9806 
9807 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
9808   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
9809                           MVT::Other, getRoot(),
9810                           getValue(I.getArgOperand(0)),
9811                           DAG.getSrcValue(I.getArgOperand(0))));
9812 }
9813 
9814 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
9815   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
9816                           MVT::Other, getRoot(),
9817                           getValue(I.getArgOperand(0)),
9818                           getValue(I.getArgOperand(1)),
9819                           DAG.getSrcValue(I.getArgOperand(0)),
9820                           DAG.getSrcValue(I.getArgOperand(1))));
9821 }
9822 
9823 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
9824                                                     const Instruction &I,
9825                                                     SDValue Op) {
9826   const MDNode *Range = getRangeMetadata(I);
9827   if (!Range)
9828     return Op;
9829 
9830   ConstantRange CR = getConstantRangeFromMetadata(*Range);
9831   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
9832     return Op;
9833 
9834   APInt Lo = CR.getUnsignedMin();
9835   if (!Lo.isMinValue())
9836     return Op;
9837 
9838   APInt Hi = CR.getUnsignedMax();
9839   unsigned Bits = std::max(Hi.getActiveBits(),
9840                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
9841 
9842   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9843 
9844   SDLoc SL = getCurSDLoc();
9845 
9846   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
9847                              DAG.getValueType(SmallVT));
9848   unsigned NumVals = Op.getNode()->getNumValues();
9849   if (NumVals == 1)
9850     return ZExt;
9851 
9852   SmallVector<SDValue, 4> Ops;
9853 
9854   Ops.push_back(ZExt);
9855   for (unsigned I = 1; I != NumVals; ++I)
9856     Ops.push_back(Op.getValue(I));
9857 
9858   return DAG.getMergeValues(Ops, SL);
9859 }
9860 
9861 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
9862 /// the call being lowered.
9863 ///
9864 /// This is a helper for lowering intrinsics that follow a target calling
9865 /// convention or require stack pointer adjustment. Only a subset of the
9866 /// intrinsic's operands need to participate in the calling convention.
9867 void SelectionDAGBuilder::populateCallLoweringInfo(
9868     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
9869     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
9870     AttributeSet RetAttrs, bool IsPatchPoint) {
9871   TargetLowering::ArgListTy Args;
9872   Args.reserve(NumArgs);
9873 
9874   // Populate the argument list.
9875   // Attributes for args start at offset 1, after the return attribute.
9876   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
9877        ArgI != ArgE; ++ArgI) {
9878     const Value *V = Call->getOperand(ArgI);
9879 
9880     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
9881 
9882     TargetLowering::ArgListEntry Entry;
9883     Entry.Node = getValue(V);
9884     Entry.Ty = V->getType();
9885     Entry.setAttributes(Call, ArgI);
9886     Args.push_back(Entry);
9887   }
9888 
9889   CLI.setDebugLoc(getCurSDLoc())
9890       .setChain(getRoot())
9891       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args),
9892                  RetAttrs)
9893       .setDiscardResult(Call->use_empty())
9894       .setIsPatchPoint(IsPatchPoint)
9895       .setIsPreallocated(
9896           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
9897 }
9898 
9899 /// Add a stack map intrinsic call's live variable operands to a stackmap
9900 /// or patchpoint target node's operand list.
9901 ///
9902 /// Constants are converted to TargetConstants purely as an optimization to
9903 /// avoid constant materialization and register allocation.
9904 ///
9905 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
9906 /// generate addess computation nodes, and so FinalizeISel can convert the
9907 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
9908 /// address materialization and register allocation, but may also be required
9909 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
9910 /// alloca in the entry block, then the runtime may assume that the alloca's
9911 /// StackMap location can be read immediately after compilation and that the
9912 /// location is valid at any point during execution (this is similar to the
9913 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
9914 /// only available in a register, then the runtime would need to trap when
9915 /// execution reaches the StackMap in order to read the alloca's location.
9916 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
9917                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
9918                                 SelectionDAGBuilder &Builder) {
9919   SelectionDAG &DAG = Builder.DAG;
9920   for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
9921     SDValue Op = Builder.getValue(Call.getArgOperand(I));
9922 
9923     // Things on the stack are pointer-typed, meaning that they are already
9924     // legal and can be emitted directly to target nodes.
9925     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
9926       Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
9927     } else {
9928       // Otherwise emit a target independent node to be legalised.
9929       Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
9930     }
9931   }
9932 }
9933 
9934 /// Lower llvm.experimental.stackmap.
9935 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
9936   // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
9937   //                                  [live variables...])
9938 
9939   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
9940 
9941   SDValue Chain, InGlue, Callee;
9942   SmallVector<SDValue, 32> Ops;
9943 
9944   SDLoc DL = getCurSDLoc();
9945   Callee = getValue(CI.getCalledOperand());
9946 
9947   // The stackmap intrinsic only records the live variables (the arguments
9948   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
9949   // intrinsic, this won't be lowered to a function call. This means we don't
9950   // have to worry about calling conventions and target specific lowering code.
9951   // Instead we perform the call lowering right here.
9952   //
9953   // chain, flag = CALLSEQ_START(chain, 0, 0)
9954   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
9955   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
9956   //
9957   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
9958   InGlue = Chain.getValue(1);
9959 
9960   // Add the STACKMAP operands, starting with DAG house-keeping.
9961   Ops.push_back(Chain);
9962   Ops.push_back(InGlue);
9963 
9964   // Add the <id>, <numShadowBytes> operands.
9965   //
9966   // These do not require legalisation, and can be emitted directly to target
9967   // constant nodes.
9968   SDValue ID = getValue(CI.getArgOperand(0));
9969   assert(ID.getValueType() == MVT::i64);
9970   SDValue IDConst = DAG.getTargetConstant(
9971       cast<ConstantSDNode>(ID)->getZExtValue(), DL, ID.getValueType());
9972   Ops.push_back(IDConst);
9973 
9974   SDValue Shad = getValue(CI.getArgOperand(1));
9975   assert(Shad.getValueType() == MVT::i32);
9976   SDValue ShadConst = DAG.getTargetConstant(
9977       cast<ConstantSDNode>(Shad)->getZExtValue(), DL, Shad.getValueType());
9978   Ops.push_back(ShadConst);
9979 
9980   // Add the live variables.
9981   addStackMapLiveVars(CI, 2, DL, Ops, *this);
9982 
9983   // Create the STACKMAP node.
9984   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9985   Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
9986   InGlue = Chain.getValue(1);
9987 
9988   Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL);
9989 
9990   // Stackmaps don't generate values, so nothing goes into the NodeMap.
9991 
9992   // Set the root to the target-lowered call chain.
9993   DAG.setRoot(Chain);
9994 
9995   // Inform the Frame Information that we have a stackmap in this function.
9996   FuncInfo.MF->getFrameInfo().setHasStackMap();
9997 }
9998 
9999 /// Lower llvm.experimental.patchpoint directly to its target opcode.
10000 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
10001                                           const BasicBlock *EHPadBB) {
10002   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
10003   //                                                 i32 <numBytes>,
10004   //                                                 i8* <target>,
10005   //                                                 i32 <numArgs>,
10006   //                                                 [Args...],
10007   //                                                 [live variables...])
10008 
10009   CallingConv::ID CC = CB.getCallingConv();
10010   bool IsAnyRegCC = CC == CallingConv::AnyReg;
10011   bool HasDef = !CB.getType()->isVoidTy();
10012   SDLoc dl = getCurSDLoc();
10013   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
10014 
10015   // Handle immediate and symbolic callees.
10016   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
10017     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
10018                                    /*isTarget=*/true);
10019   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
10020     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
10021                                          SDLoc(SymbolicCallee),
10022                                          SymbolicCallee->getValueType(0));
10023 
10024   // Get the real number of arguments participating in the call <numArgs>
10025   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
10026   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
10027 
10028   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
10029   // Intrinsics include all meta-operands up to but not including CC.
10030   unsigned NumMetaOpers = PatchPointOpers::CCPos;
10031   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
10032          "Not enough arguments provided to the patchpoint intrinsic");
10033 
10034   // For AnyRegCC the arguments are lowered later on manually.
10035   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
10036   Type *ReturnTy =
10037       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
10038 
10039   TargetLowering::CallLoweringInfo CLI(DAG);
10040   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
10041                            ReturnTy, CB.getAttributes().getRetAttrs(), true);
10042   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
10043 
10044   SDNode *CallEnd = Result.second.getNode();
10045   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
10046     CallEnd = CallEnd->getOperand(0).getNode();
10047 
10048   /// Get a call instruction from the call sequence chain.
10049   /// Tail calls are not allowed.
10050   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
10051          "Expected a callseq node.");
10052   SDNode *Call = CallEnd->getOperand(0).getNode();
10053   bool HasGlue = Call->getGluedNode();
10054 
10055   // Replace the target specific call node with the patchable intrinsic.
10056   SmallVector<SDValue, 8> Ops;
10057 
10058   // Push the chain.
10059   Ops.push_back(*(Call->op_begin()));
10060 
10061   // Optionally, push the glue (if any).
10062   if (HasGlue)
10063     Ops.push_back(*(Call->op_end() - 1));
10064 
10065   // Push the register mask info.
10066   if (HasGlue)
10067     Ops.push_back(*(Call->op_end() - 2));
10068   else
10069     Ops.push_back(*(Call->op_end() - 1));
10070 
10071   // Add the <id> and <numBytes> constants.
10072   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
10073   Ops.push_back(DAG.getTargetConstant(
10074                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
10075   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
10076   Ops.push_back(DAG.getTargetConstant(
10077                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
10078                   MVT::i32));
10079 
10080   // Add the callee.
10081   Ops.push_back(Callee);
10082 
10083   // Adjust <numArgs> to account for any arguments that have been passed on the
10084   // stack instead.
10085   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
10086   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
10087   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
10088   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
10089 
10090   // Add the calling convention
10091   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
10092 
10093   // Add the arguments we omitted previously. The register allocator should
10094   // place these in any free register.
10095   if (IsAnyRegCC)
10096     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
10097       Ops.push_back(getValue(CB.getArgOperand(i)));
10098 
10099   // Push the arguments from the call instruction.
10100   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
10101   Ops.append(Call->op_begin() + 2, e);
10102 
10103   // Push live variables for the stack map.
10104   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
10105 
10106   SDVTList NodeTys;
10107   if (IsAnyRegCC && HasDef) {
10108     // Create the return types based on the intrinsic definition
10109     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10110     SmallVector<EVT, 3> ValueVTs;
10111     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
10112     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
10113 
10114     // There is always a chain and a glue type at the end
10115     ValueVTs.push_back(MVT::Other);
10116     ValueVTs.push_back(MVT::Glue);
10117     NodeTys = DAG.getVTList(ValueVTs);
10118   } else
10119     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10120 
10121   // Replace the target specific call node with a PATCHPOINT node.
10122   SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
10123 
10124   // Update the NodeMap.
10125   if (HasDef) {
10126     if (IsAnyRegCC)
10127       setValue(&CB, SDValue(PPV.getNode(), 0));
10128     else
10129       setValue(&CB, Result.first);
10130   }
10131 
10132   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
10133   // call sequence. Furthermore the location of the chain and glue can change
10134   // when the AnyReg calling convention is used and the intrinsic returns a
10135   // value.
10136   if (IsAnyRegCC && HasDef) {
10137     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
10138     SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
10139     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10140   } else
10141     DAG.ReplaceAllUsesWith(Call, PPV.getNode());
10142   DAG.DeleteNode(Call);
10143 
10144   // Inform the Frame Information that we have a patchpoint in this function.
10145   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
10146 }
10147 
10148 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
10149                                             unsigned Intrinsic) {
10150   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10151   SDValue Op1 = getValue(I.getArgOperand(0));
10152   SDValue Op2;
10153   if (I.arg_size() > 1)
10154     Op2 = getValue(I.getArgOperand(1));
10155   SDLoc dl = getCurSDLoc();
10156   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
10157   SDValue Res;
10158   SDNodeFlags SDFlags;
10159   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
10160     SDFlags.copyFMF(*FPMO);
10161 
10162   switch (Intrinsic) {
10163   case Intrinsic::vector_reduce_fadd:
10164     if (SDFlags.hasAllowReassociation())
10165       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
10166                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
10167                         SDFlags);
10168     else
10169       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
10170     break;
10171   case Intrinsic::vector_reduce_fmul:
10172     if (SDFlags.hasAllowReassociation())
10173       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
10174                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
10175                         SDFlags);
10176     else
10177       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
10178     break;
10179   case Intrinsic::vector_reduce_add:
10180     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
10181     break;
10182   case Intrinsic::vector_reduce_mul:
10183     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
10184     break;
10185   case Intrinsic::vector_reduce_and:
10186     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
10187     break;
10188   case Intrinsic::vector_reduce_or:
10189     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
10190     break;
10191   case Intrinsic::vector_reduce_xor:
10192     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
10193     break;
10194   case Intrinsic::vector_reduce_smax:
10195     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
10196     break;
10197   case Intrinsic::vector_reduce_smin:
10198     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
10199     break;
10200   case Intrinsic::vector_reduce_umax:
10201     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
10202     break;
10203   case Intrinsic::vector_reduce_umin:
10204     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
10205     break;
10206   case Intrinsic::vector_reduce_fmax:
10207     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
10208     break;
10209   case Intrinsic::vector_reduce_fmin:
10210     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
10211     break;
10212   case Intrinsic::vector_reduce_fmaximum:
10213     Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags);
10214     break;
10215   case Intrinsic::vector_reduce_fminimum:
10216     Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags);
10217     break;
10218   default:
10219     llvm_unreachable("Unhandled vector reduce intrinsic");
10220   }
10221   setValue(&I, Res);
10222 }
10223 
10224 /// Returns an AttributeList representing the attributes applied to the return
10225 /// value of the given call.
10226 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
10227   SmallVector<Attribute::AttrKind, 2> Attrs;
10228   if (CLI.RetSExt)
10229     Attrs.push_back(Attribute::SExt);
10230   if (CLI.RetZExt)
10231     Attrs.push_back(Attribute::ZExt);
10232   if (CLI.IsInReg)
10233     Attrs.push_back(Attribute::InReg);
10234 
10235   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
10236                             Attrs);
10237 }
10238 
10239 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
10240 /// implementation, which just calls LowerCall.
10241 /// FIXME: When all targets are
10242 /// migrated to using LowerCall, this hook should be integrated into SDISel.
10243 std::pair<SDValue, SDValue>
10244 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
10245   // Handle the incoming return values from the call.
10246   CLI.Ins.clear();
10247   Type *OrigRetTy = CLI.RetTy;
10248   SmallVector<EVT, 4> RetTys;
10249   SmallVector<uint64_t, 4> Offsets;
10250   auto &DL = CLI.DAG.getDataLayout();
10251   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets, 0);
10252 
10253   if (CLI.IsPostTypeLegalization) {
10254     // If we are lowering a libcall after legalization, split the return type.
10255     SmallVector<EVT, 4> OldRetTys;
10256     SmallVector<uint64_t, 4> OldOffsets;
10257     RetTys.swap(OldRetTys);
10258     Offsets.swap(OldOffsets);
10259 
10260     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
10261       EVT RetVT = OldRetTys[i];
10262       uint64_t Offset = OldOffsets[i];
10263       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
10264       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
10265       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
10266       RetTys.append(NumRegs, RegisterVT);
10267       for (unsigned j = 0; j != NumRegs; ++j)
10268         Offsets.push_back(Offset + j * RegisterVTByteSZ);
10269     }
10270   }
10271 
10272   SmallVector<ISD::OutputArg, 4> Outs;
10273   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
10274 
10275   bool CanLowerReturn =
10276       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
10277                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
10278 
10279   SDValue DemoteStackSlot;
10280   int DemoteStackIdx = -100;
10281   if (!CanLowerReturn) {
10282     // FIXME: equivalent assert?
10283     // assert(!CS.hasInAllocaArgument() &&
10284     //        "sret demotion is incompatible with inalloca");
10285     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
10286     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
10287     MachineFunction &MF = CLI.DAG.getMachineFunction();
10288     DemoteStackIdx =
10289         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
10290     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
10291                                               DL.getAllocaAddrSpace());
10292 
10293     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
10294     ArgListEntry Entry;
10295     Entry.Node = DemoteStackSlot;
10296     Entry.Ty = StackSlotPtrType;
10297     Entry.IsSExt = false;
10298     Entry.IsZExt = false;
10299     Entry.IsInReg = false;
10300     Entry.IsSRet = true;
10301     Entry.IsNest = false;
10302     Entry.IsByVal = false;
10303     Entry.IsByRef = false;
10304     Entry.IsReturned = false;
10305     Entry.IsSwiftSelf = false;
10306     Entry.IsSwiftAsync = false;
10307     Entry.IsSwiftError = false;
10308     Entry.IsCFGuardTarget = false;
10309     Entry.Alignment = Alignment;
10310     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
10311     CLI.NumFixedArgs += 1;
10312     CLI.getArgs()[0].IndirectType = CLI.RetTy;
10313     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
10314 
10315     // sret demotion isn't compatible with tail-calls, since the sret argument
10316     // points into the callers stack frame.
10317     CLI.IsTailCall = false;
10318   } else {
10319     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10320         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
10321     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
10322       ISD::ArgFlagsTy Flags;
10323       if (NeedsRegBlock) {
10324         Flags.setInConsecutiveRegs();
10325         if (I == RetTys.size() - 1)
10326           Flags.setInConsecutiveRegsLast();
10327       }
10328       EVT VT = RetTys[I];
10329       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10330                                                      CLI.CallConv, VT);
10331       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10332                                                        CLI.CallConv, VT);
10333       for (unsigned i = 0; i != NumRegs; ++i) {
10334         ISD::InputArg MyFlags;
10335         MyFlags.Flags = Flags;
10336         MyFlags.VT = RegisterVT;
10337         MyFlags.ArgVT = VT;
10338         MyFlags.Used = CLI.IsReturnValueUsed;
10339         if (CLI.RetTy->isPointerTy()) {
10340           MyFlags.Flags.setPointer();
10341           MyFlags.Flags.setPointerAddrSpace(
10342               cast<PointerType>(CLI.RetTy)->getAddressSpace());
10343         }
10344         if (CLI.RetSExt)
10345           MyFlags.Flags.setSExt();
10346         if (CLI.RetZExt)
10347           MyFlags.Flags.setZExt();
10348         if (CLI.IsInReg)
10349           MyFlags.Flags.setInReg();
10350         CLI.Ins.push_back(MyFlags);
10351       }
10352     }
10353   }
10354 
10355   // We push in swifterror return as the last element of CLI.Ins.
10356   ArgListTy &Args = CLI.getArgs();
10357   if (supportSwiftError()) {
10358     for (const ArgListEntry &Arg : Args) {
10359       if (Arg.IsSwiftError) {
10360         ISD::InputArg MyFlags;
10361         MyFlags.VT = getPointerTy(DL);
10362         MyFlags.ArgVT = EVT(getPointerTy(DL));
10363         MyFlags.Flags.setSwiftError();
10364         CLI.Ins.push_back(MyFlags);
10365       }
10366     }
10367   }
10368 
10369   // Handle all of the outgoing arguments.
10370   CLI.Outs.clear();
10371   CLI.OutVals.clear();
10372   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
10373     SmallVector<EVT, 4> ValueVTs;
10374     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
10375     // FIXME: Split arguments if CLI.IsPostTypeLegalization
10376     Type *FinalType = Args[i].Ty;
10377     if (Args[i].IsByVal)
10378       FinalType = Args[i].IndirectType;
10379     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10380         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
10381     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
10382          ++Value) {
10383       EVT VT = ValueVTs[Value];
10384       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
10385       SDValue Op = SDValue(Args[i].Node.getNode(),
10386                            Args[i].Node.getResNo() + Value);
10387       ISD::ArgFlagsTy Flags;
10388 
10389       // Certain targets (such as MIPS), may have a different ABI alignment
10390       // for a type depending on the context. Give the target a chance to
10391       // specify the alignment it wants.
10392       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
10393       Flags.setOrigAlign(OriginalAlignment);
10394 
10395       if (Args[i].Ty->isPointerTy()) {
10396         Flags.setPointer();
10397         Flags.setPointerAddrSpace(
10398             cast<PointerType>(Args[i].Ty)->getAddressSpace());
10399       }
10400       if (Args[i].IsZExt)
10401         Flags.setZExt();
10402       if (Args[i].IsSExt)
10403         Flags.setSExt();
10404       if (Args[i].IsInReg) {
10405         // If we are using vectorcall calling convention, a structure that is
10406         // passed InReg - is surely an HVA
10407         if (CLI.CallConv == CallingConv::X86_VectorCall &&
10408             isa<StructType>(FinalType)) {
10409           // The first value of a structure is marked
10410           if (0 == Value)
10411             Flags.setHvaStart();
10412           Flags.setHva();
10413         }
10414         // Set InReg Flag
10415         Flags.setInReg();
10416       }
10417       if (Args[i].IsSRet)
10418         Flags.setSRet();
10419       if (Args[i].IsSwiftSelf)
10420         Flags.setSwiftSelf();
10421       if (Args[i].IsSwiftAsync)
10422         Flags.setSwiftAsync();
10423       if (Args[i].IsSwiftError)
10424         Flags.setSwiftError();
10425       if (Args[i].IsCFGuardTarget)
10426         Flags.setCFGuardTarget();
10427       if (Args[i].IsByVal)
10428         Flags.setByVal();
10429       if (Args[i].IsByRef)
10430         Flags.setByRef();
10431       if (Args[i].IsPreallocated) {
10432         Flags.setPreallocated();
10433         // Set the byval flag for CCAssignFn callbacks that don't know about
10434         // preallocated.  This way we can know how many bytes we should've
10435         // allocated and how many bytes a callee cleanup function will pop.  If
10436         // we port preallocated to more targets, we'll have to add custom
10437         // preallocated handling in the various CC lowering callbacks.
10438         Flags.setByVal();
10439       }
10440       if (Args[i].IsInAlloca) {
10441         Flags.setInAlloca();
10442         // Set the byval flag for CCAssignFn callbacks that don't know about
10443         // inalloca.  This way we can know how many bytes we should've allocated
10444         // and how many bytes a callee cleanup function will pop.  If we port
10445         // inalloca to more targets, we'll have to add custom inalloca handling
10446         // in the various CC lowering callbacks.
10447         Flags.setByVal();
10448       }
10449       Align MemAlign;
10450       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
10451         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
10452         Flags.setByValSize(FrameSize);
10453 
10454         // info is not there but there are cases it cannot get right.
10455         if (auto MA = Args[i].Alignment)
10456           MemAlign = *MA;
10457         else
10458           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
10459       } else if (auto MA = Args[i].Alignment) {
10460         MemAlign = *MA;
10461       } else {
10462         MemAlign = OriginalAlignment;
10463       }
10464       Flags.setMemAlign(MemAlign);
10465       if (Args[i].IsNest)
10466         Flags.setNest();
10467       if (NeedsRegBlock)
10468         Flags.setInConsecutiveRegs();
10469 
10470       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10471                                                  CLI.CallConv, VT);
10472       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10473                                                         CLI.CallConv, VT);
10474       SmallVector<SDValue, 4> Parts(NumParts);
10475       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
10476 
10477       if (Args[i].IsSExt)
10478         ExtendKind = ISD::SIGN_EXTEND;
10479       else if (Args[i].IsZExt)
10480         ExtendKind = ISD::ZERO_EXTEND;
10481 
10482       // Conservatively only handle 'returned' on non-vectors that can be lowered,
10483       // for now.
10484       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
10485           CanLowerReturn) {
10486         assert((CLI.RetTy == Args[i].Ty ||
10487                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
10488                  CLI.RetTy->getPointerAddressSpace() ==
10489                      Args[i].Ty->getPointerAddressSpace())) &&
10490                RetTys.size() == NumValues && "unexpected use of 'returned'");
10491         // Before passing 'returned' to the target lowering code, ensure that
10492         // either the register MVT and the actual EVT are the same size or that
10493         // the return value and argument are extended in the same way; in these
10494         // cases it's safe to pass the argument register value unchanged as the
10495         // return register value (although it's at the target's option whether
10496         // to do so)
10497         // TODO: allow code generation to take advantage of partially preserved
10498         // registers rather than clobbering the entire register when the
10499         // parameter extension method is not compatible with the return
10500         // extension method
10501         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
10502             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
10503              CLI.RetZExt == Args[i].IsZExt))
10504           Flags.setReturned();
10505       }
10506 
10507       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
10508                      CLI.CallConv, ExtendKind);
10509 
10510       for (unsigned j = 0; j != NumParts; ++j) {
10511         // if it isn't first piece, alignment must be 1
10512         // For scalable vectors the scalable part is currently handled
10513         // by individual targets, so we just use the known minimum size here.
10514         ISD::OutputArg MyFlags(
10515             Flags, Parts[j].getValueType().getSimpleVT(), VT,
10516             i < CLI.NumFixedArgs, i,
10517             j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
10518         if (NumParts > 1 && j == 0)
10519           MyFlags.Flags.setSplit();
10520         else if (j != 0) {
10521           MyFlags.Flags.setOrigAlign(Align(1));
10522           if (j == NumParts - 1)
10523             MyFlags.Flags.setSplitEnd();
10524         }
10525 
10526         CLI.Outs.push_back(MyFlags);
10527         CLI.OutVals.push_back(Parts[j]);
10528       }
10529 
10530       if (NeedsRegBlock && Value == NumValues - 1)
10531         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
10532     }
10533   }
10534 
10535   SmallVector<SDValue, 4> InVals;
10536   CLI.Chain = LowerCall(CLI, InVals);
10537 
10538   // Update CLI.InVals to use outside of this function.
10539   CLI.InVals = InVals;
10540 
10541   // Verify that the target's LowerCall behaved as expected.
10542   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
10543          "LowerCall didn't return a valid chain!");
10544   assert((!CLI.IsTailCall || InVals.empty()) &&
10545          "LowerCall emitted a return value for a tail call!");
10546   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
10547          "LowerCall didn't emit the correct number of values!");
10548 
10549   // For a tail call, the return value is merely live-out and there aren't
10550   // any nodes in the DAG representing it. Return a special value to
10551   // indicate that a tail call has been emitted and no more Instructions
10552   // should be processed in the current block.
10553   if (CLI.IsTailCall) {
10554     CLI.DAG.setRoot(CLI.Chain);
10555     return std::make_pair(SDValue(), SDValue());
10556   }
10557 
10558 #ifndef NDEBUG
10559   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
10560     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
10561     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
10562            "LowerCall emitted a value with the wrong type!");
10563   }
10564 #endif
10565 
10566   SmallVector<SDValue, 4> ReturnValues;
10567   if (!CanLowerReturn) {
10568     // The instruction result is the result of loading from the
10569     // hidden sret parameter.
10570     SmallVector<EVT, 1> PVTs;
10571     Type *PtrRetTy =
10572         PointerType::get(OrigRetTy->getContext(), DL.getAllocaAddrSpace());
10573 
10574     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
10575     assert(PVTs.size() == 1 && "Pointers should fit in one register");
10576     EVT PtrVT = PVTs[0];
10577 
10578     unsigned NumValues = RetTys.size();
10579     ReturnValues.resize(NumValues);
10580     SmallVector<SDValue, 4> Chains(NumValues);
10581 
10582     // An aggregate return value cannot wrap around the address space, so
10583     // offsets to its parts don't wrap either.
10584     SDNodeFlags Flags;
10585     Flags.setNoUnsignedWrap(true);
10586 
10587     MachineFunction &MF = CLI.DAG.getMachineFunction();
10588     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
10589     for (unsigned i = 0; i < NumValues; ++i) {
10590       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
10591                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
10592                                                         PtrVT), Flags);
10593       SDValue L = CLI.DAG.getLoad(
10594           RetTys[i], CLI.DL, CLI.Chain, Add,
10595           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
10596                                             DemoteStackIdx, Offsets[i]),
10597           HiddenSRetAlign);
10598       ReturnValues[i] = L;
10599       Chains[i] = L.getValue(1);
10600     }
10601 
10602     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
10603   } else {
10604     // Collect the legal value parts into potentially illegal values
10605     // that correspond to the original function's return values.
10606     std::optional<ISD::NodeType> AssertOp;
10607     if (CLI.RetSExt)
10608       AssertOp = ISD::AssertSext;
10609     else if (CLI.RetZExt)
10610       AssertOp = ISD::AssertZext;
10611     unsigned CurReg = 0;
10612     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
10613       EVT VT = RetTys[I];
10614       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10615                                                      CLI.CallConv, VT);
10616       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10617                                                        CLI.CallConv, VT);
10618 
10619       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
10620                                               NumRegs, RegisterVT, VT, nullptr,
10621                                               CLI.CallConv, AssertOp));
10622       CurReg += NumRegs;
10623     }
10624 
10625     // For a function returning void, there is no return value. We can't create
10626     // such a node, so we just return a null return value in that case. In
10627     // that case, nothing will actually look at the value.
10628     if (ReturnValues.empty())
10629       return std::make_pair(SDValue(), CLI.Chain);
10630   }
10631 
10632   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
10633                                 CLI.DAG.getVTList(RetTys), ReturnValues);
10634   return std::make_pair(Res, CLI.Chain);
10635 }
10636 
10637 /// Places new result values for the node in Results (their number
10638 /// and types must exactly match those of the original return values of
10639 /// the node), or leaves Results empty, which indicates that the node is not
10640 /// to be custom lowered after all.
10641 void TargetLowering::LowerOperationWrapper(SDNode *N,
10642                                            SmallVectorImpl<SDValue> &Results,
10643                                            SelectionDAG &DAG) const {
10644   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
10645 
10646   if (!Res.getNode())
10647     return;
10648 
10649   // If the original node has one result, take the return value from
10650   // LowerOperation as is. It might not be result number 0.
10651   if (N->getNumValues() == 1) {
10652     Results.push_back(Res);
10653     return;
10654   }
10655 
10656   // If the original node has multiple results, then the return node should
10657   // have the same number of results.
10658   assert((N->getNumValues() == Res->getNumValues()) &&
10659       "Lowering returned the wrong number of results!");
10660 
10661   // Places new result values base on N result number.
10662   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
10663     Results.push_back(Res.getValue(I));
10664 }
10665 
10666 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10667   llvm_unreachable("LowerOperation not implemented for this target!");
10668 }
10669 
10670 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
10671                                                      unsigned Reg,
10672                                                      ISD::NodeType ExtendType) {
10673   SDValue Op = getNonRegisterValue(V);
10674   assert((Op.getOpcode() != ISD::CopyFromReg ||
10675           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
10676          "Copy from a reg to the same reg!");
10677   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
10678 
10679   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10680   // If this is an InlineAsm we have to match the registers required, not the
10681   // notional registers required by the type.
10682 
10683   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
10684                    std::nullopt); // This is not an ABI copy.
10685   SDValue Chain = DAG.getEntryNode();
10686 
10687   if (ExtendType == ISD::ANY_EXTEND) {
10688     auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
10689     if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
10690       ExtendType = PreferredExtendIt->second;
10691   }
10692   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
10693   PendingExports.push_back(Chain);
10694 }
10695 
10696 #include "llvm/CodeGen/SelectionDAGISel.h"
10697 
10698 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
10699 /// entry block, return true.  This includes arguments used by switches, since
10700 /// the switch may expand into multiple basic blocks.
10701 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
10702   // With FastISel active, we may be splitting blocks, so force creation
10703   // of virtual registers for all non-dead arguments.
10704   if (FastISel)
10705     return A->use_empty();
10706 
10707   const BasicBlock &Entry = A->getParent()->front();
10708   for (const User *U : A->users())
10709     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
10710       return false;  // Use not in entry block.
10711 
10712   return true;
10713 }
10714 
10715 using ArgCopyElisionMapTy =
10716     DenseMap<const Argument *,
10717              std::pair<const AllocaInst *, const StoreInst *>>;
10718 
10719 /// Scan the entry block of the function in FuncInfo for arguments that look
10720 /// like copies into a local alloca. Record any copied arguments in
10721 /// ArgCopyElisionCandidates.
10722 static void
10723 findArgumentCopyElisionCandidates(const DataLayout &DL,
10724                                   FunctionLoweringInfo *FuncInfo,
10725                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
10726   // Record the state of every static alloca used in the entry block. Argument
10727   // allocas are all used in the entry block, so we need approximately as many
10728   // entries as we have arguments.
10729   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
10730   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
10731   unsigned NumArgs = FuncInfo->Fn->arg_size();
10732   StaticAllocas.reserve(NumArgs * 2);
10733 
10734   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
10735     if (!V)
10736       return nullptr;
10737     V = V->stripPointerCasts();
10738     const auto *AI = dyn_cast<AllocaInst>(V);
10739     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
10740       return nullptr;
10741     auto Iter = StaticAllocas.insert({AI, Unknown});
10742     return &Iter.first->second;
10743   };
10744 
10745   // Look for stores of arguments to static allocas. Look through bitcasts and
10746   // GEPs to handle type coercions, as long as the alloca is fully initialized
10747   // by the store. Any non-store use of an alloca escapes it and any subsequent
10748   // unanalyzed store might write it.
10749   // FIXME: Handle structs initialized with multiple stores.
10750   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
10751     // Look for stores, and handle non-store uses conservatively.
10752     const auto *SI = dyn_cast<StoreInst>(&I);
10753     if (!SI) {
10754       // We will look through cast uses, so ignore them completely.
10755       if (I.isCast())
10756         continue;
10757       // Ignore debug info and pseudo op intrinsics, they don't escape or store
10758       // to allocas.
10759       if (I.isDebugOrPseudoInst())
10760         continue;
10761       // This is an unknown instruction. Assume it escapes or writes to all
10762       // static alloca operands.
10763       for (const Use &U : I.operands()) {
10764         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
10765           *Info = StaticAllocaInfo::Clobbered;
10766       }
10767       continue;
10768     }
10769 
10770     // If the stored value is a static alloca, mark it as escaped.
10771     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
10772       *Info = StaticAllocaInfo::Clobbered;
10773 
10774     // Check if the destination is a static alloca.
10775     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
10776     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
10777     if (!Info)
10778       continue;
10779     const AllocaInst *AI = cast<AllocaInst>(Dst);
10780 
10781     // Skip allocas that have been initialized or clobbered.
10782     if (*Info != StaticAllocaInfo::Unknown)
10783       continue;
10784 
10785     // Check if the stored value is an argument, and that this store fully
10786     // initializes the alloca.
10787     // If the argument type has padding bits we can't directly forward a pointer
10788     // as the upper bits may contain garbage.
10789     // Don't elide copies from the same argument twice.
10790     const Value *Val = SI->getValueOperand()->stripPointerCasts();
10791     const auto *Arg = dyn_cast<Argument>(Val);
10792     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
10793         Arg->getType()->isEmptyTy() ||
10794         DL.getTypeStoreSize(Arg->getType()) !=
10795             DL.getTypeAllocSize(AI->getAllocatedType()) ||
10796         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
10797         ArgCopyElisionCandidates.count(Arg)) {
10798       *Info = StaticAllocaInfo::Clobbered;
10799       continue;
10800     }
10801 
10802     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
10803                       << '\n');
10804 
10805     // Mark this alloca and store for argument copy elision.
10806     *Info = StaticAllocaInfo::Elidable;
10807     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
10808 
10809     // Stop scanning if we've seen all arguments. This will happen early in -O0
10810     // builds, which is useful, because -O0 builds have large entry blocks and
10811     // many allocas.
10812     if (ArgCopyElisionCandidates.size() == NumArgs)
10813       break;
10814   }
10815 }
10816 
10817 /// Try to elide argument copies from memory into a local alloca. Succeeds if
10818 /// ArgVal is a load from a suitable fixed stack object.
10819 static void tryToElideArgumentCopy(
10820     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
10821     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
10822     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
10823     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
10824     ArrayRef<SDValue> ArgVals, bool &ArgHasUses) {
10825   // Check if this is a load from a fixed stack object.
10826   auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]);
10827   if (!LNode)
10828     return;
10829   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
10830   if (!FINode)
10831     return;
10832 
10833   // Check that the fixed stack object is the right size and alignment.
10834   // Look at the alignment that the user wrote on the alloca instead of looking
10835   // at the stack object.
10836   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
10837   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
10838   const AllocaInst *AI = ArgCopyIter->second.first;
10839   int FixedIndex = FINode->getIndex();
10840   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
10841   int OldIndex = AllocaIndex;
10842   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
10843   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
10844     LLVM_DEBUG(
10845         dbgs() << "  argument copy elision failed due to bad fixed stack "
10846                   "object size\n");
10847     return;
10848   }
10849   Align RequiredAlignment = AI->getAlign();
10850   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
10851     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
10852                          "greater than stack argument alignment ("
10853                       << DebugStr(RequiredAlignment) << " vs "
10854                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
10855     return;
10856   }
10857 
10858   // Perform the elision. Delete the old stack object and replace its only use
10859   // in the variable info map. Mark the stack object as mutable.
10860   LLVM_DEBUG({
10861     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
10862            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
10863            << '\n';
10864   });
10865   MFI.RemoveStackObject(OldIndex);
10866   MFI.setIsImmutableObjectIndex(FixedIndex, false);
10867   AllocaIndex = FixedIndex;
10868   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
10869   for (SDValue ArgVal : ArgVals)
10870     Chains.push_back(ArgVal.getValue(1));
10871 
10872   // Avoid emitting code for the store implementing the copy.
10873   const StoreInst *SI = ArgCopyIter->second.second;
10874   ElidedArgCopyInstrs.insert(SI);
10875 
10876   // Check for uses of the argument again so that we can avoid exporting ArgVal
10877   // if it is't used by anything other than the store.
10878   for (const Value *U : Arg.users()) {
10879     if (U != SI) {
10880       ArgHasUses = true;
10881       break;
10882     }
10883   }
10884 }
10885 
10886 void SelectionDAGISel::LowerArguments(const Function &F) {
10887   SelectionDAG &DAG = SDB->DAG;
10888   SDLoc dl = SDB->getCurSDLoc();
10889   const DataLayout &DL = DAG.getDataLayout();
10890   SmallVector<ISD::InputArg, 16> Ins;
10891 
10892   // In Naked functions we aren't going to save any registers.
10893   if (F.hasFnAttribute(Attribute::Naked))
10894     return;
10895 
10896   if (!FuncInfo->CanLowerReturn) {
10897     // Put in an sret pointer parameter before all the other parameters.
10898     SmallVector<EVT, 1> ValueVTs;
10899     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10900                     PointerType::get(F.getContext(),
10901                                      DAG.getDataLayout().getAllocaAddrSpace()),
10902                     ValueVTs);
10903 
10904     // NOTE: Assuming that a pointer will never break down to more than one VT
10905     // or one register.
10906     ISD::ArgFlagsTy Flags;
10907     Flags.setSRet();
10908     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
10909     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
10910                          ISD::InputArg::NoArgIndex, 0);
10911     Ins.push_back(RetArg);
10912   }
10913 
10914   // Look for stores of arguments to static allocas. Mark such arguments with a
10915   // flag to ask the target to give us the memory location of that argument if
10916   // available.
10917   ArgCopyElisionMapTy ArgCopyElisionCandidates;
10918   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
10919                                     ArgCopyElisionCandidates);
10920 
10921   // Set up the incoming argument description vector.
10922   for (const Argument &Arg : F.args()) {
10923     unsigned ArgNo = Arg.getArgNo();
10924     SmallVector<EVT, 4> ValueVTs;
10925     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10926     bool isArgValueUsed = !Arg.use_empty();
10927     unsigned PartBase = 0;
10928     Type *FinalType = Arg.getType();
10929     if (Arg.hasAttribute(Attribute::ByVal))
10930       FinalType = Arg.getParamByValType();
10931     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
10932         FinalType, F.getCallingConv(), F.isVarArg(), DL);
10933     for (unsigned Value = 0, NumValues = ValueVTs.size();
10934          Value != NumValues; ++Value) {
10935       EVT VT = ValueVTs[Value];
10936       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
10937       ISD::ArgFlagsTy Flags;
10938 
10939 
10940       if (Arg.getType()->isPointerTy()) {
10941         Flags.setPointer();
10942         Flags.setPointerAddrSpace(
10943             cast<PointerType>(Arg.getType())->getAddressSpace());
10944       }
10945       if (Arg.hasAttribute(Attribute::ZExt))
10946         Flags.setZExt();
10947       if (Arg.hasAttribute(Attribute::SExt))
10948         Flags.setSExt();
10949       if (Arg.hasAttribute(Attribute::InReg)) {
10950         // If we are using vectorcall calling convention, a structure that is
10951         // passed InReg - is surely an HVA
10952         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
10953             isa<StructType>(Arg.getType())) {
10954           // The first value of a structure is marked
10955           if (0 == Value)
10956             Flags.setHvaStart();
10957           Flags.setHva();
10958         }
10959         // Set InReg Flag
10960         Flags.setInReg();
10961       }
10962       if (Arg.hasAttribute(Attribute::StructRet))
10963         Flags.setSRet();
10964       if (Arg.hasAttribute(Attribute::SwiftSelf))
10965         Flags.setSwiftSelf();
10966       if (Arg.hasAttribute(Attribute::SwiftAsync))
10967         Flags.setSwiftAsync();
10968       if (Arg.hasAttribute(Attribute::SwiftError))
10969         Flags.setSwiftError();
10970       if (Arg.hasAttribute(Attribute::ByVal))
10971         Flags.setByVal();
10972       if (Arg.hasAttribute(Attribute::ByRef))
10973         Flags.setByRef();
10974       if (Arg.hasAttribute(Attribute::InAlloca)) {
10975         Flags.setInAlloca();
10976         // Set the byval flag for CCAssignFn callbacks that don't know about
10977         // inalloca.  This way we can know how many bytes we should've allocated
10978         // and how many bytes a callee cleanup function will pop.  If we port
10979         // inalloca to more targets, we'll have to add custom inalloca handling
10980         // in the various CC lowering callbacks.
10981         Flags.setByVal();
10982       }
10983       if (Arg.hasAttribute(Attribute::Preallocated)) {
10984         Flags.setPreallocated();
10985         // Set the byval flag for CCAssignFn callbacks that don't know about
10986         // preallocated.  This way we can know how many bytes we should've
10987         // allocated and how many bytes a callee cleanup function will pop.  If
10988         // we port preallocated to more targets, we'll have to add custom
10989         // preallocated handling in the various CC lowering callbacks.
10990         Flags.setByVal();
10991       }
10992 
10993       // Certain targets (such as MIPS), may have a different ABI alignment
10994       // for a type depending on the context. Give the target a chance to
10995       // specify the alignment it wants.
10996       const Align OriginalAlignment(
10997           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
10998       Flags.setOrigAlign(OriginalAlignment);
10999 
11000       Align MemAlign;
11001       Type *ArgMemTy = nullptr;
11002       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
11003           Flags.isByRef()) {
11004         if (!ArgMemTy)
11005           ArgMemTy = Arg.getPointeeInMemoryValueType();
11006 
11007         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
11008 
11009         // For in-memory arguments, size and alignment should be passed from FE.
11010         // BE will guess if this info is not there but there are cases it cannot
11011         // get right.
11012         if (auto ParamAlign = Arg.getParamStackAlign())
11013           MemAlign = *ParamAlign;
11014         else if ((ParamAlign = Arg.getParamAlign()))
11015           MemAlign = *ParamAlign;
11016         else
11017           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
11018         if (Flags.isByRef())
11019           Flags.setByRefSize(MemSize);
11020         else
11021           Flags.setByValSize(MemSize);
11022       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
11023         MemAlign = *ParamAlign;
11024       } else {
11025         MemAlign = OriginalAlignment;
11026       }
11027       Flags.setMemAlign(MemAlign);
11028 
11029       if (Arg.hasAttribute(Attribute::Nest))
11030         Flags.setNest();
11031       if (NeedsRegBlock)
11032         Flags.setInConsecutiveRegs();
11033       if (ArgCopyElisionCandidates.count(&Arg))
11034         Flags.setCopyElisionCandidate();
11035       if (Arg.hasAttribute(Attribute::Returned))
11036         Flags.setReturned();
11037 
11038       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
11039           *CurDAG->getContext(), F.getCallingConv(), VT);
11040       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
11041           *CurDAG->getContext(), F.getCallingConv(), VT);
11042       for (unsigned i = 0; i != NumRegs; ++i) {
11043         // For scalable vectors, use the minimum size; individual targets
11044         // are responsible for handling scalable vector arguments and
11045         // return values.
11046         ISD::InputArg MyFlags(
11047             Flags, RegisterVT, VT, isArgValueUsed, ArgNo,
11048             PartBase + i * RegisterVT.getStoreSize().getKnownMinValue());
11049         if (NumRegs > 1 && i == 0)
11050           MyFlags.Flags.setSplit();
11051         // if it isn't first piece, alignment must be 1
11052         else if (i > 0) {
11053           MyFlags.Flags.setOrigAlign(Align(1));
11054           if (i == NumRegs - 1)
11055             MyFlags.Flags.setSplitEnd();
11056         }
11057         Ins.push_back(MyFlags);
11058       }
11059       if (NeedsRegBlock && Value == NumValues - 1)
11060         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
11061       PartBase += VT.getStoreSize().getKnownMinValue();
11062     }
11063   }
11064 
11065   // Call the target to set up the argument values.
11066   SmallVector<SDValue, 8> InVals;
11067   SDValue NewRoot = TLI->LowerFormalArguments(
11068       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
11069 
11070   // Verify that the target's LowerFormalArguments behaved as expected.
11071   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
11072          "LowerFormalArguments didn't return a valid chain!");
11073   assert(InVals.size() == Ins.size() &&
11074          "LowerFormalArguments didn't emit the correct number of values!");
11075   LLVM_DEBUG({
11076     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
11077       assert(InVals[i].getNode() &&
11078              "LowerFormalArguments emitted a null value!");
11079       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
11080              "LowerFormalArguments emitted a value with the wrong type!");
11081     }
11082   });
11083 
11084   // Update the DAG with the new chain value resulting from argument lowering.
11085   DAG.setRoot(NewRoot);
11086 
11087   // Set up the argument values.
11088   unsigned i = 0;
11089   if (!FuncInfo->CanLowerReturn) {
11090     // Create a virtual register for the sret pointer, and put in a copy
11091     // from the sret argument into it.
11092     SmallVector<EVT, 1> ValueVTs;
11093     ComputeValueVTs(*TLI, DAG.getDataLayout(),
11094                     PointerType::get(F.getContext(),
11095                                      DAG.getDataLayout().getAllocaAddrSpace()),
11096                     ValueVTs);
11097     MVT VT = ValueVTs[0].getSimpleVT();
11098     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
11099     std::optional<ISD::NodeType> AssertOp;
11100     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
11101                                         nullptr, F.getCallingConv(), AssertOp);
11102 
11103     MachineFunction& MF = SDB->DAG.getMachineFunction();
11104     MachineRegisterInfo& RegInfo = MF.getRegInfo();
11105     Register SRetReg =
11106         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
11107     FuncInfo->DemoteRegister = SRetReg;
11108     NewRoot =
11109         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
11110     DAG.setRoot(NewRoot);
11111 
11112     // i indexes lowered arguments.  Bump it past the hidden sret argument.
11113     ++i;
11114   }
11115 
11116   SmallVector<SDValue, 4> Chains;
11117   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
11118   for (const Argument &Arg : F.args()) {
11119     SmallVector<SDValue, 4> ArgValues;
11120     SmallVector<EVT, 4> ValueVTs;
11121     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
11122     unsigned NumValues = ValueVTs.size();
11123     if (NumValues == 0)
11124       continue;
11125 
11126     bool ArgHasUses = !Arg.use_empty();
11127 
11128     // Elide the copying store if the target loaded this argument from a
11129     // suitable fixed stack object.
11130     if (Ins[i].Flags.isCopyElisionCandidate()) {
11131       unsigned NumParts = 0;
11132       for (EVT VT : ValueVTs)
11133         NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(),
11134                                                        F.getCallingConv(), VT);
11135 
11136       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
11137                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
11138                              ArrayRef(&InVals[i], NumParts), ArgHasUses);
11139     }
11140 
11141     // If this argument is unused then remember its value. It is used to generate
11142     // debugging information.
11143     bool isSwiftErrorArg =
11144         TLI->supportSwiftError() &&
11145         Arg.hasAttribute(Attribute::SwiftError);
11146     if (!ArgHasUses && !isSwiftErrorArg) {
11147       SDB->setUnusedArgValue(&Arg, InVals[i]);
11148 
11149       // Also remember any frame index for use in FastISel.
11150       if (FrameIndexSDNode *FI =
11151           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
11152         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11153     }
11154 
11155     for (unsigned Val = 0; Val != NumValues; ++Val) {
11156       EVT VT = ValueVTs[Val];
11157       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
11158                                                       F.getCallingConv(), VT);
11159       unsigned NumParts = TLI->getNumRegistersForCallingConv(
11160           *CurDAG->getContext(), F.getCallingConv(), VT);
11161 
11162       // Even an apparent 'unused' swifterror argument needs to be returned. So
11163       // we do generate a copy for it that can be used on return from the
11164       // function.
11165       if (ArgHasUses || isSwiftErrorArg) {
11166         std::optional<ISD::NodeType> AssertOp;
11167         if (Arg.hasAttribute(Attribute::SExt))
11168           AssertOp = ISD::AssertSext;
11169         else if (Arg.hasAttribute(Attribute::ZExt))
11170           AssertOp = ISD::AssertZext;
11171 
11172         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
11173                                              PartVT, VT, nullptr,
11174                                              F.getCallingConv(), AssertOp));
11175       }
11176 
11177       i += NumParts;
11178     }
11179 
11180     // We don't need to do anything else for unused arguments.
11181     if (ArgValues.empty())
11182       continue;
11183 
11184     // Note down frame index.
11185     if (FrameIndexSDNode *FI =
11186         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
11187       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11188 
11189     SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues),
11190                                      SDB->getCurSDLoc());
11191 
11192     SDB->setValue(&Arg, Res);
11193     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
11194       // We want to associate the argument with the frame index, among
11195       // involved operands, that correspond to the lowest address. The
11196       // getCopyFromParts function, called earlier, is swapping the order of
11197       // the operands to BUILD_PAIR depending on endianness. The result of
11198       // that swapping is that the least significant bits of the argument will
11199       // be in the first operand of the BUILD_PAIR node, and the most
11200       // significant bits will be in the second operand.
11201       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
11202       if (LoadSDNode *LNode =
11203           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
11204         if (FrameIndexSDNode *FI =
11205             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
11206           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11207     }
11208 
11209     // Analyses past this point are naive and don't expect an assertion.
11210     if (Res.getOpcode() == ISD::AssertZext)
11211       Res = Res.getOperand(0);
11212 
11213     // Update the SwiftErrorVRegDefMap.
11214     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
11215       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11216       if (Register::isVirtualRegister(Reg))
11217         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
11218                                    Reg);
11219     }
11220 
11221     // If this argument is live outside of the entry block, insert a copy from
11222     // wherever we got it to the vreg that other BB's will reference it as.
11223     if (Res.getOpcode() == ISD::CopyFromReg) {
11224       // If we can, though, try to skip creating an unnecessary vreg.
11225       // FIXME: This isn't very clean... it would be nice to make this more
11226       // general.
11227       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11228       if (Register::isVirtualRegister(Reg)) {
11229         FuncInfo->ValueMap[&Arg] = Reg;
11230         continue;
11231       }
11232     }
11233     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
11234       FuncInfo->InitializeRegForValue(&Arg);
11235       SDB->CopyToExportRegsIfNeeded(&Arg);
11236     }
11237   }
11238 
11239   if (!Chains.empty()) {
11240     Chains.push_back(NewRoot);
11241     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
11242   }
11243 
11244   DAG.setRoot(NewRoot);
11245 
11246   assert(i == InVals.size() && "Argument register count mismatch!");
11247 
11248   // If any argument copy elisions occurred and we have debug info, update the
11249   // stale frame indices used in the dbg.declare variable info table.
11250   if (!ArgCopyElisionFrameIndexMap.empty()) {
11251     for (MachineFunction::VariableDbgInfo &VI :
11252          MF->getInStackSlotVariableDbgInfo()) {
11253       auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot());
11254       if (I != ArgCopyElisionFrameIndexMap.end())
11255         VI.updateStackSlot(I->second);
11256     }
11257   }
11258 
11259   // Finally, if the target has anything special to do, allow it to do so.
11260   emitFunctionEntryCode();
11261 }
11262 
11263 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
11264 /// ensure constants are generated when needed.  Remember the virtual registers
11265 /// that need to be added to the Machine PHI nodes as input.  We cannot just
11266 /// directly add them, because expansion might result in multiple MBB's for one
11267 /// BB.  As such, the start of the BB might correspond to a different MBB than
11268 /// the end.
11269 void
11270 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
11271   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11272 
11273   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
11274 
11275   // Check PHI nodes in successors that expect a value to be available from this
11276   // block.
11277   for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
11278     if (!isa<PHINode>(SuccBB->begin())) continue;
11279     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
11280 
11281     // If this terminator has multiple identical successors (common for
11282     // switches), only handle each succ once.
11283     if (!SuccsHandled.insert(SuccMBB).second)
11284       continue;
11285 
11286     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
11287 
11288     // At this point we know that there is a 1-1 correspondence between LLVM PHI
11289     // nodes and Machine PHI nodes, but the incoming operands have not been
11290     // emitted yet.
11291     for (const PHINode &PN : SuccBB->phis()) {
11292       // Ignore dead phi's.
11293       if (PN.use_empty())
11294         continue;
11295 
11296       // Skip empty types
11297       if (PN.getType()->isEmptyTy())
11298         continue;
11299 
11300       unsigned Reg;
11301       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
11302 
11303       if (const auto *C = dyn_cast<Constant>(PHIOp)) {
11304         unsigned &RegOut = ConstantsOut[C];
11305         if (RegOut == 0) {
11306           RegOut = FuncInfo.CreateRegs(C);
11307           // We need to zero/sign extend ConstantInt phi operands to match
11308           // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
11309           ISD::NodeType ExtendType = ISD::ANY_EXTEND;
11310           if (auto *CI = dyn_cast<ConstantInt>(C))
11311             ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
11312                                                     : ISD::ZERO_EXTEND;
11313           CopyValueToVirtualRegister(C, RegOut, ExtendType);
11314         }
11315         Reg = RegOut;
11316       } else {
11317         DenseMap<const Value *, Register>::iterator I =
11318           FuncInfo.ValueMap.find(PHIOp);
11319         if (I != FuncInfo.ValueMap.end())
11320           Reg = I->second;
11321         else {
11322           assert(isa<AllocaInst>(PHIOp) &&
11323                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
11324                  "Didn't codegen value into a register!??");
11325           Reg = FuncInfo.CreateRegs(PHIOp);
11326           CopyValueToVirtualRegister(PHIOp, Reg);
11327         }
11328       }
11329 
11330       // Remember that this register needs to added to the machine PHI node as
11331       // the input for this MBB.
11332       SmallVector<EVT, 4> ValueVTs;
11333       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
11334       for (EVT VT : ValueVTs) {
11335         const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
11336         for (unsigned i = 0; i != NumRegisters; ++i)
11337           FuncInfo.PHINodesToUpdate.push_back(
11338               std::make_pair(&*MBBI++, Reg + i));
11339         Reg += NumRegisters;
11340       }
11341     }
11342   }
11343 
11344   ConstantsOut.clear();
11345 }
11346 
11347 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
11348   MachineFunction::iterator I(MBB);
11349   if (++I == FuncInfo.MF->end())
11350     return nullptr;
11351   return &*I;
11352 }
11353 
11354 /// During lowering new call nodes can be created (such as memset, etc.).
11355 /// Those will become new roots of the current DAG, but complications arise
11356 /// when they are tail calls. In such cases, the call lowering will update
11357 /// the root, but the builder still needs to know that a tail call has been
11358 /// lowered in order to avoid generating an additional return.
11359 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
11360   // If the node is null, we do have a tail call.
11361   if (MaybeTC.getNode() != nullptr)
11362     DAG.setRoot(MaybeTC);
11363   else
11364     HasTailCall = true;
11365 }
11366 
11367 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
11368                                         MachineBasicBlock *SwitchMBB,
11369                                         MachineBasicBlock *DefaultMBB) {
11370   MachineFunction *CurMF = FuncInfo.MF;
11371   MachineBasicBlock *NextMBB = nullptr;
11372   MachineFunction::iterator BBI(W.MBB);
11373   if (++BBI != FuncInfo.MF->end())
11374     NextMBB = &*BBI;
11375 
11376   unsigned Size = W.LastCluster - W.FirstCluster + 1;
11377 
11378   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11379 
11380   if (Size == 2 && W.MBB == SwitchMBB) {
11381     // If any two of the cases has the same destination, and if one value
11382     // is the same as the other, but has one bit unset that the other has set,
11383     // use bit manipulation to do two compares at once.  For example:
11384     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
11385     // TODO: This could be extended to merge any 2 cases in switches with 3
11386     // cases.
11387     // TODO: Handle cases where W.CaseBB != SwitchBB.
11388     CaseCluster &Small = *W.FirstCluster;
11389     CaseCluster &Big = *W.LastCluster;
11390 
11391     if (Small.Low == Small.High && Big.Low == Big.High &&
11392         Small.MBB == Big.MBB) {
11393       const APInt &SmallValue = Small.Low->getValue();
11394       const APInt &BigValue = Big.Low->getValue();
11395 
11396       // Check that there is only one bit different.
11397       APInt CommonBit = BigValue ^ SmallValue;
11398       if (CommonBit.isPowerOf2()) {
11399         SDValue CondLHS = getValue(Cond);
11400         EVT VT = CondLHS.getValueType();
11401         SDLoc DL = getCurSDLoc();
11402 
11403         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
11404                                  DAG.getConstant(CommonBit, DL, VT));
11405         SDValue Cond = DAG.getSetCC(
11406             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
11407             ISD::SETEQ);
11408 
11409         // Update successor info.
11410         // Both Small and Big will jump to Small.BB, so we sum up the
11411         // probabilities.
11412         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
11413         if (BPI)
11414           addSuccessorWithProb(
11415               SwitchMBB, DefaultMBB,
11416               // The default destination is the first successor in IR.
11417               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
11418         else
11419           addSuccessorWithProb(SwitchMBB, DefaultMBB);
11420 
11421         // Insert the true branch.
11422         SDValue BrCond =
11423             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
11424                         DAG.getBasicBlock(Small.MBB));
11425         // Insert the false branch.
11426         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
11427                              DAG.getBasicBlock(DefaultMBB));
11428 
11429         DAG.setRoot(BrCond);
11430         return;
11431       }
11432     }
11433   }
11434 
11435   if (TM.getOptLevel() != CodeGenOptLevel::None) {
11436     // Here, we order cases by probability so the most likely case will be
11437     // checked first. However, two clusters can have the same probability in
11438     // which case their relative ordering is non-deterministic. So we use Low
11439     // as a tie-breaker as clusters are guaranteed to never overlap.
11440     llvm::sort(W.FirstCluster, W.LastCluster + 1,
11441                [](const CaseCluster &a, const CaseCluster &b) {
11442       return a.Prob != b.Prob ?
11443              a.Prob > b.Prob :
11444              a.Low->getValue().slt(b.Low->getValue());
11445     });
11446 
11447     // Rearrange the case blocks so that the last one falls through if possible
11448     // without changing the order of probabilities.
11449     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
11450       --I;
11451       if (I->Prob > W.LastCluster->Prob)
11452         break;
11453       if (I->Kind == CC_Range && I->MBB == NextMBB) {
11454         std::swap(*I, *W.LastCluster);
11455         break;
11456       }
11457     }
11458   }
11459 
11460   // Compute total probability.
11461   BranchProbability DefaultProb = W.DefaultProb;
11462   BranchProbability UnhandledProbs = DefaultProb;
11463   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
11464     UnhandledProbs += I->Prob;
11465 
11466   MachineBasicBlock *CurMBB = W.MBB;
11467   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
11468     bool FallthroughUnreachable = false;
11469     MachineBasicBlock *Fallthrough;
11470     if (I == W.LastCluster) {
11471       // For the last cluster, fall through to the default destination.
11472       Fallthrough = DefaultMBB;
11473       FallthroughUnreachable = isa<UnreachableInst>(
11474           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
11475     } else {
11476       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
11477       CurMF->insert(BBI, Fallthrough);
11478       // Put Cond in a virtual register to make it available from the new blocks.
11479       ExportFromCurrentBlock(Cond);
11480     }
11481     UnhandledProbs -= I->Prob;
11482 
11483     switch (I->Kind) {
11484       case CC_JumpTable: {
11485         // FIXME: Optimize away range check based on pivot comparisons.
11486         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
11487         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
11488 
11489         // The jump block hasn't been inserted yet; insert it here.
11490         MachineBasicBlock *JumpMBB = JT->MBB;
11491         CurMF->insert(BBI, JumpMBB);
11492 
11493         auto JumpProb = I->Prob;
11494         auto FallthroughProb = UnhandledProbs;
11495 
11496         // If the default statement is a target of the jump table, we evenly
11497         // distribute the default probability to successors of CurMBB. Also
11498         // update the probability on the edge from JumpMBB to Fallthrough.
11499         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
11500                                               SE = JumpMBB->succ_end();
11501              SI != SE; ++SI) {
11502           if (*SI == DefaultMBB) {
11503             JumpProb += DefaultProb / 2;
11504             FallthroughProb -= DefaultProb / 2;
11505             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
11506             JumpMBB->normalizeSuccProbs();
11507             break;
11508           }
11509         }
11510 
11511         // If the default clause is unreachable, propagate that knowledge into
11512         // JTH->FallthroughUnreachable which will use it to suppress the range
11513         // check.
11514         //
11515         // However, don't do this if we're doing branch target enforcement,
11516         // because a table branch _without_ a range check can be a tempting JOP
11517         // gadget - out-of-bounds inputs that are impossible in correct
11518         // execution become possible again if an attacker can influence the
11519         // control flow. So if an attacker doesn't already have a BTI bypass
11520         // available, we don't want them to be able to get one out of this
11521         // table branch.
11522         if (FallthroughUnreachable) {
11523           Function &CurFunc = CurMF->getFunction();
11524           bool HasBranchTargetEnforcement = false;
11525           if (CurFunc.hasFnAttribute("branch-target-enforcement")) {
11526             HasBranchTargetEnforcement =
11527                 CurFunc.getFnAttribute("branch-target-enforcement")
11528                     .getValueAsBool();
11529           } else {
11530             HasBranchTargetEnforcement =
11531                 CurMF->getMMI().getModule()->getModuleFlag(
11532                     "branch-target-enforcement");
11533           }
11534           if (!HasBranchTargetEnforcement)
11535             JTH->FallthroughUnreachable = true;
11536         }
11537 
11538         if (!JTH->FallthroughUnreachable)
11539           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
11540         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
11541         CurMBB->normalizeSuccProbs();
11542 
11543         // The jump table header will be inserted in our current block, do the
11544         // range check, and fall through to our fallthrough block.
11545         JTH->HeaderBB = CurMBB;
11546         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
11547 
11548         // If we're in the right place, emit the jump table header right now.
11549         if (CurMBB == SwitchMBB) {
11550           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
11551           JTH->Emitted = true;
11552         }
11553         break;
11554       }
11555       case CC_BitTests: {
11556         // FIXME: Optimize away range check based on pivot comparisons.
11557         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
11558 
11559         // The bit test blocks haven't been inserted yet; insert them here.
11560         for (BitTestCase &BTC : BTB->Cases)
11561           CurMF->insert(BBI, BTC.ThisBB);
11562 
11563         // Fill in fields of the BitTestBlock.
11564         BTB->Parent = CurMBB;
11565         BTB->Default = Fallthrough;
11566 
11567         BTB->DefaultProb = UnhandledProbs;
11568         // If the cases in bit test don't form a contiguous range, we evenly
11569         // distribute the probability on the edge to Fallthrough to two
11570         // successors of CurMBB.
11571         if (!BTB->ContiguousRange) {
11572           BTB->Prob += DefaultProb / 2;
11573           BTB->DefaultProb -= DefaultProb / 2;
11574         }
11575 
11576         if (FallthroughUnreachable)
11577           BTB->FallthroughUnreachable = true;
11578 
11579         // If we're in the right place, emit the bit test header right now.
11580         if (CurMBB == SwitchMBB) {
11581           visitBitTestHeader(*BTB, SwitchMBB);
11582           BTB->Emitted = true;
11583         }
11584         break;
11585       }
11586       case CC_Range: {
11587         const Value *RHS, *LHS, *MHS;
11588         ISD::CondCode CC;
11589         if (I->Low == I->High) {
11590           // Check Cond == I->Low.
11591           CC = ISD::SETEQ;
11592           LHS = Cond;
11593           RHS=I->Low;
11594           MHS = nullptr;
11595         } else {
11596           // Check I->Low <= Cond <= I->High.
11597           CC = ISD::SETLE;
11598           LHS = I->Low;
11599           MHS = Cond;
11600           RHS = I->High;
11601         }
11602 
11603         // If Fallthrough is unreachable, fold away the comparison.
11604         if (FallthroughUnreachable)
11605           CC = ISD::SETTRUE;
11606 
11607         // The false probability is the sum of all unhandled cases.
11608         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
11609                      getCurSDLoc(), I->Prob, UnhandledProbs);
11610 
11611         if (CurMBB == SwitchMBB)
11612           visitSwitchCase(CB, SwitchMBB);
11613         else
11614           SL->SwitchCases.push_back(CB);
11615 
11616         break;
11617       }
11618     }
11619     CurMBB = Fallthrough;
11620   }
11621 }
11622 
11623 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
11624                                               CaseClusterIt First,
11625                                               CaseClusterIt Last) {
11626   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
11627     if (X.Prob != CC.Prob)
11628       return X.Prob > CC.Prob;
11629 
11630     // Ties are broken by comparing the case value.
11631     return X.Low->getValue().slt(CC.Low->getValue());
11632   });
11633 }
11634 
11635 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
11636                                         const SwitchWorkListItem &W,
11637                                         Value *Cond,
11638                                         MachineBasicBlock *SwitchMBB) {
11639   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
11640          "Clusters not sorted?");
11641 
11642   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
11643 
11644   // Balance the tree based on branch probabilities to create a near-optimal (in
11645   // terms of search time given key frequency) binary search tree. See e.g. Kurt
11646   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
11647   CaseClusterIt LastLeft = W.FirstCluster;
11648   CaseClusterIt FirstRight = W.LastCluster;
11649   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
11650   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
11651 
11652   // Move LastLeft and FirstRight towards each other from opposite directions to
11653   // find a partitioning of the clusters which balances the probability on both
11654   // sides. If LeftProb and RightProb are equal, alternate which side is
11655   // taken to ensure 0-probability nodes are distributed evenly.
11656   unsigned I = 0;
11657   while (LastLeft + 1 < FirstRight) {
11658     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
11659       LeftProb += (++LastLeft)->Prob;
11660     else
11661       RightProb += (--FirstRight)->Prob;
11662     I++;
11663   }
11664 
11665   while (true) {
11666     // Our binary search tree differs from a typical BST in that ours can have up
11667     // to three values in each leaf. The pivot selection above doesn't take that
11668     // into account, which means the tree might require more nodes and be less
11669     // efficient. We compensate for this here.
11670 
11671     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
11672     unsigned NumRight = W.LastCluster - FirstRight + 1;
11673 
11674     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
11675       // If one side has less than 3 clusters, and the other has more than 3,
11676       // consider taking a cluster from the other side.
11677 
11678       if (NumLeft < NumRight) {
11679         // Consider moving the first cluster on the right to the left side.
11680         CaseCluster &CC = *FirstRight;
11681         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
11682         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
11683         if (LeftSideRank <= RightSideRank) {
11684           // Moving the cluster to the left does not demote it.
11685           ++LastLeft;
11686           ++FirstRight;
11687           continue;
11688         }
11689       } else {
11690         assert(NumRight < NumLeft);
11691         // Consider moving the last element on the left to the right side.
11692         CaseCluster &CC = *LastLeft;
11693         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
11694         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
11695         if (RightSideRank <= LeftSideRank) {
11696           // Moving the cluster to the right does not demot it.
11697           --LastLeft;
11698           --FirstRight;
11699           continue;
11700         }
11701       }
11702     }
11703     break;
11704   }
11705 
11706   assert(LastLeft + 1 == FirstRight);
11707   assert(LastLeft >= W.FirstCluster);
11708   assert(FirstRight <= W.LastCluster);
11709 
11710   // Use the first element on the right as pivot since we will make less-than
11711   // comparisons against it.
11712   CaseClusterIt PivotCluster = FirstRight;
11713   assert(PivotCluster > W.FirstCluster);
11714   assert(PivotCluster <= W.LastCluster);
11715 
11716   CaseClusterIt FirstLeft = W.FirstCluster;
11717   CaseClusterIt LastRight = W.LastCluster;
11718 
11719   const ConstantInt *Pivot = PivotCluster->Low;
11720 
11721   // New blocks will be inserted immediately after the current one.
11722   MachineFunction::iterator BBI(W.MBB);
11723   ++BBI;
11724 
11725   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
11726   // we can branch to its destination directly if it's squeezed exactly in
11727   // between the known lower bound and Pivot - 1.
11728   MachineBasicBlock *LeftMBB;
11729   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
11730       FirstLeft->Low == W.GE &&
11731       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
11732     LeftMBB = FirstLeft->MBB;
11733   } else {
11734     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11735     FuncInfo.MF->insert(BBI, LeftMBB);
11736     WorkList.push_back(
11737         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
11738     // Put Cond in a virtual register to make it available from the new blocks.
11739     ExportFromCurrentBlock(Cond);
11740   }
11741 
11742   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
11743   // single cluster, RHS.Low == Pivot, and we can branch to its destination
11744   // directly if RHS.High equals the current upper bound.
11745   MachineBasicBlock *RightMBB;
11746   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
11747       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
11748     RightMBB = FirstRight->MBB;
11749   } else {
11750     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11751     FuncInfo.MF->insert(BBI, RightMBB);
11752     WorkList.push_back(
11753         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
11754     // Put Cond in a virtual register to make it available from the new blocks.
11755     ExportFromCurrentBlock(Cond);
11756   }
11757 
11758   // Create the CaseBlock record that will be used to lower the branch.
11759   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
11760                getCurSDLoc(), LeftProb, RightProb);
11761 
11762   if (W.MBB == SwitchMBB)
11763     visitSwitchCase(CB, SwitchMBB);
11764   else
11765     SL->SwitchCases.push_back(CB);
11766 }
11767 
11768 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
11769 // from the swith statement.
11770 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
11771                                             BranchProbability PeeledCaseProb) {
11772   if (PeeledCaseProb == BranchProbability::getOne())
11773     return BranchProbability::getZero();
11774   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
11775 
11776   uint32_t Numerator = CaseProb.getNumerator();
11777   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
11778   return BranchProbability(Numerator, std::max(Numerator, Denominator));
11779 }
11780 
11781 // Try to peel the top probability case if it exceeds the threshold.
11782 // Return current MachineBasicBlock for the switch statement if the peeling
11783 // does not occur.
11784 // If the peeling is performed, return the newly created MachineBasicBlock
11785 // for the peeled switch statement. Also update Clusters to remove the peeled
11786 // case. PeeledCaseProb is the BranchProbability for the peeled case.
11787 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
11788     const SwitchInst &SI, CaseClusterVector &Clusters,
11789     BranchProbability &PeeledCaseProb) {
11790   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11791   // Don't perform if there is only one cluster or optimizing for size.
11792   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
11793       TM.getOptLevel() == CodeGenOptLevel::None ||
11794       SwitchMBB->getParent()->getFunction().hasMinSize())
11795     return SwitchMBB;
11796 
11797   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
11798   unsigned PeeledCaseIndex = 0;
11799   bool SwitchPeeled = false;
11800   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
11801     CaseCluster &CC = Clusters[Index];
11802     if (CC.Prob < TopCaseProb)
11803       continue;
11804     TopCaseProb = CC.Prob;
11805     PeeledCaseIndex = Index;
11806     SwitchPeeled = true;
11807   }
11808   if (!SwitchPeeled)
11809     return SwitchMBB;
11810 
11811   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
11812                     << TopCaseProb << "\n");
11813 
11814   // Record the MBB for the peeled switch statement.
11815   MachineFunction::iterator BBI(SwitchMBB);
11816   ++BBI;
11817   MachineBasicBlock *PeeledSwitchMBB =
11818       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
11819   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
11820 
11821   ExportFromCurrentBlock(SI.getCondition());
11822   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
11823   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
11824                           nullptr,   nullptr,      TopCaseProb.getCompl()};
11825   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
11826 
11827   Clusters.erase(PeeledCaseIt);
11828   for (CaseCluster &CC : Clusters) {
11829     LLVM_DEBUG(
11830         dbgs() << "Scale the probablity for one cluster, before scaling: "
11831                << CC.Prob << "\n");
11832     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
11833     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
11834   }
11835   PeeledCaseProb = TopCaseProb;
11836   return PeeledSwitchMBB;
11837 }
11838 
11839 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
11840   // Extract cases from the switch.
11841   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11842   CaseClusterVector Clusters;
11843   Clusters.reserve(SI.getNumCases());
11844   for (auto I : SI.cases()) {
11845     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
11846     const ConstantInt *CaseVal = I.getCaseValue();
11847     BranchProbability Prob =
11848         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
11849             : BranchProbability(1, SI.getNumCases() + 1);
11850     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
11851   }
11852 
11853   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
11854 
11855   // Cluster adjacent cases with the same destination. We do this at all
11856   // optimization levels because it's cheap to do and will make codegen faster
11857   // if there are many clusters.
11858   sortAndRangeify(Clusters);
11859 
11860   // The branch probablity of the peeled case.
11861   BranchProbability PeeledCaseProb = BranchProbability::getZero();
11862   MachineBasicBlock *PeeledSwitchMBB =
11863       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
11864 
11865   // If there is only the default destination, jump there directly.
11866   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11867   if (Clusters.empty()) {
11868     assert(PeeledSwitchMBB == SwitchMBB);
11869     SwitchMBB->addSuccessor(DefaultMBB);
11870     if (DefaultMBB != NextBlock(SwitchMBB)) {
11871       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
11872                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
11873     }
11874     return;
11875   }
11876 
11877   SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(),
11878                      DAG.getBFI());
11879   SL->findBitTestClusters(Clusters, &SI);
11880 
11881   LLVM_DEBUG({
11882     dbgs() << "Case clusters: ";
11883     for (const CaseCluster &C : Clusters) {
11884       if (C.Kind == CC_JumpTable)
11885         dbgs() << "JT:";
11886       if (C.Kind == CC_BitTests)
11887         dbgs() << "BT:";
11888 
11889       C.Low->getValue().print(dbgs(), true);
11890       if (C.Low != C.High) {
11891         dbgs() << '-';
11892         C.High->getValue().print(dbgs(), true);
11893       }
11894       dbgs() << ' ';
11895     }
11896     dbgs() << '\n';
11897   });
11898 
11899   assert(!Clusters.empty());
11900   SwitchWorkList WorkList;
11901   CaseClusterIt First = Clusters.begin();
11902   CaseClusterIt Last = Clusters.end() - 1;
11903   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
11904   // Scale the branchprobability for DefaultMBB if the peel occurs and
11905   // DefaultMBB is not replaced.
11906   if (PeeledCaseProb != BranchProbability::getZero() &&
11907       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
11908     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
11909   WorkList.push_back(
11910       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
11911 
11912   while (!WorkList.empty()) {
11913     SwitchWorkListItem W = WorkList.pop_back_val();
11914     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
11915 
11916     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None &&
11917         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
11918       // For optimized builds, lower large range as a balanced binary tree.
11919       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
11920       continue;
11921     }
11922 
11923     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
11924   }
11925 }
11926 
11927 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
11928   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11929   auto DL = getCurSDLoc();
11930   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11931   setValue(&I, DAG.getStepVector(DL, ResultVT));
11932 }
11933 
11934 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
11935   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11936   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11937 
11938   SDLoc DL = getCurSDLoc();
11939   SDValue V = getValue(I.getOperand(0));
11940   assert(VT == V.getValueType() && "Malformed vector.reverse!");
11941 
11942   if (VT.isScalableVector()) {
11943     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
11944     return;
11945   }
11946 
11947   // Use VECTOR_SHUFFLE for the fixed-length vector
11948   // to maintain existing behavior.
11949   SmallVector<int, 8> Mask;
11950   unsigned NumElts = VT.getVectorMinNumElements();
11951   for (unsigned i = 0; i != NumElts; ++i)
11952     Mask.push_back(NumElts - 1 - i);
11953 
11954   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
11955 }
11956 
11957 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) {
11958   auto DL = getCurSDLoc();
11959   SDValue InVec = getValue(I.getOperand(0));
11960   EVT OutVT =
11961       InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
11962 
11963   unsigned OutNumElts = OutVT.getVectorMinNumElements();
11964 
11965   // ISD Node needs the input vectors split into two equal parts
11966   SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
11967                            DAG.getVectorIdxConstant(0, DL));
11968   SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
11969                            DAG.getVectorIdxConstant(OutNumElts, DL));
11970 
11971   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
11972   // legalisation and combines.
11973   if (OutVT.isFixedLengthVector()) {
11974     SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
11975                                         createStrideMask(0, 2, OutNumElts));
11976     SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
11977                                        createStrideMask(1, 2, OutNumElts));
11978     SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc());
11979     setValue(&I, Res);
11980     return;
11981   }
11982 
11983   SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL,
11984                             DAG.getVTList(OutVT, OutVT), Lo, Hi);
11985   setValue(&I, Res);
11986 }
11987 
11988 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) {
11989   auto DL = getCurSDLoc();
11990   EVT InVT = getValue(I.getOperand(0)).getValueType();
11991   SDValue InVec0 = getValue(I.getOperand(0));
11992   SDValue InVec1 = getValue(I.getOperand(1));
11993   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11994   EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11995 
11996   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
11997   // legalisation and combines.
11998   if (OutVT.isFixedLengthVector()) {
11999     unsigned NumElts = InVT.getVectorMinNumElements();
12000     SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1);
12001     setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT),
12002                                       createInterleaveMask(NumElts, 2)));
12003     return;
12004   }
12005 
12006   SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL,
12007                             DAG.getVTList(InVT, InVT), InVec0, InVec1);
12008   Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0),
12009                     Res.getValue(1));
12010   setValue(&I, Res);
12011 }
12012 
12013 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
12014   SmallVector<EVT, 4> ValueVTs;
12015   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
12016                   ValueVTs);
12017   unsigned NumValues = ValueVTs.size();
12018   if (NumValues == 0) return;
12019 
12020   SmallVector<SDValue, 4> Values(NumValues);
12021   SDValue Op = getValue(I.getOperand(0));
12022 
12023   for (unsigned i = 0; i != NumValues; ++i)
12024     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
12025                             SDValue(Op.getNode(), Op.getResNo() + i));
12026 
12027   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12028                            DAG.getVTList(ValueVTs), Values));
12029 }
12030 
12031 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
12032   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12033   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12034 
12035   SDLoc DL = getCurSDLoc();
12036   SDValue V1 = getValue(I.getOperand(0));
12037   SDValue V2 = getValue(I.getOperand(1));
12038   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
12039 
12040   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
12041   if (VT.isScalableVector()) {
12042     MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
12043     setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
12044                              DAG.getConstant(Imm, DL, IdxVT)));
12045     return;
12046   }
12047 
12048   unsigned NumElts = VT.getVectorNumElements();
12049 
12050   uint64_t Idx = (NumElts + Imm) % NumElts;
12051 
12052   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
12053   SmallVector<int, 8> Mask;
12054   for (unsigned i = 0; i < NumElts; ++i)
12055     Mask.push_back(Idx + i);
12056   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
12057 }
12058 
12059 // Consider the following MIR after SelectionDAG, which produces output in
12060 // phyregs in the first case or virtregs in the second case.
12061 //
12062 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx
12063 // %5:gr32 = COPY $ebx
12064 // %6:gr32 = COPY $edx
12065 // %1:gr32 = COPY %6:gr32
12066 // %0:gr32 = COPY %5:gr32
12067 //
12068 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32
12069 // %1:gr32 = COPY %6:gr32
12070 // %0:gr32 = COPY %5:gr32
12071 //
12072 // Given %0, we'd like to return $ebx in the first case and %5 in the second.
12073 // Given %1, we'd like to return $edx in the first case and %6 in the second.
12074 //
12075 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap
12076 // to a single virtreg (such as %0). The remaining outputs monotonically
12077 // increase in virtreg number from there. If a callbr has no outputs, then it
12078 // should not have a corresponding callbr landingpad; in fact, the callbr
12079 // landingpad would not even be able to refer to such a callbr.
12080 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) {
12081   MachineInstr *MI = MRI.def_begin(Reg)->getParent();
12082   // There is definitely at least one copy.
12083   assert(MI->getOpcode() == TargetOpcode::COPY &&
12084          "start of copy chain MUST be COPY");
12085   Reg = MI->getOperand(1).getReg();
12086   MI = MRI.def_begin(Reg)->getParent();
12087   // There may be an optional second copy.
12088   if (MI->getOpcode() == TargetOpcode::COPY) {
12089     assert(Reg.isVirtual() && "expected COPY of virtual register");
12090     Reg = MI->getOperand(1).getReg();
12091     assert(Reg.isPhysical() && "expected COPY of physical register");
12092     MI = MRI.def_begin(Reg)->getParent();
12093   }
12094   // The start of the chain must be an INLINEASM_BR.
12095   assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR &&
12096          "end of copy chain MUST be INLINEASM_BR");
12097   return Reg;
12098 }
12099 
12100 // We must do this walk rather than the simpler
12101 //   setValue(&I, getCopyFromRegs(CBR, CBR->getType()));
12102 // otherwise we will end up with copies of virtregs only valid along direct
12103 // edges.
12104 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) {
12105   SmallVector<EVT, 8> ResultVTs;
12106   SmallVector<SDValue, 8> ResultValues;
12107   const auto *CBR =
12108       cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator());
12109 
12110   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12111   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
12112   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
12113 
12114   unsigned InitialDef = FuncInfo.ValueMap[CBR];
12115   SDValue Chain = DAG.getRoot();
12116 
12117   // Re-parse the asm constraints string.
12118   TargetLowering::AsmOperandInfoVector TargetConstraints =
12119       TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR);
12120   for (auto &T : TargetConstraints) {
12121     SDISelAsmOperandInfo OpInfo(T);
12122     if (OpInfo.Type != InlineAsm::isOutput)
12123       continue;
12124 
12125     // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the
12126     // individual constraint.
12127     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
12128 
12129     switch (OpInfo.ConstraintType) {
12130     case TargetLowering::C_Register:
12131     case TargetLowering::C_RegisterClass: {
12132       // Fill in OpInfo.AssignedRegs.Regs.
12133       getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo);
12134 
12135       // getRegistersForValue may produce 1 to many registers based on whether
12136       // the OpInfo.ConstraintVT is legal on the target or not.
12137       for (size_t i = 0, e = OpInfo.AssignedRegs.Regs.size(); i != e; ++i) {
12138         Register OriginalDef = FollowCopyChain(MRI, InitialDef++);
12139         if (Register::isPhysicalRegister(OriginalDef))
12140           FuncInfo.MBB->addLiveIn(OriginalDef);
12141         // Update the assigned registers to use the original defs.
12142         OpInfo.AssignedRegs.Regs[i] = OriginalDef;
12143       }
12144 
12145       SDValue V = OpInfo.AssignedRegs.getCopyFromRegs(
12146           DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR);
12147       ResultValues.push_back(V);
12148       ResultVTs.push_back(OpInfo.ConstraintVT);
12149       break;
12150     }
12151     case TargetLowering::C_Other: {
12152       SDValue Flag;
12153       SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
12154                                                   OpInfo, DAG);
12155       ++InitialDef;
12156       ResultValues.push_back(V);
12157       ResultVTs.push_back(OpInfo.ConstraintVT);
12158       break;
12159     }
12160     default:
12161       break;
12162     }
12163   }
12164   SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12165                           DAG.getVTList(ResultVTs), ResultValues);
12166   setValue(&I, V);
12167 }
12168