xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 394bba766ddd2f5ea8ac8007dcadb724f79bafc4)
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::visit(const Instruction &I) {
1152   // Set up outgoing PHI node register values before emitting the terminator.
1153   if (I.isTerminator()) {
1154     HandlePHINodesInSuccessorBlocks(I.getParent());
1155   }
1156 
1157   // Add SDDbgValue nodes for any var locs here. Do so before updating
1158   // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1159   if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) {
1160     // Add SDDbgValue nodes for any var locs here. Do so before updating
1161     // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1162     for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I);
1163          It != End; ++It) {
1164       auto *Var = FnVarLocs->getDILocalVariable(It->VariableID);
1165       dropDanglingDebugInfo(Var, It->Expr);
1166       if (It->Values.isKillLocation(It->Expr)) {
1167         handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder);
1168         continue;
1169       }
1170       SmallVector<Value *> Values(It->Values.location_ops());
1171       if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder,
1172                             It->Values.hasArgList()))
1173         addDanglingDebugInfo(It, SDNodeOrder);
1174     }
1175   }
1176 
1177   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1178   if (!isa<DbgInfoIntrinsic>(I))
1179     ++SDNodeOrder;
1180 
1181   CurInst = &I;
1182 
1183   // Set inserted listener only if required.
1184   bool NodeInserted = false;
1185   std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener;
1186   MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections);
1187   if (PCSectionsMD) {
1188     InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>(
1189         DAG, [&](SDNode *) { NodeInserted = true; });
1190   }
1191 
1192   visit(I.getOpcode(), I);
1193 
1194   if (!I.isTerminator() && !HasTailCall &&
1195       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1196     CopyToExportRegsIfNeeded(&I);
1197 
1198   // Handle metadata.
1199   if (PCSectionsMD) {
1200     auto It = NodeMap.find(&I);
1201     if (It != NodeMap.end()) {
1202       DAG.addPCSections(It->second.getNode(), PCSectionsMD);
1203     } else if (NodeInserted) {
1204       // This should not happen; if it does, don't let it go unnoticed so we can
1205       // fix it. Relevant visit*() function is probably missing a setValue().
1206       errs() << "warning: loosing !pcsections metadata ["
1207              << I.getModule()->getName() << "]\n";
1208       LLVM_DEBUG(I.dump());
1209       assert(false);
1210     }
1211   }
1212 
1213   CurInst = nullptr;
1214 }
1215 
1216 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1217   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1218 }
1219 
1220 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1221   // Note: this doesn't use InstVisitor, because it has to work with
1222   // ConstantExpr's in addition to instructions.
1223   switch (Opcode) {
1224   default: llvm_unreachable("Unknown instruction type encountered!");
1225     // Build the switch statement using the Instruction.def file.
1226 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1227     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1228 #include "llvm/IR/Instruction.def"
1229   }
1230 }
1231 
1232 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG,
1233                                             DILocalVariable *Variable,
1234                                             DebugLoc DL, unsigned Order,
1235                                             RawLocationWrapper Values,
1236                                             DIExpression *Expression) {
1237   if (!Values.hasArgList())
1238     return false;
1239   // For variadic dbg_values we will now insert an undef.
1240   // FIXME: We can potentially recover these!
1241   SmallVector<SDDbgOperand, 2> Locs;
1242   for (const Value *V : Values.location_ops()) {
1243     auto *Undef = UndefValue::get(V->getType());
1244     Locs.push_back(SDDbgOperand::fromConst(Undef));
1245   }
1246   SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {},
1247                                         /*IsIndirect=*/false, DL, Order,
1248                                         /*IsVariadic=*/true);
1249   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1250   return true;
1251 }
1252 
1253 void SelectionDAGBuilder::addDanglingDebugInfo(const VarLocInfo *VarLoc,
1254                                                unsigned Order) {
1255   if (!handleDanglingVariadicDebugInfo(
1256           DAG,
1257           const_cast<DILocalVariable *>(DAG.getFunctionVarLocs()
1258                                             ->getVariable(VarLoc->VariableID)
1259                                             .getVariable()),
1260           VarLoc->DL, Order, VarLoc->Values, VarLoc->Expr)) {
1261     DanglingDebugInfoMap[VarLoc->Values.getVariableLocationOp(0)].emplace_back(
1262         VarLoc, Order);
1263   }
1264 }
1265 
1266 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI,
1267                                                unsigned Order) {
1268   // We treat variadic dbg_values differently at this stage.
1269   if (!handleDanglingVariadicDebugInfo(
1270           DAG, DI->getVariable(), DI->getDebugLoc(), Order,
1271           DI->getWrappedLocation(), DI->getExpression())) {
1272     // TODO: Dangling debug info will eventually either be resolved or produce
1273     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
1274     // between the original dbg.value location and its resolved DBG_VALUE,
1275     // which we should ideally fill with an extra Undef DBG_VALUE.
1276     assert(DI->getNumVariableLocationOps() == 1 &&
1277            "DbgValueInst without an ArgList should have a single location "
1278            "operand.");
1279     DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, Order);
1280   }
1281 }
1282 
1283 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1284                                                 const DIExpression *Expr) {
1285   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1286     DIVariable *DanglingVariable = DDI.getVariable(DAG.getFunctionVarLocs());
1287     DIExpression *DanglingExpr = DDI.getExpression();
1288     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1289       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << printDDI(DDI)
1290                         << "\n");
1291       return true;
1292     }
1293     return false;
1294   };
1295 
1296   for (auto &DDIMI : DanglingDebugInfoMap) {
1297     DanglingDebugInfoVector &DDIV = DDIMI.second;
1298 
1299     // If debug info is to be dropped, run it through final checks to see
1300     // whether it can be salvaged.
1301     for (auto &DDI : DDIV)
1302       if (isMatchingDbgValue(DDI))
1303         salvageUnresolvedDbgValue(DDI);
1304 
1305     erase_if(DDIV, isMatchingDbgValue);
1306   }
1307 }
1308 
1309 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1310 // generate the debug data structures now that we've seen its definition.
1311 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1312                                                    SDValue Val) {
1313   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1314   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1315     return;
1316 
1317   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1318   for (auto &DDI : DDIV) {
1319     DebugLoc DL = DDI.getDebugLoc();
1320     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1321     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1322     DILocalVariable *Variable = DDI.getVariable(DAG.getFunctionVarLocs());
1323     DIExpression *Expr = DDI.getExpression();
1324     assert(Variable->isValidLocationForIntrinsic(DL) &&
1325            "Expected inlined-at fields to agree");
1326     SDDbgValue *SDV;
1327     if (Val.getNode()) {
1328       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1329       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1330       // we couldn't resolve it directly when examining the DbgValue intrinsic
1331       // in the first place we should not be more successful here). Unless we
1332       // have some test case that prove this to be correct we should avoid
1333       // calling EmitFuncArgumentDbgValue here.
1334       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL,
1335                                     FuncArgumentDbgValueKind::Value, Val)) {
1336         LLVM_DEBUG(dbgs() << "Resolve dangling debug info for " << printDDI(DDI)
1337                           << "\n");
1338         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1339         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1340         // inserted after the definition of Val when emitting the instructions
1341         // after ISel. An alternative could be to teach
1342         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1343         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1344                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1345                    << ValSDNodeOrder << "\n");
1346         SDV = getDbgValue(Val, Variable, Expr, DL,
1347                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1348         DAG.AddDbgValue(SDV, false);
1349       } else
1350         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for "
1351                           << printDDI(DDI) << " in EmitFuncArgumentDbgValue\n");
1352     } else {
1353       LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(DDI) << "\n");
1354       auto Undef = UndefValue::get(V->getType());
1355       auto SDV =
1356           DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder);
1357       DAG.AddDbgValue(SDV, false);
1358     }
1359   }
1360   DDIV.clear();
1361 }
1362 
1363 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1364   // TODO: For the variadic implementation, instead of only checking the fail
1365   // state of `handleDebugValue`, we need know specifically which values were
1366   // invalid, so that we attempt to salvage only those values when processing
1367   // a DIArgList.
1368   Value *V = DDI.getVariableLocationOp(0);
1369   Value *OrigV = V;
1370   DILocalVariable *Var = DDI.getVariable(DAG.getFunctionVarLocs());
1371   DIExpression *Expr = DDI.getExpression();
1372   DebugLoc DL = DDI.getDebugLoc();
1373   unsigned SDOrder = DDI.getSDNodeOrder();
1374 
1375   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1376   // that DW_OP_stack_value is desired.
1377   bool StackValue = true;
1378 
1379   // Can this Value can be encoded without any further work?
1380   if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false))
1381     return;
1382 
1383   // Attempt to salvage back through as many instructions as possible. Bail if
1384   // a non-instruction is seen, such as a constant expression or global
1385   // variable. FIXME: Further work could recover those too.
1386   while (isa<Instruction>(V)) {
1387     Instruction &VAsInst = *cast<Instruction>(V);
1388     // Temporary "0", awaiting real implementation.
1389     SmallVector<uint64_t, 16> Ops;
1390     SmallVector<Value *, 4> AdditionalValues;
1391     V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops,
1392                              AdditionalValues);
1393     // If we cannot salvage any further, and haven't yet found a suitable debug
1394     // expression, bail out.
1395     if (!V)
1396       break;
1397 
1398     // TODO: If AdditionalValues isn't empty, then the salvage can only be
1399     // represented with a DBG_VALUE_LIST, so we give up. When we have support
1400     // here for variadic dbg_values, remove that condition.
1401     if (!AdditionalValues.empty())
1402       break;
1403 
1404     // New value and expr now represent this debuginfo.
1405     Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue);
1406 
1407     // Some kind of simplification occurred: check whether the operand of the
1408     // salvaged debug expression can be encoded in this DAG.
1409     if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) {
1410       LLVM_DEBUG(
1411           dbgs() << "Salvaged debug location info for:\n  " << *Var << "\n"
1412                  << *OrigV << "\nBy stripping back to:\n  " << *V << "\n");
1413       return;
1414     }
1415   }
1416 
1417   // This was the final opportunity to salvage this debug information, and it
1418   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1419   // any earlier variable location.
1420   assert(OrigV && "V shouldn't be null");
1421   auto *Undef = UndefValue::get(OrigV->getType());
1422   auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1423   DAG.AddDbgValue(SDV, false);
1424   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << printDDI(DDI)
1425                     << "\n");
1426 }
1427 
1428 void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var,
1429                                                DIExpression *Expr,
1430                                                DebugLoc DbgLoc,
1431                                                unsigned Order) {
1432   Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context));
1433   DIExpression *NewExpr =
1434       const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr));
1435   handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order,
1436                    /*IsVariadic*/ false);
1437 }
1438 
1439 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1440                                            DILocalVariable *Var,
1441                                            DIExpression *Expr, DebugLoc DbgLoc,
1442                                            unsigned Order, bool IsVariadic) {
1443   if (Values.empty())
1444     return true;
1445   SmallVector<SDDbgOperand> LocationOps;
1446   SmallVector<SDNode *> Dependencies;
1447   for (const Value *V : Values) {
1448     // Constant value.
1449     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1450         isa<ConstantPointerNull>(V)) {
1451       LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1452       continue;
1453     }
1454 
1455     // Look through IntToPtr constants.
1456     if (auto *CE = dyn_cast<ConstantExpr>(V))
1457       if (CE->getOpcode() == Instruction::IntToPtr) {
1458         LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0)));
1459         continue;
1460       }
1461 
1462     // If the Value is a frame index, we can create a FrameIndex debug value
1463     // without relying on the DAG at all.
1464     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1465       auto SI = FuncInfo.StaticAllocaMap.find(AI);
1466       if (SI != FuncInfo.StaticAllocaMap.end()) {
1467         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1468         continue;
1469       }
1470     }
1471 
1472     // Do not use getValue() in here; we don't want to generate code at
1473     // this point if it hasn't been done yet.
1474     SDValue N = NodeMap[V];
1475     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1476       N = UnusedArgNodeMap[V];
1477     if (N.getNode()) {
1478       // Only emit func arg dbg value for non-variadic dbg.values for now.
1479       if (!IsVariadic &&
1480           EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc,
1481                                    FuncArgumentDbgValueKind::Value, N))
1482         return true;
1483       if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1484         // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1485         // describe stack slot locations.
1486         //
1487         // Consider "int x = 0; int *px = &x;". There are two kinds of
1488         // interesting debug values here after optimization:
1489         //
1490         //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
1491         //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1492         //
1493         // Both describe the direct values of their associated variables.
1494         Dependencies.push_back(N.getNode());
1495         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1496         continue;
1497       }
1498       LocationOps.emplace_back(
1499           SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1500       continue;
1501     }
1502 
1503     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1504     // Special rules apply for the first dbg.values of parameter variables in a
1505     // function. Identify them by the fact they reference Argument Values, that
1506     // they're parameters, and they are parameters of the current function. We
1507     // need to let them dangle until they get an SDNode.
1508     bool IsParamOfFunc =
1509         isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt();
1510     if (IsParamOfFunc)
1511       return false;
1512 
1513     // The value is not used in this block yet (or it would have an SDNode).
1514     // We still want the value to appear for the user if possible -- if it has
1515     // an associated VReg, we can refer to that instead.
1516     auto VMI = FuncInfo.ValueMap.find(V);
1517     if (VMI != FuncInfo.ValueMap.end()) {
1518       unsigned Reg = VMI->second;
1519       // If this is a PHI node, it may be split up into several MI PHI nodes
1520       // (in FunctionLoweringInfo::set).
1521       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1522                        V->getType(), std::nullopt);
1523       if (RFV.occupiesMultipleRegs()) {
1524         // FIXME: We could potentially support variadic dbg_values here.
1525         if (IsVariadic)
1526           return false;
1527         unsigned Offset = 0;
1528         unsigned BitsToDescribe = 0;
1529         if (auto VarSize = Var->getSizeInBits())
1530           BitsToDescribe = *VarSize;
1531         if (auto Fragment = Expr->getFragmentInfo())
1532           BitsToDescribe = Fragment->SizeInBits;
1533         for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1534           // Bail out if all bits are described already.
1535           if (Offset >= BitsToDescribe)
1536             break;
1537           // TODO: handle scalable vectors.
1538           unsigned RegisterSize = RegAndSize.second;
1539           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1540                                       ? BitsToDescribe - Offset
1541                                       : RegisterSize;
1542           auto FragmentExpr = DIExpression::createFragmentExpression(
1543               Expr, Offset, FragmentSize);
1544           if (!FragmentExpr)
1545             continue;
1546           SDDbgValue *SDV = DAG.getVRegDbgValue(
1547               Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, SDNodeOrder);
1548           DAG.AddDbgValue(SDV, false);
1549           Offset += RegisterSize;
1550         }
1551         return true;
1552       }
1553       // We can use simple vreg locations for variadic dbg_values as well.
1554       LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1555       continue;
1556     }
1557     // We failed to create a SDDbgOperand for V.
1558     return false;
1559   }
1560 
1561   // We have created a SDDbgOperand for each Value in Values.
1562   // Should use Order instead of SDNodeOrder?
1563   assert(!LocationOps.empty());
1564   SDDbgValue *SDV = DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1565                                         /*IsIndirect=*/false, DbgLoc,
1566                                         SDNodeOrder, IsVariadic);
1567   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1568   return true;
1569 }
1570 
1571 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1572   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1573   for (auto &Pair : DanglingDebugInfoMap)
1574     for (auto &DDI : Pair.second)
1575       salvageUnresolvedDbgValue(DDI);
1576   clearDanglingDebugInfo();
1577 }
1578 
1579 /// getCopyFromRegs - If there was virtual register allocated for the value V
1580 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1581 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1582   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1583   SDValue Result;
1584 
1585   if (It != FuncInfo.ValueMap.end()) {
1586     Register InReg = It->second;
1587 
1588     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1589                      DAG.getDataLayout(), InReg, Ty,
1590                      std::nullopt); // This is not an ABI copy.
1591     SDValue Chain = DAG.getEntryNode();
1592     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1593                                  V);
1594     resolveDanglingDebugInfo(V, Result);
1595   }
1596 
1597   return Result;
1598 }
1599 
1600 /// getValue - Return an SDValue for the given Value.
1601 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1602   // If we already have an SDValue for this value, use it. It's important
1603   // to do this first, so that we don't create a CopyFromReg if we already
1604   // have a regular SDValue.
1605   SDValue &N = NodeMap[V];
1606   if (N.getNode()) return N;
1607 
1608   // If there's a virtual register allocated and initialized for this
1609   // value, use it.
1610   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1611     return copyFromReg;
1612 
1613   // Otherwise create a new SDValue and remember it.
1614   SDValue Val = getValueImpl(V);
1615   NodeMap[V] = Val;
1616   resolveDanglingDebugInfo(V, Val);
1617   return Val;
1618 }
1619 
1620 /// getNonRegisterValue - Return an SDValue for the given Value, but
1621 /// don't look in FuncInfo.ValueMap for a virtual register.
1622 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1623   // If we already have an SDValue for this value, use it.
1624   SDValue &N = NodeMap[V];
1625   if (N.getNode()) {
1626     if (isIntOrFPConstant(N)) {
1627       // Remove the debug location from the node as the node is about to be used
1628       // in a location which may differ from the original debug location.  This
1629       // is relevant to Constant and ConstantFP nodes because they can appear
1630       // as constant expressions inside PHI nodes.
1631       N->setDebugLoc(DebugLoc());
1632     }
1633     return N;
1634   }
1635 
1636   // Otherwise create a new SDValue and remember it.
1637   SDValue Val = getValueImpl(V);
1638   NodeMap[V] = Val;
1639   resolveDanglingDebugInfo(V, Val);
1640   return Val;
1641 }
1642 
1643 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1644 /// Create an SDValue for the given value.
1645 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1646   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1647 
1648   if (const Constant *C = dyn_cast<Constant>(V)) {
1649     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1650 
1651     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1652       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1653 
1654     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1655       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1656 
1657     if (isa<ConstantPointerNull>(C)) {
1658       unsigned AS = V->getType()->getPointerAddressSpace();
1659       return DAG.getConstant(0, getCurSDLoc(),
1660                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1661     }
1662 
1663     if (match(C, m_VScale()))
1664       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1665 
1666     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1667       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1668 
1669     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1670       return DAG.getUNDEF(VT);
1671 
1672     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1673       visit(CE->getOpcode(), *CE);
1674       SDValue N1 = NodeMap[V];
1675       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1676       return N1;
1677     }
1678 
1679     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1680       SmallVector<SDValue, 4> Constants;
1681       for (const Use &U : C->operands()) {
1682         SDNode *Val = getValue(U).getNode();
1683         // If the operand is an empty aggregate, there are no values.
1684         if (!Val) continue;
1685         // Add each leaf value from the operand to the Constants list
1686         // to form a flattened list of all the values.
1687         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1688           Constants.push_back(SDValue(Val, i));
1689       }
1690 
1691       return DAG.getMergeValues(Constants, getCurSDLoc());
1692     }
1693 
1694     if (const ConstantDataSequential *CDS =
1695           dyn_cast<ConstantDataSequential>(C)) {
1696       SmallVector<SDValue, 4> Ops;
1697       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1698         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1699         // Add each leaf value from the operand to the Constants list
1700         // to form a flattened list of all the values.
1701         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1702           Ops.push_back(SDValue(Val, i));
1703       }
1704 
1705       if (isa<ArrayType>(CDS->getType()))
1706         return DAG.getMergeValues(Ops, getCurSDLoc());
1707       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1708     }
1709 
1710     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1711       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1712              "Unknown struct or array constant!");
1713 
1714       SmallVector<EVT, 4> ValueVTs;
1715       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1716       unsigned NumElts = ValueVTs.size();
1717       if (NumElts == 0)
1718         return SDValue(); // empty struct
1719       SmallVector<SDValue, 4> Constants(NumElts);
1720       for (unsigned i = 0; i != NumElts; ++i) {
1721         EVT EltVT = ValueVTs[i];
1722         if (isa<UndefValue>(C))
1723           Constants[i] = DAG.getUNDEF(EltVT);
1724         else if (EltVT.isFloatingPoint())
1725           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1726         else
1727           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1728       }
1729 
1730       return DAG.getMergeValues(Constants, getCurSDLoc());
1731     }
1732 
1733     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1734       return DAG.getBlockAddress(BA, VT);
1735 
1736     if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1737       return getValue(Equiv->getGlobalValue());
1738 
1739     if (const auto *NC = dyn_cast<NoCFIValue>(C))
1740       return getValue(NC->getGlobalValue());
1741 
1742     if (VT == MVT::aarch64svcount) {
1743       assert(C->isNullValue() && "Can only zero this target type!");
1744       return DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT,
1745                          DAG.getConstant(0, getCurSDLoc(), MVT::nxv16i1));
1746     }
1747 
1748     VectorType *VecTy = cast<VectorType>(V->getType());
1749 
1750     // Now that we know the number and type of the elements, get that number of
1751     // elements into the Ops array based on what kind of constant it is.
1752     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1753       SmallVector<SDValue, 16> Ops;
1754       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1755       for (unsigned i = 0; i != NumElements; ++i)
1756         Ops.push_back(getValue(CV->getOperand(i)));
1757 
1758       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1759     }
1760 
1761     if (isa<ConstantAggregateZero>(C)) {
1762       EVT EltVT =
1763           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1764 
1765       SDValue Op;
1766       if (EltVT.isFloatingPoint())
1767         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1768       else
1769         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1770 
1771       return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op);
1772     }
1773 
1774     llvm_unreachable("Unknown vector constant");
1775   }
1776 
1777   // If this is a static alloca, generate it as the frameindex instead of
1778   // computation.
1779   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1780     DenseMap<const AllocaInst*, int>::iterator SI =
1781       FuncInfo.StaticAllocaMap.find(AI);
1782     if (SI != FuncInfo.StaticAllocaMap.end())
1783       return DAG.getFrameIndex(
1784           SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType()));
1785   }
1786 
1787   // If this is an instruction which fast-isel has deferred, select it now.
1788   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1789     Register InReg = FuncInfo.InitializeRegForValue(Inst);
1790 
1791     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1792                      Inst->getType(), std::nullopt);
1793     SDValue Chain = DAG.getEntryNode();
1794     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1795   }
1796 
1797   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V))
1798     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1799 
1800   if (const auto *BB = dyn_cast<BasicBlock>(V))
1801     return DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
1802 
1803   llvm_unreachable("Can't get register for value!");
1804 }
1805 
1806 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1807   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1808   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1809   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1810   bool IsSEH = isAsynchronousEHPersonality(Pers);
1811   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1812   if (!IsSEH)
1813     CatchPadMBB->setIsEHScopeEntry();
1814   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1815   if (IsMSVCCXX || IsCoreCLR)
1816     CatchPadMBB->setIsEHFuncletEntry();
1817 }
1818 
1819 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1820   // Update machine-CFG edge.
1821   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1822   FuncInfo.MBB->addSuccessor(TargetMBB);
1823   TargetMBB->setIsEHCatchretTarget(true);
1824   DAG.getMachineFunction().setHasEHCatchret(true);
1825 
1826   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1827   bool IsSEH = isAsynchronousEHPersonality(Pers);
1828   if (IsSEH) {
1829     // If this is not a fall-through branch or optimizations are switched off,
1830     // emit the branch.
1831     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1832         TM.getOptLevel() == CodeGenOptLevel::None)
1833       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1834                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1835     return;
1836   }
1837 
1838   // Figure out the funclet membership for the catchret's successor.
1839   // This will be used by the FuncletLayout pass to determine how to order the
1840   // BB's.
1841   // A 'catchret' returns to the outer scope's color.
1842   Value *ParentPad = I.getCatchSwitchParentPad();
1843   const BasicBlock *SuccessorColor;
1844   if (isa<ConstantTokenNone>(ParentPad))
1845     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1846   else
1847     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1848   assert(SuccessorColor && "No parent funclet for catchret!");
1849   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1850   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1851 
1852   // Create the terminator node.
1853   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1854                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1855                             DAG.getBasicBlock(SuccessorColorMBB));
1856   DAG.setRoot(Ret);
1857 }
1858 
1859 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1860   // Don't emit any special code for the cleanuppad instruction. It just marks
1861   // the start of an EH scope/funclet.
1862   FuncInfo.MBB->setIsEHScopeEntry();
1863   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1864   if (Pers != EHPersonality::Wasm_CXX) {
1865     FuncInfo.MBB->setIsEHFuncletEntry();
1866     FuncInfo.MBB->setIsCleanupFuncletEntry();
1867   }
1868 }
1869 
1870 // In wasm EH, even though a catchpad may not catch an exception if a tag does
1871 // not match, it is OK to add only the first unwind destination catchpad to the
1872 // successors, because there will be at least one invoke instruction within the
1873 // catch scope that points to the next unwind destination, if one exists, so
1874 // CFGSort cannot mess up with BB sorting order.
1875 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
1876 // call within them, and catchpads only consisting of 'catch (...)' have a
1877 // '__cxa_end_catch' call within them, both of which generate invokes in case
1878 // the next unwind destination exists, i.e., the next unwind destination is not
1879 // the caller.)
1880 //
1881 // Having at most one EH pad successor is also simpler and helps later
1882 // transformations.
1883 //
1884 // For example,
1885 // current:
1886 //   invoke void @foo to ... unwind label %catch.dispatch
1887 // catch.dispatch:
1888 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
1889 // catch.start:
1890 //   ...
1891 //   ... in this BB or some other child BB dominated by this BB there will be an
1892 //   invoke that points to 'next' BB as an unwind destination
1893 //
1894 // next: ; We don't need to add this to 'current' BB's successor
1895 //   ...
1896 static void findWasmUnwindDestinations(
1897     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1898     BranchProbability Prob,
1899     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1900         &UnwindDests) {
1901   while (EHPadBB) {
1902     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1903     if (isa<CleanupPadInst>(Pad)) {
1904       // Stop on cleanup pads.
1905       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1906       UnwindDests.back().first->setIsEHScopeEntry();
1907       break;
1908     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1909       // Add the catchpad handlers to the possible destinations. We don't
1910       // continue to the unwind destination of the catchswitch for wasm.
1911       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1912         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1913         UnwindDests.back().first->setIsEHScopeEntry();
1914       }
1915       break;
1916     } else {
1917       continue;
1918     }
1919   }
1920 }
1921 
1922 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1923 /// many places it could ultimately go. In the IR, we have a single unwind
1924 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1925 /// This function skips over imaginary basic blocks that hold catchswitch
1926 /// instructions, and finds all the "real" machine
1927 /// basic block destinations. As those destinations may not be successors of
1928 /// EHPadBB, here we also calculate the edge probability to those destinations.
1929 /// The passed-in Prob is the edge probability to EHPadBB.
1930 static void findUnwindDestinations(
1931     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1932     BranchProbability Prob,
1933     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1934         &UnwindDests) {
1935   EHPersonality Personality =
1936     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1937   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1938   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1939   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1940   bool IsSEH = isAsynchronousEHPersonality(Personality);
1941 
1942   if (IsWasmCXX) {
1943     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1944     assert(UnwindDests.size() <= 1 &&
1945            "There should be at most one unwind destination for wasm");
1946     return;
1947   }
1948 
1949   while (EHPadBB) {
1950     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1951     BasicBlock *NewEHPadBB = nullptr;
1952     if (isa<LandingPadInst>(Pad)) {
1953       // Stop on landingpads. They are not funclets.
1954       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1955       break;
1956     } else if (isa<CleanupPadInst>(Pad)) {
1957       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1958       // personalities.
1959       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1960       UnwindDests.back().first->setIsEHScopeEntry();
1961       UnwindDests.back().first->setIsEHFuncletEntry();
1962       break;
1963     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1964       // Add the catchpad handlers to the possible destinations.
1965       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1966         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1967         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1968         if (IsMSVCCXX || IsCoreCLR)
1969           UnwindDests.back().first->setIsEHFuncletEntry();
1970         if (!IsSEH)
1971           UnwindDests.back().first->setIsEHScopeEntry();
1972       }
1973       NewEHPadBB = CatchSwitch->getUnwindDest();
1974     } else {
1975       continue;
1976     }
1977 
1978     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1979     if (BPI && NewEHPadBB)
1980       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1981     EHPadBB = NewEHPadBB;
1982   }
1983 }
1984 
1985 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1986   // Update successor info.
1987   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1988   auto UnwindDest = I.getUnwindDest();
1989   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1990   BranchProbability UnwindDestProb =
1991       (BPI && UnwindDest)
1992           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1993           : BranchProbability::getZero();
1994   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1995   for (auto &UnwindDest : UnwindDests) {
1996     UnwindDest.first->setIsEHPad();
1997     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1998   }
1999   FuncInfo.MBB->normalizeSuccProbs();
2000 
2001   // Create the terminator node.
2002   SDValue Ret =
2003       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
2004   DAG.setRoot(Ret);
2005 }
2006 
2007 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
2008   report_fatal_error("visitCatchSwitch not yet implemented!");
2009 }
2010 
2011 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
2012   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2013   auto &DL = DAG.getDataLayout();
2014   SDValue Chain = getControlRoot();
2015   SmallVector<ISD::OutputArg, 8> Outs;
2016   SmallVector<SDValue, 8> OutVals;
2017 
2018   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
2019   // lower
2020   //
2021   //   %val = call <ty> @llvm.experimental.deoptimize()
2022   //   ret <ty> %val
2023   //
2024   // differently.
2025   if (I.getParent()->getTerminatingDeoptimizeCall()) {
2026     LowerDeoptimizingReturn();
2027     return;
2028   }
2029 
2030   if (!FuncInfo.CanLowerReturn) {
2031     unsigned DemoteReg = FuncInfo.DemoteRegister;
2032     const Function *F = I.getParent()->getParent();
2033 
2034     // Emit a store of the return value through the virtual register.
2035     // Leave Outs empty so that LowerReturn won't try to load return
2036     // registers the usual way.
2037     SmallVector<EVT, 1> PtrValueVTs;
2038     ComputeValueVTs(TLI, DL,
2039                     PointerType::get(F->getContext(),
2040                                      DAG.getDataLayout().getAllocaAddrSpace()),
2041                     PtrValueVTs);
2042 
2043     SDValue RetPtr =
2044         DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]);
2045     SDValue RetOp = getValue(I.getOperand(0));
2046 
2047     SmallVector<EVT, 4> ValueVTs, MemVTs;
2048     SmallVector<uint64_t, 4> Offsets;
2049     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
2050                     &Offsets, 0);
2051     unsigned NumValues = ValueVTs.size();
2052 
2053     SmallVector<SDValue, 4> Chains(NumValues);
2054     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
2055     for (unsigned i = 0; i != NumValues; ++i) {
2056       // An aggregate return value cannot wrap around the address space, so
2057       // offsets to its parts don't wrap either.
2058       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
2059                                            TypeSize::Fixed(Offsets[i]));
2060 
2061       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
2062       if (MemVTs[i] != ValueVTs[i])
2063         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
2064       Chains[i] = DAG.getStore(
2065           Chain, getCurSDLoc(), Val,
2066           // FIXME: better loc info would be nice.
2067           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
2068           commonAlignment(BaseAlign, Offsets[i]));
2069     }
2070 
2071     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
2072                         MVT::Other, Chains);
2073   } else if (I.getNumOperands() != 0) {
2074     SmallVector<EVT, 4> ValueVTs;
2075     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
2076     unsigned NumValues = ValueVTs.size();
2077     if (NumValues) {
2078       SDValue RetOp = getValue(I.getOperand(0));
2079 
2080       const Function *F = I.getParent()->getParent();
2081 
2082       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
2083           I.getOperand(0)->getType(), F->getCallingConv(),
2084           /*IsVarArg*/ false, DL);
2085 
2086       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
2087       if (F->getAttributes().hasRetAttr(Attribute::SExt))
2088         ExtendKind = ISD::SIGN_EXTEND;
2089       else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
2090         ExtendKind = ISD::ZERO_EXTEND;
2091 
2092       LLVMContext &Context = F->getContext();
2093       bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
2094 
2095       for (unsigned j = 0; j != NumValues; ++j) {
2096         EVT VT = ValueVTs[j];
2097 
2098         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2099           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
2100 
2101         CallingConv::ID CC = F->getCallingConv();
2102 
2103         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
2104         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2105         SmallVector<SDValue, 4> Parts(NumParts);
2106         getCopyToParts(DAG, getCurSDLoc(),
2107                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2108                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
2109 
2110         // 'inreg' on function refers to return value
2111         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2112         if (RetInReg)
2113           Flags.setInReg();
2114 
2115         if (I.getOperand(0)->getType()->isPointerTy()) {
2116           Flags.setPointer();
2117           Flags.setPointerAddrSpace(
2118               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2119         }
2120 
2121         if (NeedsRegBlock) {
2122           Flags.setInConsecutiveRegs();
2123           if (j == NumValues - 1)
2124             Flags.setInConsecutiveRegsLast();
2125         }
2126 
2127         // Propagate extension type if any
2128         if (ExtendKind == ISD::SIGN_EXTEND)
2129           Flags.setSExt();
2130         else if (ExtendKind == ISD::ZERO_EXTEND)
2131           Flags.setZExt();
2132 
2133         for (unsigned i = 0; i < NumParts; ++i) {
2134           Outs.push_back(ISD::OutputArg(Flags,
2135                                         Parts[i].getValueType().getSimpleVT(),
2136                                         VT, /*isfixed=*/true, 0, 0));
2137           OutVals.push_back(Parts[i]);
2138         }
2139       }
2140     }
2141   }
2142 
2143   // Push in swifterror virtual register as the last element of Outs. This makes
2144   // sure swifterror virtual register will be returned in the swifterror
2145   // physical register.
2146   const Function *F = I.getParent()->getParent();
2147   if (TLI.supportSwiftError() &&
2148       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2149     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2150     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2151     Flags.setSwiftError();
2152     Outs.push_back(ISD::OutputArg(
2153         Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
2154         /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
2155     // Create SDNode for the swifterror virtual register.
2156     OutVals.push_back(
2157         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2158                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2159                         EVT(TLI.getPointerTy(DL))));
2160   }
2161 
2162   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2163   CallingConv::ID CallConv =
2164     DAG.getMachineFunction().getFunction().getCallingConv();
2165   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2166       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2167 
2168   // Verify that the target's LowerReturn behaved as expected.
2169   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2170          "LowerReturn didn't return a valid chain!");
2171 
2172   // Update the DAG with the new chain value resulting from return lowering.
2173   DAG.setRoot(Chain);
2174 }
2175 
2176 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2177 /// created for it, emit nodes to copy the value into the virtual
2178 /// registers.
2179 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2180   // Skip empty types
2181   if (V->getType()->isEmptyTy())
2182     return;
2183 
2184   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2185   if (VMI != FuncInfo.ValueMap.end()) {
2186     assert((!V->use_empty() || isa<CallBrInst>(V)) &&
2187            "Unused value assigned virtual registers!");
2188     CopyValueToVirtualRegister(V, VMI->second);
2189   }
2190 }
2191 
2192 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2193 /// the current basic block, add it to ValueMap now so that we'll get a
2194 /// CopyTo/FromReg.
2195 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2196   // No need to export constants.
2197   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2198 
2199   // Already exported?
2200   if (FuncInfo.isExportedInst(V)) return;
2201 
2202   Register Reg = FuncInfo.InitializeRegForValue(V);
2203   CopyValueToVirtualRegister(V, Reg);
2204 }
2205 
2206 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2207                                                      const BasicBlock *FromBB) {
2208   // The operands of the setcc have to be in this block.  We don't know
2209   // how to export them from some other block.
2210   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2211     // Can export from current BB.
2212     if (VI->getParent() == FromBB)
2213       return true;
2214 
2215     // Is already exported, noop.
2216     return FuncInfo.isExportedInst(V);
2217   }
2218 
2219   // If this is an argument, we can export it if the BB is the entry block or
2220   // if it is already exported.
2221   if (isa<Argument>(V)) {
2222     if (FromBB->isEntryBlock())
2223       return true;
2224 
2225     // Otherwise, can only export this if it is already exported.
2226     return FuncInfo.isExportedInst(V);
2227   }
2228 
2229   // Otherwise, constants can always be exported.
2230   return true;
2231 }
2232 
2233 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2234 BranchProbability
2235 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2236                                         const MachineBasicBlock *Dst) const {
2237   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2238   const BasicBlock *SrcBB = Src->getBasicBlock();
2239   const BasicBlock *DstBB = Dst->getBasicBlock();
2240   if (!BPI) {
2241     // If BPI is not available, set the default probability as 1 / N, where N is
2242     // the number of successors.
2243     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2244     return BranchProbability(1, SuccSize);
2245   }
2246   return BPI->getEdgeProbability(SrcBB, DstBB);
2247 }
2248 
2249 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2250                                                MachineBasicBlock *Dst,
2251                                                BranchProbability Prob) {
2252   if (!FuncInfo.BPI)
2253     Src->addSuccessorWithoutProb(Dst);
2254   else {
2255     if (Prob.isUnknown())
2256       Prob = getEdgeProbability(Src, Dst);
2257     Src->addSuccessor(Dst, Prob);
2258   }
2259 }
2260 
2261 static bool InBlock(const Value *V, const BasicBlock *BB) {
2262   if (const Instruction *I = dyn_cast<Instruction>(V))
2263     return I->getParent() == BB;
2264   return true;
2265 }
2266 
2267 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2268 /// This function emits a branch and is used at the leaves of an OR or an
2269 /// AND operator tree.
2270 void
2271 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2272                                                   MachineBasicBlock *TBB,
2273                                                   MachineBasicBlock *FBB,
2274                                                   MachineBasicBlock *CurBB,
2275                                                   MachineBasicBlock *SwitchBB,
2276                                                   BranchProbability TProb,
2277                                                   BranchProbability FProb,
2278                                                   bool InvertCond) {
2279   const BasicBlock *BB = CurBB->getBasicBlock();
2280 
2281   // If the leaf of the tree is a comparison, merge the condition into
2282   // the caseblock.
2283   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2284     // The operands of the cmp have to be in this block.  We don't know
2285     // how to export them from some other block.  If this is the first block
2286     // of the sequence, no exporting is needed.
2287     if (CurBB == SwitchBB ||
2288         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2289          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2290       ISD::CondCode Condition;
2291       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2292         ICmpInst::Predicate Pred =
2293             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2294         Condition = getICmpCondCode(Pred);
2295       } else {
2296         const FCmpInst *FC = cast<FCmpInst>(Cond);
2297         FCmpInst::Predicate Pred =
2298             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2299         Condition = getFCmpCondCode(Pred);
2300         if (TM.Options.NoNaNsFPMath)
2301           Condition = getFCmpCodeWithoutNaN(Condition);
2302       }
2303 
2304       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2305                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2306       SL->SwitchCases.push_back(CB);
2307       return;
2308     }
2309   }
2310 
2311   // Create a CaseBlock record representing this branch.
2312   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2313   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2314                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2315   SL->SwitchCases.push_back(CB);
2316 }
2317 
2318 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2319                                                MachineBasicBlock *TBB,
2320                                                MachineBasicBlock *FBB,
2321                                                MachineBasicBlock *CurBB,
2322                                                MachineBasicBlock *SwitchBB,
2323                                                Instruction::BinaryOps Opc,
2324                                                BranchProbability TProb,
2325                                                BranchProbability FProb,
2326                                                bool InvertCond) {
2327   // Skip over not part of the tree and remember to invert op and operands at
2328   // next level.
2329   Value *NotCond;
2330   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2331       InBlock(NotCond, CurBB->getBasicBlock())) {
2332     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2333                          !InvertCond);
2334     return;
2335   }
2336 
2337   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2338   const Value *BOpOp0, *BOpOp1;
2339   // Compute the effective opcode for Cond, taking into account whether it needs
2340   // to be inverted, e.g.
2341   //   and (not (or A, B)), C
2342   // gets lowered as
2343   //   and (and (not A, not B), C)
2344   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2345   if (BOp) {
2346     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2347                ? Instruction::And
2348                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2349                       ? Instruction::Or
2350                       : (Instruction::BinaryOps)0);
2351     if (InvertCond) {
2352       if (BOpc == Instruction::And)
2353         BOpc = Instruction::Or;
2354       else if (BOpc == Instruction::Or)
2355         BOpc = Instruction::And;
2356     }
2357   }
2358 
2359   // If this node is not part of the or/and tree, emit it as a branch.
2360   // Note that all nodes in the tree should have same opcode.
2361   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2362   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2363       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2364       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2365     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2366                                  TProb, FProb, InvertCond);
2367     return;
2368   }
2369 
2370   //  Create TmpBB after CurBB.
2371   MachineFunction::iterator BBI(CurBB);
2372   MachineFunction &MF = DAG.getMachineFunction();
2373   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2374   CurBB->getParent()->insert(++BBI, TmpBB);
2375 
2376   if (Opc == Instruction::Or) {
2377     // Codegen X | Y as:
2378     // BB1:
2379     //   jmp_if_X TBB
2380     //   jmp TmpBB
2381     // TmpBB:
2382     //   jmp_if_Y TBB
2383     //   jmp FBB
2384     //
2385 
2386     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2387     // The requirement is that
2388     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2389     //     = TrueProb for original BB.
2390     // Assuming the original probabilities are A and B, one choice is to set
2391     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2392     // A/(1+B) and 2B/(1+B). This choice assumes that
2393     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2394     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2395     // TmpBB, but the math is more complicated.
2396 
2397     auto NewTrueProb = TProb / 2;
2398     auto NewFalseProb = TProb / 2 + FProb;
2399     // Emit the LHS condition.
2400     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2401                          NewFalseProb, InvertCond);
2402 
2403     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2404     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2405     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2406     // Emit the RHS condition into TmpBB.
2407     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2408                          Probs[1], InvertCond);
2409   } else {
2410     assert(Opc == Instruction::And && "Unknown merge op!");
2411     // Codegen X & Y as:
2412     // BB1:
2413     //   jmp_if_X TmpBB
2414     //   jmp FBB
2415     // TmpBB:
2416     //   jmp_if_Y TBB
2417     //   jmp FBB
2418     //
2419     //  This requires creation of TmpBB after CurBB.
2420 
2421     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2422     // The requirement is that
2423     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2424     //     = FalseProb for original BB.
2425     // Assuming the original probabilities are A and B, one choice is to set
2426     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2427     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2428     // TrueProb for BB1 * FalseProb for TmpBB.
2429 
2430     auto NewTrueProb = TProb + FProb / 2;
2431     auto NewFalseProb = FProb / 2;
2432     // Emit the LHS condition.
2433     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2434                          NewFalseProb, InvertCond);
2435 
2436     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2437     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2438     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2439     // Emit the RHS condition into TmpBB.
2440     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2441                          Probs[1], InvertCond);
2442   }
2443 }
2444 
2445 /// If the set of cases should be emitted as a series of branches, return true.
2446 /// If we should emit this as a bunch of and/or'd together conditions, return
2447 /// false.
2448 bool
2449 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2450   if (Cases.size() != 2) return true;
2451 
2452   // If this is two comparisons of the same values or'd or and'd together, they
2453   // will get folded into a single comparison, so don't emit two blocks.
2454   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2455        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2456       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2457        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2458     return false;
2459   }
2460 
2461   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2462   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2463   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2464       Cases[0].CC == Cases[1].CC &&
2465       isa<Constant>(Cases[0].CmpRHS) &&
2466       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2467     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2468       return false;
2469     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2470       return false;
2471   }
2472 
2473   return true;
2474 }
2475 
2476 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2477   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2478 
2479   // Update machine-CFG edges.
2480   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2481 
2482   if (I.isUnconditional()) {
2483     // Update machine-CFG edges.
2484     BrMBB->addSuccessor(Succ0MBB);
2485 
2486     // If this is not a fall-through branch or optimizations are switched off,
2487     // emit the branch.
2488     if (Succ0MBB != NextBlock(BrMBB) ||
2489         TM.getOptLevel() == CodeGenOptLevel::None) {
2490       auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
2491                             getControlRoot(), DAG.getBasicBlock(Succ0MBB));
2492       setValue(&I, Br);
2493       DAG.setRoot(Br);
2494     }
2495 
2496     return;
2497   }
2498 
2499   // If this condition is one of the special cases we handle, do special stuff
2500   // now.
2501   const Value *CondVal = I.getCondition();
2502   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2503 
2504   // If this is a series of conditions that are or'd or and'd together, emit
2505   // this as a sequence of branches instead of setcc's with and/or operations.
2506   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2507   // unpredictable branches, and vector extracts because those jumps are likely
2508   // expensive for any target), this should improve performance.
2509   // For example, instead of something like:
2510   //     cmp A, B
2511   //     C = seteq
2512   //     cmp D, E
2513   //     F = setle
2514   //     or C, F
2515   //     jnz foo
2516   // Emit:
2517   //     cmp A, B
2518   //     je foo
2519   //     cmp D, E
2520   //     jle foo
2521   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2522   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2523       BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2524     Value *Vec;
2525     const Value *BOp0, *BOp1;
2526     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2527     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2528       Opcode = Instruction::And;
2529     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2530       Opcode = Instruction::Or;
2531 
2532     if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2533                     match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
2534       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2535                            getEdgeProbability(BrMBB, Succ0MBB),
2536                            getEdgeProbability(BrMBB, Succ1MBB),
2537                            /*InvertCond=*/false);
2538       // If the compares in later blocks need to use values not currently
2539       // exported from this block, export them now.  This block should always
2540       // be the first entry.
2541       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2542 
2543       // Allow some cases to be rejected.
2544       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2545         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2546           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2547           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2548         }
2549 
2550         // Emit the branch for this block.
2551         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2552         SL->SwitchCases.erase(SL->SwitchCases.begin());
2553         return;
2554       }
2555 
2556       // Okay, we decided not to do this, remove any inserted MBB's and clear
2557       // SwitchCases.
2558       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2559         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2560 
2561       SL->SwitchCases.clear();
2562     }
2563   }
2564 
2565   // Create a CaseBlock record representing this branch.
2566   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2567                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2568 
2569   // Use visitSwitchCase to actually insert the fast branch sequence for this
2570   // cond branch.
2571   visitSwitchCase(CB, BrMBB);
2572 }
2573 
2574 /// visitSwitchCase - Emits the necessary code to represent a single node in
2575 /// the binary search tree resulting from lowering a switch instruction.
2576 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2577                                           MachineBasicBlock *SwitchBB) {
2578   SDValue Cond;
2579   SDValue CondLHS = getValue(CB.CmpLHS);
2580   SDLoc dl = CB.DL;
2581 
2582   if (CB.CC == ISD::SETTRUE) {
2583     // Branch or fall through to TrueBB.
2584     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2585     SwitchBB->normalizeSuccProbs();
2586     if (CB.TrueBB != NextBlock(SwitchBB)) {
2587       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2588                               DAG.getBasicBlock(CB.TrueBB)));
2589     }
2590     return;
2591   }
2592 
2593   auto &TLI = DAG.getTargetLoweringInfo();
2594   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2595 
2596   // Build the setcc now.
2597   if (!CB.CmpMHS) {
2598     // Fold "(X == true)" to X and "(X == false)" to !X to
2599     // handle common cases produced by branch lowering.
2600     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2601         CB.CC == ISD::SETEQ)
2602       Cond = CondLHS;
2603     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2604              CB.CC == ISD::SETEQ) {
2605       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2606       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2607     } else {
2608       SDValue CondRHS = getValue(CB.CmpRHS);
2609 
2610       // If a pointer's DAG type is larger than its memory type then the DAG
2611       // values are zero-extended. This breaks signed comparisons so truncate
2612       // back to the underlying type before doing the compare.
2613       if (CondLHS.getValueType() != MemVT) {
2614         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2615         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2616       }
2617       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2618     }
2619   } else {
2620     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2621 
2622     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2623     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2624 
2625     SDValue CmpOp = getValue(CB.CmpMHS);
2626     EVT VT = CmpOp.getValueType();
2627 
2628     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2629       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2630                           ISD::SETLE);
2631     } else {
2632       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2633                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2634       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2635                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2636     }
2637   }
2638 
2639   // Update successor info
2640   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2641   // TrueBB and FalseBB are always different unless the incoming IR is
2642   // degenerate. This only happens when running llc on weird IR.
2643   if (CB.TrueBB != CB.FalseBB)
2644     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2645   SwitchBB->normalizeSuccProbs();
2646 
2647   // If the lhs block is the next block, invert the condition so that we can
2648   // fall through to the lhs instead of the rhs block.
2649   if (CB.TrueBB == NextBlock(SwitchBB)) {
2650     std::swap(CB.TrueBB, CB.FalseBB);
2651     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2652     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2653   }
2654 
2655   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2656                                MVT::Other, getControlRoot(), Cond,
2657                                DAG.getBasicBlock(CB.TrueBB));
2658 
2659   setValue(CurInst, BrCond);
2660 
2661   // Insert the false branch. Do this even if it's a fall through branch,
2662   // this makes it easier to do DAG optimizations which require inverting
2663   // the branch condition.
2664   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2665                        DAG.getBasicBlock(CB.FalseBB));
2666 
2667   DAG.setRoot(BrCond);
2668 }
2669 
2670 /// visitJumpTable - Emit JumpTable node in the current MBB
2671 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2672   // Emit the code for the jump table
2673   assert(JT.SL && "Should set SDLoc for SelectionDAG!");
2674   assert(JT.Reg != -1U && "Should lower JT Header first!");
2675   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2676   SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy);
2677   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2678   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other,
2679                                     Index.getValue(1), Table, Index);
2680   DAG.setRoot(BrJumpTable);
2681 }
2682 
2683 /// visitJumpTableHeader - This function emits necessary code to produce index
2684 /// in the JumpTable from switch case.
2685 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2686                                                JumpTableHeader &JTH,
2687                                                MachineBasicBlock *SwitchBB) {
2688   assert(JT.SL && "Should set SDLoc for SelectionDAG!");
2689   const SDLoc &dl = *JT.SL;
2690 
2691   // Subtract the lowest switch case value from the value being switched on.
2692   SDValue SwitchOp = getValue(JTH.SValue);
2693   EVT VT = SwitchOp.getValueType();
2694   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2695                             DAG.getConstant(JTH.First, dl, VT));
2696 
2697   // The SDNode we just created, which holds the value being switched on minus
2698   // the smallest case value, needs to be copied to a virtual register so it
2699   // can be used as an index into the jump table in a subsequent basic block.
2700   // This value may be smaller or larger than the target's pointer type, and
2701   // therefore require extension or truncating.
2702   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2703   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2704 
2705   unsigned JumpTableReg =
2706       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2707   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2708                                     JumpTableReg, SwitchOp);
2709   JT.Reg = JumpTableReg;
2710 
2711   if (!JTH.FallthroughUnreachable) {
2712     // Emit the range check for the jump table, and branch to the default block
2713     // for the switch statement if the value being switched on exceeds the
2714     // largest case in the switch.
2715     SDValue CMP = DAG.getSetCC(
2716         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2717                                    Sub.getValueType()),
2718         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2719 
2720     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2721                                  MVT::Other, CopyTo, CMP,
2722                                  DAG.getBasicBlock(JT.Default));
2723 
2724     // Avoid emitting unnecessary branches to the next block.
2725     if (JT.MBB != NextBlock(SwitchBB))
2726       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2727                            DAG.getBasicBlock(JT.MBB));
2728 
2729     DAG.setRoot(BrCond);
2730   } else {
2731     // Avoid emitting unnecessary branches to the next block.
2732     if (JT.MBB != NextBlock(SwitchBB))
2733       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2734                               DAG.getBasicBlock(JT.MBB)));
2735     else
2736       DAG.setRoot(CopyTo);
2737   }
2738 }
2739 
2740 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2741 /// variable if there exists one.
2742 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2743                                  SDValue &Chain) {
2744   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2745   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2746   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2747   MachineFunction &MF = DAG.getMachineFunction();
2748   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2749   MachineSDNode *Node =
2750       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2751   if (Global) {
2752     MachinePointerInfo MPInfo(Global);
2753     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2754                  MachineMemOperand::MODereferenceable;
2755     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2756         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2757     DAG.setNodeMemRefs(Node, {MemRef});
2758   }
2759   if (PtrTy != PtrMemTy)
2760     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2761   return SDValue(Node, 0);
2762 }
2763 
2764 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2765 /// tail spliced into a stack protector check success bb.
2766 ///
2767 /// For a high level explanation of how this fits into the stack protector
2768 /// generation see the comment on the declaration of class
2769 /// StackProtectorDescriptor.
2770 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2771                                                   MachineBasicBlock *ParentBB) {
2772 
2773   // First create the loads to the guard/stack slot for the comparison.
2774   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2775   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2776   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2777 
2778   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2779   int FI = MFI.getStackProtectorIndex();
2780 
2781   SDValue Guard;
2782   SDLoc dl = getCurSDLoc();
2783   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2784   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2785   Align Align =
2786       DAG.getDataLayout().getPrefTypeAlign(PointerType::get(M.getContext(), 0));
2787 
2788   // Generate code to load the content of the guard slot.
2789   SDValue GuardVal = DAG.getLoad(
2790       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2791       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2792       MachineMemOperand::MOVolatile);
2793 
2794   if (TLI.useStackGuardXorFP())
2795     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2796 
2797   // Retrieve guard check function, nullptr if instrumentation is inlined.
2798   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2799     // The target provides a guard check function to validate the guard value.
2800     // Generate a call to that function with the content of the guard slot as
2801     // argument.
2802     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2803     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2804 
2805     TargetLowering::ArgListTy Args;
2806     TargetLowering::ArgListEntry Entry;
2807     Entry.Node = GuardVal;
2808     Entry.Ty = FnTy->getParamType(0);
2809     if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
2810       Entry.IsInReg = true;
2811     Args.push_back(Entry);
2812 
2813     TargetLowering::CallLoweringInfo CLI(DAG);
2814     CLI.setDebugLoc(getCurSDLoc())
2815         .setChain(DAG.getEntryNode())
2816         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2817                    getValue(GuardCheckFn), std::move(Args));
2818 
2819     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2820     DAG.setRoot(Result.second);
2821     return;
2822   }
2823 
2824   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2825   // Otherwise, emit a volatile load to retrieve the stack guard value.
2826   SDValue Chain = DAG.getEntryNode();
2827   if (TLI.useLoadStackGuardNode()) {
2828     Guard = getLoadStackGuard(DAG, dl, Chain);
2829   } else {
2830     const Value *IRGuard = TLI.getSDagStackGuard(M);
2831     SDValue GuardPtr = getValue(IRGuard);
2832 
2833     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2834                         MachinePointerInfo(IRGuard, 0), Align,
2835                         MachineMemOperand::MOVolatile);
2836   }
2837 
2838   // Perform the comparison via a getsetcc.
2839   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2840                                                         *DAG.getContext(),
2841                                                         Guard.getValueType()),
2842                              Guard, GuardVal, ISD::SETNE);
2843 
2844   // If the guard/stackslot do not equal, branch to failure MBB.
2845   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2846                                MVT::Other, GuardVal.getOperand(0),
2847                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2848   // Otherwise branch to success MBB.
2849   SDValue Br = DAG.getNode(ISD::BR, dl,
2850                            MVT::Other, BrCond,
2851                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2852 
2853   DAG.setRoot(Br);
2854 }
2855 
2856 /// Codegen the failure basic block for a stack protector check.
2857 ///
2858 /// A failure stack protector machine basic block consists simply of a call to
2859 /// __stack_chk_fail().
2860 ///
2861 /// For a high level explanation of how this fits into the stack protector
2862 /// generation see the comment on the declaration of class
2863 /// StackProtectorDescriptor.
2864 void
2865 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2866   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2867   TargetLowering::MakeLibCallOptions CallOptions;
2868   CallOptions.setDiscardResult(true);
2869   SDValue Chain =
2870       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2871                       std::nullopt, CallOptions, getCurSDLoc())
2872           .second;
2873   // On PS4/PS5, the "return address" must still be within the calling
2874   // function, even if it's at the very end, so emit an explicit TRAP here.
2875   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2876   if (TM.getTargetTriple().isPS())
2877     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2878   // WebAssembly needs an unreachable instruction after a non-returning call,
2879   // because the function return type can be different from __stack_chk_fail's
2880   // return type (void).
2881   if (TM.getTargetTriple().isWasm())
2882     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2883 
2884   DAG.setRoot(Chain);
2885 }
2886 
2887 /// visitBitTestHeader - This function emits necessary code to produce value
2888 /// suitable for "bit tests"
2889 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2890                                              MachineBasicBlock *SwitchBB) {
2891   SDLoc dl = getCurSDLoc();
2892 
2893   // Subtract the minimum value.
2894   SDValue SwitchOp = getValue(B.SValue);
2895   EVT VT = SwitchOp.getValueType();
2896   SDValue RangeSub =
2897       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2898 
2899   // Determine the type of the test operands.
2900   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2901   bool UsePtrType = false;
2902   if (!TLI.isTypeLegal(VT)) {
2903     UsePtrType = true;
2904   } else {
2905     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2906       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2907         // Switch table case range are encoded into series of masks.
2908         // Just use pointer type, it's guaranteed to fit.
2909         UsePtrType = true;
2910         break;
2911       }
2912   }
2913   SDValue Sub = RangeSub;
2914   if (UsePtrType) {
2915     VT = TLI.getPointerTy(DAG.getDataLayout());
2916     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2917   }
2918 
2919   B.RegVT = VT.getSimpleVT();
2920   B.Reg = FuncInfo.CreateReg(B.RegVT);
2921   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2922 
2923   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2924 
2925   if (!B.FallthroughUnreachable)
2926     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2927   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2928   SwitchBB->normalizeSuccProbs();
2929 
2930   SDValue Root = CopyTo;
2931   if (!B.FallthroughUnreachable) {
2932     // Conditional branch to the default block.
2933     SDValue RangeCmp = DAG.getSetCC(dl,
2934         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2935                                RangeSub.getValueType()),
2936         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2937         ISD::SETUGT);
2938 
2939     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2940                        DAG.getBasicBlock(B.Default));
2941   }
2942 
2943   // Avoid emitting unnecessary branches to the next block.
2944   if (MBB != NextBlock(SwitchBB))
2945     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2946 
2947   DAG.setRoot(Root);
2948 }
2949 
2950 /// visitBitTestCase - this function produces one "bit test"
2951 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2952                                            MachineBasicBlock* NextMBB,
2953                                            BranchProbability BranchProbToNext,
2954                                            unsigned Reg,
2955                                            BitTestCase &B,
2956                                            MachineBasicBlock *SwitchBB) {
2957   SDLoc dl = getCurSDLoc();
2958   MVT VT = BB.RegVT;
2959   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2960   SDValue Cmp;
2961   unsigned PopCount = llvm::popcount(B.Mask);
2962   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2963   if (PopCount == 1) {
2964     // Testing for a single bit; just compare the shift count with what it
2965     // would need to be to shift a 1 bit in that position.
2966     Cmp = DAG.getSetCC(
2967         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2968         ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT),
2969         ISD::SETEQ);
2970   } else if (PopCount == BB.Range) {
2971     // There is only one zero bit in the range, test for it directly.
2972     Cmp = DAG.getSetCC(
2973         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2974         ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE);
2975   } else {
2976     // Make desired shift
2977     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2978                                     DAG.getConstant(1, dl, VT), ShiftOp);
2979 
2980     // Emit bit tests and jumps
2981     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2982                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2983     Cmp = DAG.getSetCC(
2984         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2985         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2986   }
2987 
2988   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2989   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2990   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2991   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2992   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2993   // one as they are relative probabilities (and thus work more like weights),
2994   // and hence we need to normalize them to let the sum of them become one.
2995   SwitchBB->normalizeSuccProbs();
2996 
2997   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2998                               MVT::Other, getControlRoot(),
2999                               Cmp, DAG.getBasicBlock(B.TargetBB));
3000 
3001   // Avoid emitting unnecessary branches to the next block.
3002   if (NextMBB != NextBlock(SwitchBB))
3003     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
3004                         DAG.getBasicBlock(NextMBB));
3005 
3006   DAG.setRoot(BrAnd);
3007 }
3008 
3009 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
3010   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
3011 
3012   // Retrieve successors. Look through artificial IR level blocks like
3013   // catchswitch for successors.
3014   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
3015   const BasicBlock *EHPadBB = I.getSuccessor(1);
3016   MachineBasicBlock *EHPadMBB = FuncInfo.MBBMap[EHPadBB];
3017 
3018   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3019   // have to do anything here to lower funclet bundles.
3020   assert(!I.hasOperandBundlesOtherThan(
3021              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
3022               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
3023               LLVMContext::OB_cfguardtarget,
3024               LLVMContext::OB_clang_arc_attachedcall}) &&
3025          "Cannot lower invokes with arbitrary operand bundles yet!");
3026 
3027   const Value *Callee(I.getCalledOperand());
3028   const Function *Fn = dyn_cast<Function>(Callee);
3029   if (isa<InlineAsm>(Callee))
3030     visitInlineAsm(I, EHPadBB);
3031   else if (Fn && Fn->isIntrinsic()) {
3032     switch (Fn->getIntrinsicID()) {
3033     default:
3034       llvm_unreachable("Cannot invoke this intrinsic");
3035     case Intrinsic::donothing:
3036       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
3037     case Intrinsic::seh_try_begin:
3038     case Intrinsic::seh_scope_begin:
3039     case Intrinsic::seh_try_end:
3040     case Intrinsic::seh_scope_end:
3041       if (EHPadMBB)
3042           // a block referenced by EH table
3043           // so dtor-funclet not removed by opts
3044           EHPadMBB->setMachineBlockAddressTaken();
3045       break;
3046     case Intrinsic::experimental_patchpoint_void:
3047     case Intrinsic::experimental_patchpoint_i64:
3048       visitPatchpoint(I, EHPadBB);
3049       break;
3050     case Intrinsic::experimental_gc_statepoint:
3051       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
3052       break;
3053     case Intrinsic::wasm_rethrow: {
3054       // This is usually done in visitTargetIntrinsic, but this intrinsic is
3055       // special because it can be invoked, so we manually lower it to a DAG
3056       // node here.
3057       SmallVector<SDValue, 8> Ops;
3058       Ops.push_back(getRoot()); // inchain
3059       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3060       Ops.push_back(
3061           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
3062                                 TLI.getPointerTy(DAG.getDataLayout())));
3063       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3064       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3065       break;
3066     }
3067     }
3068   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
3069     // Currently we do not lower any intrinsic calls with deopt operand bundles.
3070     // Eventually we will support lowering the @llvm.experimental.deoptimize
3071     // intrinsic, and right now there are no plans to support other intrinsics
3072     // with deopt state.
3073     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
3074   } else {
3075     LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
3076   }
3077 
3078   // If the value of the invoke is used outside of its defining block, make it
3079   // available as a virtual register.
3080   // We already took care of the exported value for the statepoint instruction
3081   // during call to the LowerStatepoint.
3082   if (!isa<GCStatepointInst>(I)) {
3083     CopyToExportRegsIfNeeded(&I);
3084   }
3085 
3086   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
3087   BranchProbabilityInfo *BPI = FuncInfo.BPI;
3088   BranchProbability EHPadBBProb =
3089       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3090           : BranchProbability::getZero();
3091   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
3092 
3093   // Update successor info.
3094   addSuccessorWithProb(InvokeMBB, Return);
3095   for (auto &UnwindDest : UnwindDests) {
3096     UnwindDest.first->setIsEHPad();
3097     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3098   }
3099   InvokeMBB->normalizeSuccProbs();
3100 
3101   // Drop into normal successor.
3102   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
3103                           DAG.getBasicBlock(Return)));
3104 }
3105 
3106 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3107   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3108 
3109   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3110   // have to do anything here to lower funclet bundles.
3111   assert(!I.hasOperandBundlesOtherThan(
3112              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
3113          "Cannot lower callbrs with arbitrary operand bundles yet!");
3114 
3115   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
3116   visitInlineAsm(I);
3117   CopyToExportRegsIfNeeded(&I);
3118 
3119   // Retrieve successors.
3120   SmallPtrSet<BasicBlock *, 8> Dests;
3121   Dests.insert(I.getDefaultDest());
3122   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
3123 
3124   // Update successor info.
3125   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3126   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
3127     BasicBlock *Dest = I.getIndirectDest(i);
3128     MachineBasicBlock *Target = FuncInfo.MBBMap[Dest];
3129     Target->setIsInlineAsmBrIndirectTarget();
3130     Target->setMachineBlockAddressTaken();
3131     Target->setLabelMustBeEmitted();
3132     // Don't add duplicate machine successors.
3133     if (Dests.insert(Dest).second)
3134       addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3135   }
3136   CallBrMBB->normalizeSuccProbs();
3137 
3138   // Drop into default successor.
3139   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3140                           MVT::Other, getControlRoot(),
3141                           DAG.getBasicBlock(Return)));
3142 }
3143 
3144 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3145   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3146 }
3147 
3148 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3149   assert(FuncInfo.MBB->isEHPad() &&
3150          "Call to landingpad not in landing pad!");
3151 
3152   // If there aren't registers to copy the values into (e.g., during SjLj
3153   // exceptions), then don't bother to create these DAG nodes.
3154   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3155   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3156   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3157       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3158     return;
3159 
3160   // If landingpad's return type is token type, we don't create DAG nodes
3161   // for its exception pointer and selector value. The extraction of exception
3162   // pointer or selector value from token type landingpads is not currently
3163   // supported.
3164   if (LP.getType()->isTokenTy())
3165     return;
3166 
3167   SmallVector<EVT, 2> ValueVTs;
3168   SDLoc dl = getCurSDLoc();
3169   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3170   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3171 
3172   // Get the two live-in registers as SDValues. The physregs have already been
3173   // copied into virtual registers.
3174   SDValue Ops[2];
3175   if (FuncInfo.ExceptionPointerVirtReg) {
3176     Ops[0] = DAG.getZExtOrTrunc(
3177         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3178                            FuncInfo.ExceptionPointerVirtReg,
3179                            TLI.getPointerTy(DAG.getDataLayout())),
3180         dl, ValueVTs[0]);
3181   } else {
3182     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3183   }
3184   Ops[1] = DAG.getZExtOrTrunc(
3185       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3186                          FuncInfo.ExceptionSelectorVirtReg,
3187                          TLI.getPointerTy(DAG.getDataLayout())),
3188       dl, ValueVTs[1]);
3189 
3190   // Merge into one.
3191   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3192                             DAG.getVTList(ValueVTs), Ops);
3193   setValue(&LP, Res);
3194 }
3195 
3196 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3197                                            MachineBasicBlock *Last) {
3198   // Update JTCases.
3199   for (JumpTableBlock &JTB : SL->JTCases)
3200     if (JTB.first.HeaderBB == First)
3201       JTB.first.HeaderBB = Last;
3202 
3203   // Update BitTestCases.
3204   for (BitTestBlock &BTB : SL->BitTestCases)
3205     if (BTB.Parent == First)
3206       BTB.Parent = Last;
3207 }
3208 
3209 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3210   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3211 
3212   // Update machine-CFG edges with unique successors.
3213   SmallSet<BasicBlock*, 32> Done;
3214   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3215     BasicBlock *BB = I.getSuccessor(i);
3216     bool Inserted = Done.insert(BB).second;
3217     if (!Inserted)
3218         continue;
3219 
3220     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
3221     addSuccessorWithProb(IndirectBrMBB, Succ);
3222   }
3223   IndirectBrMBB->normalizeSuccProbs();
3224 
3225   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3226                           MVT::Other, getControlRoot(),
3227                           getValue(I.getAddress())));
3228 }
3229 
3230 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3231   if (!DAG.getTarget().Options.TrapUnreachable)
3232     return;
3233 
3234   // We may be able to ignore unreachable behind a noreturn call.
3235   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
3236     if (const CallInst *Call = dyn_cast_or_null<CallInst>(I.getPrevNode())) {
3237       if (Call->doesNotReturn())
3238         return;
3239     }
3240   }
3241 
3242   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3243 }
3244 
3245 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3246   SDNodeFlags Flags;
3247   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3248     Flags.copyFMF(*FPOp);
3249 
3250   SDValue Op = getValue(I.getOperand(0));
3251   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3252                                     Op, Flags);
3253   setValue(&I, UnNodeValue);
3254 }
3255 
3256 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3257   SDNodeFlags Flags;
3258   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3259     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3260     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3261   }
3262   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3263     Flags.setExact(ExactOp->isExact());
3264   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3265     Flags.copyFMF(*FPOp);
3266 
3267   SDValue Op1 = getValue(I.getOperand(0));
3268   SDValue Op2 = getValue(I.getOperand(1));
3269   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3270                                      Op1, Op2, Flags);
3271   setValue(&I, BinNodeValue);
3272 }
3273 
3274 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3275   SDValue Op1 = getValue(I.getOperand(0));
3276   SDValue Op2 = getValue(I.getOperand(1));
3277 
3278   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3279       Op1.getValueType(), DAG.getDataLayout());
3280 
3281   // Coerce the shift amount to the right type if we can. This exposes the
3282   // truncate or zext to optimization early.
3283   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3284     assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) &&
3285            "Unexpected shift type");
3286     Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3287   }
3288 
3289   bool nuw = false;
3290   bool nsw = false;
3291   bool exact = false;
3292 
3293   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3294 
3295     if (const OverflowingBinaryOperator *OFBinOp =
3296             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3297       nuw = OFBinOp->hasNoUnsignedWrap();
3298       nsw = OFBinOp->hasNoSignedWrap();
3299     }
3300     if (const PossiblyExactOperator *ExactOp =
3301             dyn_cast<const PossiblyExactOperator>(&I))
3302       exact = ExactOp->isExact();
3303   }
3304   SDNodeFlags Flags;
3305   Flags.setExact(exact);
3306   Flags.setNoSignedWrap(nsw);
3307   Flags.setNoUnsignedWrap(nuw);
3308   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3309                             Flags);
3310   setValue(&I, Res);
3311 }
3312 
3313 void SelectionDAGBuilder::visitSDiv(const User &I) {
3314   SDValue Op1 = getValue(I.getOperand(0));
3315   SDValue Op2 = getValue(I.getOperand(1));
3316 
3317   SDNodeFlags Flags;
3318   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3319                  cast<PossiblyExactOperator>(&I)->isExact());
3320   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3321                            Op2, Flags));
3322 }
3323 
3324 void SelectionDAGBuilder::visitICmp(const User &I) {
3325   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3326   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3327     predicate = IC->getPredicate();
3328   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3329     predicate = ICmpInst::Predicate(IC->getPredicate());
3330   SDValue Op1 = getValue(I.getOperand(0));
3331   SDValue Op2 = getValue(I.getOperand(1));
3332   ISD::CondCode Opcode = getICmpCondCode(predicate);
3333 
3334   auto &TLI = DAG.getTargetLoweringInfo();
3335   EVT MemVT =
3336       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3337 
3338   // If a pointer's DAG type is larger than its memory type then the DAG values
3339   // are zero-extended. This breaks signed comparisons so truncate back to the
3340   // underlying type before doing the compare.
3341   if (Op1.getValueType() != MemVT) {
3342     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3343     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3344   }
3345 
3346   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3347                                                         I.getType());
3348   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3349 }
3350 
3351 void SelectionDAGBuilder::visitFCmp(const User &I) {
3352   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3353   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3354     predicate = FC->getPredicate();
3355   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3356     predicate = FCmpInst::Predicate(FC->getPredicate());
3357   SDValue Op1 = getValue(I.getOperand(0));
3358   SDValue Op2 = getValue(I.getOperand(1));
3359 
3360   ISD::CondCode Condition = getFCmpCondCode(predicate);
3361   auto *FPMO = cast<FPMathOperator>(&I);
3362   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3363     Condition = getFCmpCodeWithoutNaN(Condition);
3364 
3365   SDNodeFlags Flags;
3366   Flags.copyFMF(*FPMO);
3367   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3368 
3369   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3370                                                         I.getType());
3371   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3372 }
3373 
3374 // Check if the condition of the select has one use or two users that are both
3375 // selects with the same condition.
3376 static bool hasOnlySelectUsers(const Value *Cond) {
3377   return llvm::all_of(Cond->users(), [](const Value *V) {
3378     return isa<SelectInst>(V);
3379   });
3380 }
3381 
3382 void SelectionDAGBuilder::visitSelect(const User &I) {
3383   SmallVector<EVT, 4> ValueVTs;
3384   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3385                   ValueVTs);
3386   unsigned NumValues = ValueVTs.size();
3387   if (NumValues == 0) return;
3388 
3389   SmallVector<SDValue, 4> Values(NumValues);
3390   SDValue Cond     = getValue(I.getOperand(0));
3391   SDValue LHSVal   = getValue(I.getOperand(1));
3392   SDValue RHSVal   = getValue(I.getOperand(2));
3393   SmallVector<SDValue, 1> BaseOps(1, Cond);
3394   ISD::NodeType OpCode =
3395       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3396 
3397   bool IsUnaryAbs = false;
3398   bool Negate = false;
3399 
3400   SDNodeFlags Flags;
3401   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3402     Flags.copyFMF(*FPOp);
3403 
3404   Flags.setUnpredictable(
3405       cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable));
3406 
3407   // Min/max matching is only viable if all output VTs are the same.
3408   if (all_equal(ValueVTs)) {
3409     EVT VT = ValueVTs[0];
3410     LLVMContext &Ctx = *DAG.getContext();
3411     auto &TLI = DAG.getTargetLoweringInfo();
3412 
3413     // We care about the legality of the operation after it has been type
3414     // legalized.
3415     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3416       VT = TLI.getTypeToTransformTo(Ctx, VT);
3417 
3418     // If the vselect is legal, assume we want to leave this as a vector setcc +
3419     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3420     // min/max is legal on the scalar type.
3421     bool UseScalarMinMax = VT.isVector() &&
3422       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3423 
3424     // ValueTracking's select pattern matching does not account for -0.0,
3425     // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that
3426     // -0.0 is less than +0.0.
3427     Value *LHS, *RHS;
3428     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3429     ISD::NodeType Opc = ISD::DELETED_NODE;
3430     switch (SPR.Flavor) {
3431     case SPF_UMAX:    Opc = ISD::UMAX; break;
3432     case SPF_UMIN:    Opc = ISD::UMIN; break;
3433     case SPF_SMAX:    Opc = ISD::SMAX; break;
3434     case SPF_SMIN:    Opc = ISD::SMIN; break;
3435     case SPF_FMINNUM:
3436       switch (SPR.NaNBehavior) {
3437       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3438       case SPNB_RETURNS_NAN: break;
3439       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3440       case SPNB_RETURNS_ANY:
3441         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) ||
3442             (UseScalarMinMax &&
3443              TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType())))
3444           Opc = ISD::FMINNUM;
3445         break;
3446       }
3447       break;
3448     case SPF_FMAXNUM:
3449       switch (SPR.NaNBehavior) {
3450       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3451       case SPNB_RETURNS_NAN: break;
3452       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3453       case SPNB_RETURNS_ANY:
3454         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) ||
3455             (UseScalarMinMax &&
3456              TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType())))
3457           Opc = ISD::FMAXNUM;
3458         break;
3459       }
3460       break;
3461     case SPF_NABS:
3462       Negate = true;
3463       [[fallthrough]];
3464     case SPF_ABS:
3465       IsUnaryAbs = true;
3466       Opc = ISD::ABS;
3467       break;
3468     default: break;
3469     }
3470 
3471     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3472         (TLI.isOperationLegalOrCustomOrPromote(Opc, VT) ||
3473          (UseScalarMinMax &&
3474           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3475         // If the underlying comparison instruction is used by any other
3476         // instruction, the consumed instructions won't be destroyed, so it is
3477         // not profitable to convert to a min/max.
3478         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3479       OpCode = Opc;
3480       LHSVal = getValue(LHS);
3481       RHSVal = getValue(RHS);
3482       BaseOps.clear();
3483     }
3484 
3485     if (IsUnaryAbs) {
3486       OpCode = Opc;
3487       LHSVal = getValue(LHS);
3488       BaseOps.clear();
3489     }
3490   }
3491 
3492   if (IsUnaryAbs) {
3493     for (unsigned i = 0; i != NumValues; ++i) {
3494       SDLoc dl = getCurSDLoc();
3495       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3496       Values[i] =
3497           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3498       if (Negate)
3499         Values[i] = DAG.getNegative(Values[i], dl, VT);
3500     }
3501   } else {
3502     for (unsigned i = 0; i != NumValues; ++i) {
3503       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3504       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3505       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3506       Values[i] = DAG.getNode(
3507           OpCode, getCurSDLoc(),
3508           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3509     }
3510   }
3511 
3512   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3513                            DAG.getVTList(ValueVTs), Values));
3514 }
3515 
3516 void SelectionDAGBuilder::visitTrunc(const User &I) {
3517   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3518   SDValue N = getValue(I.getOperand(0));
3519   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3520                                                         I.getType());
3521   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3522 }
3523 
3524 void SelectionDAGBuilder::visitZExt(const User &I) {
3525   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3526   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3527   SDValue N = getValue(I.getOperand(0));
3528   auto &TLI = DAG.getTargetLoweringInfo();
3529   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3530 
3531   SDNodeFlags Flags;
3532   if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
3533     Flags.setNonNeg(PNI->hasNonNeg());
3534 
3535   // Eagerly use nonneg information to canonicalize towards sign_extend if
3536   // that is the target's preference.
3537   // TODO: Let the target do this later.
3538   if (Flags.hasNonNeg() &&
3539       TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) {
3540     setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3541     return;
3542   }
3543 
3544   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags));
3545 }
3546 
3547 void SelectionDAGBuilder::visitSExt(const User &I) {
3548   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3549   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3550   SDValue N = getValue(I.getOperand(0));
3551   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3552                                                         I.getType());
3553   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3554 }
3555 
3556 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3557   // FPTrunc is never a no-op cast, no need to check
3558   SDValue N = getValue(I.getOperand(0));
3559   SDLoc dl = getCurSDLoc();
3560   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3561   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3562   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3563                            DAG.getTargetConstant(
3564                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3565 }
3566 
3567 void SelectionDAGBuilder::visitFPExt(const User &I) {
3568   // FPExt is never a no-op cast, no need to check
3569   SDValue N = getValue(I.getOperand(0));
3570   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3571                                                         I.getType());
3572   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3573 }
3574 
3575 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3576   // FPToUI is never a no-op cast, no need to check
3577   SDValue N = getValue(I.getOperand(0));
3578   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3579                                                         I.getType());
3580   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3581 }
3582 
3583 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3584   // FPToSI is never a no-op cast, no need to check
3585   SDValue N = getValue(I.getOperand(0));
3586   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3587                                                         I.getType());
3588   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3589 }
3590 
3591 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3592   // UIToFP is never a no-op cast, no need to check
3593   SDValue N = getValue(I.getOperand(0));
3594   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3595                                                         I.getType());
3596   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3597 }
3598 
3599 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3600   // SIToFP is never a no-op cast, no need to check
3601   SDValue N = getValue(I.getOperand(0));
3602   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3603                                                         I.getType());
3604   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3605 }
3606 
3607 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3608   // What to do depends on the size of the integer and the size of the pointer.
3609   // We can either truncate, zero extend, or no-op, accordingly.
3610   SDValue N = getValue(I.getOperand(0));
3611   auto &TLI = DAG.getTargetLoweringInfo();
3612   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3613                                                         I.getType());
3614   EVT PtrMemVT =
3615       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3616   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3617   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3618   setValue(&I, N);
3619 }
3620 
3621 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3622   // What to do depends on the size of the integer and the size of the pointer.
3623   // We can either truncate, zero extend, or no-op, accordingly.
3624   SDValue N = getValue(I.getOperand(0));
3625   auto &TLI = DAG.getTargetLoweringInfo();
3626   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3627   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3628   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3629   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3630   setValue(&I, N);
3631 }
3632 
3633 void SelectionDAGBuilder::visitBitCast(const User &I) {
3634   SDValue N = getValue(I.getOperand(0));
3635   SDLoc dl = getCurSDLoc();
3636   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3637                                                         I.getType());
3638 
3639   // BitCast assures us that source and destination are the same size so this is
3640   // either a BITCAST or a no-op.
3641   if (DestVT != N.getValueType())
3642     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3643                              DestVT, N)); // convert types.
3644   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3645   // might fold any kind of constant expression to an integer constant and that
3646   // is not what we are looking for. Only recognize a bitcast of a genuine
3647   // constant integer as an opaque constant.
3648   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3649     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3650                                  /*isOpaque*/true));
3651   else
3652     setValue(&I, N);            // noop cast.
3653 }
3654 
3655 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3656   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3657   const Value *SV = I.getOperand(0);
3658   SDValue N = getValue(SV);
3659   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3660 
3661   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3662   unsigned DestAS = I.getType()->getPointerAddressSpace();
3663 
3664   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3665     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3666 
3667   setValue(&I, N);
3668 }
3669 
3670 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3671   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3672   SDValue InVec = getValue(I.getOperand(0));
3673   SDValue InVal = getValue(I.getOperand(1));
3674   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3675                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3676   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3677                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3678                            InVec, InVal, InIdx));
3679 }
3680 
3681 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3682   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3683   SDValue InVec = getValue(I.getOperand(0));
3684   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3685                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3686   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3687                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3688                            InVec, InIdx));
3689 }
3690 
3691 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3692   SDValue Src1 = getValue(I.getOperand(0));
3693   SDValue Src2 = getValue(I.getOperand(1));
3694   ArrayRef<int> Mask;
3695   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3696     Mask = SVI->getShuffleMask();
3697   else
3698     Mask = cast<ConstantExpr>(I).getShuffleMask();
3699   SDLoc DL = getCurSDLoc();
3700   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3701   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3702   EVT SrcVT = Src1.getValueType();
3703 
3704   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3705       VT.isScalableVector()) {
3706     // Canonical splat form of first element of first input vector.
3707     SDValue FirstElt =
3708         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3709                     DAG.getVectorIdxConstant(0, DL));
3710     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3711     return;
3712   }
3713 
3714   // For now, we only handle splats for scalable vectors.
3715   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3716   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3717   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3718 
3719   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3720   unsigned MaskNumElts = Mask.size();
3721 
3722   if (SrcNumElts == MaskNumElts) {
3723     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3724     return;
3725   }
3726 
3727   // Normalize the shuffle vector since mask and vector length don't match.
3728   if (SrcNumElts < MaskNumElts) {
3729     // Mask is longer than the source vectors. We can use concatenate vector to
3730     // make the mask and vectors lengths match.
3731 
3732     if (MaskNumElts % SrcNumElts == 0) {
3733       // Mask length is a multiple of the source vector length.
3734       // Check if the shuffle is some kind of concatenation of the input
3735       // vectors.
3736       unsigned NumConcat = MaskNumElts / SrcNumElts;
3737       bool IsConcat = true;
3738       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3739       for (unsigned i = 0; i != MaskNumElts; ++i) {
3740         int Idx = Mask[i];
3741         if (Idx < 0)
3742           continue;
3743         // Ensure the indices in each SrcVT sized piece are sequential and that
3744         // the same source is used for the whole piece.
3745         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3746             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3747              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3748           IsConcat = false;
3749           break;
3750         }
3751         // Remember which source this index came from.
3752         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3753       }
3754 
3755       // The shuffle is concatenating multiple vectors together. Just emit
3756       // a CONCAT_VECTORS operation.
3757       if (IsConcat) {
3758         SmallVector<SDValue, 8> ConcatOps;
3759         for (auto Src : ConcatSrcs) {
3760           if (Src < 0)
3761             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3762           else if (Src == 0)
3763             ConcatOps.push_back(Src1);
3764           else
3765             ConcatOps.push_back(Src2);
3766         }
3767         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3768         return;
3769       }
3770     }
3771 
3772     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3773     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3774     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3775                                     PaddedMaskNumElts);
3776 
3777     // Pad both vectors with undefs to make them the same length as the mask.
3778     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3779 
3780     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3781     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3782     MOps1[0] = Src1;
3783     MOps2[0] = Src2;
3784 
3785     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3786     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3787 
3788     // Readjust mask for new input vector length.
3789     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3790     for (unsigned i = 0; i != MaskNumElts; ++i) {
3791       int Idx = Mask[i];
3792       if (Idx >= (int)SrcNumElts)
3793         Idx -= SrcNumElts - PaddedMaskNumElts;
3794       MappedOps[i] = Idx;
3795     }
3796 
3797     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3798 
3799     // If the concatenated vector was padded, extract a subvector with the
3800     // correct number of elements.
3801     if (MaskNumElts != PaddedMaskNumElts)
3802       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3803                            DAG.getVectorIdxConstant(0, DL));
3804 
3805     setValue(&I, Result);
3806     return;
3807   }
3808 
3809   if (SrcNumElts > MaskNumElts) {
3810     // Analyze the access pattern of the vector to see if we can extract
3811     // two subvectors and do the shuffle.
3812     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3813     bool CanExtract = true;
3814     for (int Idx : Mask) {
3815       unsigned Input = 0;
3816       if (Idx < 0)
3817         continue;
3818 
3819       if (Idx >= (int)SrcNumElts) {
3820         Input = 1;
3821         Idx -= SrcNumElts;
3822       }
3823 
3824       // If all the indices come from the same MaskNumElts sized portion of
3825       // the sources we can use extract. Also make sure the extract wouldn't
3826       // extract past the end of the source.
3827       int NewStartIdx = alignDown(Idx, MaskNumElts);
3828       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3829           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3830         CanExtract = false;
3831       // Make sure we always update StartIdx as we use it to track if all
3832       // elements are undef.
3833       StartIdx[Input] = NewStartIdx;
3834     }
3835 
3836     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3837       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3838       return;
3839     }
3840     if (CanExtract) {
3841       // Extract appropriate subvector and generate a vector shuffle
3842       for (unsigned Input = 0; Input < 2; ++Input) {
3843         SDValue &Src = Input == 0 ? Src1 : Src2;
3844         if (StartIdx[Input] < 0)
3845           Src = DAG.getUNDEF(VT);
3846         else {
3847           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3848                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3849         }
3850       }
3851 
3852       // Calculate new mask.
3853       SmallVector<int, 8> MappedOps(Mask);
3854       for (int &Idx : MappedOps) {
3855         if (Idx >= (int)SrcNumElts)
3856           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3857         else if (Idx >= 0)
3858           Idx -= StartIdx[0];
3859       }
3860 
3861       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3862       return;
3863     }
3864   }
3865 
3866   // We can't use either concat vectors or extract subvectors so fall back to
3867   // replacing the shuffle with extract and build vector.
3868   // to insert and build vector.
3869   EVT EltVT = VT.getVectorElementType();
3870   SmallVector<SDValue,8> Ops;
3871   for (int Idx : Mask) {
3872     SDValue Res;
3873 
3874     if (Idx < 0) {
3875       Res = DAG.getUNDEF(EltVT);
3876     } else {
3877       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3878       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3879 
3880       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3881                         DAG.getVectorIdxConstant(Idx, DL));
3882     }
3883 
3884     Ops.push_back(Res);
3885   }
3886 
3887   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3888 }
3889 
3890 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
3891   ArrayRef<unsigned> Indices = I.getIndices();
3892   const Value *Op0 = I.getOperand(0);
3893   const Value *Op1 = I.getOperand(1);
3894   Type *AggTy = I.getType();
3895   Type *ValTy = Op1->getType();
3896   bool IntoUndef = isa<UndefValue>(Op0);
3897   bool FromUndef = isa<UndefValue>(Op1);
3898 
3899   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3900 
3901   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3902   SmallVector<EVT, 4> AggValueVTs;
3903   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3904   SmallVector<EVT, 4> ValValueVTs;
3905   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3906 
3907   unsigned NumAggValues = AggValueVTs.size();
3908   unsigned NumValValues = ValValueVTs.size();
3909   SmallVector<SDValue, 4> Values(NumAggValues);
3910 
3911   // Ignore an insertvalue that produces an empty object
3912   if (!NumAggValues) {
3913     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3914     return;
3915   }
3916 
3917   SDValue Agg = getValue(Op0);
3918   unsigned i = 0;
3919   // Copy the beginning value(s) from the original aggregate.
3920   for (; i != LinearIndex; ++i)
3921     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3922                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3923   // Copy values from the inserted value(s).
3924   if (NumValValues) {
3925     SDValue Val = getValue(Op1);
3926     for (; i != LinearIndex + NumValValues; ++i)
3927       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3928                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3929   }
3930   // Copy remaining value(s) from the original aggregate.
3931   for (; i != NumAggValues; ++i)
3932     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3933                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3934 
3935   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3936                            DAG.getVTList(AggValueVTs), Values));
3937 }
3938 
3939 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
3940   ArrayRef<unsigned> Indices = I.getIndices();
3941   const Value *Op0 = I.getOperand(0);
3942   Type *AggTy = Op0->getType();
3943   Type *ValTy = I.getType();
3944   bool OutOfUndef = isa<UndefValue>(Op0);
3945 
3946   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3947 
3948   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3949   SmallVector<EVT, 4> ValValueVTs;
3950   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3951 
3952   unsigned NumValValues = ValValueVTs.size();
3953 
3954   // Ignore a extractvalue that produces an empty object
3955   if (!NumValValues) {
3956     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3957     return;
3958   }
3959 
3960   SmallVector<SDValue, 4> Values(NumValValues);
3961 
3962   SDValue Agg = getValue(Op0);
3963   // Copy out the selected value(s).
3964   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3965     Values[i - LinearIndex] =
3966       OutOfUndef ?
3967         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3968         SDValue(Agg.getNode(), Agg.getResNo() + i);
3969 
3970   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3971                            DAG.getVTList(ValValueVTs), Values));
3972 }
3973 
3974 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3975   Value *Op0 = I.getOperand(0);
3976   // Note that the pointer operand may be a vector of pointers. Take the scalar
3977   // element which holds a pointer.
3978   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3979   SDValue N = getValue(Op0);
3980   SDLoc dl = getCurSDLoc();
3981   auto &TLI = DAG.getTargetLoweringInfo();
3982 
3983   // Normalize Vector GEP - all scalar operands should be converted to the
3984   // splat vector.
3985   bool IsVectorGEP = I.getType()->isVectorTy();
3986   ElementCount VectorElementCount =
3987       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3988                   : ElementCount::getFixed(0);
3989 
3990   if (IsVectorGEP && !N.getValueType().isVector()) {
3991     LLVMContext &Context = *DAG.getContext();
3992     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3993     N = DAG.getSplat(VT, dl, N);
3994   }
3995 
3996   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3997        GTI != E; ++GTI) {
3998     const Value *Idx = GTI.getOperand();
3999     if (StructType *StTy = GTI.getStructTypeOrNull()) {
4000       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
4001       if (Field) {
4002         // N = N + Offset
4003         uint64_t Offset =
4004             DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
4005 
4006         // In an inbounds GEP with an offset that is nonnegative even when
4007         // interpreted as signed, assume there is no unsigned overflow.
4008         SDNodeFlags Flags;
4009         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
4010           Flags.setNoUnsignedWrap(true);
4011 
4012         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
4013                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
4014       }
4015     } else {
4016       // IdxSize is the width of the arithmetic according to IR semantics.
4017       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
4018       // (and fix up the result later).
4019       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
4020       MVT IdxTy = MVT::getIntegerVT(IdxSize);
4021       TypeSize ElementSize =
4022           DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType());
4023       // We intentionally mask away the high bits here; ElementSize may not
4024       // fit in IdxTy.
4025       APInt ElementMul(IdxSize, ElementSize.getKnownMinValue());
4026       bool ElementScalable = ElementSize.isScalable();
4027 
4028       // If this is a scalar constant or a splat vector of constants,
4029       // handle it quickly.
4030       const auto *C = dyn_cast<Constant>(Idx);
4031       if (C && isa<VectorType>(C->getType()))
4032         C = C->getSplatValue();
4033 
4034       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
4035       if (CI && CI->isZero())
4036         continue;
4037       if (CI && !ElementScalable) {
4038         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
4039         LLVMContext &Context = *DAG.getContext();
4040         SDValue OffsVal;
4041         if (IsVectorGEP)
4042           OffsVal = DAG.getConstant(
4043               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
4044         else
4045           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
4046 
4047         // In an inbounds GEP with an offset that is nonnegative even when
4048         // interpreted as signed, assume there is no unsigned overflow.
4049         SDNodeFlags Flags;
4050         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
4051           Flags.setNoUnsignedWrap(true);
4052 
4053         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
4054 
4055         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
4056         continue;
4057       }
4058 
4059       // N = N + Idx * ElementMul;
4060       SDValue IdxN = getValue(Idx);
4061 
4062       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
4063         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
4064                                   VectorElementCount);
4065         IdxN = DAG.getSplat(VT, dl, IdxN);
4066       }
4067 
4068       // If the index is smaller or larger than intptr_t, truncate or extend
4069       // it.
4070       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
4071 
4072       if (ElementScalable) {
4073         EVT VScaleTy = N.getValueType().getScalarType();
4074         SDValue VScale = DAG.getNode(
4075             ISD::VSCALE, dl, VScaleTy,
4076             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
4077         if (IsVectorGEP)
4078           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
4079         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
4080       } else {
4081         // If this is a multiply by a power of two, turn it into a shl
4082         // immediately.  This is a very common case.
4083         if (ElementMul != 1) {
4084           if (ElementMul.isPowerOf2()) {
4085             unsigned Amt = ElementMul.logBase2();
4086             IdxN = DAG.getNode(ISD::SHL, dl,
4087                                N.getValueType(), IdxN,
4088                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
4089           } else {
4090             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
4091                                             IdxN.getValueType());
4092             IdxN = DAG.getNode(ISD::MUL, dl,
4093                                N.getValueType(), IdxN, Scale);
4094           }
4095         }
4096       }
4097 
4098       N = DAG.getNode(ISD::ADD, dl,
4099                       N.getValueType(), N, IdxN);
4100     }
4101   }
4102 
4103   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4104   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4105   if (IsVectorGEP) {
4106     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4107     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4108   }
4109 
4110   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4111     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4112 
4113   setValue(&I, N);
4114 }
4115 
4116 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4117   // If this is a fixed sized alloca in the entry block of the function,
4118   // allocate it statically on the stack.
4119   if (FuncInfo.StaticAllocaMap.count(&I))
4120     return;   // getValue will auto-populate this.
4121 
4122   SDLoc dl = getCurSDLoc();
4123   Type *Ty = I.getAllocatedType();
4124   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4125   auto &DL = DAG.getDataLayout();
4126   TypeSize TySize = DL.getTypeAllocSize(Ty);
4127   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4128 
4129   SDValue AllocSize = getValue(I.getArraySize());
4130 
4131   EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace());
4132   if (AllocSize.getValueType() != IntPtr)
4133     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4134 
4135   if (TySize.isScalable())
4136     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4137                             DAG.getVScale(dl, IntPtr,
4138                                           APInt(IntPtr.getScalarSizeInBits(),
4139                                                 TySize.getKnownMinValue())));
4140   else {
4141     SDValue TySizeValue =
4142         DAG.getConstant(TySize.getFixedValue(), dl, MVT::getIntegerVT(64));
4143     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4144                             DAG.getZExtOrTrunc(TySizeValue, dl, IntPtr));
4145   }
4146 
4147   // Handle alignment.  If the requested alignment is less than or equal to
4148   // the stack alignment, ignore it.  If the size is greater than or equal to
4149   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4150   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4151   if (*Alignment <= StackAlign)
4152     Alignment = std::nullopt;
4153 
4154   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4155   // Round the size of the allocation up to the stack alignment size
4156   // by add SA-1 to the size. This doesn't overflow because we're computing
4157   // an address inside an alloca.
4158   SDNodeFlags Flags;
4159   Flags.setNoUnsignedWrap(true);
4160   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4161                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4162 
4163   // Mask out the low bits for alignment purposes.
4164   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4165                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
4166 
4167   SDValue Ops[] = {
4168       getRoot(), AllocSize,
4169       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4170   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4171   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4172   setValue(&I, DSA);
4173   DAG.setRoot(DSA.getValue(1));
4174 
4175   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4176 }
4177 
4178 static const MDNode *getRangeMetadata(const Instruction &I) {
4179   // If !noundef is not present, then !range violation results in a poison
4180   // value rather than immediate undefined behavior. In theory, transferring
4181   // these annotations to SDAG is fine, but in practice there are key SDAG
4182   // transforms that are known not to be poison-safe, such as folding logical
4183   // and/or to bitwise and/or. For now, only transfer !range if !noundef is
4184   // also present.
4185   if (!I.hasMetadata(LLVMContext::MD_noundef))
4186     return nullptr;
4187   return I.getMetadata(LLVMContext::MD_range);
4188 }
4189 
4190 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4191   if (I.isAtomic())
4192     return visitAtomicLoad(I);
4193 
4194   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4195   const Value *SV = I.getOperand(0);
4196   if (TLI.supportSwiftError()) {
4197     // Swifterror values can come from either a function parameter with
4198     // swifterror attribute or an alloca with swifterror attribute.
4199     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4200       if (Arg->hasSwiftErrorAttr())
4201         return visitLoadFromSwiftError(I);
4202     }
4203 
4204     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4205       if (Alloca->isSwiftError())
4206         return visitLoadFromSwiftError(I);
4207     }
4208   }
4209 
4210   SDValue Ptr = getValue(SV);
4211 
4212   Type *Ty = I.getType();
4213   SmallVector<EVT, 4> ValueVTs, MemVTs;
4214   SmallVector<TypeSize, 4> Offsets;
4215   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets, 0);
4216   unsigned NumValues = ValueVTs.size();
4217   if (NumValues == 0)
4218     return;
4219 
4220   Align Alignment = I.getAlign();
4221   AAMDNodes AAInfo = I.getAAMetadata();
4222   const MDNode *Ranges = getRangeMetadata(I);
4223   bool isVolatile = I.isVolatile();
4224   MachineMemOperand::Flags MMOFlags =
4225       TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4226 
4227   SDValue Root;
4228   bool ConstantMemory = false;
4229   if (isVolatile)
4230     // Serialize volatile loads with other side effects.
4231     Root = getRoot();
4232   else if (NumValues > MaxParallelChains)
4233     Root = getMemoryRoot();
4234   else if (AA &&
4235            AA->pointsToConstantMemory(MemoryLocation(
4236                SV,
4237                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4238                AAInfo))) {
4239     // Do not serialize (non-volatile) loads of constant memory with anything.
4240     Root = DAG.getEntryNode();
4241     ConstantMemory = true;
4242     MMOFlags |= MachineMemOperand::MOInvariant;
4243   } else {
4244     // Do not serialize non-volatile loads against each other.
4245     Root = DAG.getRoot();
4246   }
4247 
4248   SDLoc dl = getCurSDLoc();
4249 
4250   if (isVolatile)
4251     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4252 
4253   SmallVector<SDValue, 4> Values(NumValues);
4254   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4255 
4256   unsigned ChainI = 0;
4257   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4258     // Serializing loads here may result in excessive register pressure, and
4259     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4260     // could recover a bit by hoisting nodes upward in the chain by recognizing
4261     // they are side-effect free or do not alias. The optimizer should really
4262     // avoid this case by converting large object/array copies to llvm.memcpy
4263     // (MaxParallelChains should always remain as failsafe).
4264     if (ChainI == MaxParallelChains) {
4265       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4266       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4267                                   ArrayRef(Chains.data(), ChainI));
4268       Root = Chain;
4269       ChainI = 0;
4270     }
4271 
4272     // TODO: MachinePointerInfo only supports a fixed length offset.
4273     MachinePointerInfo PtrInfo =
4274         !Offsets[i].isScalable() || Offsets[i].isZero()
4275             ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue())
4276             : MachinePointerInfo();
4277 
4278     SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4279     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment,
4280                             MMOFlags, AAInfo, Ranges);
4281     Chains[ChainI] = L.getValue(1);
4282 
4283     if (MemVTs[i] != ValueVTs[i])
4284       L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]);
4285 
4286     Values[i] = L;
4287   }
4288 
4289   if (!ConstantMemory) {
4290     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4291                                 ArrayRef(Chains.data(), ChainI));
4292     if (isVolatile)
4293       DAG.setRoot(Chain);
4294     else
4295       PendingLoads.push_back(Chain);
4296   }
4297 
4298   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4299                            DAG.getVTList(ValueVTs), Values));
4300 }
4301 
4302 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4303   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4304          "call visitStoreToSwiftError when backend supports swifterror");
4305 
4306   SmallVector<EVT, 4> ValueVTs;
4307   SmallVector<uint64_t, 4> Offsets;
4308   const Value *SrcV = I.getOperand(0);
4309   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4310                   SrcV->getType(), ValueVTs, &Offsets, 0);
4311   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4312          "expect a single EVT for swifterror");
4313 
4314   SDValue Src = getValue(SrcV);
4315   // Create a virtual register, then update the virtual register.
4316   Register VReg =
4317       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4318   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4319   // Chain can be getRoot or getControlRoot.
4320   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4321                                       SDValue(Src.getNode(), Src.getResNo()));
4322   DAG.setRoot(CopyNode);
4323 }
4324 
4325 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4326   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4327          "call visitLoadFromSwiftError when backend supports swifterror");
4328 
4329   assert(!I.isVolatile() &&
4330          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4331          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4332          "Support volatile, non temporal, invariant for load_from_swift_error");
4333 
4334   const Value *SV = I.getOperand(0);
4335   Type *Ty = I.getType();
4336   assert(
4337       (!AA ||
4338        !AA->pointsToConstantMemory(MemoryLocation(
4339            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4340            I.getAAMetadata()))) &&
4341       "load_from_swift_error should not be constant memory");
4342 
4343   SmallVector<EVT, 4> ValueVTs;
4344   SmallVector<uint64_t, 4> Offsets;
4345   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4346                   ValueVTs, &Offsets, 0);
4347   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4348          "expect a single EVT for swifterror");
4349 
4350   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4351   SDValue L = DAG.getCopyFromReg(
4352       getRoot(), getCurSDLoc(),
4353       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4354 
4355   setValue(&I, L);
4356 }
4357 
4358 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4359   if (I.isAtomic())
4360     return visitAtomicStore(I);
4361 
4362   const Value *SrcV = I.getOperand(0);
4363   const Value *PtrV = I.getOperand(1);
4364 
4365   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4366   if (TLI.supportSwiftError()) {
4367     // Swifterror values can come from either a function parameter with
4368     // swifterror attribute or an alloca with swifterror attribute.
4369     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4370       if (Arg->hasSwiftErrorAttr())
4371         return visitStoreToSwiftError(I);
4372     }
4373 
4374     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4375       if (Alloca->isSwiftError())
4376         return visitStoreToSwiftError(I);
4377     }
4378   }
4379 
4380   SmallVector<EVT, 4> ValueVTs, MemVTs;
4381   SmallVector<TypeSize, 4> Offsets;
4382   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4383                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets, 0);
4384   unsigned NumValues = ValueVTs.size();
4385   if (NumValues == 0)
4386     return;
4387 
4388   // Get the lowered operands. Note that we do this after
4389   // checking if NumResults is zero, because with zero results
4390   // the operands won't have values in the map.
4391   SDValue Src = getValue(SrcV);
4392   SDValue Ptr = getValue(PtrV);
4393 
4394   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4395   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4396   SDLoc dl = getCurSDLoc();
4397   Align Alignment = I.getAlign();
4398   AAMDNodes AAInfo = I.getAAMetadata();
4399 
4400   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4401 
4402   unsigned ChainI = 0;
4403   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4404     // See visitLoad comments.
4405     if (ChainI == MaxParallelChains) {
4406       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4407                                   ArrayRef(Chains.data(), ChainI));
4408       Root = Chain;
4409       ChainI = 0;
4410     }
4411 
4412     // TODO: MachinePointerInfo only supports a fixed length offset.
4413     MachinePointerInfo PtrInfo =
4414         !Offsets[i].isScalable() || Offsets[i].isZero()
4415             ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue())
4416             : MachinePointerInfo();
4417 
4418     SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4419     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4420     if (MemVTs[i] != ValueVTs[i])
4421       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4422     SDValue St =
4423         DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags, AAInfo);
4424     Chains[ChainI] = St;
4425   }
4426 
4427   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4428                                   ArrayRef(Chains.data(), ChainI));
4429   setValue(&I, StoreNode);
4430   DAG.setRoot(StoreNode);
4431 }
4432 
4433 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4434                                            bool IsCompressing) {
4435   SDLoc sdl = getCurSDLoc();
4436 
4437   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4438                                MaybeAlign &Alignment) {
4439     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4440     Src0 = I.getArgOperand(0);
4441     Ptr = I.getArgOperand(1);
4442     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
4443     Mask = I.getArgOperand(3);
4444   };
4445   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4446                                     MaybeAlign &Alignment) {
4447     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4448     Src0 = I.getArgOperand(0);
4449     Ptr = I.getArgOperand(1);
4450     Mask = I.getArgOperand(2);
4451     Alignment = std::nullopt;
4452   };
4453 
4454   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4455   MaybeAlign Alignment;
4456   if (IsCompressing)
4457     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4458   else
4459     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4460 
4461   SDValue Ptr = getValue(PtrOperand);
4462   SDValue Src0 = getValue(Src0Operand);
4463   SDValue Mask = getValue(MaskOperand);
4464   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4465 
4466   EVT VT = Src0.getValueType();
4467   if (!Alignment)
4468     Alignment = DAG.getEVTAlign(VT);
4469 
4470   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4471       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4472       MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata());
4473   SDValue StoreNode =
4474       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4475                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4476   DAG.setRoot(StoreNode);
4477   setValue(&I, StoreNode);
4478 }
4479 
4480 // Get a uniform base for the Gather/Scatter intrinsic.
4481 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4482 // We try to represent it as a base pointer + vector of indices.
4483 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4484 // The first operand of the GEP may be a single pointer or a vector of pointers
4485 // Example:
4486 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4487 //  or
4488 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4489 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4490 //
4491 // When the first GEP operand is a single pointer - it is the uniform base we
4492 // are looking for. If first operand of the GEP is a splat vector - we
4493 // extract the splat value and use it as a uniform base.
4494 // In all other cases the function returns 'false'.
4495 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4496                            ISD::MemIndexType &IndexType, SDValue &Scale,
4497                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB,
4498                            uint64_t ElemSize) {
4499   SelectionDAG& DAG = SDB->DAG;
4500   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4501   const DataLayout &DL = DAG.getDataLayout();
4502 
4503   assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4504 
4505   // Handle splat constant pointer.
4506   if (auto *C = dyn_cast<Constant>(Ptr)) {
4507     C = C->getSplatValue();
4508     if (!C)
4509       return false;
4510 
4511     Base = SDB->getValue(C);
4512 
4513     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4514     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4515     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4516     IndexType = ISD::SIGNED_SCALED;
4517     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4518     return true;
4519   }
4520 
4521   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4522   if (!GEP || GEP->getParent() != CurBB)
4523     return false;
4524 
4525   if (GEP->getNumOperands() != 2)
4526     return false;
4527 
4528   const Value *BasePtr = GEP->getPointerOperand();
4529   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4530 
4531   // Make sure the base is scalar and the index is a vector.
4532   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4533     return false;
4534 
4535   TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
4536   if (ScaleVal.isScalable())
4537     return false;
4538 
4539   // Target may not support the required addressing mode.
4540   if (ScaleVal != 1 &&
4541       !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize))
4542     return false;
4543 
4544   Base = SDB->getValue(BasePtr);
4545   Index = SDB->getValue(IndexVal);
4546   IndexType = ISD::SIGNED_SCALED;
4547 
4548   Scale =
4549       DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4550   return true;
4551 }
4552 
4553 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4554   SDLoc sdl = getCurSDLoc();
4555 
4556   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4557   const Value *Ptr = I.getArgOperand(1);
4558   SDValue Src0 = getValue(I.getArgOperand(0));
4559   SDValue Mask = getValue(I.getArgOperand(3));
4560   EVT VT = Src0.getValueType();
4561   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4562                         ->getMaybeAlignValue()
4563                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4564   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4565 
4566   SDValue Base;
4567   SDValue Index;
4568   ISD::MemIndexType IndexType;
4569   SDValue Scale;
4570   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4571                                     I.getParent(), VT.getScalarStoreSize());
4572 
4573   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4574   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4575       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4576       // TODO: Make MachineMemOperands aware of scalable
4577       // vectors.
4578       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata());
4579   if (!UniformBase) {
4580     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4581     Index = getValue(Ptr);
4582     IndexType = ISD::SIGNED_SCALED;
4583     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4584   }
4585 
4586   EVT IdxVT = Index.getValueType();
4587   EVT EltTy = IdxVT.getVectorElementType();
4588   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4589     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4590     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4591   }
4592 
4593   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4594   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4595                                          Ops, MMO, IndexType, false);
4596   DAG.setRoot(Scatter);
4597   setValue(&I, Scatter);
4598 }
4599 
4600 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4601   SDLoc sdl = getCurSDLoc();
4602 
4603   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4604                               MaybeAlign &Alignment) {
4605     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4606     Ptr = I.getArgOperand(0);
4607     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4608     Mask = I.getArgOperand(2);
4609     Src0 = I.getArgOperand(3);
4610   };
4611   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4612                                  MaybeAlign &Alignment) {
4613     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4614     Ptr = I.getArgOperand(0);
4615     Alignment = std::nullopt;
4616     Mask = I.getArgOperand(1);
4617     Src0 = I.getArgOperand(2);
4618   };
4619 
4620   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4621   MaybeAlign Alignment;
4622   if (IsExpanding)
4623     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4624   else
4625     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4626 
4627   SDValue Ptr = getValue(PtrOperand);
4628   SDValue Src0 = getValue(Src0Operand);
4629   SDValue Mask = getValue(MaskOperand);
4630   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4631 
4632   EVT VT = Src0.getValueType();
4633   if (!Alignment)
4634     Alignment = DAG.getEVTAlign(VT);
4635 
4636   AAMDNodes AAInfo = I.getAAMetadata();
4637   const MDNode *Ranges = getRangeMetadata(I);
4638 
4639   // Do not serialize masked loads of constant memory with anything.
4640   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
4641   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4642 
4643   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4644 
4645   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4646       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4647       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
4648 
4649   SDValue Load =
4650       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4651                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4652   if (AddToChain)
4653     PendingLoads.push_back(Load.getValue(1));
4654   setValue(&I, Load);
4655 }
4656 
4657 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4658   SDLoc sdl = getCurSDLoc();
4659 
4660   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4661   const Value *Ptr = I.getArgOperand(0);
4662   SDValue Src0 = getValue(I.getArgOperand(3));
4663   SDValue Mask = getValue(I.getArgOperand(2));
4664 
4665   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4666   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4667   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4668                         ->getMaybeAlignValue()
4669                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4670 
4671   const MDNode *Ranges = getRangeMetadata(I);
4672 
4673   SDValue Root = DAG.getRoot();
4674   SDValue Base;
4675   SDValue Index;
4676   ISD::MemIndexType IndexType;
4677   SDValue Scale;
4678   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4679                                     I.getParent(), VT.getScalarStoreSize());
4680   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4681   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4682       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4683       // TODO: Make MachineMemOperands aware of scalable
4684       // vectors.
4685       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
4686 
4687   if (!UniformBase) {
4688     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4689     Index = getValue(Ptr);
4690     IndexType = ISD::SIGNED_SCALED;
4691     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4692   }
4693 
4694   EVT IdxVT = Index.getValueType();
4695   EVT EltTy = IdxVT.getVectorElementType();
4696   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4697     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4698     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4699   }
4700 
4701   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4702   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4703                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
4704 
4705   PendingLoads.push_back(Gather.getValue(1));
4706   setValue(&I, Gather);
4707 }
4708 
4709 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4710   SDLoc dl = getCurSDLoc();
4711   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4712   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4713   SyncScope::ID SSID = I.getSyncScopeID();
4714 
4715   SDValue InChain = getRoot();
4716 
4717   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4718   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4719 
4720   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4721   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4722 
4723   MachineFunction &MF = DAG.getMachineFunction();
4724   MachineMemOperand *MMO = MF.getMachineMemOperand(
4725       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4726       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4727       FailureOrdering);
4728 
4729   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4730                                    dl, MemVT, VTs, InChain,
4731                                    getValue(I.getPointerOperand()),
4732                                    getValue(I.getCompareOperand()),
4733                                    getValue(I.getNewValOperand()), MMO);
4734 
4735   SDValue OutChain = L.getValue(2);
4736 
4737   setValue(&I, L);
4738   DAG.setRoot(OutChain);
4739 }
4740 
4741 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4742   SDLoc dl = getCurSDLoc();
4743   ISD::NodeType NT;
4744   switch (I.getOperation()) {
4745   default: llvm_unreachable("Unknown atomicrmw operation");
4746   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4747   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4748   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4749   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4750   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4751   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4752   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4753   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4754   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4755   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4756   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4757   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4758   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4759   case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break;
4760   case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break;
4761   case AtomicRMWInst::UIncWrap:
4762     NT = ISD::ATOMIC_LOAD_UINC_WRAP;
4763     break;
4764   case AtomicRMWInst::UDecWrap:
4765     NT = ISD::ATOMIC_LOAD_UDEC_WRAP;
4766     break;
4767   }
4768   AtomicOrdering Ordering = I.getOrdering();
4769   SyncScope::ID SSID = I.getSyncScopeID();
4770 
4771   SDValue InChain = getRoot();
4772 
4773   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4774   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4775   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4776 
4777   MachineFunction &MF = DAG.getMachineFunction();
4778   MachineMemOperand *MMO = MF.getMachineMemOperand(
4779       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4780       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4781 
4782   SDValue L =
4783     DAG.getAtomic(NT, dl, MemVT, InChain,
4784                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4785                   MMO);
4786 
4787   SDValue OutChain = L.getValue(1);
4788 
4789   setValue(&I, L);
4790   DAG.setRoot(OutChain);
4791 }
4792 
4793 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4794   SDLoc dl = getCurSDLoc();
4795   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4796   SDValue Ops[3];
4797   Ops[0] = getRoot();
4798   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4799                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4800   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4801                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4802   SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
4803   setValue(&I, N);
4804   DAG.setRoot(N);
4805 }
4806 
4807 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4808   SDLoc dl = getCurSDLoc();
4809   AtomicOrdering Order = I.getOrdering();
4810   SyncScope::ID SSID = I.getSyncScopeID();
4811 
4812   SDValue InChain = getRoot();
4813 
4814   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4815   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4816   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4817 
4818   if (!TLI.supportsUnalignedAtomics() &&
4819       I.getAlign().value() < MemVT.getSizeInBits() / 8)
4820     report_fatal_error("Cannot generate unaligned atomic load");
4821 
4822   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4823 
4824   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4825       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4826       I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4827 
4828   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4829 
4830   SDValue Ptr = getValue(I.getPointerOperand());
4831 
4832   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4833     // TODO: Once this is better exercised by tests, it should be merged with
4834     // the normal path for loads to prevent future divergence.
4835     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4836     if (MemVT != VT)
4837       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4838 
4839     setValue(&I, L);
4840     SDValue OutChain = L.getValue(1);
4841     if (!I.isUnordered())
4842       DAG.setRoot(OutChain);
4843     else
4844       PendingLoads.push_back(OutChain);
4845     return;
4846   }
4847 
4848   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4849                             Ptr, MMO);
4850 
4851   SDValue OutChain = L.getValue(1);
4852   if (MemVT != VT)
4853     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4854 
4855   setValue(&I, L);
4856   DAG.setRoot(OutChain);
4857 }
4858 
4859 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4860   SDLoc dl = getCurSDLoc();
4861 
4862   AtomicOrdering Ordering = I.getOrdering();
4863   SyncScope::ID SSID = I.getSyncScopeID();
4864 
4865   SDValue InChain = getRoot();
4866 
4867   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4868   EVT MemVT =
4869       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4870 
4871   if (!TLI.supportsUnalignedAtomics() &&
4872       I.getAlign().value() < MemVT.getSizeInBits() / 8)
4873     report_fatal_error("Cannot generate unaligned atomic store");
4874 
4875   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4876 
4877   MachineFunction &MF = DAG.getMachineFunction();
4878   MachineMemOperand *MMO = MF.getMachineMemOperand(
4879       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4880       I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4881 
4882   SDValue Val = getValue(I.getValueOperand());
4883   if (Val.getValueType() != MemVT)
4884     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4885   SDValue Ptr = getValue(I.getPointerOperand());
4886 
4887   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4888     // TODO: Once this is better exercised by tests, it should be merged with
4889     // the normal path for stores to prevent future divergence.
4890     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4891     setValue(&I, S);
4892     DAG.setRoot(S);
4893     return;
4894   }
4895   SDValue OutChain =
4896       DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO);
4897 
4898   setValue(&I, OutChain);
4899   DAG.setRoot(OutChain);
4900 }
4901 
4902 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4903 /// node.
4904 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4905                                                unsigned Intrinsic) {
4906   // Ignore the callsite's attributes. A specific call site may be marked with
4907   // readnone, but the lowering code will expect the chain based on the
4908   // definition.
4909   const Function *F = I.getCalledFunction();
4910   bool HasChain = !F->doesNotAccessMemory();
4911   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4912 
4913   // Build the operand list.
4914   SmallVector<SDValue, 8> Ops;
4915   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4916     if (OnlyLoad) {
4917       // We don't need to serialize loads against other loads.
4918       Ops.push_back(DAG.getRoot());
4919     } else {
4920       Ops.push_back(getRoot());
4921     }
4922   }
4923 
4924   // Info is set by getTgtMemIntrinsic
4925   TargetLowering::IntrinsicInfo Info;
4926   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4927   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4928                                                DAG.getMachineFunction(),
4929                                                Intrinsic);
4930 
4931   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4932   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4933       Info.opc == ISD::INTRINSIC_W_CHAIN)
4934     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4935                                         TLI.getPointerTy(DAG.getDataLayout())));
4936 
4937   // Add all operands of the call to the operand list.
4938   for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
4939     const Value *Arg = I.getArgOperand(i);
4940     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4941       Ops.push_back(getValue(Arg));
4942       continue;
4943     }
4944 
4945     // Use TargetConstant instead of a regular constant for immarg.
4946     EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
4947     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4948       assert(CI->getBitWidth() <= 64 &&
4949              "large intrinsic immediates not handled");
4950       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4951     } else {
4952       Ops.push_back(
4953           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4954     }
4955   }
4956 
4957   SmallVector<EVT, 4> ValueVTs;
4958   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4959 
4960   if (HasChain)
4961     ValueVTs.push_back(MVT::Other);
4962 
4963   SDVTList VTs = DAG.getVTList(ValueVTs);
4964 
4965   // Propagate fast-math-flags from IR to node(s).
4966   SDNodeFlags Flags;
4967   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
4968     Flags.copyFMF(*FPMO);
4969   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
4970 
4971   // Create the node.
4972   SDValue Result;
4973   // In some cases, custom collection of operands from CallInst I may be needed.
4974   TLI.CollectTargetIntrinsicOperands(I, Ops, DAG);
4975   if (IsTgtIntrinsic) {
4976     // This is target intrinsic that touches memory
4977     //
4978     // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic
4979     //       didn't yield anything useful.
4980     MachinePointerInfo MPI;
4981     if (Info.ptrVal)
4982       MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
4983     else if (Info.fallbackAddressSpace)
4984       MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
4985     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops,
4986                                      Info.memVT, MPI, Info.align, Info.flags,
4987                                      Info.size, I.getAAMetadata());
4988   } else if (!HasChain) {
4989     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4990   } else if (!I.getType()->isVoidTy()) {
4991     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4992   } else {
4993     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4994   }
4995 
4996   if (HasChain) {
4997     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4998     if (OnlyLoad)
4999       PendingLoads.push_back(Chain);
5000     else
5001       DAG.setRoot(Chain);
5002   }
5003 
5004   if (!I.getType()->isVoidTy()) {
5005     if (!isa<VectorType>(I.getType()))
5006       Result = lowerRangeToAssertZExt(DAG, I, Result);
5007 
5008     MaybeAlign Alignment = I.getRetAlign();
5009 
5010     // Insert `assertalign` node if there's an alignment.
5011     if (InsertAssertAlign && Alignment) {
5012       Result =
5013           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
5014     }
5015 
5016     setValue(&I, Result);
5017   }
5018 }
5019 
5020 /// GetSignificand - Get the significand and build it into a floating-point
5021 /// number with exponent of 1:
5022 ///
5023 ///   Op = (Op & 0x007fffff) | 0x3f800000;
5024 ///
5025 /// where Op is the hexadecimal representation of floating point value.
5026 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
5027   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5028                            DAG.getConstant(0x007fffff, dl, MVT::i32));
5029   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
5030                            DAG.getConstant(0x3f800000, dl, MVT::i32));
5031   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
5032 }
5033 
5034 /// GetExponent - Get the exponent:
5035 ///
5036 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
5037 ///
5038 /// where Op is the hexadecimal representation of floating point value.
5039 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
5040                            const TargetLowering &TLI, const SDLoc &dl) {
5041   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5042                            DAG.getConstant(0x7f800000, dl, MVT::i32));
5043   SDValue t1 = DAG.getNode(
5044       ISD::SRL, dl, MVT::i32, t0,
5045       DAG.getConstant(23, dl,
5046                       TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout())));
5047   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
5048                            DAG.getConstant(127, dl, MVT::i32));
5049   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
5050 }
5051 
5052 /// getF32Constant - Get 32-bit floating point constant.
5053 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
5054                               const SDLoc &dl) {
5055   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
5056                            MVT::f32);
5057 }
5058 
5059 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
5060                                        SelectionDAG &DAG) {
5061   // TODO: What fast-math-flags should be set on the floating-point nodes?
5062 
5063   //   IntegerPartOfX = ((int32_t)(t0);
5064   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
5065 
5066   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
5067   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
5068   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
5069 
5070   //   IntegerPartOfX <<= 23;
5071   IntegerPartOfX =
5072       DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
5073                   DAG.getConstant(23, dl,
5074                                   DAG.getTargetLoweringInfo().getShiftAmountTy(
5075                                       MVT::i32, DAG.getDataLayout())));
5076 
5077   SDValue TwoToFractionalPartOfX;
5078   if (LimitFloatPrecision <= 6) {
5079     // For floating-point precision of 6:
5080     //
5081     //   TwoToFractionalPartOfX =
5082     //     0.997535578f +
5083     //       (0.735607626f + 0.252464424f * x) * x;
5084     //
5085     // error 0.0144103317, which is 6 bits
5086     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5087                              getF32Constant(DAG, 0x3e814304, dl));
5088     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5089                              getF32Constant(DAG, 0x3f3c50c8, dl));
5090     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5091     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5092                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
5093   } else if (LimitFloatPrecision <= 12) {
5094     // For floating-point precision of 12:
5095     //
5096     //   TwoToFractionalPartOfX =
5097     //     0.999892986f +
5098     //       (0.696457318f +
5099     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
5100     //
5101     // error 0.000107046256, which is 13 to 14 bits
5102     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5103                              getF32Constant(DAG, 0x3da235e3, dl));
5104     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5105                              getF32Constant(DAG, 0x3e65b8f3, dl));
5106     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5107     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5108                              getF32Constant(DAG, 0x3f324b07, dl));
5109     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5110     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5111                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
5112   } else { // LimitFloatPrecision <= 18
5113     // For floating-point precision of 18:
5114     //
5115     //   TwoToFractionalPartOfX =
5116     //     0.999999982f +
5117     //       (0.693148872f +
5118     //         (0.240227044f +
5119     //           (0.554906021e-1f +
5120     //             (0.961591928e-2f +
5121     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5122     // error 2.47208000*10^(-7), which is better than 18 bits
5123     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5124                              getF32Constant(DAG, 0x3924b03e, dl));
5125     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5126                              getF32Constant(DAG, 0x3ab24b87, dl));
5127     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5128     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5129                              getF32Constant(DAG, 0x3c1d8c17, dl));
5130     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5131     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5132                              getF32Constant(DAG, 0x3d634a1d, dl));
5133     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5134     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5135                              getF32Constant(DAG, 0x3e75fe14, dl));
5136     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5137     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5138                               getF32Constant(DAG, 0x3f317234, dl));
5139     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5140     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5141                                          getF32Constant(DAG, 0x3f800000, dl));
5142   }
5143 
5144   // Add the exponent into the result in integer domain.
5145   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5146   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5147                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5148 }
5149 
5150 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5151 /// limited-precision mode.
5152 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5153                          const TargetLowering &TLI, SDNodeFlags Flags) {
5154   if (Op.getValueType() == MVT::f32 &&
5155       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5156 
5157     // Put the exponent in the right bit position for later addition to the
5158     // final result:
5159     //
5160     // t0 = Op * log2(e)
5161 
5162     // TODO: What fast-math-flags should be set here?
5163     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5164                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5165     return getLimitedPrecisionExp2(t0, dl, DAG);
5166   }
5167 
5168   // No special expansion.
5169   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5170 }
5171 
5172 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5173 /// limited-precision mode.
5174 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5175                          const TargetLowering &TLI, SDNodeFlags Flags) {
5176   // TODO: What fast-math-flags should be set on the floating-point nodes?
5177 
5178   if (Op.getValueType() == MVT::f32 &&
5179       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5180     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5181 
5182     // Scale the exponent by log(2).
5183     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5184     SDValue LogOfExponent =
5185         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5186                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5187 
5188     // Get the significand and build it into a floating-point number with
5189     // exponent of 1.
5190     SDValue X = GetSignificand(DAG, Op1, dl);
5191 
5192     SDValue LogOfMantissa;
5193     if (LimitFloatPrecision <= 6) {
5194       // For floating-point precision of 6:
5195       //
5196       //   LogofMantissa =
5197       //     -1.1609546f +
5198       //       (1.4034025f - 0.23903021f * x) * x;
5199       //
5200       // error 0.0034276066, which is better than 8 bits
5201       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5202                                getF32Constant(DAG, 0xbe74c456, dl));
5203       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5204                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5205       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5206       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5207                                   getF32Constant(DAG, 0x3f949a29, dl));
5208     } else if (LimitFloatPrecision <= 12) {
5209       // For floating-point precision of 12:
5210       //
5211       //   LogOfMantissa =
5212       //     -1.7417939f +
5213       //       (2.8212026f +
5214       //         (-1.4699568f +
5215       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5216       //
5217       // error 0.000061011436, which is 14 bits
5218       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5219                                getF32Constant(DAG, 0xbd67b6d6, dl));
5220       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5221                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5222       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5223       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5224                                getF32Constant(DAG, 0x3fbc278b, dl));
5225       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5226       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5227                                getF32Constant(DAG, 0x40348e95, dl));
5228       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5229       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5230                                   getF32Constant(DAG, 0x3fdef31a, dl));
5231     } else { // LimitFloatPrecision <= 18
5232       // For floating-point precision of 18:
5233       //
5234       //   LogOfMantissa =
5235       //     -2.1072184f +
5236       //       (4.2372794f +
5237       //         (-3.7029485f +
5238       //           (2.2781945f +
5239       //             (-0.87823314f +
5240       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5241       //
5242       // error 0.0000023660568, which is better than 18 bits
5243       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5244                                getF32Constant(DAG, 0xbc91e5ac, dl));
5245       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5246                                getF32Constant(DAG, 0x3e4350aa, dl));
5247       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5248       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5249                                getF32Constant(DAG, 0x3f60d3e3, dl));
5250       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5251       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5252                                getF32Constant(DAG, 0x4011cdf0, dl));
5253       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5254       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5255                                getF32Constant(DAG, 0x406cfd1c, dl));
5256       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5257       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5258                                getF32Constant(DAG, 0x408797cb, dl));
5259       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5260       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5261                                   getF32Constant(DAG, 0x4006dcab, dl));
5262     }
5263 
5264     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5265   }
5266 
5267   // No special expansion.
5268   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5269 }
5270 
5271 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5272 /// limited-precision mode.
5273 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5274                           const TargetLowering &TLI, SDNodeFlags Flags) {
5275   // TODO: What fast-math-flags should be set on the floating-point nodes?
5276 
5277   if (Op.getValueType() == MVT::f32 &&
5278       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5279     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5280 
5281     // Get the exponent.
5282     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5283 
5284     // Get the significand and build it into a floating-point number with
5285     // exponent of 1.
5286     SDValue X = GetSignificand(DAG, Op1, dl);
5287 
5288     // Different possible minimax approximations of significand in
5289     // floating-point for various degrees of accuracy over [1,2].
5290     SDValue Log2ofMantissa;
5291     if (LimitFloatPrecision <= 6) {
5292       // For floating-point precision of 6:
5293       //
5294       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5295       //
5296       // error 0.0049451742, which is more than 7 bits
5297       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5298                                getF32Constant(DAG, 0xbeb08fe0, dl));
5299       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5300                                getF32Constant(DAG, 0x40019463, dl));
5301       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5302       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5303                                    getF32Constant(DAG, 0x3fd6633d, dl));
5304     } else if (LimitFloatPrecision <= 12) {
5305       // For floating-point precision of 12:
5306       //
5307       //   Log2ofMantissa =
5308       //     -2.51285454f +
5309       //       (4.07009056f +
5310       //         (-2.12067489f +
5311       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5312       //
5313       // error 0.0000876136000, which is better than 13 bits
5314       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5315                                getF32Constant(DAG, 0xbda7262e, dl));
5316       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5317                                getF32Constant(DAG, 0x3f25280b, dl));
5318       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5319       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5320                                getF32Constant(DAG, 0x4007b923, dl));
5321       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5322       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5323                                getF32Constant(DAG, 0x40823e2f, dl));
5324       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5325       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5326                                    getF32Constant(DAG, 0x4020d29c, dl));
5327     } else { // LimitFloatPrecision <= 18
5328       // For floating-point precision of 18:
5329       //
5330       //   Log2ofMantissa =
5331       //     -3.0400495f +
5332       //       (6.1129976f +
5333       //         (-5.3420409f +
5334       //           (3.2865683f +
5335       //             (-1.2669343f +
5336       //               (0.27515199f -
5337       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5338       //
5339       // error 0.0000018516, which is better than 18 bits
5340       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5341                                getF32Constant(DAG, 0xbcd2769e, dl));
5342       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5343                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5344       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5345       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5346                                getF32Constant(DAG, 0x3fa22ae7, dl));
5347       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5348       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5349                                getF32Constant(DAG, 0x40525723, dl));
5350       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5351       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5352                                getF32Constant(DAG, 0x40aaf200, dl));
5353       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5354       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5355                                getF32Constant(DAG, 0x40c39dad, dl));
5356       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5357       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5358                                    getF32Constant(DAG, 0x4042902c, dl));
5359     }
5360 
5361     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5362   }
5363 
5364   // No special expansion.
5365   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5366 }
5367 
5368 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5369 /// limited-precision mode.
5370 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5371                            const TargetLowering &TLI, SDNodeFlags Flags) {
5372   // TODO: What fast-math-flags should be set on the floating-point nodes?
5373 
5374   if (Op.getValueType() == MVT::f32 &&
5375       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5376     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5377 
5378     // Scale the exponent by log10(2) [0.30102999f].
5379     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5380     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5381                                         getF32Constant(DAG, 0x3e9a209a, dl));
5382 
5383     // Get the significand and build it into a floating-point number with
5384     // exponent of 1.
5385     SDValue X = GetSignificand(DAG, Op1, dl);
5386 
5387     SDValue Log10ofMantissa;
5388     if (LimitFloatPrecision <= 6) {
5389       // For floating-point precision of 6:
5390       //
5391       //   Log10ofMantissa =
5392       //     -0.50419619f +
5393       //       (0.60948995f - 0.10380950f * x) * x;
5394       //
5395       // error 0.0014886165, which is 6 bits
5396       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5397                                getF32Constant(DAG, 0xbdd49a13, dl));
5398       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5399                                getF32Constant(DAG, 0x3f1c0789, dl));
5400       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5401       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5402                                     getF32Constant(DAG, 0x3f011300, dl));
5403     } else if (LimitFloatPrecision <= 12) {
5404       // For floating-point precision of 12:
5405       //
5406       //   Log10ofMantissa =
5407       //     -0.64831180f +
5408       //       (0.91751397f +
5409       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5410       //
5411       // error 0.00019228036, which is better than 12 bits
5412       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5413                                getF32Constant(DAG, 0x3d431f31, dl));
5414       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5415                                getF32Constant(DAG, 0x3ea21fb2, dl));
5416       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5417       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5418                                getF32Constant(DAG, 0x3f6ae232, dl));
5419       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5420       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5421                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5422     } else { // LimitFloatPrecision <= 18
5423       // For floating-point precision of 18:
5424       //
5425       //   Log10ofMantissa =
5426       //     -0.84299375f +
5427       //       (1.5327582f +
5428       //         (-1.0688956f +
5429       //           (0.49102474f +
5430       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5431       //
5432       // error 0.0000037995730, which is better than 18 bits
5433       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5434                                getF32Constant(DAG, 0x3c5d51ce, dl));
5435       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5436                                getF32Constant(DAG, 0x3e00685a, dl));
5437       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5438       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5439                                getF32Constant(DAG, 0x3efb6798, dl));
5440       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5441       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5442                                getF32Constant(DAG, 0x3f88d192, dl));
5443       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5444       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5445                                getF32Constant(DAG, 0x3fc4316c, dl));
5446       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5447       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5448                                     getF32Constant(DAG, 0x3f57ce70, dl));
5449     }
5450 
5451     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5452   }
5453 
5454   // No special expansion.
5455   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5456 }
5457 
5458 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5459 /// limited-precision mode.
5460 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5461                           const TargetLowering &TLI, SDNodeFlags Flags) {
5462   if (Op.getValueType() == MVT::f32 &&
5463       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5464     return getLimitedPrecisionExp2(Op, dl, DAG);
5465 
5466   // No special expansion.
5467   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5468 }
5469 
5470 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5471 /// limited-precision mode with x == 10.0f.
5472 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5473                          SelectionDAG &DAG, const TargetLowering &TLI,
5474                          SDNodeFlags Flags) {
5475   bool IsExp10 = false;
5476   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5477       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5478     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5479       APFloat Ten(10.0f);
5480       IsExp10 = LHSC->isExactlyValue(Ten);
5481     }
5482   }
5483 
5484   // TODO: What fast-math-flags should be set on the FMUL node?
5485   if (IsExp10) {
5486     // Put the exponent in the right bit position for later addition to the
5487     // final result:
5488     //
5489     //   #define LOG2OF10 3.3219281f
5490     //   t0 = Op * LOG2OF10;
5491     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5492                              getF32Constant(DAG, 0x40549a78, dl));
5493     return getLimitedPrecisionExp2(t0, dl, DAG);
5494   }
5495 
5496   // No special expansion.
5497   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5498 }
5499 
5500 /// ExpandPowI - Expand a llvm.powi intrinsic.
5501 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5502                           SelectionDAG &DAG) {
5503   // If RHS is a constant, we can expand this out to a multiplication tree if
5504   // it's beneficial on the target, otherwise we end up lowering to a call to
5505   // __powidf2 (for example).
5506   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5507     unsigned Val = RHSC->getSExtValue();
5508 
5509     // powi(x, 0) -> 1.0
5510     if (Val == 0)
5511       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5512 
5513     if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI(
5514             Val, DAG.shouldOptForSize())) {
5515       // Get the exponent as a positive value.
5516       if ((int)Val < 0)
5517         Val = -Val;
5518       // We use the simple binary decomposition method to generate the multiply
5519       // sequence.  There are more optimal ways to do this (for example,
5520       // powi(x,15) generates one more multiply than it should), but this has
5521       // the benefit of being both really simple and much better than a libcall.
5522       SDValue Res; // Logically starts equal to 1.0
5523       SDValue CurSquare = LHS;
5524       // TODO: Intrinsics should have fast-math-flags that propagate to these
5525       // nodes.
5526       while (Val) {
5527         if (Val & 1) {
5528           if (Res.getNode())
5529             Res =
5530                 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
5531           else
5532             Res = CurSquare; // 1.0*CurSquare.
5533         }
5534 
5535         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5536                                 CurSquare, CurSquare);
5537         Val >>= 1;
5538       }
5539 
5540       // If the original was negative, invert the result, producing 1/(x*x*x).
5541       if (RHSC->getSExtValue() < 0)
5542         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5543                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5544       return Res;
5545     }
5546   }
5547 
5548   // Otherwise, expand to a libcall.
5549   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5550 }
5551 
5552 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5553                             SDValue LHS, SDValue RHS, SDValue Scale,
5554                             SelectionDAG &DAG, const TargetLowering &TLI) {
5555   EVT VT = LHS.getValueType();
5556   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5557   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5558   LLVMContext &Ctx = *DAG.getContext();
5559 
5560   // If the type is legal but the operation isn't, this node might survive all
5561   // the way to operation legalization. If we end up there and we do not have
5562   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5563   // node.
5564 
5565   // Coax the legalizer into expanding the node during type legalization instead
5566   // by bumping the size by one bit. This will force it to Promote, enabling the
5567   // early expansion and avoiding the need to expand later.
5568 
5569   // We don't have to do this if Scale is 0; that can always be expanded, unless
5570   // it's a saturating signed operation. Those can experience true integer
5571   // division overflow, a case which we must avoid.
5572 
5573   // FIXME: We wouldn't have to do this (or any of the early
5574   // expansion/promotion) if it was possible to expand a libcall of an
5575   // illegal type during operation legalization. But it's not, so things
5576   // get a bit hacky.
5577   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5578   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5579       (TLI.isTypeLegal(VT) ||
5580        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5581     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5582         Opcode, VT, ScaleInt);
5583     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5584       EVT PromVT;
5585       if (VT.isScalarInteger())
5586         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5587       else if (VT.isVector()) {
5588         PromVT = VT.getVectorElementType();
5589         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5590         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5591       } else
5592         llvm_unreachable("Wrong VT for DIVFIX?");
5593       LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT);
5594       RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT);
5595       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5596       // For saturating operations, we need to shift up the LHS to get the
5597       // proper saturation width, and then shift down again afterwards.
5598       if (Saturating)
5599         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5600                           DAG.getConstant(1, DL, ShiftTy));
5601       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5602       if (Saturating)
5603         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5604                           DAG.getConstant(1, DL, ShiftTy));
5605       return DAG.getZExtOrTrunc(Res, DL, VT);
5606     }
5607   }
5608 
5609   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5610 }
5611 
5612 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5613 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5614 static void
5615 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5616                      const SDValue &N) {
5617   switch (N.getOpcode()) {
5618   case ISD::CopyFromReg: {
5619     SDValue Op = N.getOperand(1);
5620     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5621                       Op.getValueType().getSizeInBits());
5622     return;
5623   }
5624   case ISD::BITCAST:
5625   case ISD::AssertZext:
5626   case ISD::AssertSext:
5627   case ISD::TRUNCATE:
5628     getUnderlyingArgRegs(Regs, N.getOperand(0));
5629     return;
5630   case ISD::BUILD_PAIR:
5631   case ISD::BUILD_VECTOR:
5632   case ISD::CONCAT_VECTORS:
5633     for (SDValue Op : N->op_values())
5634       getUnderlyingArgRegs(Regs, Op);
5635     return;
5636   default:
5637     return;
5638   }
5639 }
5640 
5641 /// If the DbgValueInst is a dbg_value of a function argument, create the
5642 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5643 /// instruction selection, they will be inserted to the entry BB.
5644 /// We don't currently support this for variadic dbg_values, as they shouldn't
5645 /// appear for function arguments or in the prologue.
5646 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5647     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5648     DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
5649   const Argument *Arg = dyn_cast<Argument>(V);
5650   if (!Arg)
5651     return false;
5652 
5653   MachineFunction &MF = DAG.getMachineFunction();
5654   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5655 
5656   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
5657   // we've been asked to pursue.
5658   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
5659                               bool Indirect) {
5660     if (Reg.isVirtual() && MF.useDebugInstrRef()) {
5661       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
5662       // pointing at the VReg, which will be patched up later.
5663       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
5664       SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg(
5665           /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
5666           /* isKill */ false, /* isDead */ false,
5667           /* isUndef */ false, /* isEarlyClobber */ false,
5668           /* SubReg */ 0, /* isDebug */ true)});
5669 
5670       auto *NewDIExpr = FragExpr;
5671       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
5672       // the DIExpression.
5673       if (Indirect)
5674         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
5675       SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0});
5676       NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops);
5677       return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr);
5678     } else {
5679       // Create a completely standard DBG_VALUE.
5680       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
5681       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
5682     }
5683   };
5684 
5685   if (Kind == FuncArgumentDbgValueKind::Value) {
5686     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5687     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5688     // the entry block.
5689     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5690     if (!IsInEntryBlock)
5691       return false;
5692 
5693     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5694     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5695     // variable that also is a param.
5696     //
5697     // Although, if we are at the top of the entry block already, we can still
5698     // emit using ArgDbgValue. This might catch some situations when the
5699     // dbg.value refers to an argument that isn't used in the entry block, so
5700     // any CopyToReg node would be optimized out and the only way to express
5701     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5702     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5703     // we should only emit as ArgDbgValue if the Variable is an argument to the
5704     // current function, and the dbg.value intrinsic is found in the entry
5705     // block.
5706     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5707         !DL->getInlinedAt();
5708     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5709     if (!IsInPrologue && !VariableIsFunctionInputArg)
5710       return false;
5711 
5712     // Here we assume that a function argument on IR level only can be used to
5713     // describe one input parameter on source level. If we for example have
5714     // source code like this
5715     //
5716     //    struct A { long x, y; };
5717     //    void foo(struct A a, long b) {
5718     //      ...
5719     //      b = a.x;
5720     //      ...
5721     //    }
5722     //
5723     // and IR like this
5724     //
5725     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5726     //  entry:
5727     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5728     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5729     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5730     //    ...
5731     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5732     //    ...
5733     //
5734     // then the last dbg.value is describing a parameter "b" using a value that
5735     // is an argument. But since we already has used %a1 to describe a parameter
5736     // we should not handle that last dbg.value here (that would result in an
5737     // incorrect hoisting of the DBG_VALUE to the function entry).
5738     // Notice that we allow one dbg.value per IR level argument, to accommodate
5739     // for the situation with fragments above.
5740     if (VariableIsFunctionInputArg) {
5741       unsigned ArgNo = Arg->getArgNo();
5742       if (ArgNo >= FuncInfo.DescribedArgs.size())
5743         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5744       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5745         return false;
5746       FuncInfo.DescribedArgs.set(ArgNo);
5747     }
5748   }
5749 
5750   bool IsIndirect = false;
5751   std::optional<MachineOperand> Op;
5752   // Some arguments' frame index is recorded during argument lowering.
5753   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5754   if (FI != std::numeric_limits<int>::max())
5755     Op = MachineOperand::CreateFI(FI);
5756 
5757   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
5758   if (!Op && N.getNode()) {
5759     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5760     Register Reg;
5761     if (ArgRegsAndSizes.size() == 1)
5762       Reg = ArgRegsAndSizes.front().first;
5763 
5764     if (Reg && Reg.isVirtual()) {
5765       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5766       Register PR = RegInfo.getLiveInPhysReg(Reg);
5767       if (PR)
5768         Reg = PR;
5769     }
5770     if (Reg) {
5771       Op = MachineOperand::CreateReg(Reg, false);
5772       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
5773     }
5774   }
5775 
5776   if (!Op && N.getNode()) {
5777     // Check if frame index is available.
5778     SDValue LCandidate = peekThroughBitcasts(N);
5779     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5780       if (FrameIndexSDNode *FINode =
5781           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5782         Op = MachineOperand::CreateFI(FINode->getIndex());
5783   }
5784 
5785   if (!Op) {
5786     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5787     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
5788                                          SplitRegs) {
5789       unsigned Offset = 0;
5790       for (const auto &RegAndSize : SplitRegs) {
5791         // If the expression is already a fragment, the current register
5792         // offset+size might extend beyond the fragment. In this case, only
5793         // the register bits that are inside the fragment are relevant.
5794         int RegFragmentSizeInBits = RegAndSize.second;
5795         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5796           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5797           // The register is entirely outside the expression fragment,
5798           // so is irrelevant for debug info.
5799           if (Offset >= ExprFragmentSizeInBits)
5800             break;
5801           // The register is partially outside the expression fragment, only
5802           // the low bits within the fragment are relevant for debug info.
5803           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5804             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5805           }
5806         }
5807 
5808         auto FragmentExpr = DIExpression::createFragmentExpression(
5809             Expr, Offset, RegFragmentSizeInBits);
5810         Offset += RegAndSize.second;
5811         // If a valid fragment expression cannot be created, the variable's
5812         // correct value cannot be determined and so it is set as Undef.
5813         if (!FragmentExpr) {
5814           SDDbgValue *SDV = DAG.getConstantDbgValue(
5815               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5816           DAG.AddDbgValue(SDV, false);
5817           continue;
5818         }
5819         MachineInstr *NewMI =
5820             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr,
5821                              Kind != FuncArgumentDbgValueKind::Value);
5822         FuncInfo.ArgDbgValues.push_back(NewMI);
5823       }
5824     };
5825 
5826     // Check if ValueMap has reg number.
5827     DenseMap<const Value *, Register>::const_iterator
5828       VMI = FuncInfo.ValueMap.find(V);
5829     if (VMI != FuncInfo.ValueMap.end()) {
5830       const auto &TLI = DAG.getTargetLoweringInfo();
5831       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5832                        V->getType(), std::nullopt);
5833       if (RFV.occupiesMultipleRegs()) {
5834         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5835         return true;
5836       }
5837 
5838       Op = MachineOperand::CreateReg(VMI->second, false);
5839       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
5840     } else if (ArgRegsAndSizes.size() > 1) {
5841       // This was split due to the calling convention, and no virtual register
5842       // mapping exists for the value.
5843       splitMultiRegDbgValue(ArgRegsAndSizes);
5844       return true;
5845     }
5846   }
5847 
5848   if (!Op)
5849     return false;
5850 
5851   assert(Variable->isValidLocationForIntrinsic(DL) &&
5852          "Expected inlined-at fields to agree");
5853   MachineInstr *NewMI = nullptr;
5854 
5855   if (Op->isReg())
5856     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
5857   else
5858     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
5859                     Variable, Expr);
5860 
5861   // Otherwise, use ArgDbgValues.
5862   FuncInfo.ArgDbgValues.push_back(NewMI);
5863   return true;
5864 }
5865 
5866 /// Return the appropriate SDDbgValue based on N.
5867 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5868                                              DILocalVariable *Variable,
5869                                              DIExpression *Expr,
5870                                              const DebugLoc &dl,
5871                                              unsigned DbgSDNodeOrder) {
5872   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5873     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5874     // stack slot locations.
5875     //
5876     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5877     // debug values here after optimization:
5878     //
5879     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5880     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5881     //
5882     // Both describe the direct values of their associated variables.
5883     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5884                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5885   }
5886   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5887                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5888 }
5889 
5890 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5891   switch (Intrinsic) {
5892   case Intrinsic::smul_fix:
5893     return ISD::SMULFIX;
5894   case Intrinsic::umul_fix:
5895     return ISD::UMULFIX;
5896   case Intrinsic::smul_fix_sat:
5897     return ISD::SMULFIXSAT;
5898   case Intrinsic::umul_fix_sat:
5899     return ISD::UMULFIXSAT;
5900   case Intrinsic::sdiv_fix:
5901     return ISD::SDIVFIX;
5902   case Intrinsic::udiv_fix:
5903     return ISD::UDIVFIX;
5904   case Intrinsic::sdiv_fix_sat:
5905     return ISD::SDIVFIXSAT;
5906   case Intrinsic::udiv_fix_sat:
5907     return ISD::UDIVFIXSAT;
5908   default:
5909     llvm_unreachable("Unhandled fixed point intrinsic");
5910   }
5911 }
5912 
5913 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5914                                            const char *FunctionName) {
5915   assert(FunctionName && "FunctionName must not be nullptr");
5916   SDValue Callee = DAG.getExternalSymbol(
5917       FunctionName,
5918       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5919   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
5920 }
5921 
5922 /// Given a @llvm.call.preallocated.setup, return the corresponding
5923 /// preallocated call.
5924 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
5925   assert(cast<CallBase>(PreallocatedSetup)
5926                  ->getCalledFunction()
5927                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
5928          "expected call_preallocated_setup Value");
5929   for (const auto *U : PreallocatedSetup->users()) {
5930     auto *UseCall = cast<CallBase>(U);
5931     const Function *Fn = UseCall->getCalledFunction();
5932     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
5933       return UseCall;
5934     }
5935   }
5936   llvm_unreachable("expected corresponding call to preallocated setup/arg");
5937 }
5938 
5939 /// If DI is a debug value with an EntryValue expression, lower it using the
5940 /// corresponding physical register of the associated Argument value
5941 /// (guaranteed to exist by the verifier).
5942 bool SelectionDAGBuilder::visitEntryValueDbgValue(const DbgValueInst &DI) {
5943   DILocalVariable *Variable = DI.getVariable();
5944   DIExpression *Expr = DI.getExpression();
5945   if (!Expr->isEntryValue() || !hasSingleElement(DI.getValues()))
5946     return false;
5947 
5948   // These properties are guaranteed by the verifier.
5949   Argument *Arg = cast<Argument>(DI.getValue(0));
5950   assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync));
5951 
5952   auto ArgIt = FuncInfo.ValueMap.find(Arg);
5953   if (ArgIt == FuncInfo.ValueMap.end()) {
5954     LLVM_DEBUG(
5955         dbgs() << "Dropping dbg.value: expression is entry_value but "
5956                   "couldn't find an associated register for the Argument\n");
5957     return true;
5958   }
5959   Register ArgVReg = ArgIt->getSecond();
5960 
5961   for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
5962     if (ArgVReg == VirtReg || ArgVReg == PhysReg) {
5963       SDDbgValue *SDV =
5964           DAG.getVRegDbgValue(Variable, Expr, PhysReg, false /*IsIndidrect*/,
5965                               DI.getDebugLoc(), SDNodeOrder);
5966       DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/);
5967       return true;
5968     }
5969   LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but "
5970                        "couldn't find a physical register\n");
5971   return true;
5972 }
5973 
5974 /// Lower the call to the specified intrinsic function.
5975 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5976                                              unsigned Intrinsic) {
5977   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5978   SDLoc sdl = getCurSDLoc();
5979   DebugLoc dl = getCurDebugLoc();
5980   SDValue Res;
5981 
5982   SDNodeFlags Flags;
5983   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
5984     Flags.copyFMF(*FPOp);
5985 
5986   switch (Intrinsic) {
5987   default:
5988     // By default, turn this into a target intrinsic node.
5989     visitTargetIntrinsic(I, Intrinsic);
5990     return;
5991   case Intrinsic::vscale: {
5992     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5993     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
5994     return;
5995   }
5996   case Intrinsic::vastart:  visitVAStart(I); return;
5997   case Intrinsic::vaend:    visitVAEnd(I); return;
5998   case Intrinsic::vacopy:   visitVACopy(I); return;
5999   case Intrinsic::returnaddress:
6000     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
6001                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6002                              getValue(I.getArgOperand(0))));
6003     return;
6004   case Intrinsic::addressofreturnaddress:
6005     setValue(&I,
6006              DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
6007                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6008     return;
6009   case Intrinsic::sponentry:
6010     setValue(&I,
6011              DAG.getNode(ISD::SPONENTRY, sdl,
6012                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6013     return;
6014   case Intrinsic::frameaddress:
6015     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
6016                              TLI.getFrameIndexTy(DAG.getDataLayout()),
6017                              getValue(I.getArgOperand(0))));
6018     return;
6019   case Intrinsic::read_volatile_register:
6020   case Intrinsic::read_register: {
6021     Value *Reg = I.getArgOperand(0);
6022     SDValue Chain = getRoot();
6023     SDValue RegName =
6024         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6025     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6026     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
6027       DAG.getVTList(VT, MVT::Other), Chain, RegName);
6028     setValue(&I, Res);
6029     DAG.setRoot(Res.getValue(1));
6030     return;
6031   }
6032   case Intrinsic::write_register: {
6033     Value *Reg = I.getArgOperand(0);
6034     Value *RegValue = I.getArgOperand(1);
6035     SDValue Chain = getRoot();
6036     SDValue RegName =
6037         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6038     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
6039                             RegName, getValue(RegValue)));
6040     return;
6041   }
6042   case Intrinsic::memcpy: {
6043     const auto &MCI = cast<MemCpyInst>(I);
6044     SDValue Op1 = getValue(I.getArgOperand(0));
6045     SDValue Op2 = getValue(I.getArgOperand(1));
6046     SDValue Op3 = getValue(I.getArgOperand(2));
6047     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
6048     Align DstAlign = MCI.getDestAlign().valueOrOne();
6049     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6050     Align Alignment = std::min(DstAlign, SrcAlign);
6051     bool isVol = MCI.isVolatile();
6052     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6053     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6054     // node.
6055     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6056     SDValue MC = DAG.getMemcpy(
6057         Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6058         /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)),
6059         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
6060     updateDAGForMaybeTailCall(MC);
6061     return;
6062   }
6063   case Intrinsic::memcpy_inline: {
6064     const auto &MCI = cast<MemCpyInlineInst>(I);
6065     SDValue Dst = getValue(I.getArgOperand(0));
6066     SDValue Src = getValue(I.getArgOperand(1));
6067     SDValue Size = getValue(I.getArgOperand(2));
6068     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
6069     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
6070     Align DstAlign = MCI.getDestAlign().valueOrOne();
6071     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6072     Align Alignment = std::min(DstAlign, SrcAlign);
6073     bool isVol = MCI.isVolatile();
6074     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6075     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6076     // node.
6077     SDValue MC = DAG.getMemcpy(
6078         getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
6079         /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)),
6080         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
6081     updateDAGForMaybeTailCall(MC);
6082     return;
6083   }
6084   case Intrinsic::memset: {
6085     const auto &MSI = cast<MemSetInst>(I);
6086     SDValue Op1 = getValue(I.getArgOperand(0));
6087     SDValue Op2 = getValue(I.getArgOperand(1));
6088     SDValue Op3 = getValue(I.getArgOperand(2));
6089     // @llvm.memset defines 0 and 1 to both mean no alignment.
6090     Align Alignment = MSI.getDestAlign().valueOrOne();
6091     bool isVol = MSI.isVolatile();
6092     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6093     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6094     SDValue MS = DAG.getMemset(
6095         Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false,
6096         isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
6097     updateDAGForMaybeTailCall(MS);
6098     return;
6099   }
6100   case Intrinsic::memset_inline: {
6101     const auto &MSII = cast<MemSetInlineInst>(I);
6102     SDValue Dst = getValue(I.getArgOperand(0));
6103     SDValue Value = getValue(I.getArgOperand(1));
6104     SDValue Size = getValue(I.getArgOperand(2));
6105     assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size");
6106     // @llvm.memset defines 0 and 1 to both mean no alignment.
6107     Align DstAlign = MSII.getDestAlign().valueOrOne();
6108     bool isVol = MSII.isVolatile();
6109     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6110     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6111     SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol,
6112                                /* AlwaysInline */ true, isTC,
6113                                MachinePointerInfo(I.getArgOperand(0)),
6114                                I.getAAMetadata());
6115     updateDAGForMaybeTailCall(MC);
6116     return;
6117   }
6118   case Intrinsic::memmove: {
6119     const auto &MMI = cast<MemMoveInst>(I);
6120     SDValue Op1 = getValue(I.getArgOperand(0));
6121     SDValue Op2 = getValue(I.getArgOperand(1));
6122     SDValue Op3 = getValue(I.getArgOperand(2));
6123     // @llvm.memmove defines 0 and 1 to both mean no alignment.
6124     Align DstAlign = MMI.getDestAlign().valueOrOne();
6125     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
6126     Align Alignment = std::min(DstAlign, SrcAlign);
6127     bool isVol = MMI.isVolatile();
6128     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6129     // FIXME: Support passing different dest/src alignments to the memmove DAG
6130     // node.
6131     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6132     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6133                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
6134                                 MachinePointerInfo(I.getArgOperand(1)),
6135                                 I.getAAMetadata(), AA);
6136     updateDAGForMaybeTailCall(MM);
6137     return;
6138   }
6139   case Intrinsic::memcpy_element_unordered_atomic: {
6140     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
6141     SDValue Dst = getValue(MI.getRawDest());
6142     SDValue Src = getValue(MI.getRawSource());
6143     SDValue Length = getValue(MI.getLength());
6144 
6145     Type *LengthTy = MI.getLength()->getType();
6146     unsigned ElemSz = MI.getElementSizeInBytes();
6147     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6148     SDValue MC =
6149         DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6150                             isTC, MachinePointerInfo(MI.getRawDest()),
6151                             MachinePointerInfo(MI.getRawSource()));
6152     updateDAGForMaybeTailCall(MC);
6153     return;
6154   }
6155   case Intrinsic::memmove_element_unordered_atomic: {
6156     auto &MI = cast<AtomicMemMoveInst>(I);
6157     SDValue Dst = getValue(MI.getRawDest());
6158     SDValue Src = getValue(MI.getRawSource());
6159     SDValue Length = getValue(MI.getLength());
6160 
6161     Type *LengthTy = MI.getLength()->getType();
6162     unsigned ElemSz = MI.getElementSizeInBytes();
6163     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6164     SDValue MC =
6165         DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6166                              isTC, MachinePointerInfo(MI.getRawDest()),
6167                              MachinePointerInfo(MI.getRawSource()));
6168     updateDAGForMaybeTailCall(MC);
6169     return;
6170   }
6171   case Intrinsic::memset_element_unordered_atomic: {
6172     auto &MI = cast<AtomicMemSetInst>(I);
6173     SDValue Dst = getValue(MI.getRawDest());
6174     SDValue Val = getValue(MI.getValue());
6175     SDValue Length = getValue(MI.getLength());
6176 
6177     Type *LengthTy = MI.getLength()->getType();
6178     unsigned ElemSz = MI.getElementSizeInBytes();
6179     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6180     SDValue MC =
6181         DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
6182                             isTC, MachinePointerInfo(MI.getRawDest()));
6183     updateDAGForMaybeTailCall(MC);
6184     return;
6185   }
6186   case Intrinsic::call_preallocated_setup: {
6187     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
6188     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6189     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
6190                               getRoot(), SrcValue);
6191     setValue(&I, Res);
6192     DAG.setRoot(Res);
6193     return;
6194   }
6195   case Intrinsic::call_preallocated_arg: {
6196     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6197     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6198     SDValue Ops[3];
6199     Ops[0] = getRoot();
6200     Ops[1] = SrcValue;
6201     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6202                                    MVT::i32); // arg index
6203     SDValue Res = DAG.getNode(
6204         ISD::PREALLOCATED_ARG, sdl,
6205         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6206     setValue(&I, Res);
6207     DAG.setRoot(Res.getValue(1));
6208     return;
6209   }
6210   case Intrinsic::dbg_declare: {
6211     const auto &DI = cast<DbgDeclareInst>(I);
6212     // Debug intrinsics are handled separately in assignment tracking mode.
6213     // Some intrinsics are handled right after Argument lowering.
6214     if (AssignmentTrackingEnabled ||
6215         FuncInfo.PreprocessedDbgDeclares.count(&DI))
6216       return;
6217     // Assume dbg.declare can not currently use DIArgList, i.e.
6218     // it is non-variadic.
6219     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6220     DILocalVariable *Variable = DI.getVariable();
6221     DIExpression *Expression = DI.getExpression();
6222     dropDanglingDebugInfo(Variable, Expression);
6223     assert(Variable && "Missing variable");
6224     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
6225                       << "\n");
6226     // Check if address has undef value.
6227     const Value *Address = DI.getVariableLocationOp(0);
6228     if (!Address || isa<UndefValue>(Address) ||
6229         (Address->use_empty() && !isa<Argument>(Address))) {
6230       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6231                         << " (bad/undef/unused-arg address)\n");
6232       return;
6233     }
6234 
6235     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
6236 
6237     SDValue &N = NodeMap[Address];
6238     if (!N.getNode() && isa<Argument>(Address))
6239       // Check unused arguments map.
6240       N = UnusedArgNodeMap[Address];
6241     SDDbgValue *SDV;
6242     if (N.getNode()) {
6243       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
6244         Address = BCI->getOperand(0);
6245       // Parameters are handled specially.
6246       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
6247       if (isParameter && FINode) {
6248         // Byval parameter. We have a frame index at this point.
6249         SDV =
6250             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
6251                                       /*IsIndirect*/ true, dl, SDNodeOrder);
6252       } else if (isa<Argument>(Address)) {
6253         // Address is an argument, so try to emit its dbg value using
6254         // virtual register info from the FuncInfo.ValueMap.
6255         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl,
6256                                  FuncArgumentDbgValueKind::Declare, N);
6257         return;
6258       } else {
6259         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
6260                               true, dl, SDNodeOrder);
6261       }
6262       DAG.AddDbgValue(SDV, isParameter);
6263     } else {
6264       // If Address is an argument then try to emit its dbg value using
6265       // virtual register info from the FuncInfo.ValueMap.
6266       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl,
6267                                     FuncArgumentDbgValueKind::Declare, N)) {
6268         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6269                           << " (could not emit func-arg dbg_value)\n");
6270       }
6271     }
6272     return;
6273   }
6274   case Intrinsic::dbg_label: {
6275     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6276     DILabel *Label = DI.getLabel();
6277     assert(Label && "Missing label");
6278 
6279     SDDbgLabel *SDV;
6280     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6281     DAG.AddDbgLabel(SDV);
6282     return;
6283   }
6284   case Intrinsic::dbg_assign: {
6285     // Debug intrinsics are handled seperately in assignment tracking mode.
6286     if (AssignmentTrackingEnabled)
6287       return;
6288     // If assignment tracking hasn't been enabled then fall through and treat
6289     // the dbg.assign as a dbg.value.
6290     [[fallthrough]];
6291   }
6292   case Intrinsic::dbg_value: {
6293     // Debug intrinsics are handled seperately in assignment tracking mode.
6294     if (AssignmentTrackingEnabled)
6295       return;
6296     const DbgValueInst &DI = cast<DbgValueInst>(I);
6297     assert(DI.getVariable() && "Missing variable");
6298 
6299     DILocalVariable *Variable = DI.getVariable();
6300     DIExpression *Expression = DI.getExpression();
6301     dropDanglingDebugInfo(Variable, Expression);
6302 
6303     if (visitEntryValueDbgValue(DI))
6304       return;
6305 
6306     if (DI.isKillLocation()) {
6307       handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder);
6308       return;
6309     }
6310 
6311     SmallVector<Value *, 4> Values(DI.getValues());
6312     if (Values.empty())
6313       return;
6314 
6315     bool IsVariadic = DI.hasArgList();
6316     if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(),
6317                           SDNodeOrder, IsVariadic))
6318       addDanglingDebugInfo(&DI, SDNodeOrder);
6319     return;
6320   }
6321 
6322   case Intrinsic::eh_typeid_for: {
6323     // Find the type id for the given typeinfo.
6324     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6325     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6326     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6327     setValue(&I, Res);
6328     return;
6329   }
6330 
6331   case Intrinsic::eh_return_i32:
6332   case Intrinsic::eh_return_i64:
6333     DAG.getMachineFunction().setCallsEHReturn(true);
6334     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6335                             MVT::Other,
6336                             getControlRoot(),
6337                             getValue(I.getArgOperand(0)),
6338                             getValue(I.getArgOperand(1))));
6339     return;
6340   case Intrinsic::eh_unwind_init:
6341     DAG.getMachineFunction().setCallsUnwindInit(true);
6342     return;
6343   case Intrinsic::eh_dwarf_cfa:
6344     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6345                              TLI.getPointerTy(DAG.getDataLayout()),
6346                              getValue(I.getArgOperand(0))));
6347     return;
6348   case Intrinsic::eh_sjlj_callsite: {
6349     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6350     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
6351     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6352 
6353     MMI.setCurrentCallSite(CI->getZExtValue());
6354     return;
6355   }
6356   case Intrinsic::eh_sjlj_functioncontext: {
6357     // Get and store the index of the function context.
6358     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6359     AllocaInst *FnCtx =
6360       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6361     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6362     MFI.setFunctionContextIndex(FI);
6363     return;
6364   }
6365   case Intrinsic::eh_sjlj_setjmp: {
6366     SDValue Ops[2];
6367     Ops[0] = getRoot();
6368     Ops[1] = getValue(I.getArgOperand(0));
6369     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6370                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6371     setValue(&I, Op.getValue(0));
6372     DAG.setRoot(Op.getValue(1));
6373     return;
6374   }
6375   case Intrinsic::eh_sjlj_longjmp:
6376     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6377                             getRoot(), getValue(I.getArgOperand(0))));
6378     return;
6379   case Intrinsic::eh_sjlj_setup_dispatch:
6380     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6381                             getRoot()));
6382     return;
6383   case Intrinsic::masked_gather:
6384     visitMaskedGather(I);
6385     return;
6386   case Intrinsic::masked_load:
6387     visitMaskedLoad(I);
6388     return;
6389   case Intrinsic::masked_scatter:
6390     visitMaskedScatter(I);
6391     return;
6392   case Intrinsic::masked_store:
6393     visitMaskedStore(I);
6394     return;
6395   case Intrinsic::masked_expandload:
6396     visitMaskedLoad(I, true /* IsExpanding */);
6397     return;
6398   case Intrinsic::masked_compressstore:
6399     visitMaskedStore(I, true /* IsCompressing */);
6400     return;
6401   case Intrinsic::powi:
6402     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6403                             getValue(I.getArgOperand(1)), DAG));
6404     return;
6405   case Intrinsic::log:
6406     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6407     return;
6408   case Intrinsic::log2:
6409     setValue(&I,
6410              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6411     return;
6412   case Intrinsic::log10:
6413     setValue(&I,
6414              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6415     return;
6416   case Intrinsic::exp:
6417     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6418     return;
6419   case Intrinsic::exp2:
6420     setValue(&I,
6421              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6422     return;
6423   case Intrinsic::pow:
6424     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6425                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6426     return;
6427   case Intrinsic::sqrt:
6428   case Intrinsic::fabs:
6429   case Intrinsic::sin:
6430   case Intrinsic::cos:
6431   case Intrinsic::exp10:
6432   case Intrinsic::floor:
6433   case Intrinsic::ceil:
6434   case Intrinsic::trunc:
6435   case Intrinsic::rint:
6436   case Intrinsic::nearbyint:
6437   case Intrinsic::round:
6438   case Intrinsic::roundeven:
6439   case Intrinsic::canonicalize: {
6440     unsigned Opcode;
6441     switch (Intrinsic) {
6442     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6443     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6444     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6445     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6446     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6447     case Intrinsic::exp10:     Opcode = ISD::FEXP10;     break;
6448     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6449     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6450     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6451     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6452     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6453     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6454     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6455     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6456     }
6457 
6458     setValue(&I, DAG.getNode(Opcode, sdl,
6459                              getValue(I.getArgOperand(0)).getValueType(),
6460                              getValue(I.getArgOperand(0)), Flags));
6461     return;
6462   }
6463   case Intrinsic::lround:
6464   case Intrinsic::llround:
6465   case Intrinsic::lrint:
6466   case Intrinsic::llrint: {
6467     unsigned Opcode;
6468     switch (Intrinsic) {
6469     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6470     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6471     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6472     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6473     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6474     }
6475 
6476     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6477     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6478                              getValue(I.getArgOperand(0))));
6479     return;
6480   }
6481   case Intrinsic::minnum:
6482     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6483                              getValue(I.getArgOperand(0)).getValueType(),
6484                              getValue(I.getArgOperand(0)),
6485                              getValue(I.getArgOperand(1)), Flags));
6486     return;
6487   case Intrinsic::maxnum:
6488     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6489                              getValue(I.getArgOperand(0)).getValueType(),
6490                              getValue(I.getArgOperand(0)),
6491                              getValue(I.getArgOperand(1)), Flags));
6492     return;
6493   case Intrinsic::minimum:
6494     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6495                              getValue(I.getArgOperand(0)).getValueType(),
6496                              getValue(I.getArgOperand(0)),
6497                              getValue(I.getArgOperand(1)), Flags));
6498     return;
6499   case Intrinsic::maximum:
6500     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6501                              getValue(I.getArgOperand(0)).getValueType(),
6502                              getValue(I.getArgOperand(0)),
6503                              getValue(I.getArgOperand(1)), Flags));
6504     return;
6505   case Intrinsic::copysign:
6506     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6507                              getValue(I.getArgOperand(0)).getValueType(),
6508                              getValue(I.getArgOperand(0)),
6509                              getValue(I.getArgOperand(1)), Flags));
6510     return;
6511   case Intrinsic::ldexp:
6512     setValue(&I, DAG.getNode(ISD::FLDEXP, sdl,
6513                              getValue(I.getArgOperand(0)).getValueType(),
6514                              getValue(I.getArgOperand(0)),
6515                              getValue(I.getArgOperand(1)), Flags));
6516     return;
6517   case Intrinsic::frexp: {
6518     SmallVector<EVT, 2> ValueVTs;
6519     ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
6520     SDVTList VTs = DAG.getVTList(ValueVTs);
6521     setValue(&I,
6522              DAG.getNode(ISD::FFREXP, sdl, VTs, getValue(I.getArgOperand(0))));
6523     return;
6524   }
6525   case Intrinsic::arithmetic_fence: {
6526     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6527                              getValue(I.getArgOperand(0)).getValueType(),
6528                              getValue(I.getArgOperand(0)), Flags));
6529     return;
6530   }
6531   case Intrinsic::fma:
6532     setValue(&I, DAG.getNode(
6533                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6534                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6535                      getValue(I.getArgOperand(2)), Flags));
6536     return;
6537 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6538   case Intrinsic::INTRINSIC:
6539 #include "llvm/IR/ConstrainedOps.def"
6540     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6541     return;
6542 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6543 #include "llvm/IR/VPIntrinsics.def"
6544     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6545     return;
6546   case Intrinsic::fptrunc_round: {
6547     // Get the last argument, the metadata and convert it to an integer in the
6548     // call
6549     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
6550     std::optional<RoundingMode> RoundMode =
6551         convertStrToRoundingMode(cast<MDString>(MD)->getString());
6552 
6553     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6554 
6555     // Propagate fast-math-flags from IR to node(s).
6556     SDNodeFlags Flags;
6557     Flags.copyFMF(*cast<FPMathOperator>(&I));
6558     SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
6559 
6560     SDValue Result;
6561     Result = DAG.getNode(
6562         ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
6563         DAG.getTargetConstant((int)*RoundMode, sdl,
6564                               TLI.getPointerTy(DAG.getDataLayout())));
6565     setValue(&I, Result);
6566 
6567     return;
6568   }
6569   case Intrinsic::fmuladd: {
6570     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6571     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6572         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6573       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6574                                getValue(I.getArgOperand(0)).getValueType(),
6575                                getValue(I.getArgOperand(0)),
6576                                getValue(I.getArgOperand(1)),
6577                                getValue(I.getArgOperand(2)), Flags));
6578     } else {
6579       // TODO: Intrinsic calls should have fast-math-flags.
6580       SDValue Mul = DAG.getNode(
6581           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6582           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6583       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6584                                 getValue(I.getArgOperand(0)).getValueType(),
6585                                 Mul, getValue(I.getArgOperand(2)), Flags);
6586       setValue(&I, Add);
6587     }
6588     return;
6589   }
6590   case Intrinsic::convert_to_fp16:
6591     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6592                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6593                                          getValue(I.getArgOperand(0)),
6594                                          DAG.getTargetConstant(0, sdl,
6595                                                                MVT::i32))));
6596     return;
6597   case Intrinsic::convert_from_fp16:
6598     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6599                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6600                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6601                                          getValue(I.getArgOperand(0)))));
6602     return;
6603   case Intrinsic::fptosi_sat: {
6604     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6605     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
6606                              getValue(I.getArgOperand(0)),
6607                              DAG.getValueType(VT.getScalarType())));
6608     return;
6609   }
6610   case Intrinsic::fptoui_sat: {
6611     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6612     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
6613                              getValue(I.getArgOperand(0)),
6614                              DAG.getValueType(VT.getScalarType())));
6615     return;
6616   }
6617   case Intrinsic::set_rounding:
6618     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6619                       {getRoot(), getValue(I.getArgOperand(0))});
6620     setValue(&I, Res);
6621     DAG.setRoot(Res.getValue(0));
6622     return;
6623   case Intrinsic::is_fpclass: {
6624     const DataLayout DLayout = DAG.getDataLayout();
6625     EVT DestVT = TLI.getValueType(DLayout, I.getType());
6626     EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
6627     FPClassTest Test = static_cast<FPClassTest>(
6628         cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
6629     MachineFunction &MF = DAG.getMachineFunction();
6630     const Function &F = MF.getFunction();
6631     SDValue Op = getValue(I.getArgOperand(0));
6632     SDNodeFlags Flags;
6633     Flags.setNoFPExcept(
6634         !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
6635     // If ISD::IS_FPCLASS should be expanded, do it right now, because the
6636     // expansion can use illegal types. Making expansion early allows
6637     // legalizing these types prior to selection.
6638     if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) {
6639       SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
6640       setValue(&I, Result);
6641       return;
6642     }
6643 
6644     SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
6645     SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
6646     setValue(&I, V);
6647     return;
6648   }
6649   case Intrinsic::get_fpenv: {
6650     const DataLayout DLayout = DAG.getDataLayout();
6651     EVT EnvVT = TLI.getValueType(DLayout, I.getType());
6652     Align TempAlign = DAG.getEVTAlign(EnvVT);
6653     SDValue Chain = getRoot();
6654     // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node
6655     // and temporary storage in stack.
6656     if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) {
6657       Res = DAG.getNode(
6658           ISD::GET_FPENV, sdl,
6659           DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
6660                         MVT::Other),
6661           Chain);
6662     } else {
6663       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
6664       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
6665       auto MPI =
6666           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
6667       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6668           MPI, MachineMemOperand::MOStore, MemoryLocation::UnknownSize,
6669           TempAlign);
6670       Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
6671       Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI);
6672     }
6673     setValue(&I, Res);
6674     DAG.setRoot(Res.getValue(1));
6675     return;
6676   }
6677   case Intrinsic::set_fpenv: {
6678     const DataLayout DLayout = DAG.getDataLayout();
6679     SDValue Env = getValue(I.getArgOperand(0));
6680     EVT EnvVT = Env.getValueType();
6681     Align TempAlign = DAG.getEVTAlign(EnvVT);
6682     SDValue Chain = getRoot();
6683     // If SET_FPENV is custom or legal, use it. Otherwise use loading
6684     // environment from memory.
6685     if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) {
6686       Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env);
6687     } else {
6688       // Allocate space in stack, copy environment bits into it and use this
6689       // memory in SET_FPENV_MEM.
6690       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
6691       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
6692       auto MPI =
6693           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
6694       Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign,
6695                            MachineMemOperand::MOStore);
6696       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6697           MPI, MachineMemOperand::MOLoad, MemoryLocation::UnknownSize,
6698           TempAlign);
6699       Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
6700     }
6701     DAG.setRoot(Chain);
6702     return;
6703   }
6704   case Intrinsic::reset_fpenv:
6705     DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot()));
6706     return;
6707   case Intrinsic::get_fpmode:
6708     Res = DAG.getNode(
6709         ISD::GET_FPMODE, sdl,
6710         DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
6711                       MVT::Other),
6712         DAG.getRoot());
6713     setValue(&I, Res);
6714     DAG.setRoot(Res.getValue(1));
6715     return;
6716   case Intrinsic::set_fpmode:
6717     Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()},
6718                       getValue(I.getArgOperand(0)));
6719     DAG.setRoot(Res);
6720     return;
6721   case Intrinsic::reset_fpmode: {
6722     Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot());
6723     DAG.setRoot(Res);
6724     return;
6725   }
6726   case Intrinsic::pcmarker: {
6727     SDValue Tmp = getValue(I.getArgOperand(0));
6728     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6729     return;
6730   }
6731   case Intrinsic::readcyclecounter: {
6732     SDValue Op = getRoot();
6733     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6734                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6735     setValue(&I, Res);
6736     DAG.setRoot(Res.getValue(1));
6737     return;
6738   }
6739   case Intrinsic::bitreverse:
6740     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6741                              getValue(I.getArgOperand(0)).getValueType(),
6742                              getValue(I.getArgOperand(0))));
6743     return;
6744   case Intrinsic::bswap:
6745     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6746                              getValue(I.getArgOperand(0)).getValueType(),
6747                              getValue(I.getArgOperand(0))));
6748     return;
6749   case Intrinsic::cttz: {
6750     SDValue Arg = getValue(I.getArgOperand(0));
6751     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6752     EVT Ty = Arg.getValueType();
6753     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6754                              sdl, Ty, Arg));
6755     return;
6756   }
6757   case Intrinsic::ctlz: {
6758     SDValue Arg = getValue(I.getArgOperand(0));
6759     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6760     EVT Ty = Arg.getValueType();
6761     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6762                              sdl, Ty, Arg));
6763     return;
6764   }
6765   case Intrinsic::ctpop: {
6766     SDValue Arg = getValue(I.getArgOperand(0));
6767     EVT Ty = Arg.getValueType();
6768     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6769     return;
6770   }
6771   case Intrinsic::fshl:
6772   case Intrinsic::fshr: {
6773     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6774     SDValue X = getValue(I.getArgOperand(0));
6775     SDValue Y = getValue(I.getArgOperand(1));
6776     SDValue Z = getValue(I.getArgOperand(2));
6777     EVT VT = X.getValueType();
6778 
6779     if (X == Y) {
6780       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6781       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6782     } else {
6783       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6784       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6785     }
6786     return;
6787   }
6788   case Intrinsic::sadd_sat: {
6789     SDValue Op1 = getValue(I.getArgOperand(0));
6790     SDValue Op2 = getValue(I.getArgOperand(1));
6791     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6792     return;
6793   }
6794   case Intrinsic::uadd_sat: {
6795     SDValue Op1 = getValue(I.getArgOperand(0));
6796     SDValue Op2 = getValue(I.getArgOperand(1));
6797     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6798     return;
6799   }
6800   case Intrinsic::ssub_sat: {
6801     SDValue Op1 = getValue(I.getArgOperand(0));
6802     SDValue Op2 = getValue(I.getArgOperand(1));
6803     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6804     return;
6805   }
6806   case Intrinsic::usub_sat: {
6807     SDValue Op1 = getValue(I.getArgOperand(0));
6808     SDValue Op2 = getValue(I.getArgOperand(1));
6809     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6810     return;
6811   }
6812   case Intrinsic::sshl_sat: {
6813     SDValue Op1 = getValue(I.getArgOperand(0));
6814     SDValue Op2 = getValue(I.getArgOperand(1));
6815     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6816     return;
6817   }
6818   case Intrinsic::ushl_sat: {
6819     SDValue Op1 = getValue(I.getArgOperand(0));
6820     SDValue Op2 = getValue(I.getArgOperand(1));
6821     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6822     return;
6823   }
6824   case Intrinsic::smul_fix:
6825   case Intrinsic::umul_fix:
6826   case Intrinsic::smul_fix_sat:
6827   case Intrinsic::umul_fix_sat: {
6828     SDValue Op1 = getValue(I.getArgOperand(0));
6829     SDValue Op2 = getValue(I.getArgOperand(1));
6830     SDValue Op3 = getValue(I.getArgOperand(2));
6831     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6832                              Op1.getValueType(), Op1, Op2, Op3));
6833     return;
6834   }
6835   case Intrinsic::sdiv_fix:
6836   case Intrinsic::udiv_fix:
6837   case Intrinsic::sdiv_fix_sat:
6838   case Intrinsic::udiv_fix_sat: {
6839     SDValue Op1 = getValue(I.getArgOperand(0));
6840     SDValue Op2 = getValue(I.getArgOperand(1));
6841     SDValue Op3 = getValue(I.getArgOperand(2));
6842     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6843                               Op1, Op2, Op3, DAG, TLI));
6844     return;
6845   }
6846   case Intrinsic::smax: {
6847     SDValue Op1 = getValue(I.getArgOperand(0));
6848     SDValue Op2 = getValue(I.getArgOperand(1));
6849     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
6850     return;
6851   }
6852   case Intrinsic::smin: {
6853     SDValue Op1 = getValue(I.getArgOperand(0));
6854     SDValue Op2 = getValue(I.getArgOperand(1));
6855     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
6856     return;
6857   }
6858   case Intrinsic::umax: {
6859     SDValue Op1 = getValue(I.getArgOperand(0));
6860     SDValue Op2 = getValue(I.getArgOperand(1));
6861     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
6862     return;
6863   }
6864   case Intrinsic::umin: {
6865     SDValue Op1 = getValue(I.getArgOperand(0));
6866     SDValue Op2 = getValue(I.getArgOperand(1));
6867     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
6868     return;
6869   }
6870   case Intrinsic::abs: {
6871     // TODO: Preserve "int min is poison" arg in SDAG?
6872     SDValue Op1 = getValue(I.getArgOperand(0));
6873     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
6874     return;
6875   }
6876   case Intrinsic::stacksave: {
6877     SDValue Op = getRoot();
6878     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6879     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6880     setValue(&I, Res);
6881     DAG.setRoot(Res.getValue(1));
6882     return;
6883   }
6884   case Intrinsic::stackrestore:
6885     Res = getValue(I.getArgOperand(0));
6886     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6887     return;
6888   case Intrinsic::get_dynamic_area_offset: {
6889     SDValue Op = getRoot();
6890     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6891     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6892     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6893     // target.
6894     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
6895       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6896                          " intrinsic!");
6897     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6898                       Op);
6899     DAG.setRoot(Op);
6900     setValue(&I, Res);
6901     return;
6902   }
6903   case Intrinsic::stackguard: {
6904     MachineFunction &MF = DAG.getMachineFunction();
6905     const Module &M = *MF.getFunction().getParent();
6906     SDValue Chain = getRoot();
6907     if (TLI.useLoadStackGuardNode()) {
6908       Res = getLoadStackGuard(DAG, sdl, Chain);
6909     } else {
6910       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6911       const Value *Global = TLI.getSDagStackGuard(M);
6912       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
6913       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6914                         MachinePointerInfo(Global, 0), Align,
6915                         MachineMemOperand::MOVolatile);
6916     }
6917     if (TLI.useStackGuardXorFP())
6918       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6919     DAG.setRoot(Chain);
6920     setValue(&I, Res);
6921     return;
6922   }
6923   case Intrinsic::stackprotector: {
6924     // Emit code into the DAG to store the stack guard onto the stack.
6925     MachineFunction &MF = DAG.getMachineFunction();
6926     MachineFrameInfo &MFI = MF.getFrameInfo();
6927     SDValue Src, Chain = getRoot();
6928 
6929     if (TLI.useLoadStackGuardNode())
6930       Src = getLoadStackGuard(DAG, sdl, Chain);
6931     else
6932       Src = getValue(I.getArgOperand(0));   // The guard's value.
6933 
6934     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6935 
6936     int FI = FuncInfo.StaticAllocaMap[Slot];
6937     MFI.setStackProtectorIndex(FI);
6938     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6939 
6940     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6941 
6942     // Store the stack protector onto the stack.
6943     Res = DAG.getStore(
6944         Chain, sdl, Src, FIN,
6945         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
6946         MaybeAlign(), MachineMemOperand::MOVolatile);
6947     setValue(&I, Res);
6948     DAG.setRoot(Res);
6949     return;
6950   }
6951   case Intrinsic::objectsize:
6952     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6953 
6954   case Intrinsic::is_constant:
6955     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6956 
6957   case Intrinsic::annotation:
6958   case Intrinsic::ptr_annotation:
6959   case Intrinsic::launder_invariant_group:
6960   case Intrinsic::strip_invariant_group:
6961     // Drop the intrinsic, but forward the value
6962     setValue(&I, getValue(I.getOperand(0)));
6963     return;
6964 
6965   case Intrinsic::assume:
6966   case Intrinsic::experimental_noalias_scope_decl:
6967   case Intrinsic::var_annotation:
6968   case Intrinsic::sideeffect:
6969     // Discard annotate attributes, noalias scope declarations, assumptions, and
6970     // artificial side-effects.
6971     return;
6972 
6973   case Intrinsic::codeview_annotation: {
6974     // Emit a label associated with this metadata.
6975     MachineFunction &MF = DAG.getMachineFunction();
6976     MCSymbol *Label =
6977         MF.getMMI().getContext().createTempSymbol("annotation", true);
6978     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6979     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6980     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6981     DAG.setRoot(Res);
6982     return;
6983   }
6984 
6985   case Intrinsic::init_trampoline: {
6986     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6987 
6988     SDValue Ops[6];
6989     Ops[0] = getRoot();
6990     Ops[1] = getValue(I.getArgOperand(0));
6991     Ops[2] = getValue(I.getArgOperand(1));
6992     Ops[3] = getValue(I.getArgOperand(2));
6993     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6994     Ops[5] = DAG.getSrcValue(F);
6995 
6996     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6997 
6998     DAG.setRoot(Res);
6999     return;
7000   }
7001   case Intrinsic::adjust_trampoline:
7002     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
7003                              TLI.getPointerTy(DAG.getDataLayout()),
7004                              getValue(I.getArgOperand(0))));
7005     return;
7006   case Intrinsic::gcroot: {
7007     assert(DAG.getMachineFunction().getFunction().hasGC() &&
7008            "only valid in functions with gc specified, enforced by Verifier");
7009     assert(GFI && "implied by previous");
7010     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
7011     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
7012 
7013     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
7014     GFI->addStackRoot(FI->getIndex(), TypeMap);
7015     return;
7016   }
7017   case Intrinsic::gcread:
7018   case Intrinsic::gcwrite:
7019     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
7020   case Intrinsic::get_rounding:
7021     Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot());
7022     setValue(&I, Res);
7023     DAG.setRoot(Res.getValue(1));
7024     return;
7025 
7026   case Intrinsic::expect:
7027     // Just replace __builtin_expect(exp, c) with EXP.
7028     setValue(&I, getValue(I.getArgOperand(0)));
7029     return;
7030 
7031   case Intrinsic::ubsantrap:
7032   case Intrinsic::debugtrap:
7033   case Intrinsic::trap: {
7034     StringRef TrapFuncName =
7035         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
7036     if (TrapFuncName.empty()) {
7037       switch (Intrinsic) {
7038       case Intrinsic::trap:
7039         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
7040         break;
7041       case Intrinsic::debugtrap:
7042         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
7043         break;
7044       case Intrinsic::ubsantrap:
7045         DAG.setRoot(DAG.getNode(
7046             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
7047             DAG.getTargetConstant(
7048                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
7049                 MVT::i32)));
7050         break;
7051       default: llvm_unreachable("unknown trap intrinsic");
7052       }
7053       return;
7054     }
7055     TargetLowering::ArgListTy Args;
7056     if (Intrinsic == Intrinsic::ubsantrap) {
7057       Args.push_back(TargetLoweringBase::ArgListEntry());
7058       Args[0].Val = I.getArgOperand(0);
7059       Args[0].Node = getValue(Args[0].Val);
7060       Args[0].Ty = Args[0].Val->getType();
7061     }
7062 
7063     TargetLowering::CallLoweringInfo CLI(DAG);
7064     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
7065         CallingConv::C, I.getType(),
7066         DAG.getExternalSymbol(TrapFuncName.data(),
7067                               TLI.getPointerTy(DAG.getDataLayout())),
7068         std::move(Args));
7069 
7070     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7071     DAG.setRoot(Result.second);
7072     return;
7073   }
7074 
7075   case Intrinsic::uadd_with_overflow:
7076   case Intrinsic::sadd_with_overflow:
7077   case Intrinsic::usub_with_overflow:
7078   case Intrinsic::ssub_with_overflow:
7079   case Intrinsic::umul_with_overflow:
7080   case Intrinsic::smul_with_overflow: {
7081     ISD::NodeType Op;
7082     switch (Intrinsic) {
7083     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7084     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
7085     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
7086     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
7087     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
7088     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
7089     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
7090     }
7091     SDValue Op1 = getValue(I.getArgOperand(0));
7092     SDValue Op2 = getValue(I.getArgOperand(1));
7093 
7094     EVT ResultVT = Op1.getValueType();
7095     EVT OverflowVT = MVT::i1;
7096     if (ResultVT.isVector())
7097       OverflowVT = EVT::getVectorVT(
7098           *Context, OverflowVT, ResultVT.getVectorElementCount());
7099 
7100     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
7101     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
7102     return;
7103   }
7104   case Intrinsic::prefetch: {
7105     SDValue Ops[5];
7106     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7107     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
7108     Ops[0] = DAG.getRoot();
7109     Ops[1] = getValue(I.getArgOperand(0));
7110     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
7111                                    MVT::i32);
7112     Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl,
7113                                    MVT::i32);
7114     Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl,
7115                                    MVT::i32);
7116     SDValue Result = DAG.getMemIntrinsicNode(
7117         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
7118         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
7119         /* align */ std::nullopt, Flags);
7120 
7121     // Chain the prefetch in parallell with any pending loads, to stay out of
7122     // the way of later optimizations.
7123     PendingLoads.push_back(Result);
7124     Result = getRoot();
7125     DAG.setRoot(Result);
7126     return;
7127   }
7128   case Intrinsic::lifetime_start:
7129   case Intrinsic::lifetime_end: {
7130     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
7131     // Stack coloring is not enabled in O0, discard region information.
7132     if (TM.getOptLevel() == CodeGenOptLevel::None)
7133       return;
7134 
7135     const int64_t ObjectSize =
7136         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
7137     Value *const ObjectPtr = I.getArgOperand(1);
7138     SmallVector<const Value *, 4> Allocas;
7139     getUnderlyingObjects(ObjectPtr, Allocas);
7140 
7141     for (const Value *Alloca : Allocas) {
7142       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
7143 
7144       // Could not find an Alloca.
7145       if (!LifetimeObject)
7146         continue;
7147 
7148       // First check that the Alloca is static, otherwise it won't have a
7149       // valid frame index.
7150       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
7151       if (SI == FuncInfo.StaticAllocaMap.end())
7152         return;
7153 
7154       const int FrameIndex = SI->second;
7155       int64_t Offset;
7156       if (GetPointerBaseWithConstantOffset(
7157               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
7158         Offset = -1; // Cannot determine offset from alloca to lifetime object.
7159       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
7160                                 Offset);
7161       DAG.setRoot(Res);
7162     }
7163     return;
7164   }
7165   case Intrinsic::pseudoprobe: {
7166     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
7167     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7168     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
7169     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
7170     DAG.setRoot(Res);
7171     return;
7172   }
7173   case Intrinsic::invariant_start:
7174     // Discard region information.
7175     setValue(&I,
7176              DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
7177     return;
7178   case Intrinsic::invariant_end:
7179     // Discard region information.
7180     return;
7181   case Intrinsic::clear_cache:
7182     /// FunctionName may be null.
7183     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
7184       lowerCallToExternalSymbol(I, FunctionName);
7185     return;
7186   case Intrinsic::donothing:
7187   case Intrinsic::seh_try_begin:
7188   case Intrinsic::seh_scope_begin:
7189   case Intrinsic::seh_try_end:
7190   case Intrinsic::seh_scope_end:
7191     // ignore
7192     return;
7193   case Intrinsic::experimental_stackmap:
7194     visitStackmap(I);
7195     return;
7196   case Intrinsic::experimental_patchpoint_void:
7197   case Intrinsic::experimental_patchpoint_i64:
7198     visitPatchpoint(I);
7199     return;
7200   case Intrinsic::experimental_gc_statepoint:
7201     LowerStatepoint(cast<GCStatepointInst>(I));
7202     return;
7203   case Intrinsic::experimental_gc_result:
7204     visitGCResult(cast<GCResultInst>(I));
7205     return;
7206   case Intrinsic::experimental_gc_relocate:
7207     visitGCRelocate(cast<GCRelocateInst>(I));
7208     return;
7209   case Intrinsic::instrprof_cover:
7210     llvm_unreachable("instrprof failed to lower a cover");
7211   case Intrinsic::instrprof_increment:
7212     llvm_unreachable("instrprof failed to lower an increment");
7213   case Intrinsic::instrprof_timestamp:
7214     llvm_unreachable("instrprof failed to lower a timestamp");
7215   case Intrinsic::instrprof_value_profile:
7216     llvm_unreachable("instrprof failed to lower a value profiling call");
7217   case Intrinsic::instrprof_mcdc_parameters:
7218     llvm_unreachable("instrprof failed to lower mcdc parameters");
7219   case Intrinsic::instrprof_mcdc_tvbitmap_update:
7220     llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update");
7221   case Intrinsic::instrprof_mcdc_condbitmap_update:
7222     llvm_unreachable("instrprof failed to lower an mcdc condbitmap update");
7223   case Intrinsic::localescape: {
7224     MachineFunction &MF = DAG.getMachineFunction();
7225     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
7226 
7227     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
7228     // is the same on all targets.
7229     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
7230       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
7231       if (isa<ConstantPointerNull>(Arg))
7232         continue; // Skip null pointers. They represent a hole in index space.
7233       AllocaInst *Slot = cast<AllocaInst>(Arg);
7234       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
7235              "can only escape static allocas");
7236       int FI = FuncInfo.StaticAllocaMap[Slot];
7237       MCSymbol *FrameAllocSym =
7238           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7239               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
7240       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
7241               TII->get(TargetOpcode::LOCAL_ESCAPE))
7242           .addSym(FrameAllocSym)
7243           .addFrameIndex(FI);
7244     }
7245 
7246     return;
7247   }
7248 
7249   case Intrinsic::localrecover: {
7250     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
7251     MachineFunction &MF = DAG.getMachineFunction();
7252 
7253     // Get the symbol that defines the frame offset.
7254     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
7255     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
7256     unsigned IdxVal =
7257         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
7258     MCSymbol *FrameAllocSym =
7259         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7260             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
7261 
7262     Value *FP = I.getArgOperand(1);
7263     SDValue FPVal = getValue(FP);
7264     EVT PtrVT = FPVal.getValueType();
7265 
7266     // Create a MCSymbol for the label to avoid any target lowering
7267     // that would make this PC relative.
7268     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
7269     SDValue OffsetVal =
7270         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
7271 
7272     // Add the offset to the FP.
7273     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
7274     setValue(&I, Add);
7275 
7276     return;
7277   }
7278 
7279   case Intrinsic::eh_exceptionpointer:
7280   case Intrinsic::eh_exceptioncode: {
7281     // Get the exception pointer vreg, copy from it, and resize it to fit.
7282     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
7283     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
7284     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
7285     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
7286     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
7287     if (Intrinsic == Intrinsic::eh_exceptioncode)
7288       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
7289     setValue(&I, N);
7290     return;
7291   }
7292   case Intrinsic::xray_customevent: {
7293     // Here we want to make sure that the intrinsic behaves as if it has a
7294     // specific calling convention.
7295     const auto &Triple = DAG.getTarget().getTargetTriple();
7296     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7297       return;
7298 
7299     SmallVector<SDValue, 8> Ops;
7300 
7301     // We want to say that we always want the arguments in registers.
7302     SDValue LogEntryVal = getValue(I.getArgOperand(0));
7303     SDValue StrSizeVal = getValue(I.getArgOperand(1));
7304     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7305     SDValue Chain = getRoot();
7306     Ops.push_back(LogEntryVal);
7307     Ops.push_back(StrSizeVal);
7308     Ops.push_back(Chain);
7309 
7310     // We need to enforce the calling convention for the callsite, so that
7311     // argument ordering is enforced correctly, and that register allocation can
7312     // see that some registers may be assumed clobbered and have to preserve
7313     // them across calls to the intrinsic.
7314     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
7315                                            sdl, NodeTys, Ops);
7316     SDValue patchableNode = SDValue(MN, 0);
7317     DAG.setRoot(patchableNode);
7318     setValue(&I, patchableNode);
7319     return;
7320   }
7321   case Intrinsic::xray_typedevent: {
7322     // Here we want to make sure that the intrinsic behaves as if it has a
7323     // specific calling convention.
7324     const auto &Triple = DAG.getTarget().getTargetTriple();
7325     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7326       return;
7327 
7328     SmallVector<SDValue, 8> Ops;
7329 
7330     // We want to say that we always want the arguments in registers.
7331     // It's unclear to me how manipulating the selection DAG here forces callers
7332     // to provide arguments in registers instead of on the stack.
7333     SDValue LogTypeId = getValue(I.getArgOperand(0));
7334     SDValue LogEntryVal = getValue(I.getArgOperand(1));
7335     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7336     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7337     SDValue Chain = getRoot();
7338     Ops.push_back(LogTypeId);
7339     Ops.push_back(LogEntryVal);
7340     Ops.push_back(StrSizeVal);
7341     Ops.push_back(Chain);
7342 
7343     // We need to enforce the calling convention for the callsite, so that
7344     // argument ordering is enforced correctly, and that register allocation can
7345     // see that some registers may be assumed clobbered and have to preserve
7346     // them across calls to the intrinsic.
7347     MachineSDNode *MN = DAG.getMachineNode(
7348         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7349     SDValue patchableNode = SDValue(MN, 0);
7350     DAG.setRoot(patchableNode);
7351     setValue(&I, patchableNode);
7352     return;
7353   }
7354   case Intrinsic::experimental_deoptimize:
7355     LowerDeoptimizeCall(&I);
7356     return;
7357   case Intrinsic::experimental_stepvector:
7358     visitStepVector(I);
7359     return;
7360   case Intrinsic::vector_reduce_fadd:
7361   case Intrinsic::vector_reduce_fmul:
7362   case Intrinsic::vector_reduce_add:
7363   case Intrinsic::vector_reduce_mul:
7364   case Intrinsic::vector_reduce_and:
7365   case Intrinsic::vector_reduce_or:
7366   case Intrinsic::vector_reduce_xor:
7367   case Intrinsic::vector_reduce_smax:
7368   case Intrinsic::vector_reduce_smin:
7369   case Intrinsic::vector_reduce_umax:
7370   case Intrinsic::vector_reduce_umin:
7371   case Intrinsic::vector_reduce_fmax:
7372   case Intrinsic::vector_reduce_fmin:
7373   case Intrinsic::vector_reduce_fmaximum:
7374   case Intrinsic::vector_reduce_fminimum:
7375     visitVectorReduce(I, Intrinsic);
7376     return;
7377 
7378   case Intrinsic::icall_branch_funnel: {
7379     SmallVector<SDValue, 16> Ops;
7380     Ops.push_back(getValue(I.getArgOperand(0)));
7381 
7382     int64_t Offset;
7383     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7384         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7385     if (!Base)
7386       report_fatal_error(
7387           "llvm.icall.branch.funnel operand must be a GlobalValue");
7388     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7389 
7390     struct BranchFunnelTarget {
7391       int64_t Offset;
7392       SDValue Target;
7393     };
7394     SmallVector<BranchFunnelTarget, 8> Targets;
7395 
7396     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7397       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7398           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7399       if (ElemBase != Base)
7400         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7401                            "to the same GlobalValue");
7402 
7403       SDValue Val = getValue(I.getArgOperand(Op + 1));
7404       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7405       if (!GA)
7406         report_fatal_error(
7407             "llvm.icall.branch.funnel operand must be a GlobalValue");
7408       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7409                                      GA->getGlobal(), sdl, Val.getValueType(),
7410                                      GA->getOffset())});
7411     }
7412     llvm::sort(Targets,
7413                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7414                  return T1.Offset < T2.Offset;
7415                });
7416 
7417     for (auto &T : Targets) {
7418       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7419       Ops.push_back(T.Target);
7420     }
7421 
7422     Ops.push_back(DAG.getRoot()); // Chain
7423     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7424                                  MVT::Other, Ops),
7425               0);
7426     DAG.setRoot(N);
7427     setValue(&I, N);
7428     HasTailCall = true;
7429     return;
7430   }
7431 
7432   case Intrinsic::wasm_landingpad_index:
7433     // Information this intrinsic contained has been transferred to
7434     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7435     // delete it now.
7436     return;
7437 
7438   case Intrinsic::aarch64_settag:
7439   case Intrinsic::aarch64_settag_zero: {
7440     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7441     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7442     SDValue Val = TSI.EmitTargetCodeForSetTag(
7443         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7444         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7445         ZeroMemory);
7446     DAG.setRoot(Val);
7447     setValue(&I, Val);
7448     return;
7449   }
7450   case Intrinsic::amdgcn_cs_chain: {
7451     assert(I.arg_size() == 5 && "Additional args not supported yet");
7452     assert(cast<ConstantInt>(I.getOperand(4))->isZero() &&
7453            "Non-zero flags not supported yet");
7454 
7455     // At this point we don't care if it's amdgpu_cs_chain or
7456     // amdgpu_cs_chain_preserve.
7457     CallingConv::ID CC = CallingConv::AMDGPU_CS_Chain;
7458 
7459     Type *RetTy = I.getType();
7460     assert(RetTy->isVoidTy() && "Should not return");
7461 
7462     SDValue Callee = getValue(I.getOperand(0));
7463 
7464     // We only have 2 actual args: one for the SGPRs and one for the VGPRs.
7465     // We'll also tack the value of the EXEC mask at the end.
7466     TargetLowering::ArgListTy Args;
7467     Args.reserve(3);
7468 
7469     for (unsigned Idx : {2, 3, 1}) {
7470       TargetLowering::ArgListEntry Arg;
7471       Arg.Node = getValue(I.getOperand(Idx));
7472       Arg.Ty = I.getOperand(Idx)->getType();
7473       Arg.setAttributes(&I, Idx);
7474       Args.push_back(Arg);
7475     }
7476 
7477     assert(Args[0].IsInReg && "SGPR args should be marked inreg");
7478     assert(!Args[1].IsInReg && "VGPR args should not be marked inreg");
7479     Args[2].IsInReg = true; // EXEC should be inreg
7480 
7481     TargetLowering::CallLoweringInfo CLI(DAG);
7482     CLI.setDebugLoc(getCurSDLoc())
7483         .setChain(getRoot())
7484         .setCallee(CC, RetTy, Callee, std::move(Args))
7485         .setNoReturn(true)
7486         .setTailCall(true)
7487         .setConvergent(I.isConvergent());
7488     CLI.CB = &I;
7489     std::pair<SDValue, SDValue> Result =
7490         lowerInvokable(CLI, /*EHPadBB*/ nullptr);
7491     (void)Result;
7492     assert(!Result.first.getNode() && !Result.second.getNode() &&
7493            "Should've lowered as tail call");
7494 
7495     HasTailCall = true;
7496     return;
7497   }
7498   case Intrinsic::ptrmask: {
7499     SDValue Ptr = getValue(I.getOperand(0));
7500     SDValue Mask = getValue(I.getOperand(1));
7501 
7502     EVT PtrVT = Ptr.getValueType();
7503     assert(PtrVT == Mask.getValueType() &&
7504            "Pointers with different index type are not supported by SDAG");
7505     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask));
7506     return;
7507   }
7508   case Intrinsic::threadlocal_address: {
7509     setValue(&I, getValue(I.getOperand(0)));
7510     return;
7511   }
7512   case Intrinsic::get_active_lane_mask: {
7513     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7514     SDValue Index = getValue(I.getOperand(0));
7515     EVT ElementVT = Index.getValueType();
7516 
7517     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
7518       visitTargetIntrinsic(I, Intrinsic);
7519       return;
7520     }
7521 
7522     SDValue TripCount = getValue(I.getOperand(1));
7523     EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT,
7524                                  CCVT.getVectorElementCount());
7525 
7526     SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
7527     SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
7528     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
7529     SDValue VectorInduction = DAG.getNode(
7530         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
7531     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
7532                                  VectorTripCount, ISD::CondCode::SETULT);
7533     setValue(&I, SetCC);
7534     return;
7535   }
7536   case Intrinsic::experimental_get_vector_length: {
7537     assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 &&
7538            "Expected positive VF");
7539     unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue();
7540     bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne();
7541 
7542     SDValue Count = getValue(I.getOperand(0));
7543     EVT CountVT = Count.getValueType();
7544 
7545     if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) {
7546       visitTargetIntrinsic(I, Intrinsic);
7547       return;
7548     }
7549 
7550     // Expand to a umin between the trip count and the maximum elements the type
7551     // can hold.
7552     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7553 
7554     // Extend the trip count to at least the result VT.
7555     if (CountVT.bitsLT(VT)) {
7556       Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count);
7557       CountVT = VT;
7558     }
7559 
7560     SDValue MaxEVL = DAG.getElementCount(sdl, CountVT,
7561                                          ElementCount::get(VF, IsScalable));
7562 
7563     SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL);
7564     // Clip to the result type if needed.
7565     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin);
7566 
7567     setValue(&I, Trunc);
7568     return;
7569   }
7570   case Intrinsic::experimental_cttz_elts: {
7571     auto DL = getCurSDLoc();
7572     SDValue Op = getValue(I.getOperand(0));
7573     EVT OpVT = Op.getValueType();
7574 
7575     if (!TLI.shouldExpandCttzElements(OpVT)) {
7576       visitTargetIntrinsic(I, Intrinsic);
7577       return;
7578     }
7579 
7580     if (OpVT.getScalarType() != MVT::i1) {
7581       // Compare the input vector elements to zero & use to count trailing zeros
7582       SDValue AllZero = DAG.getConstant(0, DL, OpVT);
7583       OpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
7584                               OpVT.getVectorElementCount());
7585       Op = DAG.getSetCC(DL, OpVT, Op, AllZero, ISD::SETNE);
7586     }
7587 
7588     // Find the smallest "sensible" element type to use for the expansion.
7589     ConstantRange CR(
7590         APInt(64, OpVT.getVectorElementCount().getKnownMinValue()));
7591     if (OpVT.isScalableVT())
7592       CR = CR.umul_sat(getVScaleRange(I.getCaller(), 64));
7593 
7594     // If the zero-is-poison flag is set, we can assume the upper limit
7595     // of the result is VF-1.
7596     if (!cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero())
7597       CR = CR.subtract(APInt(64, 1));
7598 
7599     unsigned EltWidth = I.getType()->getScalarSizeInBits();
7600     EltWidth = std::min(EltWidth, (unsigned)CR.getActiveBits());
7601     EltWidth = std::max(llvm::bit_ceil(EltWidth), (unsigned)8);
7602 
7603     MVT NewEltTy = MVT::getIntegerVT(EltWidth);
7604 
7605     // Create the new vector type & get the vector length
7606     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), NewEltTy,
7607                                  OpVT.getVectorElementCount());
7608 
7609     SDValue VL =
7610         DAG.getElementCount(DL, NewEltTy, OpVT.getVectorElementCount());
7611 
7612     SDValue StepVec = DAG.getStepVector(DL, NewVT);
7613     SDValue SplatVL = DAG.getSplat(NewVT, DL, VL);
7614     SDValue StepVL = DAG.getNode(ISD::SUB, DL, NewVT, SplatVL, StepVec);
7615     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, Op);
7616     SDValue And = DAG.getNode(ISD::AND, DL, NewVT, StepVL, Ext);
7617     SDValue Max = DAG.getNode(ISD::VECREDUCE_UMAX, DL, NewEltTy, And);
7618     SDValue Sub = DAG.getNode(ISD::SUB, DL, NewEltTy, VL, Max);
7619 
7620     EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7621     SDValue Ret = DAG.getZExtOrTrunc(Sub, DL, RetTy);
7622 
7623     setValue(&I, Ret);
7624     return;
7625   }
7626   case Intrinsic::vector_insert: {
7627     SDValue Vec = getValue(I.getOperand(0));
7628     SDValue SubVec = getValue(I.getOperand(1));
7629     SDValue Index = getValue(I.getOperand(2));
7630 
7631     // The intrinsic's index type is i64, but the SDNode requires an index type
7632     // suitable for the target. Convert the index as required.
7633     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7634     if (Index.getValueType() != VectorIdxTy)
7635       Index = DAG.getVectorIdxConstant(
7636           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7637 
7638     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7639     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
7640                              Index));
7641     return;
7642   }
7643   case Intrinsic::vector_extract: {
7644     SDValue Vec = getValue(I.getOperand(0));
7645     SDValue Index = getValue(I.getOperand(1));
7646     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7647 
7648     // The intrinsic's index type is i64, but the SDNode requires an index type
7649     // suitable for the target. Convert the index as required.
7650     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7651     if (Index.getValueType() != VectorIdxTy)
7652       Index = DAG.getVectorIdxConstant(
7653           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7654 
7655     setValue(&I,
7656              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
7657     return;
7658   }
7659   case Intrinsic::experimental_vector_reverse:
7660     visitVectorReverse(I);
7661     return;
7662   case Intrinsic::experimental_vector_splice:
7663     visitVectorSplice(I);
7664     return;
7665   case Intrinsic::callbr_landingpad:
7666     visitCallBrLandingPad(I);
7667     return;
7668   case Intrinsic::experimental_vector_interleave2:
7669     visitVectorInterleave(I);
7670     return;
7671   case Intrinsic::experimental_vector_deinterleave2:
7672     visitVectorDeinterleave(I);
7673     return;
7674   }
7675 }
7676 
7677 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7678     const ConstrainedFPIntrinsic &FPI) {
7679   SDLoc sdl = getCurSDLoc();
7680 
7681   // We do not need to serialize constrained FP intrinsics against
7682   // each other or against (nonvolatile) loads, so they can be
7683   // chained like loads.
7684   SDValue Chain = DAG.getRoot();
7685   SmallVector<SDValue, 4> Opers;
7686   Opers.push_back(Chain);
7687   if (FPI.isUnaryOp()) {
7688     Opers.push_back(getValue(FPI.getArgOperand(0)));
7689   } else if (FPI.isTernaryOp()) {
7690     Opers.push_back(getValue(FPI.getArgOperand(0)));
7691     Opers.push_back(getValue(FPI.getArgOperand(1)));
7692     Opers.push_back(getValue(FPI.getArgOperand(2)));
7693   } else {
7694     Opers.push_back(getValue(FPI.getArgOperand(0)));
7695     Opers.push_back(getValue(FPI.getArgOperand(1)));
7696   }
7697 
7698   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
7699     assert(Result.getNode()->getNumValues() == 2);
7700 
7701     // Push node to the appropriate list so that future instructions can be
7702     // chained up correctly.
7703     SDValue OutChain = Result.getValue(1);
7704     switch (EB) {
7705     case fp::ExceptionBehavior::ebIgnore:
7706       // The only reason why ebIgnore nodes still need to be chained is that
7707       // they might depend on the current rounding mode, and therefore must
7708       // not be moved across instruction that may change that mode.
7709       [[fallthrough]];
7710     case fp::ExceptionBehavior::ebMayTrap:
7711       // These must not be moved across calls or instructions that may change
7712       // floating-point exception masks.
7713       PendingConstrainedFP.push_back(OutChain);
7714       break;
7715     case fp::ExceptionBehavior::ebStrict:
7716       // These must not be moved across calls or instructions that may change
7717       // floating-point exception masks or read floating-point exception flags.
7718       // In addition, they cannot be optimized out even if unused.
7719       PendingConstrainedFPStrict.push_back(OutChain);
7720       break;
7721     }
7722   };
7723 
7724   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7725   EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
7726   SDVTList VTs = DAG.getVTList(VT, MVT::Other);
7727   fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
7728 
7729   SDNodeFlags Flags;
7730   if (EB == fp::ExceptionBehavior::ebIgnore)
7731     Flags.setNoFPExcept(true);
7732 
7733   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
7734     Flags.copyFMF(*FPOp);
7735 
7736   unsigned Opcode;
7737   switch (FPI.getIntrinsicID()) {
7738   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7739 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7740   case Intrinsic::INTRINSIC:                                                   \
7741     Opcode = ISD::STRICT_##DAGN;                                               \
7742     break;
7743 #include "llvm/IR/ConstrainedOps.def"
7744   case Intrinsic::experimental_constrained_fmuladd: {
7745     Opcode = ISD::STRICT_FMA;
7746     // Break fmuladd into fmul and fadd.
7747     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7748         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
7749       Opers.pop_back();
7750       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
7751       pushOutChain(Mul, EB);
7752       Opcode = ISD::STRICT_FADD;
7753       Opers.clear();
7754       Opers.push_back(Mul.getValue(1));
7755       Opers.push_back(Mul.getValue(0));
7756       Opers.push_back(getValue(FPI.getArgOperand(2)));
7757     }
7758     break;
7759   }
7760   }
7761 
7762   // A few strict DAG nodes carry additional operands that are not
7763   // set up by the default code above.
7764   switch (Opcode) {
7765   default: break;
7766   case ISD::STRICT_FP_ROUND:
7767     Opers.push_back(
7768         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7769     break;
7770   case ISD::STRICT_FSETCC:
7771   case ISD::STRICT_FSETCCS: {
7772     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7773     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
7774     if (TM.Options.NoNaNsFPMath)
7775       Condition = getFCmpCodeWithoutNaN(Condition);
7776     Opers.push_back(DAG.getCondCode(Condition));
7777     break;
7778   }
7779   }
7780 
7781   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7782   pushOutChain(Result, EB);
7783 
7784   SDValue FPResult = Result.getValue(0);
7785   setValue(&FPI, FPResult);
7786 }
7787 
7788 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
7789   std::optional<unsigned> ResOPC;
7790   switch (VPIntrin.getIntrinsicID()) {
7791   case Intrinsic::vp_ctlz: {
7792     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
7793     ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ;
7794     break;
7795   }
7796   case Intrinsic::vp_cttz: {
7797     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
7798     ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ;
7799     break;
7800   }
7801 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD)                                    \
7802   case Intrinsic::VPID:                                                        \
7803     ResOPC = ISD::VPSD;                                                        \
7804     break;
7805 #include "llvm/IR/VPIntrinsics.def"
7806   }
7807 
7808   if (!ResOPC)
7809     llvm_unreachable(
7810         "Inconsistency: no SDNode available for this VPIntrinsic!");
7811 
7812   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
7813       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
7814     if (VPIntrin.getFastMathFlags().allowReassoc())
7815       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
7816                                                 : ISD::VP_REDUCE_FMUL;
7817   }
7818 
7819   return *ResOPC;
7820 }
7821 
7822 void SelectionDAGBuilder::visitVPLoad(
7823     const VPIntrinsic &VPIntrin, EVT VT,
7824     const SmallVectorImpl<SDValue> &OpValues) {
7825   SDLoc DL = getCurSDLoc();
7826   Value *PtrOperand = VPIntrin.getArgOperand(0);
7827   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7828   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7829   const MDNode *Ranges = getRangeMetadata(VPIntrin);
7830   SDValue LD;
7831   // Do not serialize variable-length loads of constant memory with
7832   // anything.
7833   if (!Alignment)
7834     Alignment = DAG.getEVTAlign(VT);
7835   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7836   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7837   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7838   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7839       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7840       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7841   LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
7842                      MMO, false /*IsExpanding */);
7843   if (AddToChain)
7844     PendingLoads.push_back(LD.getValue(1));
7845   setValue(&VPIntrin, LD);
7846 }
7847 
7848 void SelectionDAGBuilder::visitVPGather(
7849     const VPIntrinsic &VPIntrin, EVT VT,
7850     const SmallVectorImpl<SDValue> &OpValues) {
7851   SDLoc DL = getCurSDLoc();
7852   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7853   Value *PtrOperand = VPIntrin.getArgOperand(0);
7854   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7855   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7856   const MDNode *Ranges = getRangeMetadata(VPIntrin);
7857   SDValue LD;
7858   if (!Alignment)
7859     Alignment = DAG.getEVTAlign(VT.getScalarType());
7860   unsigned AS =
7861     PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7862   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7863      MachinePointerInfo(AS), MachineMemOperand::MOLoad,
7864      MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7865   SDValue Base, Index, Scale;
7866   ISD::MemIndexType IndexType;
7867   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7868                                     this, VPIntrin.getParent(),
7869                                     VT.getScalarStoreSize());
7870   if (!UniformBase) {
7871     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7872     Index = getValue(PtrOperand);
7873     IndexType = ISD::SIGNED_SCALED;
7874     Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7875   }
7876   EVT IdxVT = Index.getValueType();
7877   EVT EltTy = IdxVT.getVectorElementType();
7878   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7879     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7880     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7881   }
7882   LD = DAG.getGatherVP(
7883       DAG.getVTList(VT, MVT::Other), VT, DL,
7884       {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
7885       IndexType);
7886   PendingLoads.push_back(LD.getValue(1));
7887   setValue(&VPIntrin, LD);
7888 }
7889 
7890 void SelectionDAGBuilder::visitVPStore(
7891     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
7892   SDLoc DL = getCurSDLoc();
7893   Value *PtrOperand = VPIntrin.getArgOperand(1);
7894   EVT VT = OpValues[0].getValueType();
7895   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7896   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7897   SDValue ST;
7898   if (!Alignment)
7899     Alignment = DAG.getEVTAlign(VT);
7900   SDValue Ptr = OpValues[1];
7901   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
7902   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7903       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7904       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7905   ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
7906                       OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
7907                       /* IsTruncating */ false, /*IsCompressing*/ false);
7908   DAG.setRoot(ST);
7909   setValue(&VPIntrin, ST);
7910 }
7911 
7912 void SelectionDAGBuilder::visitVPScatter(
7913     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
7914   SDLoc DL = getCurSDLoc();
7915   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7916   Value *PtrOperand = VPIntrin.getArgOperand(1);
7917   EVT VT = OpValues[0].getValueType();
7918   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7919   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7920   SDValue ST;
7921   if (!Alignment)
7922     Alignment = DAG.getEVTAlign(VT.getScalarType());
7923   unsigned AS =
7924       PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7925   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7926       MachinePointerInfo(AS), MachineMemOperand::MOStore,
7927       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7928   SDValue Base, Index, Scale;
7929   ISD::MemIndexType IndexType;
7930   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7931                                     this, VPIntrin.getParent(),
7932                                     VT.getScalarStoreSize());
7933   if (!UniformBase) {
7934     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7935     Index = getValue(PtrOperand);
7936     IndexType = ISD::SIGNED_SCALED;
7937     Scale =
7938       DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7939   }
7940   EVT IdxVT = Index.getValueType();
7941   EVT EltTy = IdxVT.getVectorElementType();
7942   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7943     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7944     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7945   }
7946   ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
7947                         {getMemoryRoot(), OpValues[0], Base, Index, Scale,
7948                          OpValues[2], OpValues[3]},
7949                         MMO, IndexType);
7950   DAG.setRoot(ST);
7951   setValue(&VPIntrin, ST);
7952 }
7953 
7954 void SelectionDAGBuilder::visitVPStridedLoad(
7955     const VPIntrinsic &VPIntrin, EVT VT,
7956     const SmallVectorImpl<SDValue> &OpValues) {
7957   SDLoc DL = getCurSDLoc();
7958   Value *PtrOperand = VPIntrin.getArgOperand(0);
7959   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7960   if (!Alignment)
7961     Alignment = DAG.getEVTAlign(VT.getScalarType());
7962   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7963   const MDNode *Ranges = getRangeMetadata(VPIntrin);
7964   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7965   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7966   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7967   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7968       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7969       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7970 
7971   SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
7972                                     OpValues[2], OpValues[3], MMO,
7973                                     false /*IsExpanding*/);
7974 
7975   if (AddToChain)
7976     PendingLoads.push_back(LD.getValue(1));
7977   setValue(&VPIntrin, LD);
7978 }
7979 
7980 void SelectionDAGBuilder::visitVPStridedStore(
7981     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
7982   SDLoc DL = getCurSDLoc();
7983   Value *PtrOperand = VPIntrin.getArgOperand(1);
7984   EVT VT = OpValues[0].getValueType();
7985   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7986   if (!Alignment)
7987     Alignment = DAG.getEVTAlign(VT.getScalarType());
7988   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7989   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7990       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7991       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7992 
7993   SDValue ST = DAG.getStridedStoreVP(
7994       getMemoryRoot(), DL, OpValues[0], OpValues[1],
7995       DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3],
7996       OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
7997       /*IsCompressing*/ false);
7998 
7999   DAG.setRoot(ST);
8000   setValue(&VPIntrin, ST);
8001 }
8002 
8003 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) {
8004   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8005   SDLoc DL = getCurSDLoc();
8006 
8007   ISD::CondCode Condition;
8008   CmpInst::Predicate CondCode = VPIntrin.getPredicate();
8009   bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy();
8010   if (IsFP) {
8011     // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan)
8012     // flags, but calls that don't return floating-point types can't be
8013     // FPMathOperators, like vp.fcmp. This affects constrained fcmp too.
8014     Condition = getFCmpCondCode(CondCode);
8015     if (TM.Options.NoNaNsFPMath)
8016       Condition = getFCmpCodeWithoutNaN(Condition);
8017   } else {
8018     Condition = getICmpCondCode(CondCode);
8019   }
8020 
8021   SDValue Op1 = getValue(VPIntrin.getOperand(0));
8022   SDValue Op2 = getValue(VPIntrin.getOperand(1));
8023   // #2 is the condition code
8024   SDValue MaskOp = getValue(VPIntrin.getOperand(3));
8025   SDValue EVL = getValue(VPIntrin.getOperand(4));
8026   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8027   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8028          "Unexpected target EVL type");
8029   EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL);
8030 
8031   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8032                                                         VPIntrin.getType());
8033   setValue(&VPIntrin,
8034            DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL));
8035 }
8036 
8037 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
8038     const VPIntrinsic &VPIntrin) {
8039   SDLoc DL = getCurSDLoc();
8040   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
8041 
8042   auto IID = VPIntrin.getIntrinsicID();
8043 
8044   if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin))
8045     return visitVPCmp(*CmpI);
8046 
8047   SmallVector<EVT, 4> ValueVTs;
8048   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8049   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
8050   SDVTList VTs = DAG.getVTList(ValueVTs);
8051 
8052   auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
8053 
8054   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8055   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8056          "Unexpected target EVL type");
8057 
8058   // Request operands.
8059   SmallVector<SDValue, 7> OpValues;
8060   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
8061     auto Op = getValue(VPIntrin.getArgOperand(I));
8062     if (I == EVLParamPos)
8063       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
8064     OpValues.push_back(Op);
8065   }
8066 
8067   switch (Opcode) {
8068   default: {
8069     SDNodeFlags SDFlags;
8070     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8071       SDFlags.copyFMF(*FPMO);
8072     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
8073     setValue(&VPIntrin, Result);
8074     break;
8075   }
8076   case ISD::VP_LOAD:
8077     visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
8078     break;
8079   case ISD::VP_GATHER:
8080     visitVPGather(VPIntrin, ValueVTs[0], OpValues);
8081     break;
8082   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
8083     visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
8084     break;
8085   case ISD::VP_STORE:
8086     visitVPStore(VPIntrin, OpValues);
8087     break;
8088   case ISD::VP_SCATTER:
8089     visitVPScatter(VPIntrin, OpValues);
8090     break;
8091   case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
8092     visitVPStridedStore(VPIntrin, OpValues);
8093     break;
8094   case ISD::VP_FMULADD: {
8095     assert(OpValues.size() == 5 && "Unexpected number of operands");
8096     SDNodeFlags SDFlags;
8097     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8098       SDFlags.copyFMF(*FPMO);
8099     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
8100         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) {
8101       setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags));
8102     } else {
8103       SDValue Mul = DAG.getNode(
8104           ISD::VP_FMUL, DL, VTs,
8105           {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags);
8106       SDValue Add =
8107           DAG.getNode(ISD::VP_FADD, DL, VTs,
8108                       {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags);
8109       setValue(&VPIntrin, Add);
8110     }
8111     break;
8112   }
8113   case ISD::VP_IS_FPCLASS: {
8114     const DataLayout DLayout = DAG.getDataLayout();
8115     EVT DestVT = TLI.getValueType(DLayout, VPIntrin.getType());
8116     auto Constant = cast<ConstantSDNode>(OpValues[1])->getZExtValue();
8117     SDValue Check = DAG.getTargetConstant(Constant, DL, MVT::i32);
8118     SDValue V = DAG.getNode(ISD::VP_IS_FPCLASS, DL, DestVT,
8119                             {OpValues[0], Check, OpValues[2], OpValues[3]});
8120     setValue(&VPIntrin, V);
8121     return;
8122   }
8123   case ISD::VP_INTTOPTR: {
8124     SDValue N = OpValues[0];
8125     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType());
8126     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType());
8127     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8128                                OpValues[2]);
8129     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8130                              OpValues[2]);
8131     setValue(&VPIntrin, N);
8132     break;
8133   }
8134   case ISD::VP_PTRTOINT: {
8135     SDValue N = OpValues[0];
8136     EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8137                                                           VPIntrin.getType());
8138     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(),
8139                                        VPIntrin.getOperand(0)->getType());
8140     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8141                                OpValues[2]);
8142     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8143                              OpValues[2]);
8144     setValue(&VPIntrin, N);
8145     break;
8146   }
8147   case ISD::VP_ABS:
8148   case ISD::VP_CTLZ:
8149   case ISD::VP_CTLZ_ZERO_UNDEF:
8150   case ISD::VP_CTTZ:
8151   case ISD::VP_CTTZ_ZERO_UNDEF: {
8152     SDValue Result =
8153         DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]});
8154     setValue(&VPIntrin, Result);
8155     break;
8156   }
8157   }
8158 }
8159 
8160 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
8161                                           const BasicBlock *EHPadBB,
8162                                           MCSymbol *&BeginLabel) {
8163   MachineFunction &MF = DAG.getMachineFunction();
8164   MachineModuleInfo &MMI = MF.getMMI();
8165 
8166   // Insert a label before the invoke call to mark the try range.  This can be
8167   // used to detect deletion of the invoke via the MachineModuleInfo.
8168   BeginLabel = MMI.getContext().createTempSymbol();
8169 
8170   // For SjLj, keep track of which landing pads go with which invokes
8171   // so as to maintain the ordering of pads in the LSDA.
8172   unsigned CallSiteIndex = MMI.getCurrentCallSite();
8173   if (CallSiteIndex) {
8174     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
8175     LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
8176 
8177     // Now that the call site is handled, stop tracking it.
8178     MMI.setCurrentCallSite(0);
8179   }
8180 
8181   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
8182 }
8183 
8184 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
8185                                         const BasicBlock *EHPadBB,
8186                                         MCSymbol *BeginLabel) {
8187   assert(BeginLabel && "BeginLabel should've been set");
8188 
8189   MachineFunction &MF = DAG.getMachineFunction();
8190   MachineModuleInfo &MMI = MF.getMMI();
8191 
8192   // Insert a label at the end of the invoke call to mark the try range.  This
8193   // can be used to detect deletion of the invoke via the MachineModuleInfo.
8194   MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
8195   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
8196 
8197   // Inform MachineModuleInfo of range.
8198   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
8199   // There is a platform (e.g. wasm) that uses funclet style IR but does not
8200   // actually use outlined funclets and their LSDA info style.
8201   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
8202     assert(II && "II should've been set");
8203     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
8204     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
8205   } else if (!isScopedEHPersonality(Pers)) {
8206     assert(EHPadBB);
8207     MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
8208   }
8209 
8210   return Chain;
8211 }
8212 
8213 std::pair<SDValue, SDValue>
8214 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
8215                                     const BasicBlock *EHPadBB) {
8216   MCSymbol *BeginLabel = nullptr;
8217 
8218   if (EHPadBB) {
8219     // Both PendingLoads and PendingExports must be flushed here;
8220     // this call might not return.
8221     (void)getRoot();
8222     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
8223     CLI.setChain(getRoot());
8224   }
8225 
8226   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8227   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
8228 
8229   assert((CLI.IsTailCall || Result.second.getNode()) &&
8230          "Non-null chain expected with non-tail call!");
8231   assert((Result.second.getNode() || !Result.first.getNode()) &&
8232          "Null value expected with tail call!");
8233 
8234   if (!Result.second.getNode()) {
8235     // As a special case, a null chain means that a tail call has been emitted
8236     // and the DAG root is already updated.
8237     HasTailCall = true;
8238 
8239     // Since there's no actual continuation from this block, nothing can be
8240     // relying on us setting vregs for them.
8241     PendingExports.clear();
8242   } else {
8243     DAG.setRoot(Result.second);
8244   }
8245 
8246   if (EHPadBB) {
8247     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
8248                            BeginLabel));
8249   }
8250 
8251   return Result;
8252 }
8253 
8254 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
8255                                       bool isTailCall,
8256                                       bool isMustTailCall,
8257                                       const BasicBlock *EHPadBB) {
8258   auto &DL = DAG.getDataLayout();
8259   FunctionType *FTy = CB.getFunctionType();
8260   Type *RetTy = CB.getType();
8261 
8262   TargetLowering::ArgListTy Args;
8263   Args.reserve(CB.arg_size());
8264 
8265   const Value *SwiftErrorVal = nullptr;
8266   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8267 
8268   if (isTailCall) {
8269     // Avoid emitting tail calls in functions with the disable-tail-calls
8270     // attribute.
8271     auto *Caller = CB.getParent()->getParent();
8272     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
8273         "true" && !isMustTailCall)
8274       isTailCall = false;
8275 
8276     // We can't tail call inside a function with a swifterror argument. Lowering
8277     // does not support this yet. It would have to move into the swifterror
8278     // register before the call.
8279     if (TLI.supportSwiftError() &&
8280         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
8281       isTailCall = false;
8282   }
8283 
8284   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
8285     TargetLowering::ArgListEntry Entry;
8286     const Value *V = *I;
8287 
8288     // Skip empty types
8289     if (V->getType()->isEmptyTy())
8290       continue;
8291 
8292     SDValue ArgNode = getValue(V);
8293     Entry.Node = ArgNode; Entry.Ty = V->getType();
8294 
8295     Entry.setAttributes(&CB, I - CB.arg_begin());
8296 
8297     // Use swifterror virtual register as input to the call.
8298     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
8299       SwiftErrorVal = V;
8300       // We find the virtual register for the actual swifterror argument.
8301       // Instead of using the Value, we use the virtual register instead.
8302       Entry.Node =
8303           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
8304                           EVT(TLI.getPointerTy(DL)));
8305     }
8306 
8307     Args.push_back(Entry);
8308 
8309     // If we have an explicit sret argument that is an Instruction, (i.e., it
8310     // might point to function-local memory), we can't meaningfully tail-call.
8311     if (Entry.IsSRet && isa<Instruction>(V))
8312       isTailCall = false;
8313   }
8314 
8315   // If call site has a cfguardtarget operand bundle, create and add an
8316   // additional ArgListEntry.
8317   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
8318     TargetLowering::ArgListEntry Entry;
8319     Value *V = Bundle->Inputs[0];
8320     SDValue ArgNode = getValue(V);
8321     Entry.Node = ArgNode;
8322     Entry.Ty = V->getType();
8323     Entry.IsCFGuardTarget = true;
8324     Args.push_back(Entry);
8325   }
8326 
8327   // Check if target-independent constraints permit a tail call here.
8328   // Target-dependent constraints are checked within TLI->LowerCallTo.
8329   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
8330     isTailCall = false;
8331 
8332   // Disable tail calls if there is an swifterror argument. Targets have not
8333   // been updated to support tail calls.
8334   if (TLI.supportSwiftError() && SwiftErrorVal)
8335     isTailCall = false;
8336 
8337   ConstantInt *CFIType = nullptr;
8338   if (CB.isIndirectCall()) {
8339     if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
8340       if (!TLI.supportKCFIBundles())
8341         report_fatal_error(
8342             "Target doesn't support calls with kcfi operand bundles.");
8343       CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
8344       assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
8345     }
8346   }
8347 
8348   TargetLowering::CallLoweringInfo CLI(DAG);
8349   CLI.setDebugLoc(getCurSDLoc())
8350       .setChain(getRoot())
8351       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
8352       .setTailCall(isTailCall)
8353       .setConvergent(CB.isConvergent())
8354       .setIsPreallocated(
8355           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
8356       .setCFIType(CFIType);
8357   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8358 
8359   if (Result.first.getNode()) {
8360     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
8361     setValue(&CB, Result.first);
8362   }
8363 
8364   // The last element of CLI.InVals has the SDValue for swifterror return.
8365   // Here we copy it to a virtual register and update SwiftErrorMap for
8366   // book-keeping.
8367   if (SwiftErrorVal && TLI.supportSwiftError()) {
8368     // Get the last element of InVals.
8369     SDValue Src = CLI.InVals.back();
8370     Register VReg =
8371         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
8372     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
8373     DAG.setRoot(CopyNode);
8374   }
8375 }
8376 
8377 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
8378                              SelectionDAGBuilder &Builder) {
8379   // Check to see if this load can be trivially constant folded, e.g. if the
8380   // input is from a string literal.
8381   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
8382     // Cast pointer to the type we really want to load.
8383     Type *LoadTy =
8384         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
8385     if (LoadVT.isVector())
8386       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
8387 
8388     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
8389                                          PointerType::getUnqual(LoadTy));
8390 
8391     if (const Constant *LoadCst =
8392             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
8393                                          LoadTy, Builder.DAG.getDataLayout()))
8394       return Builder.getValue(LoadCst);
8395   }
8396 
8397   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
8398   // still constant memory, the input chain can be the entry node.
8399   SDValue Root;
8400   bool ConstantMemory = false;
8401 
8402   // Do not serialize (non-volatile) loads of constant memory with anything.
8403   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
8404     Root = Builder.DAG.getEntryNode();
8405     ConstantMemory = true;
8406   } else {
8407     // Do not serialize non-volatile loads against each other.
8408     Root = Builder.DAG.getRoot();
8409   }
8410 
8411   SDValue Ptr = Builder.getValue(PtrVal);
8412   SDValue LoadVal =
8413       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
8414                           MachinePointerInfo(PtrVal), Align(1));
8415 
8416   if (!ConstantMemory)
8417     Builder.PendingLoads.push_back(LoadVal.getValue(1));
8418   return LoadVal;
8419 }
8420 
8421 /// Record the value for an instruction that produces an integer result,
8422 /// converting the type where necessary.
8423 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
8424                                                   SDValue Value,
8425                                                   bool IsSigned) {
8426   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8427                                                     I.getType(), true);
8428   Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT);
8429   setValue(&I, Value);
8430 }
8431 
8432 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
8433 /// true and lower it. Otherwise return false, and it will be lowered like a
8434 /// normal call.
8435 /// The caller already checked that \p I calls the appropriate LibFunc with a
8436 /// correct prototype.
8437 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
8438   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
8439   const Value *Size = I.getArgOperand(2);
8440   const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
8441   if (CSize && CSize->getZExtValue() == 0) {
8442     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8443                                                           I.getType(), true);
8444     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
8445     return true;
8446   }
8447 
8448   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8449   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
8450       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
8451       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
8452   if (Res.first.getNode()) {
8453     processIntegerCallValue(I, Res.first, true);
8454     PendingLoads.push_back(Res.second);
8455     return true;
8456   }
8457 
8458   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
8459   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
8460   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
8461     return false;
8462 
8463   // If the target has a fast compare for the given size, it will return a
8464   // preferred load type for that size. Require that the load VT is legal and
8465   // that the target supports unaligned loads of that type. Otherwise, return
8466   // INVALID.
8467   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
8468     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8469     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
8470     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
8471       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
8472       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
8473       // TODO: Check alignment of src and dest ptrs.
8474       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
8475       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
8476       if (!TLI.isTypeLegal(LVT) ||
8477           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
8478           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
8479         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
8480     }
8481 
8482     return LVT;
8483   };
8484 
8485   // This turns into unaligned loads. We only do this if the target natively
8486   // supports the MVT we'll be loading or if it is small enough (<= 4) that
8487   // we'll only produce a small number of byte loads.
8488   MVT LoadVT;
8489   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
8490   switch (NumBitsToCompare) {
8491   default:
8492     return false;
8493   case 16:
8494     LoadVT = MVT::i16;
8495     break;
8496   case 32:
8497     LoadVT = MVT::i32;
8498     break;
8499   case 64:
8500   case 128:
8501   case 256:
8502     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
8503     break;
8504   }
8505 
8506   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
8507     return false;
8508 
8509   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
8510   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
8511 
8512   // Bitcast to a wide integer type if the loads are vectors.
8513   if (LoadVT.isVector()) {
8514     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
8515     LoadL = DAG.getBitcast(CmpVT, LoadL);
8516     LoadR = DAG.getBitcast(CmpVT, LoadR);
8517   }
8518 
8519   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
8520   processIntegerCallValue(I, Cmp, false);
8521   return true;
8522 }
8523 
8524 /// See if we can lower a memchr call into an optimized form. If so, return
8525 /// true and lower it. Otherwise return false, and it will be lowered like a
8526 /// normal call.
8527 /// The caller already checked that \p I calls the appropriate LibFunc with a
8528 /// correct prototype.
8529 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
8530   const Value *Src = I.getArgOperand(0);
8531   const Value *Char = I.getArgOperand(1);
8532   const Value *Length = I.getArgOperand(2);
8533 
8534   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8535   std::pair<SDValue, SDValue> Res =
8536     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
8537                                 getValue(Src), getValue(Char), getValue(Length),
8538                                 MachinePointerInfo(Src));
8539   if (Res.first.getNode()) {
8540     setValue(&I, Res.first);
8541     PendingLoads.push_back(Res.second);
8542     return true;
8543   }
8544 
8545   return false;
8546 }
8547 
8548 /// See if we can lower a mempcpy call into an optimized form. If so, return
8549 /// true and lower it. Otherwise return false, and it will be lowered like a
8550 /// normal call.
8551 /// The caller already checked that \p I calls the appropriate LibFunc with a
8552 /// correct prototype.
8553 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
8554   SDValue Dst = getValue(I.getArgOperand(0));
8555   SDValue Src = getValue(I.getArgOperand(1));
8556   SDValue Size = getValue(I.getArgOperand(2));
8557 
8558   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
8559   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
8560   // DAG::getMemcpy needs Alignment to be defined.
8561   Align Alignment = std::min(DstAlign, SrcAlign);
8562 
8563   SDLoc sdl = getCurSDLoc();
8564 
8565   // In the mempcpy context we need to pass in a false value for isTailCall
8566   // because the return pointer needs to be adjusted by the size of
8567   // the copied memory.
8568   SDValue Root = getMemoryRoot();
8569   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, false, false,
8570                              /*isTailCall=*/false,
8571                              MachinePointerInfo(I.getArgOperand(0)),
8572                              MachinePointerInfo(I.getArgOperand(1)),
8573                              I.getAAMetadata());
8574   assert(MC.getNode() != nullptr &&
8575          "** memcpy should not be lowered as TailCall in mempcpy context **");
8576   DAG.setRoot(MC);
8577 
8578   // Check if Size needs to be truncated or extended.
8579   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
8580 
8581   // Adjust return pointer to point just past the last dst byte.
8582   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
8583                                     Dst, Size);
8584   setValue(&I, DstPlusSize);
8585   return true;
8586 }
8587 
8588 /// See if we can lower a strcpy call into an optimized form.  If so, return
8589 /// true and lower it, otherwise return false and it will be lowered like a
8590 /// normal call.
8591 /// The caller already checked that \p I calls the appropriate LibFunc with a
8592 /// correct prototype.
8593 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
8594   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8595 
8596   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8597   std::pair<SDValue, SDValue> Res =
8598     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
8599                                 getValue(Arg0), getValue(Arg1),
8600                                 MachinePointerInfo(Arg0),
8601                                 MachinePointerInfo(Arg1), isStpcpy);
8602   if (Res.first.getNode()) {
8603     setValue(&I, Res.first);
8604     DAG.setRoot(Res.second);
8605     return true;
8606   }
8607 
8608   return false;
8609 }
8610 
8611 /// See if we can lower a strcmp call into an optimized form.  If so, return
8612 /// true and lower it, otherwise return false and it will be lowered like a
8613 /// normal call.
8614 /// The caller already checked that \p I calls the appropriate LibFunc with a
8615 /// correct prototype.
8616 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
8617   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8618 
8619   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8620   std::pair<SDValue, SDValue> Res =
8621     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
8622                                 getValue(Arg0), getValue(Arg1),
8623                                 MachinePointerInfo(Arg0),
8624                                 MachinePointerInfo(Arg1));
8625   if (Res.first.getNode()) {
8626     processIntegerCallValue(I, Res.first, true);
8627     PendingLoads.push_back(Res.second);
8628     return true;
8629   }
8630 
8631   return false;
8632 }
8633 
8634 /// See if we can lower a strlen call into an optimized form.  If so, return
8635 /// true and lower it, otherwise return false and it will be lowered like a
8636 /// normal call.
8637 /// The caller already checked that \p I calls the appropriate LibFunc with a
8638 /// correct prototype.
8639 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
8640   const Value *Arg0 = I.getArgOperand(0);
8641 
8642   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8643   std::pair<SDValue, SDValue> Res =
8644     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
8645                                 getValue(Arg0), MachinePointerInfo(Arg0));
8646   if (Res.first.getNode()) {
8647     processIntegerCallValue(I, Res.first, false);
8648     PendingLoads.push_back(Res.second);
8649     return true;
8650   }
8651 
8652   return false;
8653 }
8654 
8655 /// See if we can lower a strnlen call into an optimized form.  If so, return
8656 /// true and lower it, otherwise return false and it will be lowered like a
8657 /// normal call.
8658 /// The caller already checked that \p I calls the appropriate LibFunc with a
8659 /// correct prototype.
8660 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
8661   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8662 
8663   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8664   std::pair<SDValue, SDValue> Res =
8665     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
8666                                  getValue(Arg0), getValue(Arg1),
8667                                  MachinePointerInfo(Arg0));
8668   if (Res.first.getNode()) {
8669     processIntegerCallValue(I, Res.first, false);
8670     PendingLoads.push_back(Res.second);
8671     return true;
8672   }
8673 
8674   return false;
8675 }
8676 
8677 /// See if we can lower a unary floating-point operation into an SDNode with
8678 /// the specified Opcode.  If so, return true and lower it, otherwise return
8679 /// false and it will be lowered like a normal call.
8680 /// The caller already checked that \p I calls the appropriate LibFunc with a
8681 /// correct prototype.
8682 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
8683                                               unsigned Opcode) {
8684   // We already checked this call's prototype; verify it doesn't modify errno.
8685   if (!I.onlyReadsMemory())
8686     return false;
8687 
8688   SDNodeFlags Flags;
8689   Flags.copyFMF(cast<FPMathOperator>(I));
8690 
8691   SDValue Tmp = getValue(I.getArgOperand(0));
8692   setValue(&I,
8693            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
8694   return true;
8695 }
8696 
8697 /// See if we can lower a binary floating-point operation into an SDNode with
8698 /// the specified Opcode. If so, return true and lower it. Otherwise return
8699 /// false, and it will be lowered like a normal call.
8700 /// The caller already checked that \p I calls the appropriate LibFunc with a
8701 /// correct prototype.
8702 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
8703                                                unsigned Opcode) {
8704   // We already checked this call's prototype; verify it doesn't modify errno.
8705   if (!I.onlyReadsMemory())
8706     return false;
8707 
8708   SDNodeFlags Flags;
8709   Flags.copyFMF(cast<FPMathOperator>(I));
8710 
8711   SDValue Tmp0 = getValue(I.getArgOperand(0));
8712   SDValue Tmp1 = getValue(I.getArgOperand(1));
8713   EVT VT = Tmp0.getValueType();
8714   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
8715   return true;
8716 }
8717 
8718 void SelectionDAGBuilder::visitCall(const CallInst &I) {
8719   // Handle inline assembly differently.
8720   if (I.isInlineAsm()) {
8721     visitInlineAsm(I);
8722     return;
8723   }
8724 
8725   diagnoseDontCall(I);
8726 
8727   if (Function *F = I.getCalledFunction()) {
8728     if (F->isDeclaration()) {
8729       // Is this an LLVM intrinsic or a target-specific intrinsic?
8730       unsigned IID = F->getIntrinsicID();
8731       if (!IID)
8732         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
8733           IID = II->getIntrinsicID(F);
8734 
8735       if (IID) {
8736         visitIntrinsicCall(I, IID);
8737         return;
8738       }
8739     }
8740 
8741     // Check for well-known libc/libm calls.  If the function is internal, it
8742     // can't be a library call.  Don't do the check if marked as nobuiltin for
8743     // some reason or the call site requires strict floating point semantics.
8744     LibFunc Func;
8745     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
8746         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
8747         LibInfo->hasOptimizedCodeGen(Func)) {
8748       switch (Func) {
8749       default: break;
8750       case LibFunc_bcmp:
8751         if (visitMemCmpBCmpCall(I))
8752           return;
8753         break;
8754       case LibFunc_copysign:
8755       case LibFunc_copysignf:
8756       case LibFunc_copysignl:
8757         // We already checked this call's prototype; verify it doesn't modify
8758         // errno.
8759         if (I.onlyReadsMemory()) {
8760           SDValue LHS = getValue(I.getArgOperand(0));
8761           SDValue RHS = getValue(I.getArgOperand(1));
8762           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
8763                                    LHS.getValueType(), LHS, RHS));
8764           return;
8765         }
8766         break;
8767       case LibFunc_fabs:
8768       case LibFunc_fabsf:
8769       case LibFunc_fabsl:
8770         if (visitUnaryFloatCall(I, ISD::FABS))
8771           return;
8772         break;
8773       case LibFunc_fmin:
8774       case LibFunc_fminf:
8775       case LibFunc_fminl:
8776         if (visitBinaryFloatCall(I, ISD::FMINNUM))
8777           return;
8778         break;
8779       case LibFunc_fmax:
8780       case LibFunc_fmaxf:
8781       case LibFunc_fmaxl:
8782         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
8783           return;
8784         break;
8785       case LibFunc_sin:
8786       case LibFunc_sinf:
8787       case LibFunc_sinl:
8788         if (visitUnaryFloatCall(I, ISD::FSIN))
8789           return;
8790         break;
8791       case LibFunc_cos:
8792       case LibFunc_cosf:
8793       case LibFunc_cosl:
8794         if (visitUnaryFloatCall(I, ISD::FCOS))
8795           return;
8796         break;
8797       case LibFunc_sqrt:
8798       case LibFunc_sqrtf:
8799       case LibFunc_sqrtl:
8800       case LibFunc_sqrt_finite:
8801       case LibFunc_sqrtf_finite:
8802       case LibFunc_sqrtl_finite:
8803         if (visitUnaryFloatCall(I, ISD::FSQRT))
8804           return;
8805         break;
8806       case LibFunc_floor:
8807       case LibFunc_floorf:
8808       case LibFunc_floorl:
8809         if (visitUnaryFloatCall(I, ISD::FFLOOR))
8810           return;
8811         break;
8812       case LibFunc_nearbyint:
8813       case LibFunc_nearbyintf:
8814       case LibFunc_nearbyintl:
8815         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
8816           return;
8817         break;
8818       case LibFunc_ceil:
8819       case LibFunc_ceilf:
8820       case LibFunc_ceill:
8821         if (visitUnaryFloatCall(I, ISD::FCEIL))
8822           return;
8823         break;
8824       case LibFunc_rint:
8825       case LibFunc_rintf:
8826       case LibFunc_rintl:
8827         if (visitUnaryFloatCall(I, ISD::FRINT))
8828           return;
8829         break;
8830       case LibFunc_round:
8831       case LibFunc_roundf:
8832       case LibFunc_roundl:
8833         if (visitUnaryFloatCall(I, ISD::FROUND))
8834           return;
8835         break;
8836       case LibFunc_trunc:
8837       case LibFunc_truncf:
8838       case LibFunc_truncl:
8839         if (visitUnaryFloatCall(I, ISD::FTRUNC))
8840           return;
8841         break;
8842       case LibFunc_log2:
8843       case LibFunc_log2f:
8844       case LibFunc_log2l:
8845         if (visitUnaryFloatCall(I, ISD::FLOG2))
8846           return;
8847         break;
8848       case LibFunc_exp2:
8849       case LibFunc_exp2f:
8850       case LibFunc_exp2l:
8851         if (visitUnaryFloatCall(I, ISD::FEXP2))
8852           return;
8853         break;
8854       case LibFunc_exp10:
8855       case LibFunc_exp10f:
8856       case LibFunc_exp10l:
8857         if (visitUnaryFloatCall(I, ISD::FEXP10))
8858           return;
8859         break;
8860       case LibFunc_ldexp:
8861       case LibFunc_ldexpf:
8862       case LibFunc_ldexpl:
8863         if (visitBinaryFloatCall(I, ISD::FLDEXP))
8864           return;
8865         break;
8866       case LibFunc_memcmp:
8867         if (visitMemCmpBCmpCall(I))
8868           return;
8869         break;
8870       case LibFunc_mempcpy:
8871         if (visitMemPCpyCall(I))
8872           return;
8873         break;
8874       case LibFunc_memchr:
8875         if (visitMemChrCall(I))
8876           return;
8877         break;
8878       case LibFunc_strcpy:
8879         if (visitStrCpyCall(I, false))
8880           return;
8881         break;
8882       case LibFunc_stpcpy:
8883         if (visitStrCpyCall(I, true))
8884           return;
8885         break;
8886       case LibFunc_strcmp:
8887         if (visitStrCmpCall(I))
8888           return;
8889         break;
8890       case LibFunc_strlen:
8891         if (visitStrLenCall(I))
8892           return;
8893         break;
8894       case LibFunc_strnlen:
8895         if (visitStrNLenCall(I))
8896           return;
8897         break;
8898       }
8899     }
8900   }
8901 
8902   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
8903   // have to do anything here to lower funclet bundles.
8904   // CFGuardTarget bundles are lowered in LowerCallTo.
8905   assert(!I.hasOperandBundlesOtherThan(
8906              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
8907               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
8908               LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) &&
8909          "Cannot lower calls with arbitrary operand bundles!");
8910 
8911   SDValue Callee = getValue(I.getCalledOperand());
8912 
8913   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
8914     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
8915   else
8916     // Check if we can potentially perform a tail call. More detailed checking
8917     // is be done within LowerCallTo, after more information about the call is
8918     // known.
8919     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
8920 }
8921 
8922 namespace {
8923 
8924 /// AsmOperandInfo - This contains information for each constraint that we are
8925 /// lowering.
8926 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
8927 public:
8928   /// CallOperand - If this is the result output operand or a clobber
8929   /// this is null, otherwise it is the incoming operand to the CallInst.
8930   /// This gets modified as the asm is processed.
8931   SDValue CallOperand;
8932 
8933   /// AssignedRegs - If this is a register or register class operand, this
8934   /// contains the set of register corresponding to the operand.
8935   RegsForValue AssignedRegs;
8936 
8937   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
8938     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
8939   }
8940 
8941   /// Whether or not this operand accesses memory
8942   bool hasMemory(const TargetLowering &TLI) const {
8943     // Indirect operand accesses access memory.
8944     if (isIndirect)
8945       return true;
8946 
8947     for (const auto &Code : Codes)
8948       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
8949         return true;
8950 
8951     return false;
8952   }
8953 };
8954 
8955 
8956 } // end anonymous namespace
8957 
8958 /// Make sure that the output operand \p OpInfo and its corresponding input
8959 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
8960 /// out).
8961 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
8962                                SDISelAsmOperandInfo &MatchingOpInfo,
8963                                SelectionDAG &DAG) {
8964   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
8965     return;
8966 
8967   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
8968   const auto &TLI = DAG.getTargetLoweringInfo();
8969 
8970   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
8971       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
8972                                        OpInfo.ConstraintVT);
8973   std::pair<unsigned, const TargetRegisterClass *> InputRC =
8974       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
8975                                        MatchingOpInfo.ConstraintVT);
8976   if ((OpInfo.ConstraintVT.isInteger() !=
8977        MatchingOpInfo.ConstraintVT.isInteger()) ||
8978       (MatchRC.second != InputRC.second)) {
8979     // FIXME: error out in a more elegant fashion
8980     report_fatal_error("Unsupported asm: input constraint"
8981                        " with a matching output constraint of"
8982                        " incompatible type!");
8983   }
8984   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
8985 }
8986 
8987 /// Get a direct memory input to behave well as an indirect operand.
8988 /// This may introduce stores, hence the need for a \p Chain.
8989 /// \return The (possibly updated) chain.
8990 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
8991                                         SDISelAsmOperandInfo &OpInfo,
8992                                         SelectionDAG &DAG) {
8993   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8994 
8995   // If we don't have an indirect input, put it in the constpool if we can,
8996   // otherwise spill it to a stack slot.
8997   // TODO: This isn't quite right. We need to handle these according to
8998   // the addressing mode that the constraint wants. Also, this may take
8999   // an additional register for the computation and we don't want that
9000   // either.
9001 
9002   // If the operand is a float, integer, or vector constant, spill to a
9003   // constant pool entry to get its address.
9004   const Value *OpVal = OpInfo.CallOperandVal;
9005   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
9006       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
9007     OpInfo.CallOperand = DAG.getConstantPool(
9008         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
9009     return Chain;
9010   }
9011 
9012   // Otherwise, create a stack slot and emit a store to it before the asm.
9013   Type *Ty = OpVal->getType();
9014   auto &DL = DAG.getDataLayout();
9015   uint64_t TySize = DL.getTypeAllocSize(Ty);
9016   MachineFunction &MF = DAG.getMachineFunction();
9017   int SSFI = MF.getFrameInfo().CreateStackObject(
9018       TySize, DL.getPrefTypeAlign(Ty), false);
9019   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
9020   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
9021                             MachinePointerInfo::getFixedStack(MF, SSFI),
9022                             TLI.getMemValueType(DL, Ty));
9023   OpInfo.CallOperand = StackSlot;
9024 
9025   return Chain;
9026 }
9027 
9028 /// GetRegistersForValue - Assign registers (virtual or physical) for the
9029 /// specified operand.  We prefer to assign virtual registers, to allow the
9030 /// register allocator to handle the assignment process.  However, if the asm
9031 /// uses features that we can't model on machineinstrs, we have SDISel do the
9032 /// allocation.  This produces generally horrible, but correct, code.
9033 ///
9034 ///   OpInfo describes the operand
9035 ///   RefOpInfo describes the matching operand if any, the operand otherwise
9036 static std::optional<unsigned>
9037 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
9038                      SDISelAsmOperandInfo &OpInfo,
9039                      SDISelAsmOperandInfo &RefOpInfo) {
9040   LLVMContext &Context = *DAG.getContext();
9041   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9042 
9043   MachineFunction &MF = DAG.getMachineFunction();
9044   SmallVector<unsigned, 4> Regs;
9045   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9046 
9047   // No work to do for memory/address operands.
9048   if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9049       OpInfo.ConstraintType == TargetLowering::C_Address)
9050     return std::nullopt;
9051 
9052   // If this is a constraint for a single physreg, or a constraint for a
9053   // register class, find it.
9054   unsigned AssignedReg;
9055   const TargetRegisterClass *RC;
9056   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
9057       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
9058   // RC is unset only on failure. Return immediately.
9059   if (!RC)
9060     return std::nullopt;
9061 
9062   // Get the actual register value type.  This is important, because the user
9063   // may have asked for (e.g.) the AX register in i32 type.  We need to
9064   // remember that AX is actually i16 to get the right extension.
9065   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
9066 
9067   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
9068     // If this is an FP operand in an integer register (or visa versa), or more
9069     // generally if the operand value disagrees with the register class we plan
9070     // to stick it in, fix the operand type.
9071     //
9072     // If this is an input value, the bitcast to the new type is done now.
9073     // Bitcast for output value is done at the end of visitInlineAsm().
9074     if ((OpInfo.Type == InlineAsm::isOutput ||
9075          OpInfo.Type == InlineAsm::isInput) &&
9076         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
9077       // Try to convert to the first EVT that the reg class contains.  If the
9078       // types are identical size, use a bitcast to convert (e.g. two differing
9079       // vector types).  Note: output bitcast is done at the end of
9080       // visitInlineAsm().
9081       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
9082         // Exclude indirect inputs while they are unsupported because the code
9083         // to perform the load is missing and thus OpInfo.CallOperand still
9084         // refers to the input address rather than the pointed-to value.
9085         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
9086           OpInfo.CallOperand =
9087               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
9088         OpInfo.ConstraintVT = RegVT;
9089         // If the operand is an FP value and we want it in integer registers,
9090         // use the corresponding integer type. This turns an f64 value into
9091         // i64, which can be passed with two i32 values on a 32-bit machine.
9092       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
9093         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
9094         if (OpInfo.Type == InlineAsm::isInput)
9095           OpInfo.CallOperand =
9096               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
9097         OpInfo.ConstraintVT = VT;
9098       }
9099     }
9100   }
9101 
9102   // No need to allocate a matching input constraint since the constraint it's
9103   // matching to has already been allocated.
9104   if (OpInfo.isMatchingInputConstraint())
9105     return std::nullopt;
9106 
9107   EVT ValueVT = OpInfo.ConstraintVT;
9108   if (OpInfo.ConstraintVT == MVT::Other)
9109     ValueVT = RegVT;
9110 
9111   // Initialize NumRegs.
9112   unsigned NumRegs = 1;
9113   if (OpInfo.ConstraintVT != MVT::Other)
9114     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
9115 
9116   // If this is a constraint for a specific physical register, like {r17},
9117   // assign it now.
9118 
9119   // If this associated to a specific register, initialize iterator to correct
9120   // place. If virtual, make sure we have enough registers
9121 
9122   // Initialize iterator if necessary
9123   TargetRegisterClass::iterator I = RC->begin();
9124   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9125 
9126   // Do not check for single registers.
9127   if (AssignedReg) {
9128     I = std::find(I, RC->end(), AssignedReg);
9129     if (I == RC->end()) {
9130       // RC does not contain the selected register, which indicates a
9131       // mismatch between the register and the required type/bitwidth.
9132       return {AssignedReg};
9133     }
9134   }
9135 
9136   for (; NumRegs; --NumRegs, ++I) {
9137     assert(I != RC->end() && "Ran out of registers to allocate!");
9138     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
9139     Regs.push_back(R);
9140   }
9141 
9142   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
9143   return std::nullopt;
9144 }
9145 
9146 static unsigned
9147 findMatchingInlineAsmOperand(unsigned OperandNo,
9148                              const std::vector<SDValue> &AsmNodeOperands) {
9149   // Scan until we find the definition we already emitted of this operand.
9150   unsigned CurOp = InlineAsm::Op_FirstOperand;
9151   for (; OperandNo; --OperandNo) {
9152     // Advance to the next operand.
9153     unsigned OpFlag =
9154         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
9155     const InlineAsm::Flag F(OpFlag);
9156     assert(
9157         (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) &&
9158         "Skipped past definitions?");
9159     CurOp += F.getNumOperandRegisters() + 1;
9160   }
9161   return CurOp;
9162 }
9163 
9164 namespace {
9165 
9166 class ExtraFlags {
9167   unsigned Flags = 0;
9168 
9169 public:
9170   explicit ExtraFlags(const CallBase &Call) {
9171     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9172     if (IA->hasSideEffects())
9173       Flags |= InlineAsm::Extra_HasSideEffects;
9174     if (IA->isAlignStack())
9175       Flags |= InlineAsm::Extra_IsAlignStack;
9176     if (Call.isConvergent())
9177       Flags |= InlineAsm::Extra_IsConvergent;
9178     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
9179   }
9180 
9181   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
9182     // Ideally, we would only check against memory constraints.  However, the
9183     // meaning of an Other constraint can be target-specific and we can't easily
9184     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
9185     // for Other constraints as well.
9186     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9187         OpInfo.ConstraintType == TargetLowering::C_Other) {
9188       if (OpInfo.Type == InlineAsm::isInput)
9189         Flags |= InlineAsm::Extra_MayLoad;
9190       else if (OpInfo.Type == InlineAsm::isOutput)
9191         Flags |= InlineAsm::Extra_MayStore;
9192       else if (OpInfo.Type == InlineAsm::isClobber)
9193         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
9194     }
9195   }
9196 
9197   unsigned get() const { return Flags; }
9198 };
9199 
9200 } // end anonymous namespace
9201 
9202 static bool isFunction(SDValue Op) {
9203   if (Op && Op.getOpcode() == ISD::GlobalAddress) {
9204     if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
9205       auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
9206 
9207       // In normal "call dllimport func" instruction (non-inlineasm) it force
9208       // indirect access by specifing call opcode. And usually specially print
9209       // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
9210       // not do in this way now. (In fact, this is similar with "Data Access"
9211       // action). So here we ignore dllimport function.
9212       if (Fn && !Fn->hasDLLImportStorageClass())
9213         return true;
9214     }
9215   }
9216   return false;
9217 }
9218 
9219 /// visitInlineAsm - Handle a call to an InlineAsm object.
9220 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
9221                                          const BasicBlock *EHPadBB) {
9222   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9223 
9224   /// ConstraintOperands - Information about all of the constraints.
9225   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
9226 
9227   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9228   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
9229       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
9230 
9231   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
9232   // AsmDialect, MayLoad, MayStore).
9233   bool HasSideEffect = IA->hasSideEffects();
9234   ExtraFlags ExtraInfo(Call);
9235 
9236   for (auto &T : TargetConstraints) {
9237     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
9238     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
9239 
9240     if (OpInfo.CallOperandVal)
9241       OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
9242 
9243     if (!HasSideEffect)
9244       HasSideEffect = OpInfo.hasMemory(TLI);
9245 
9246     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
9247     // FIXME: Could we compute this on OpInfo rather than T?
9248 
9249     // Compute the constraint code and ConstraintType to use.
9250     TLI.ComputeConstraintToUse(T, SDValue());
9251 
9252     if (T.ConstraintType == TargetLowering::C_Immediate &&
9253         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
9254       // We've delayed emitting a diagnostic like the "n" constraint because
9255       // inlining could cause an integer showing up.
9256       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
9257                                           "' expects an integer constant "
9258                                           "expression");
9259 
9260     ExtraInfo.update(T);
9261   }
9262 
9263   // We won't need to flush pending loads if this asm doesn't touch
9264   // memory and is nonvolatile.
9265   SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
9266 
9267   bool EmitEHLabels = isa<InvokeInst>(Call);
9268   if (EmitEHLabels) {
9269     assert(EHPadBB && "InvokeInst must have an EHPadBB");
9270   }
9271   bool IsCallBr = isa<CallBrInst>(Call);
9272 
9273   if (IsCallBr || EmitEHLabels) {
9274     // If this is a callbr or invoke we need to flush pending exports since
9275     // inlineasm_br and invoke are terminators.
9276     // We need to do this before nodes are glued to the inlineasm_br node.
9277     Chain = getControlRoot();
9278   }
9279 
9280   MCSymbol *BeginLabel = nullptr;
9281   if (EmitEHLabels) {
9282     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
9283   }
9284 
9285   int OpNo = -1;
9286   SmallVector<StringRef> AsmStrs;
9287   IA->collectAsmStrs(AsmStrs);
9288 
9289   // Second pass over the constraints: compute which constraint option to use.
9290   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9291     if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
9292       OpNo++;
9293 
9294     // If this is an output operand with a matching input operand, look up the
9295     // matching input. If their types mismatch, e.g. one is an integer, the
9296     // other is floating point, or their sizes are different, flag it as an
9297     // error.
9298     if (OpInfo.hasMatchingInput()) {
9299       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
9300       patchMatchingInput(OpInfo, Input, DAG);
9301     }
9302 
9303     // Compute the constraint code and ConstraintType to use.
9304     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
9305 
9306     if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
9307          OpInfo.Type == InlineAsm::isClobber) ||
9308         OpInfo.ConstraintType == TargetLowering::C_Address)
9309       continue;
9310 
9311     // In Linux PIC model, there are 4 cases about value/label addressing:
9312     //
9313     // 1: Function call or Label jmp inside the module.
9314     // 2: Data access (such as global variable, static variable) inside module.
9315     // 3: Function call or Label jmp outside the module.
9316     // 4: Data access (such as global variable) outside the module.
9317     //
9318     // Due to current llvm inline asm architecture designed to not "recognize"
9319     // the asm code, there are quite troubles for us to treat mem addressing
9320     // differently for same value/adress used in different instuctions.
9321     // For example, in pic model, call a func may in plt way or direclty
9322     // pc-related, but lea/mov a function adress may use got.
9323     //
9324     // Here we try to "recognize" function call for the case 1 and case 3 in
9325     // inline asm. And try to adjust the constraint for them.
9326     //
9327     // TODO: Due to current inline asm didn't encourage to jmp to the outsider
9328     // label, so here we don't handle jmp function label now, but we need to
9329     // enhance it (especilly in PIC model) if we meet meaningful requirements.
9330     if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
9331         TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
9332         TM.getCodeModel() != CodeModel::Large) {
9333       OpInfo.isIndirect = false;
9334       OpInfo.ConstraintType = TargetLowering::C_Address;
9335     }
9336 
9337     // If this is a memory input, and if the operand is not indirect, do what we
9338     // need to provide an address for the memory input.
9339     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
9340         !OpInfo.isIndirect) {
9341       assert((OpInfo.isMultipleAlternative ||
9342               (OpInfo.Type == InlineAsm::isInput)) &&
9343              "Can only indirectify direct input operands!");
9344 
9345       // Memory operands really want the address of the value.
9346       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
9347 
9348       // There is no longer a Value* corresponding to this operand.
9349       OpInfo.CallOperandVal = nullptr;
9350 
9351       // It is now an indirect operand.
9352       OpInfo.isIndirect = true;
9353     }
9354 
9355   }
9356 
9357   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
9358   std::vector<SDValue> AsmNodeOperands;
9359   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
9360   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
9361       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
9362 
9363   // If we have a !srcloc metadata node associated with it, we want to attach
9364   // this to the ultimately generated inline asm machineinstr.  To do this, we
9365   // pass in the third operand as this (potentially null) inline asm MDNode.
9366   const MDNode *SrcLoc = Call.getMetadata("srcloc");
9367   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
9368 
9369   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
9370   // bits as operand 3.
9371   AsmNodeOperands.push_back(DAG.getTargetConstant(
9372       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9373 
9374   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
9375   // this, assign virtual and physical registers for inputs and otput.
9376   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9377     // Assign Registers.
9378     SDISelAsmOperandInfo &RefOpInfo =
9379         OpInfo.isMatchingInputConstraint()
9380             ? ConstraintOperands[OpInfo.getMatchedOperand()]
9381             : OpInfo;
9382     const auto RegError =
9383         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
9384     if (RegError) {
9385       const MachineFunction &MF = DAG.getMachineFunction();
9386       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9387       const char *RegName = TRI.getName(*RegError);
9388       emitInlineAsmError(Call, "register '" + Twine(RegName) +
9389                                    "' allocated for constraint '" +
9390                                    Twine(OpInfo.ConstraintCode) +
9391                                    "' does not match required type");
9392       return;
9393     }
9394 
9395     auto DetectWriteToReservedRegister = [&]() {
9396       const MachineFunction &MF = DAG.getMachineFunction();
9397       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9398       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
9399         if (Register::isPhysicalRegister(Reg) &&
9400             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
9401           const char *RegName = TRI.getName(Reg);
9402           emitInlineAsmError(Call, "write to reserved register '" +
9403                                        Twine(RegName) + "'");
9404           return true;
9405         }
9406       }
9407       return false;
9408     };
9409     assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
9410             (OpInfo.Type == InlineAsm::isInput &&
9411              !OpInfo.isMatchingInputConstraint())) &&
9412            "Only address as input operand is allowed.");
9413 
9414     switch (OpInfo.Type) {
9415     case InlineAsm::isOutput:
9416       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
9417         const InlineAsm::ConstraintCode ConstraintID =
9418             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9419         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
9420                "Failed to convert memory constraint code to constraint id.");
9421 
9422         // Add information to the INLINEASM node to know about this output.
9423         InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1);
9424         OpFlags.setMemConstraint(ConstraintID);
9425         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
9426                                                         MVT::i32));
9427         AsmNodeOperands.push_back(OpInfo.CallOperand);
9428       } else {
9429         // Otherwise, this outputs to a register (directly for C_Register /
9430         // C_RegisterClass, and a target-defined fashion for
9431         // C_Immediate/C_Other). Find a register that we can use.
9432         if (OpInfo.AssignedRegs.Regs.empty()) {
9433           emitInlineAsmError(
9434               Call, "couldn't allocate output register for constraint '" +
9435                         Twine(OpInfo.ConstraintCode) + "'");
9436           return;
9437         }
9438 
9439         if (DetectWriteToReservedRegister())
9440           return;
9441 
9442         // Add information to the INLINEASM node to know that this register is
9443         // set.
9444         OpInfo.AssignedRegs.AddInlineAsmOperands(
9445             OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber
9446                                   : InlineAsm::Kind::RegDef,
9447             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
9448       }
9449       break;
9450 
9451     case InlineAsm::isInput:
9452     case InlineAsm::isLabel: {
9453       SDValue InOperandVal = OpInfo.CallOperand;
9454 
9455       if (OpInfo.isMatchingInputConstraint()) {
9456         // If this is required to match an output register we have already set,
9457         // just use its register.
9458         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
9459                                                   AsmNodeOperands);
9460         InlineAsm::Flag Flag(
9461             cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue());
9462         if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) {
9463           if (OpInfo.isIndirect) {
9464             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
9465             emitInlineAsmError(Call, "inline asm not supported yet: "
9466                                      "don't know how to handle tied "
9467                                      "indirect register inputs");
9468             return;
9469           }
9470 
9471           SmallVector<unsigned, 4> Regs;
9472           MachineFunction &MF = DAG.getMachineFunction();
9473           MachineRegisterInfo &MRI = MF.getRegInfo();
9474           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9475           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
9476           Register TiedReg = R->getReg();
9477           MVT RegVT = R->getSimpleValueType(0);
9478           const TargetRegisterClass *RC =
9479               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
9480               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
9481                                       : TRI.getMinimalPhysRegClass(TiedReg);
9482           for (unsigned i = 0, e = Flag.getNumOperandRegisters(); i != e; ++i)
9483             Regs.push_back(MRI.createVirtualRegister(RC));
9484 
9485           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
9486 
9487           SDLoc dl = getCurSDLoc();
9488           // Use the produced MatchedRegs object to
9489           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call);
9490           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, true,
9491                                            OpInfo.getMatchedOperand(), dl, DAG,
9492                                            AsmNodeOperands);
9493           break;
9494         }
9495 
9496         assert(Flag.isMemKind() && "Unknown matching constraint!");
9497         assert(Flag.getNumOperandRegisters() == 1 &&
9498                "Unexpected number of operands");
9499         // Add information to the INLINEASM node to know about this input.
9500         // See InlineAsm.h isUseOperandTiedToDef.
9501         Flag.clearMemConstraint();
9502         Flag.setMatchingOp(OpInfo.getMatchedOperand());
9503         AsmNodeOperands.push_back(DAG.getTargetConstant(
9504             Flag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9505         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
9506         break;
9507       }
9508 
9509       // Treat indirect 'X' constraint as memory.
9510       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
9511           OpInfo.isIndirect)
9512         OpInfo.ConstraintType = TargetLowering::C_Memory;
9513 
9514       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
9515           OpInfo.ConstraintType == TargetLowering::C_Other) {
9516         std::vector<SDValue> Ops;
9517         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
9518                                           Ops, DAG);
9519         if (Ops.empty()) {
9520           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
9521             if (isa<ConstantSDNode>(InOperandVal)) {
9522               emitInlineAsmError(Call, "value out of range for constraint '" +
9523                                            Twine(OpInfo.ConstraintCode) + "'");
9524               return;
9525             }
9526 
9527           emitInlineAsmError(Call,
9528                              "invalid operand for inline asm constraint '" +
9529                                  Twine(OpInfo.ConstraintCode) + "'");
9530           return;
9531         }
9532 
9533         // Add information to the INLINEASM node to know about this input.
9534         InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size());
9535         AsmNodeOperands.push_back(DAG.getTargetConstant(
9536             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9537         llvm::append_range(AsmNodeOperands, Ops);
9538         break;
9539       }
9540 
9541       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
9542         assert((OpInfo.isIndirect ||
9543                 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
9544                "Operand must be indirect to be a mem!");
9545         assert(InOperandVal.getValueType() ==
9546                    TLI.getPointerTy(DAG.getDataLayout()) &&
9547                "Memory operands expect pointer values");
9548 
9549         const InlineAsm::ConstraintCode ConstraintID =
9550             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9551         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
9552                "Failed to convert memory constraint code to constraint id.");
9553 
9554         // Add information to the INLINEASM node to know about this input.
9555         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
9556         ResOpType.setMemConstraint(ConstraintID);
9557         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
9558                                                         getCurSDLoc(),
9559                                                         MVT::i32));
9560         AsmNodeOperands.push_back(InOperandVal);
9561         break;
9562       }
9563 
9564       if (OpInfo.ConstraintType == TargetLowering::C_Address) {
9565         const InlineAsm::ConstraintCode ConstraintID =
9566             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9567         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
9568                "Failed to convert memory constraint code to constraint id.");
9569 
9570         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
9571 
9572         SDValue AsmOp = InOperandVal;
9573         if (isFunction(InOperandVal)) {
9574           auto *GA = cast<GlobalAddressSDNode>(InOperandVal);
9575           ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1);
9576           AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(),
9577                                              InOperandVal.getValueType(),
9578                                              GA->getOffset());
9579         }
9580 
9581         // Add information to the INLINEASM node to know about this input.
9582         ResOpType.setMemConstraint(ConstraintID);
9583 
9584         AsmNodeOperands.push_back(
9585             DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32));
9586 
9587         AsmNodeOperands.push_back(AsmOp);
9588         break;
9589       }
9590 
9591       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
9592               OpInfo.ConstraintType == TargetLowering::C_Register) &&
9593              "Unknown constraint type!");
9594 
9595       // TODO: Support this.
9596       if (OpInfo.isIndirect) {
9597         emitInlineAsmError(
9598             Call, "Don't know how to handle indirect register inputs yet "
9599                   "for constraint '" +
9600                       Twine(OpInfo.ConstraintCode) + "'");
9601         return;
9602       }
9603 
9604       // Copy the input into the appropriate registers.
9605       if (OpInfo.AssignedRegs.Regs.empty()) {
9606         emitInlineAsmError(Call,
9607                            "couldn't allocate input reg for constraint '" +
9608                                Twine(OpInfo.ConstraintCode) + "'");
9609         return;
9610       }
9611 
9612       if (DetectWriteToReservedRegister())
9613         return;
9614 
9615       SDLoc dl = getCurSDLoc();
9616 
9617       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue,
9618                                         &Call);
9619 
9620       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, false,
9621                                                0, dl, DAG, AsmNodeOperands);
9622       break;
9623     }
9624     case InlineAsm::isClobber:
9625       // Add the clobbered value to the operand list, so that the register
9626       // allocator is aware that the physreg got clobbered.
9627       if (!OpInfo.AssignedRegs.Regs.empty())
9628         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::Clobber,
9629                                                  false, 0, getCurSDLoc(), DAG,
9630                                                  AsmNodeOperands);
9631       break;
9632     }
9633   }
9634 
9635   // Finish up input operands.  Set the input chain and add the flag last.
9636   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
9637   if (Glue.getNode()) AsmNodeOperands.push_back(Glue);
9638 
9639   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
9640   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
9641                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
9642   Glue = Chain.getValue(1);
9643 
9644   // Do additional work to generate outputs.
9645 
9646   SmallVector<EVT, 1> ResultVTs;
9647   SmallVector<SDValue, 1> ResultValues;
9648   SmallVector<SDValue, 8> OutChains;
9649 
9650   llvm::Type *CallResultType = Call.getType();
9651   ArrayRef<Type *> ResultTypes;
9652   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
9653     ResultTypes = StructResult->elements();
9654   else if (!CallResultType->isVoidTy())
9655     ResultTypes = ArrayRef(CallResultType);
9656 
9657   auto CurResultType = ResultTypes.begin();
9658   auto handleRegAssign = [&](SDValue V) {
9659     assert(CurResultType != ResultTypes.end() && "Unexpected value");
9660     assert((*CurResultType)->isSized() && "Unexpected unsized type");
9661     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
9662     ++CurResultType;
9663     // If the type of the inline asm call site return value is different but has
9664     // same size as the type of the asm output bitcast it.  One example of this
9665     // is for vectors with different width / number of elements.  This can
9666     // happen for register classes that can contain multiple different value
9667     // types.  The preg or vreg allocated may not have the same VT as was
9668     // expected.
9669     //
9670     // This can also happen for a return value that disagrees with the register
9671     // class it is put in, eg. a double in a general-purpose register on a
9672     // 32-bit machine.
9673     if (ResultVT != V.getValueType() &&
9674         ResultVT.getSizeInBits() == V.getValueSizeInBits())
9675       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
9676     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
9677              V.getValueType().isInteger()) {
9678       // If a result value was tied to an input value, the computed result
9679       // may have a wider width than the expected result.  Extract the
9680       // relevant portion.
9681       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
9682     }
9683     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
9684     ResultVTs.push_back(ResultVT);
9685     ResultValues.push_back(V);
9686   };
9687 
9688   // Deal with output operands.
9689   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9690     if (OpInfo.Type == InlineAsm::isOutput) {
9691       SDValue Val;
9692       // Skip trivial output operands.
9693       if (OpInfo.AssignedRegs.Regs.empty())
9694         continue;
9695 
9696       switch (OpInfo.ConstraintType) {
9697       case TargetLowering::C_Register:
9698       case TargetLowering::C_RegisterClass:
9699         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
9700                                                   Chain, &Glue, &Call);
9701         break;
9702       case TargetLowering::C_Immediate:
9703       case TargetLowering::C_Other:
9704         Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(),
9705                                               OpInfo, DAG);
9706         break;
9707       case TargetLowering::C_Memory:
9708         break; // Already handled.
9709       case TargetLowering::C_Address:
9710         break; // Silence warning.
9711       case TargetLowering::C_Unknown:
9712         assert(false && "Unexpected unknown constraint");
9713       }
9714 
9715       // Indirect output manifest as stores. Record output chains.
9716       if (OpInfo.isIndirect) {
9717         const Value *Ptr = OpInfo.CallOperandVal;
9718         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
9719         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
9720                                      MachinePointerInfo(Ptr));
9721         OutChains.push_back(Store);
9722       } else {
9723         // generate CopyFromRegs to associated registers.
9724         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
9725         if (Val.getOpcode() == ISD::MERGE_VALUES) {
9726           for (const SDValue &V : Val->op_values())
9727             handleRegAssign(V);
9728         } else
9729           handleRegAssign(Val);
9730       }
9731     }
9732   }
9733 
9734   // Set results.
9735   if (!ResultValues.empty()) {
9736     assert(CurResultType == ResultTypes.end() &&
9737            "Mismatch in number of ResultTypes");
9738     assert(ResultValues.size() == ResultTypes.size() &&
9739            "Mismatch in number of output operands in asm result");
9740 
9741     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
9742                             DAG.getVTList(ResultVTs), ResultValues);
9743     setValue(&Call, V);
9744   }
9745 
9746   // Collect store chains.
9747   if (!OutChains.empty())
9748     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
9749 
9750   if (EmitEHLabels) {
9751     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
9752   }
9753 
9754   // Only Update Root if inline assembly has a memory effect.
9755   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
9756       EmitEHLabels)
9757     DAG.setRoot(Chain);
9758 }
9759 
9760 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
9761                                              const Twine &Message) {
9762   LLVMContext &Ctx = *DAG.getContext();
9763   Ctx.emitError(&Call, Message);
9764 
9765   // Make sure we leave the DAG in a valid state
9766   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9767   SmallVector<EVT, 1> ValueVTs;
9768   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
9769 
9770   if (ValueVTs.empty())
9771     return;
9772 
9773   SmallVector<SDValue, 1> Ops;
9774   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
9775     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
9776 
9777   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
9778 }
9779 
9780 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
9781   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
9782                           MVT::Other, getRoot(),
9783                           getValue(I.getArgOperand(0)),
9784                           DAG.getSrcValue(I.getArgOperand(0))));
9785 }
9786 
9787 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
9788   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9789   const DataLayout &DL = DAG.getDataLayout();
9790   SDValue V = DAG.getVAArg(
9791       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
9792       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
9793       DL.getABITypeAlign(I.getType()).value());
9794   DAG.setRoot(V.getValue(1));
9795 
9796   if (I.getType()->isPointerTy())
9797     V = DAG.getPtrExtOrTrunc(
9798         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
9799   setValue(&I, V);
9800 }
9801 
9802 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
9803   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
9804                           MVT::Other, getRoot(),
9805                           getValue(I.getArgOperand(0)),
9806                           DAG.getSrcValue(I.getArgOperand(0))));
9807 }
9808 
9809 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
9810   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
9811                           MVT::Other, getRoot(),
9812                           getValue(I.getArgOperand(0)),
9813                           getValue(I.getArgOperand(1)),
9814                           DAG.getSrcValue(I.getArgOperand(0)),
9815                           DAG.getSrcValue(I.getArgOperand(1))));
9816 }
9817 
9818 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
9819                                                     const Instruction &I,
9820                                                     SDValue Op) {
9821   const MDNode *Range = getRangeMetadata(I);
9822   if (!Range)
9823     return Op;
9824 
9825   ConstantRange CR = getConstantRangeFromMetadata(*Range);
9826   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
9827     return Op;
9828 
9829   APInt Lo = CR.getUnsignedMin();
9830   if (!Lo.isMinValue())
9831     return Op;
9832 
9833   APInt Hi = CR.getUnsignedMax();
9834   unsigned Bits = std::max(Hi.getActiveBits(),
9835                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
9836 
9837   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9838 
9839   SDLoc SL = getCurSDLoc();
9840 
9841   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
9842                              DAG.getValueType(SmallVT));
9843   unsigned NumVals = Op.getNode()->getNumValues();
9844   if (NumVals == 1)
9845     return ZExt;
9846 
9847   SmallVector<SDValue, 4> Ops;
9848 
9849   Ops.push_back(ZExt);
9850   for (unsigned I = 1; I != NumVals; ++I)
9851     Ops.push_back(Op.getValue(I));
9852 
9853   return DAG.getMergeValues(Ops, SL);
9854 }
9855 
9856 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
9857 /// the call being lowered.
9858 ///
9859 /// This is a helper for lowering intrinsics that follow a target calling
9860 /// convention or require stack pointer adjustment. Only a subset of the
9861 /// intrinsic's operands need to participate in the calling convention.
9862 void SelectionDAGBuilder::populateCallLoweringInfo(
9863     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
9864     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
9865     AttributeSet RetAttrs, bool IsPatchPoint) {
9866   TargetLowering::ArgListTy Args;
9867   Args.reserve(NumArgs);
9868 
9869   // Populate the argument list.
9870   // Attributes for args start at offset 1, after the return attribute.
9871   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
9872        ArgI != ArgE; ++ArgI) {
9873     const Value *V = Call->getOperand(ArgI);
9874 
9875     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
9876 
9877     TargetLowering::ArgListEntry Entry;
9878     Entry.Node = getValue(V);
9879     Entry.Ty = V->getType();
9880     Entry.setAttributes(Call, ArgI);
9881     Args.push_back(Entry);
9882   }
9883 
9884   CLI.setDebugLoc(getCurSDLoc())
9885       .setChain(getRoot())
9886       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args),
9887                  RetAttrs)
9888       .setDiscardResult(Call->use_empty())
9889       .setIsPatchPoint(IsPatchPoint)
9890       .setIsPreallocated(
9891           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
9892 }
9893 
9894 /// Add a stack map intrinsic call's live variable operands to a stackmap
9895 /// or patchpoint target node's operand list.
9896 ///
9897 /// Constants are converted to TargetConstants purely as an optimization to
9898 /// avoid constant materialization and register allocation.
9899 ///
9900 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
9901 /// generate addess computation nodes, and so FinalizeISel can convert the
9902 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
9903 /// address materialization and register allocation, but may also be required
9904 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
9905 /// alloca in the entry block, then the runtime may assume that the alloca's
9906 /// StackMap location can be read immediately after compilation and that the
9907 /// location is valid at any point during execution (this is similar to the
9908 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
9909 /// only available in a register, then the runtime would need to trap when
9910 /// execution reaches the StackMap in order to read the alloca's location.
9911 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
9912                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
9913                                 SelectionDAGBuilder &Builder) {
9914   SelectionDAG &DAG = Builder.DAG;
9915   for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
9916     SDValue Op = Builder.getValue(Call.getArgOperand(I));
9917 
9918     // Things on the stack are pointer-typed, meaning that they are already
9919     // legal and can be emitted directly to target nodes.
9920     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
9921       Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
9922     } else {
9923       // Otherwise emit a target independent node to be legalised.
9924       Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
9925     }
9926   }
9927 }
9928 
9929 /// Lower llvm.experimental.stackmap.
9930 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
9931   // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
9932   //                                  [live variables...])
9933 
9934   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
9935 
9936   SDValue Chain, InGlue, Callee;
9937   SmallVector<SDValue, 32> Ops;
9938 
9939   SDLoc DL = getCurSDLoc();
9940   Callee = getValue(CI.getCalledOperand());
9941 
9942   // The stackmap intrinsic only records the live variables (the arguments
9943   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
9944   // intrinsic, this won't be lowered to a function call. This means we don't
9945   // have to worry about calling conventions and target specific lowering code.
9946   // Instead we perform the call lowering right here.
9947   //
9948   // chain, flag = CALLSEQ_START(chain, 0, 0)
9949   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
9950   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
9951   //
9952   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
9953   InGlue = Chain.getValue(1);
9954 
9955   // Add the STACKMAP operands, starting with DAG house-keeping.
9956   Ops.push_back(Chain);
9957   Ops.push_back(InGlue);
9958 
9959   // Add the <id>, <numShadowBytes> operands.
9960   //
9961   // These do not require legalisation, and can be emitted directly to target
9962   // constant nodes.
9963   SDValue ID = getValue(CI.getArgOperand(0));
9964   assert(ID.getValueType() == MVT::i64);
9965   SDValue IDConst = DAG.getTargetConstant(
9966       cast<ConstantSDNode>(ID)->getZExtValue(), DL, ID.getValueType());
9967   Ops.push_back(IDConst);
9968 
9969   SDValue Shad = getValue(CI.getArgOperand(1));
9970   assert(Shad.getValueType() == MVT::i32);
9971   SDValue ShadConst = DAG.getTargetConstant(
9972       cast<ConstantSDNode>(Shad)->getZExtValue(), DL, Shad.getValueType());
9973   Ops.push_back(ShadConst);
9974 
9975   // Add the live variables.
9976   addStackMapLiveVars(CI, 2, DL, Ops, *this);
9977 
9978   // Create the STACKMAP node.
9979   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9980   Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
9981   InGlue = Chain.getValue(1);
9982 
9983   Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL);
9984 
9985   // Stackmaps don't generate values, so nothing goes into the NodeMap.
9986 
9987   // Set the root to the target-lowered call chain.
9988   DAG.setRoot(Chain);
9989 
9990   // Inform the Frame Information that we have a stackmap in this function.
9991   FuncInfo.MF->getFrameInfo().setHasStackMap();
9992 }
9993 
9994 /// Lower llvm.experimental.patchpoint directly to its target opcode.
9995 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
9996                                           const BasicBlock *EHPadBB) {
9997   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
9998   //                                                 i32 <numBytes>,
9999   //                                                 i8* <target>,
10000   //                                                 i32 <numArgs>,
10001   //                                                 [Args...],
10002   //                                                 [live variables...])
10003 
10004   CallingConv::ID CC = CB.getCallingConv();
10005   bool IsAnyRegCC = CC == CallingConv::AnyReg;
10006   bool HasDef = !CB.getType()->isVoidTy();
10007   SDLoc dl = getCurSDLoc();
10008   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
10009 
10010   // Handle immediate and symbolic callees.
10011   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
10012     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
10013                                    /*isTarget=*/true);
10014   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
10015     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
10016                                          SDLoc(SymbolicCallee),
10017                                          SymbolicCallee->getValueType(0));
10018 
10019   // Get the real number of arguments participating in the call <numArgs>
10020   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
10021   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
10022 
10023   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
10024   // Intrinsics include all meta-operands up to but not including CC.
10025   unsigned NumMetaOpers = PatchPointOpers::CCPos;
10026   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
10027          "Not enough arguments provided to the patchpoint intrinsic");
10028 
10029   // For AnyRegCC the arguments are lowered later on manually.
10030   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
10031   Type *ReturnTy =
10032       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
10033 
10034   TargetLowering::CallLoweringInfo CLI(DAG);
10035   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
10036                            ReturnTy, CB.getAttributes().getRetAttrs(), true);
10037   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
10038 
10039   SDNode *CallEnd = Result.second.getNode();
10040   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
10041     CallEnd = CallEnd->getOperand(0).getNode();
10042 
10043   /// Get a call instruction from the call sequence chain.
10044   /// Tail calls are not allowed.
10045   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
10046          "Expected a callseq node.");
10047   SDNode *Call = CallEnd->getOperand(0).getNode();
10048   bool HasGlue = Call->getGluedNode();
10049 
10050   // Replace the target specific call node with the patchable intrinsic.
10051   SmallVector<SDValue, 8> Ops;
10052 
10053   // Push the chain.
10054   Ops.push_back(*(Call->op_begin()));
10055 
10056   // Optionally, push the glue (if any).
10057   if (HasGlue)
10058     Ops.push_back(*(Call->op_end() - 1));
10059 
10060   // Push the register mask info.
10061   if (HasGlue)
10062     Ops.push_back(*(Call->op_end() - 2));
10063   else
10064     Ops.push_back(*(Call->op_end() - 1));
10065 
10066   // Add the <id> and <numBytes> constants.
10067   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
10068   Ops.push_back(DAG.getTargetConstant(
10069                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
10070   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
10071   Ops.push_back(DAG.getTargetConstant(
10072                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
10073                   MVT::i32));
10074 
10075   // Add the callee.
10076   Ops.push_back(Callee);
10077 
10078   // Adjust <numArgs> to account for any arguments that have been passed on the
10079   // stack instead.
10080   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
10081   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
10082   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
10083   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
10084 
10085   // Add the calling convention
10086   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
10087 
10088   // Add the arguments we omitted previously. The register allocator should
10089   // place these in any free register.
10090   if (IsAnyRegCC)
10091     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
10092       Ops.push_back(getValue(CB.getArgOperand(i)));
10093 
10094   // Push the arguments from the call instruction.
10095   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
10096   Ops.append(Call->op_begin() + 2, e);
10097 
10098   // Push live variables for the stack map.
10099   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
10100 
10101   SDVTList NodeTys;
10102   if (IsAnyRegCC && HasDef) {
10103     // Create the return types based on the intrinsic definition
10104     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10105     SmallVector<EVT, 3> ValueVTs;
10106     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
10107     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
10108 
10109     // There is always a chain and a glue type at the end
10110     ValueVTs.push_back(MVT::Other);
10111     ValueVTs.push_back(MVT::Glue);
10112     NodeTys = DAG.getVTList(ValueVTs);
10113   } else
10114     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10115 
10116   // Replace the target specific call node with a PATCHPOINT node.
10117   SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
10118 
10119   // Update the NodeMap.
10120   if (HasDef) {
10121     if (IsAnyRegCC)
10122       setValue(&CB, SDValue(PPV.getNode(), 0));
10123     else
10124       setValue(&CB, Result.first);
10125   }
10126 
10127   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
10128   // call sequence. Furthermore the location of the chain and glue can change
10129   // when the AnyReg calling convention is used and the intrinsic returns a
10130   // value.
10131   if (IsAnyRegCC && HasDef) {
10132     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
10133     SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
10134     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10135   } else
10136     DAG.ReplaceAllUsesWith(Call, PPV.getNode());
10137   DAG.DeleteNode(Call);
10138 
10139   // Inform the Frame Information that we have a patchpoint in this function.
10140   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
10141 }
10142 
10143 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
10144                                             unsigned Intrinsic) {
10145   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10146   SDValue Op1 = getValue(I.getArgOperand(0));
10147   SDValue Op2;
10148   if (I.arg_size() > 1)
10149     Op2 = getValue(I.getArgOperand(1));
10150   SDLoc dl = getCurSDLoc();
10151   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
10152   SDValue Res;
10153   SDNodeFlags SDFlags;
10154   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
10155     SDFlags.copyFMF(*FPMO);
10156 
10157   switch (Intrinsic) {
10158   case Intrinsic::vector_reduce_fadd:
10159     if (SDFlags.hasAllowReassociation())
10160       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
10161                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
10162                         SDFlags);
10163     else
10164       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
10165     break;
10166   case Intrinsic::vector_reduce_fmul:
10167     if (SDFlags.hasAllowReassociation())
10168       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
10169                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
10170                         SDFlags);
10171     else
10172       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
10173     break;
10174   case Intrinsic::vector_reduce_add:
10175     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
10176     break;
10177   case Intrinsic::vector_reduce_mul:
10178     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
10179     break;
10180   case Intrinsic::vector_reduce_and:
10181     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
10182     break;
10183   case Intrinsic::vector_reduce_or:
10184     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
10185     break;
10186   case Intrinsic::vector_reduce_xor:
10187     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
10188     break;
10189   case Intrinsic::vector_reduce_smax:
10190     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
10191     break;
10192   case Intrinsic::vector_reduce_smin:
10193     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
10194     break;
10195   case Intrinsic::vector_reduce_umax:
10196     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
10197     break;
10198   case Intrinsic::vector_reduce_umin:
10199     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
10200     break;
10201   case Intrinsic::vector_reduce_fmax:
10202     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
10203     break;
10204   case Intrinsic::vector_reduce_fmin:
10205     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
10206     break;
10207   case Intrinsic::vector_reduce_fmaximum:
10208     Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags);
10209     break;
10210   case Intrinsic::vector_reduce_fminimum:
10211     Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags);
10212     break;
10213   default:
10214     llvm_unreachable("Unhandled vector reduce intrinsic");
10215   }
10216   setValue(&I, Res);
10217 }
10218 
10219 /// Returns an AttributeList representing the attributes applied to the return
10220 /// value of the given call.
10221 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
10222   SmallVector<Attribute::AttrKind, 2> Attrs;
10223   if (CLI.RetSExt)
10224     Attrs.push_back(Attribute::SExt);
10225   if (CLI.RetZExt)
10226     Attrs.push_back(Attribute::ZExt);
10227   if (CLI.IsInReg)
10228     Attrs.push_back(Attribute::InReg);
10229 
10230   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
10231                             Attrs);
10232 }
10233 
10234 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
10235 /// implementation, which just calls LowerCall.
10236 /// FIXME: When all targets are
10237 /// migrated to using LowerCall, this hook should be integrated into SDISel.
10238 std::pair<SDValue, SDValue>
10239 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
10240   // Handle the incoming return values from the call.
10241   CLI.Ins.clear();
10242   Type *OrigRetTy = CLI.RetTy;
10243   SmallVector<EVT, 4> RetTys;
10244   SmallVector<uint64_t, 4> Offsets;
10245   auto &DL = CLI.DAG.getDataLayout();
10246   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets, 0);
10247 
10248   if (CLI.IsPostTypeLegalization) {
10249     // If we are lowering a libcall after legalization, split the return type.
10250     SmallVector<EVT, 4> OldRetTys;
10251     SmallVector<uint64_t, 4> OldOffsets;
10252     RetTys.swap(OldRetTys);
10253     Offsets.swap(OldOffsets);
10254 
10255     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
10256       EVT RetVT = OldRetTys[i];
10257       uint64_t Offset = OldOffsets[i];
10258       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
10259       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
10260       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
10261       RetTys.append(NumRegs, RegisterVT);
10262       for (unsigned j = 0; j != NumRegs; ++j)
10263         Offsets.push_back(Offset + j * RegisterVTByteSZ);
10264     }
10265   }
10266 
10267   SmallVector<ISD::OutputArg, 4> Outs;
10268   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
10269 
10270   bool CanLowerReturn =
10271       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
10272                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
10273 
10274   SDValue DemoteStackSlot;
10275   int DemoteStackIdx = -100;
10276   if (!CanLowerReturn) {
10277     // FIXME: equivalent assert?
10278     // assert(!CS.hasInAllocaArgument() &&
10279     //        "sret demotion is incompatible with inalloca");
10280     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
10281     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
10282     MachineFunction &MF = CLI.DAG.getMachineFunction();
10283     DemoteStackIdx =
10284         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
10285     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
10286                                               DL.getAllocaAddrSpace());
10287 
10288     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
10289     ArgListEntry Entry;
10290     Entry.Node = DemoteStackSlot;
10291     Entry.Ty = StackSlotPtrType;
10292     Entry.IsSExt = false;
10293     Entry.IsZExt = false;
10294     Entry.IsInReg = false;
10295     Entry.IsSRet = true;
10296     Entry.IsNest = false;
10297     Entry.IsByVal = false;
10298     Entry.IsByRef = false;
10299     Entry.IsReturned = false;
10300     Entry.IsSwiftSelf = false;
10301     Entry.IsSwiftAsync = false;
10302     Entry.IsSwiftError = false;
10303     Entry.IsCFGuardTarget = false;
10304     Entry.Alignment = Alignment;
10305     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
10306     CLI.NumFixedArgs += 1;
10307     CLI.getArgs()[0].IndirectType = CLI.RetTy;
10308     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
10309 
10310     // sret demotion isn't compatible with tail-calls, since the sret argument
10311     // points into the callers stack frame.
10312     CLI.IsTailCall = false;
10313   } else {
10314     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10315         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
10316     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
10317       ISD::ArgFlagsTy Flags;
10318       if (NeedsRegBlock) {
10319         Flags.setInConsecutiveRegs();
10320         if (I == RetTys.size() - 1)
10321           Flags.setInConsecutiveRegsLast();
10322       }
10323       EVT VT = RetTys[I];
10324       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10325                                                      CLI.CallConv, VT);
10326       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10327                                                        CLI.CallConv, VT);
10328       for (unsigned i = 0; i != NumRegs; ++i) {
10329         ISD::InputArg MyFlags;
10330         MyFlags.Flags = Flags;
10331         MyFlags.VT = RegisterVT;
10332         MyFlags.ArgVT = VT;
10333         MyFlags.Used = CLI.IsReturnValueUsed;
10334         if (CLI.RetTy->isPointerTy()) {
10335           MyFlags.Flags.setPointer();
10336           MyFlags.Flags.setPointerAddrSpace(
10337               cast<PointerType>(CLI.RetTy)->getAddressSpace());
10338         }
10339         if (CLI.RetSExt)
10340           MyFlags.Flags.setSExt();
10341         if (CLI.RetZExt)
10342           MyFlags.Flags.setZExt();
10343         if (CLI.IsInReg)
10344           MyFlags.Flags.setInReg();
10345         CLI.Ins.push_back(MyFlags);
10346       }
10347     }
10348   }
10349 
10350   // We push in swifterror return as the last element of CLI.Ins.
10351   ArgListTy &Args = CLI.getArgs();
10352   if (supportSwiftError()) {
10353     for (const ArgListEntry &Arg : Args) {
10354       if (Arg.IsSwiftError) {
10355         ISD::InputArg MyFlags;
10356         MyFlags.VT = getPointerTy(DL);
10357         MyFlags.ArgVT = EVT(getPointerTy(DL));
10358         MyFlags.Flags.setSwiftError();
10359         CLI.Ins.push_back(MyFlags);
10360       }
10361     }
10362   }
10363 
10364   // Handle all of the outgoing arguments.
10365   CLI.Outs.clear();
10366   CLI.OutVals.clear();
10367   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
10368     SmallVector<EVT, 4> ValueVTs;
10369     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
10370     // FIXME: Split arguments if CLI.IsPostTypeLegalization
10371     Type *FinalType = Args[i].Ty;
10372     if (Args[i].IsByVal)
10373       FinalType = Args[i].IndirectType;
10374     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10375         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
10376     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
10377          ++Value) {
10378       EVT VT = ValueVTs[Value];
10379       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
10380       SDValue Op = SDValue(Args[i].Node.getNode(),
10381                            Args[i].Node.getResNo() + Value);
10382       ISD::ArgFlagsTy Flags;
10383 
10384       // Certain targets (such as MIPS), may have a different ABI alignment
10385       // for a type depending on the context. Give the target a chance to
10386       // specify the alignment it wants.
10387       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
10388       Flags.setOrigAlign(OriginalAlignment);
10389 
10390       if (Args[i].Ty->isPointerTy()) {
10391         Flags.setPointer();
10392         Flags.setPointerAddrSpace(
10393             cast<PointerType>(Args[i].Ty)->getAddressSpace());
10394       }
10395       if (Args[i].IsZExt)
10396         Flags.setZExt();
10397       if (Args[i].IsSExt)
10398         Flags.setSExt();
10399       if (Args[i].IsInReg) {
10400         // If we are using vectorcall calling convention, a structure that is
10401         // passed InReg - is surely an HVA
10402         if (CLI.CallConv == CallingConv::X86_VectorCall &&
10403             isa<StructType>(FinalType)) {
10404           // The first value of a structure is marked
10405           if (0 == Value)
10406             Flags.setHvaStart();
10407           Flags.setHva();
10408         }
10409         // Set InReg Flag
10410         Flags.setInReg();
10411       }
10412       if (Args[i].IsSRet)
10413         Flags.setSRet();
10414       if (Args[i].IsSwiftSelf)
10415         Flags.setSwiftSelf();
10416       if (Args[i].IsSwiftAsync)
10417         Flags.setSwiftAsync();
10418       if (Args[i].IsSwiftError)
10419         Flags.setSwiftError();
10420       if (Args[i].IsCFGuardTarget)
10421         Flags.setCFGuardTarget();
10422       if (Args[i].IsByVal)
10423         Flags.setByVal();
10424       if (Args[i].IsByRef)
10425         Flags.setByRef();
10426       if (Args[i].IsPreallocated) {
10427         Flags.setPreallocated();
10428         // Set the byval flag for CCAssignFn callbacks that don't know about
10429         // preallocated.  This way we can know how many bytes we should've
10430         // allocated and how many bytes a callee cleanup function will pop.  If
10431         // we port preallocated to more targets, we'll have to add custom
10432         // preallocated handling in the various CC lowering callbacks.
10433         Flags.setByVal();
10434       }
10435       if (Args[i].IsInAlloca) {
10436         Flags.setInAlloca();
10437         // Set the byval flag for CCAssignFn callbacks that don't know about
10438         // inalloca.  This way we can know how many bytes we should've allocated
10439         // and how many bytes a callee cleanup function will pop.  If we port
10440         // inalloca to more targets, we'll have to add custom inalloca handling
10441         // in the various CC lowering callbacks.
10442         Flags.setByVal();
10443       }
10444       Align MemAlign;
10445       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
10446         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
10447         Flags.setByValSize(FrameSize);
10448 
10449         // info is not there but there are cases it cannot get right.
10450         if (auto MA = Args[i].Alignment)
10451           MemAlign = *MA;
10452         else
10453           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
10454       } else if (auto MA = Args[i].Alignment) {
10455         MemAlign = *MA;
10456       } else {
10457         MemAlign = OriginalAlignment;
10458       }
10459       Flags.setMemAlign(MemAlign);
10460       if (Args[i].IsNest)
10461         Flags.setNest();
10462       if (NeedsRegBlock)
10463         Flags.setInConsecutiveRegs();
10464 
10465       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10466                                                  CLI.CallConv, VT);
10467       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10468                                                         CLI.CallConv, VT);
10469       SmallVector<SDValue, 4> Parts(NumParts);
10470       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
10471 
10472       if (Args[i].IsSExt)
10473         ExtendKind = ISD::SIGN_EXTEND;
10474       else if (Args[i].IsZExt)
10475         ExtendKind = ISD::ZERO_EXTEND;
10476 
10477       // Conservatively only handle 'returned' on non-vectors that can be lowered,
10478       // for now.
10479       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
10480           CanLowerReturn) {
10481         assert((CLI.RetTy == Args[i].Ty ||
10482                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
10483                  CLI.RetTy->getPointerAddressSpace() ==
10484                      Args[i].Ty->getPointerAddressSpace())) &&
10485                RetTys.size() == NumValues && "unexpected use of 'returned'");
10486         // Before passing 'returned' to the target lowering code, ensure that
10487         // either the register MVT and the actual EVT are the same size or that
10488         // the return value and argument are extended in the same way; in these
10489         // cases it's safe to pass the argument register value unchanged as the
10490         // return register value (although it's at the target's option whether
10491         // to do so)
10492         // TODO: allow code generation to take advantage of partially preserved
10493         // registers rather than clobbering the entire register when the
10494         // parameter extension method is not compatible with the return
10495         // extension method
10496         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
10497             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
10498              CLI.RetZExt == Args[i].IsZExt))
10499           Flags.setReturned();
10500       }
10501 
10502       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
10503                      CLI.CallConv, ExtendKind);
10504 
10505       for (unsigned j = 0; j != NumParts; ++j) {
10506         // if it isn't first piece, alignment must be 1
10507         // For scalable vectors the scalable part is currently handled
10508         // by individual targets, so we just use the known minimum size here.
10509         ISD::OutputArg MyFlags(
10510             Flags, Parts[j].getValueType().getSimpleVT(), VT,
10511             i < CLI.NumFixedArgs, i,
10512             j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
10513         if (NumParts > 1 && j == 0)
10514           MyFlags.Flags.setSplit();
10515         else if (j != 0) {
10516           MyFlags.Flags.setOrigAlign(Align(1));
10517           if (j == NumParts - 1)
10518             MyFlags.Flags.setSplitEnd();
10519         }
10520 
10521         CLI.Outs.push_back(MyFlags);
10522         CLI.OutVals.push_back(Parts[j]);
10523       }
10524 
10525       if (NeedsRegBlock && Value == NumValues - 1)
10526         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
10527     }
10528   }
10529 
10530   SmallVector<SDValue, 4> InVals;
10531   CLI.Chain = LowerCall(CLI, InVals);
10532 
10533   // Update CLI.InVals to use outside of this function.
10534   CLI.InVals = InVals;
10535 
10536   // Verify that the target's LowerCall behaved as expected.
10537   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
10538          "LowerCall didn't return a valid chain!");
10539   assert((!CLI.IsTailCall || InVals.empty()) &&
10540          "LowerCall emitted a return value for a tail call!");
10541   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
10542          "LowerCall didn't emit the correct number of values!");
10543 
10544   // For a tail call, the return value is merely live-out and there aren't
10545   // any nodes in the DAG representing it. Return a special value to
10546   // indicate that a tail call has been emitted and no more Instructions
10547   // should be processed in the current block.
10548   if (CLI.IsTailCall) {
10549     CLI.DAG.setRoot(CLI.Chain);
10550     return std::make_pair(SDValue(), SDValue());
10551   }
10552 
10553 #ifndef NDEBUG
10554   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
10555     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
10556     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
10557            "LowerCall emitted a value with the wrong type!");
10558   }
10559 #endif
10560 
10561   SmallVector<SDValue, 4> ReturnValues;
10562   if (!CanLowerReturn) {
10563     // The instruction result is the result of loading from the
10564     // hidden sret parameter.
10565     SmallVector<EVT, 1> PVTs;
10566     Type *PtrRetTy =
10567         PointerType::get(OrigRetTy->getContext(), DL.getAllocaAddrSpace());
10568 
10569     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
10570     assert(PVTs.size() == 1 && "Pointers should fit in one register");
10571     EVT PtrVT = PVTs[0];
10572 
10573     unsigned NumValues = RetTys.size();
10574     ReturnValues.resize(NumValues);
10575     SmallVector<SDValue, 4> Chains(NumValues);
10576 
10577     // An aggregate return value cannot wrap around the address space, so
10578     // offsets to its parts don't wrap either.
10579     SDNodeFlags Flags;
10580     Flags.setNoUnsignedWrap(true);
10581 
10582     MachineFunction &MF = CLI.DAG.getMachineFunction();
10583     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
10584     for (unsigned i = 0; i < NumValues; ++i) {
10585       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
10586                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
10587                                                         PtrVT), Flags);
10588       SDValue L = CLI.DAG.getLoad(
10589           RetTys[i], CLI.DL, CLI.Chain, Add,
10590           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
10591                                             DemoteStackIdx, Offsets[i]),
10592           HiddenSRetAlign);
10593       ReturnValues[i] = L;
10594       Chains[i] = L.getValue(1);
10595     }
10596 
10597     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
10598   } else {
10599     // Collect the legal value parts into potentially illegal values
10600     // that correspond to the original function's return values.
10601     std::optional<ISD::NodeType> AssertOp;
10602     if (CLI.RetSExt)
10603       AssertOp = ISD::AssertSext;
10604     else if (CLI.RetZExt)
10605       AssertOp = ISD::AssertZext;
10606     unsigned CurReg = 0;
10607     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
10608       EVT VT = RetTys[I];
10609       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10610                                                      CLI.CallConv, VT);
10611       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10612                                                        CLI.CallConv, VT);
10613 
10614       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
10615                                               NumRegs, RegisterVT, VT, nullptr,
10616                                               CLI.CallConv, AssertOp));
10617       CurReg += NumRegs;
10618     }
10619 
10620     // For a function returning void, there is no return value. We can't create
10621     // such a node, so we just return a null return value in that case. In
10622     // that case, nothing will actually look at the value.
10623     if (ReturnValues.empty())
10624       return std::make_pair(SDValue(), CLI.Chain);
10625   }
10626 
10627   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
10628                                 CLI.DAG.getVTList(RetTys), ReturnValues);
10629   return std::make_pair(Res, CLI.Chain);
10630 }
10631 
10632 /// Places new result values for the node in Results (their number
10633 /// and types must exactly match those of the original return values of
10634 /// the node), or leaves Results empty, which indicates that the node is not
10635 /// to be custom lowered after all.
10636 void TargetLowering::LowerOperationWrapper(SDNode *N,
10637                                            SmallVectorImpl<SDValue> &Results,
10638                                            SelectionDAG &DAG) const {
10639   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
10640 
10641   if (!Res.getNode())
10642     return;
10643 
10644   // If the original node has one result, take the return value from
10645   // LowerOperation as is. It might not be result number 0.
10646   if (N->getNumValues() == 1) {
10647     Results.push_back(Res);
10648     return;
10649   }
10650 
10651   // If the original node has multiple results, then the return node should
10652   // have the same number of results.
10653   assert((N->getNumValues() == Res->getNumValues()) &&
10654       "Lowering returned the wrong number of results!");
10655 
10656   // Places new result values base on N result number.
10657   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
10658     Results.push_back(Res.getValue(I));
10659 }
10660 
10661 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10662   llvm_unreachable("LowerOperation not implemented for this target!");
10663 }
10664 
10665 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
10666                                                      unsigned Reg,
10667                                                      ISD::NodeType ExtendType) {
10668   SDValue Op = getNonRegisterValue(V);
10669   assert((Op.getOpcode() != ISD::CopyFromReg ||
10670           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
10671          "Copy from a reg to the same reg!");
10672   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
10673 
10674   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10675   // If this is an InlineAsm we have to match the registers required, not the
10676   // notional registers required by the type.
10677 
10678   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
10679                    std::nullopt); // This is not an ABI copy.
10680   SDValue Chain = DAG.getEntryNode();
10681 
10682   if (ExtendType == ISD::ANY_EXTEND) {
10683     auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
10684     if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
10685       ExtendType = PreferredExtendIt->second;
10686   }
10687   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
10688   PendingExports.push_back(Chain);
10689 }
10690 
10691 #include "llvm/CodeGen/SelectionDAGISel.h"
10692 
10693 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
10694 /// entry block, return true.  This includes arguments used by switches, since
10695 /// the switch may expand into multiple basic blocks.
10696 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
10697   // With FastISel active, we may be splitting blocks, so force creation
10698   // of virtual registers for all non-dead arguments.
10699   if (FastISel)
10700     return A->use_empty();
10701 
10702   const BasicBlock &Entry = A->getParent()->front();
10703   for (const User *U : A->users())
10704     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
10705       return false;  // Use not in entry block.
10706 
10707   return true;
10708 }
10709 
10710 using ArgCopyElisionMapTy =
10711     DenseMap<const Argument *,
10712              std::pair<const AllocaInst *, const StoreInst *>>;
10713 
10714 /// Scan the entry block of the function in FuncInfo for arguments that look
10715 /// like copies into a local alloca. Record any copied arguments in
10716 /// ArgCopyElisionCandidates.
10717 static void
10718 findArgumentCopyElisionCandidates(const DataLayout &DL,
10719                                   FunctionLoweringInfo *FuncInfo,
10720                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
10721   // Record the state of every static alloca used in the entry block. Argument
10722   // allocas are all used in the entry block, so we need approximately as many
10723   // entries as we have arguments.
10724   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
10725   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
10726   unsigned NumArgs = FuncInfo->Fn->arg_size();
10727   StaticAllocas.reserve(NumArgs * 2);
10728 
10729   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
10730     if (!V)
10731       return nullptr;
10732     V = V->stripPointerCasts();
10733     const auto *AI = dyn_cast<AllocaInst>(V);
10734     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
10735       return nullptr;
10736     auto Iter = StaticAllocas.insert({AI, Unknown});
10737     return &Iter.first->second;
10738   };
10739 
10740   // Look for stores of arguments to static allocas. Look through bitcasts and
10741   // GEPs to handle type coercions, as long as the alloca is fully initialized
10742   // by the store. Any non-store use of an alloca escapes it and any subsequent
10743   // unanalyzed store might write it.
10744   // FIXME: Handle structs initialized with multiple stores.
10745   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
10746     // Look for stores, and handle non-store uses conservatively.
10747     const auto *SI = dyn_cast<StoreInst>(&I);
10748     if (!SI) {
10749       // We will look through cast uses, so ignore them completely.
10750       if (I.isCast())
10751         continue;
10752       // Ignore debug info and pseudo op intrinsics, they don't escape or store
10753       // to allocas.
10754       if (I.isDebugOrPseudoInst())
10755         continue;
10756       // This is an unknown instruction. Assume it escapes or writes to all
10757       // static alloca operands.
10758       for (const Use &U : I.operands()) {
10759         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
10760           *Info = StaticAllocaInfo::Clobbered;
10761       }
10762       continue;
10763     }
10764 
10765     // If the stored value is a static alloca, mark it as escaped.
10766     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
10767       *Info = StaticAllocaInfo::Clobbered;
10768 
10769     // Check if the destination is a static alloca.
10770     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
10771     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
10772     if (!Info)
10773       continue;
10774     const AllocaInst *AI = cast<AllocaInst>(Dst);
10775 
10776     // Skip allocas that have been initialized or clobbered.
10777     if (*Info != StaticAllocaInfo::Unknown)
10778       continue;
10779 
10780     // Check if the stored value is an argument, and that this store fully
10781     // initializes the alloca.
10782     // If the argument type has padding bits we can't directly forward a pointer
10783     // as the upper bits may contain garbage.
10784     // Don't elide copies from the same argument twice.
10785     const Value *Val = SI->getValueOperand()->stripPointerCasts();
10786     const auto *Arg = dyn_cast<Argument>(Val);
10787     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
10788         Arg->getType()->isEmptyTy() ||
10789         DL.getTypeStoreSize(Arg->getType()) !=
10790             DL.getTypeAllocSize(AI->getAllocatedType()) ||
10791         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
10792         ArgCopyElisionCandidates.count(Arg)) {
10793       *Info = StaticAllocaInfo::Clobbered;
10794       continue;
10795     }
10796 
10797     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
10798                       << '\n');
10799 
10800     // Mark this alloca and store for argument copy elision.
10801     *Info = StaticAllocaInfo::Elidable;
10802     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
10803 
10804     // Stop scanning if we've seen all arguments. This will happen early in -O0
10805     // builds, which is useful, because -O0 builds have large entry blocks and
10806     // many allocas.
10807     if (ArgCopyElisionCandidates.size() == NumArgs)
10808       break;
10809   }
10810 }
10811 
10812 /// Try to elide argument copies from memory into a local alloca. Succeeds if
10813 /// ArgVal is a load from a suitable fixed stack object.
10814 static void tryToElideArgumentCopy(
10815     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
10816     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
10817     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
10818     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
10819     ArrayRef<SDValue> ArgVals, bool &ArgHasUses) {
10820   // Check if this is a load from a fixed stack object.
10821   auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]);
10822   if (!LNode)
10823     return;
10824   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
10825   if (!FINode)
10826     return;
10827 
10828   // Check that the fixed stack object is the right size and alignment.
10829   // Look at the alignment that the user wrote on the alloca instead of looking
10830   // at the stack object.
10831   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
10832   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
10833   const AllocaInst *AI = ArgCopyIter->second.first;
10834   int FixedIndex = FINode->getIndex();
10835   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
10836   int OldIndex = AllocaIndex;
10837   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
10838   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
10839     LLVM_DEBUG(
10840         dbgs() << "  argument copy elision failed due to bad fixed stack "
10841                   "object size\n");
10842     return;
10843   }
10844   Align RequiredAlignment = AI->getAlign();
10845   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
10846     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
10847                          "greater than stack argument alignment ("
10848                       << DebugStr(RequiredAlignment) << " vs "
10849                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
10850     return;
10851   }
10852 
10853   // Perform the elision. Delete the old stack object and replace its only use
10854   // in the variable info map. Mark the stack object as mutable.
10855   LLVM_DEBUG({
10856     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
10857            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
10858            << '\n';
10859   });
10860   MFI.RemoveStackObject(OldIndex);
10861   MFI.setIsImmutableObjectIndex(FixedIndex, false);
10862   AllocaIndex = FixedIndex;
10863   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
10864   for (SDValue ArgVal : ArgVals)
10865     Chains.push_back(ArgVal.getValue(1));
10866 
10867   // Avoid emitting code for the store implementing the copy.
10868   const StoreInst *SI = ArgCopyIter->second.second;
10869   ElidedArgCopyInstrs.insert(SI);
10870 
10871   // Check for uses of the argument again so that we can avoid exporting ArgVal
10872   // if it is't used by anything other than the store.
10873   for (const Value *U : Arg.users()) {
10874     if (U != SI) {
10875       ArgHasUses = true;
10876       break;
10877     }
10878   }
10879 }
10880 
10881 void SelectionDAGISel::LowerArguments(const Function &F) {
10882   SelectionDAG &DAG = SDB->DAG;
10883   SDLoc dl = SDB->getCurSDLoc();
10884   const DataLayout &DL = DAG.getDataLayout();
10885   SmallVector<ISD::InputArg, 16> Ins;
10886 
10887   // In Naked functions we aren't going to save any registers.
10888   if (F.hasFnAttribute(Attribute::Naked))
10889     return;
10890 
10891   if (!FuncInfo->CanLowerReturn) {
10892     // Put in an sret pointer parameter before all the other parameters.
10893     SmallVector<EVT, 1> ValueVTs;
10894     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10895                     PointerType::get(F.getContext(),
10896                                      DAG.getDataLayout().getAllocaAddrSpace()),
10897                     ValueVTs);
10898 
10899     // NOTE: Assuming that a pointer will never break down to more than one VT
10900     // or one register.
10901     ISD::ArgFlagsTy Flags;
10902     Flags.setSRet();
10903     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
10904     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
10905                          ISD::InputArg::NoArgIndex, 0);
10906     Ins.push_back(RetArg);
10907   }
10908 
10909   // Look for stores of arguments to static allocas. Mark such arguments with a
10910   // flag to ask the target to give us the memory location of that argument if
10911   // available.
10912   ArgCopyElisionMapTy ArgCopyElisionCandidates;
10913   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
10914                                     ArgCopyElisionCandidates);
10915 
10916   // Set up the incoming argument description vector.
10917   for (const Argument &Arg : F.args()) {
10918     unsigned ArgNo = Arg.getArgNo();
10919     SmallVector<EVT, 4> ValueVTs;
10920     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10921     bool isArgValueUsed = !Arg.use_empty();
10922     unsigned PartBase = 0;
10923     Type *FinalType = Arg.getType();
10924     if (Arg.hasAttribute(Attribute::ByVal))
10925       FinalType = Arg.getParamByValType();
10926     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
10927         FinalType, F.getCallingConv(), F.isVarArg(), DL);
10928     for (unsigned Value = 0, NumValues = ValueVTs.size();
10929          Value != NumValues; ++Value) {
10930       EVT VT = ValueVTs[Value];
10931       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
10932       ISD::ArgFlagsTy Flags;
10933 
10934 
10935       if (Arg.getType()->isPointerTy()) {
10936         Flags.setPointer();
10937         Flags.setPointerAddrSpace(
10938             cast<PointerType>(Arg.getType())->getAddressSpace());
10939       }
10940       if (Arg.hasAttribute(Attribute::ZExt))
10941         Flags.setZExt();
10942       if (Arg.hasAttribute(Attribute::SExt))
10943         Flags.setSExt();
10944       if (Arg.hasAttribute(Attribute::InReg)) {
10945         // If we are using vectorcall calling convention, a structure that is
10946         // passed InReg - is surely an HVA
10947         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
10948             isa<StructType>(Arg.getType())) {
10949           // The first value of a structure is marked
10950           if (0 == Value)
10951             Flags.setHvaStart();
10952           Flags.setHva();
10953         }
10954         // Set InReg Flag
10955         Flags.setInReg();
10956       }
10957       if (Arg.hasAttribute(Attribute::StructRet))
10958         Flags.setSRet();
10959       if (Arg.hasAttribute(Attribute::SwiftSelf))
10960         Flags.setSwiftSelf();
10961       if (Arg.hasAttribute(Attribute::SwiftAsync))
10962         Flags.setSwiftAsync();
10963       if (Arg.hasAttribute(Attribute::SwiftError))
10964         Flags.setSwiftError();
10965       if (Arg.hasAttribute(Attribute::ByVal))
10966         Flags.setByVal();
10967       if (Arg.hasAttribute(Attribute::ByRef))
10968         Flags.setByRef();
10969       if (Arg.hasAttribute(Attribute::InAlloca)) {
10970         Flags.setInAlloca();
10971         // Set the byval flag for CCAssignFn callbacks that don't know about
10972         // inalloca.  This way we can know how many bytes we should've allocated
10973         // and how many bytes a callee cleanup function will pop.  If we port
10974         // inalloca to more targets, we'll have to add custom inalloca handling
10975         // in the various CC lowering callbacks.
10976         Flags.setByVal();
10977       }
10978       if (Arg.hasAttribute(Attribute::Preallocated)) {
10979         Flags.setPreallocated();
10980         // Set the byval flag for CCAssignFn callbacks that don't know about
10981         // preallocated.  This way we can know how many bytes we should've
10982         // allocated and how many bytes a callee cleanup function will pop.  If
10983         // we port preallocated to more targets, we'll have to add custom
10984         // preallocated handling in the various CC lowering callbacks.
10985         Flags.setByVal();
10986       }
10987 
10988       // Certain targets (such as MIPS), may have a different ABI alignment
10989       // for a type depending on the context. Give the target a chance to
10990       // specify the alignment it wants.
10991       const Align OriginalAlignment(
10992           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
10993       Flags.setOrigAlign(OriginalAlignment);
10994 
10995       Align MemAlign;
10996       Type *ArgMemTy = nullptr;
10997       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
10998           Flags.isByRef()) {
10999         if (!ArgMemTy)
11000           ArgMemTy = Arg.getPointeeInMemoryValueType();
11001 
11002         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
11003 
11004         // For in-memory arguments, size and alignment should be passed from FE.
11005         // BE will guess if this info is not there but there are cases it cannot
11006         // get right.
11007         if (auto ParamAlign = Arg.getParamStackAlign())
11008           MemAlign = *ParamAlign;
11009         else if ((ParamAlign = Arg.getParamAlign()))
11010           MemAlign = *ParamAlign;
11011         else
11012           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
11013         if (Flags.isByRef())
11014           Flags.setByRefSize(MemSize);
11015         else
11016           Flags.setByValSize(MemSize);
11017       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
11018         MemAlign = *ParamAlign;
11019       } else {
11020         MemAlign = OriginalAlignment;
11021       }
11022       Flags.setMemAlign(MemAlign);
11023 
11024       if (Arg.hasAttribute(Attribute::Nest))
11025         Flags.setNest();
11026       if (NeedsRegBlock)
11027         Flags.setInConsecutiveRegs();
11028       if (ArgCopyElisionCandidates.count(&Arg))
11029         Flags.setCopyElisionCandidate();
11030       if (Arg.hasAttribute(Attribute::Returned))
11031         Flags.setReturned();
11032 
11033       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
11034           *CurDAG->getContext(), F.getCallingConv(), VT);
11035       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
11036           *CurDAG->getContext(), F.getCallingConv(), VT);
11037       for (unsigned i = 0; i != NumRegs; ++i) {
11038         // For scalable vectors, use the minimum size; individual targets
11039         // are responsible for handling scalable vector arguments and
11040         // return values.
11041         ISD::InputArg MyFlags(
11042             Flags, RegisterVT, VT, isArgValueUsed, ArgNo,
11043             PartBase + i * RegisterVT.getStoreSize().getKnownMinValue());
11044         if (NumRegs > 1 && i == 0)
11045           MyFlags.Flags.setSplit();
11046         // if it isn't first piece, alignment must be 1
11047         else if (i > 0) {
11048           MyFlags.Flags.setOrigAlign(Align(1));
11049           if (i == NumRegs - 1)
11050             MyFlags.Flags.setSplitEnd();
11051         }
11052         Ins.push_back(MyFlags);
11053       }
11054       if (NeedsRegBlock && Value == NumValues - 1)
11055         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
11056       PartBase += VT.getStoreSize().getKnownMinValue();
11057     }
11058   }
11059 
11060   // Call the target to set up the argument values.
11061   SmallVector<SDValue, 8> InVals;
11062   SDValue NewRoot = TLI->LowerFormalArguments(
11063       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
11064 
11065   // Verify that the target's LowerFormalArguments behaved as expected.
11066   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
11067          "LowerFormalArguments didn't return a valid chain!");
11068   assert(InVals.size() == Ins.size() &&
11069          "LowerFormalArguments didn't emit the correct number of values!");
11070   LLVM_DEBUG({
11071     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
11072       assert(InVals[i].getNode() &&
11073              "LowerFormalArguments emitted a null value!");
11074       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
11075              "LowerFormalArguments emitted a value with the wrong type!");
11076     }
11077   });
11078 
11079   // Update the DAG with the new chain value resulting from argument lowering.
11080   DAG.setRoot(NewRoot);
11081 
11082   // Set up the argument values.
11083   unsigned i = 0;
11084   if (!FuncInfo->CanLowerReturn) {
11085     // Create a virtual register for the sret pointer, and put in a copy
11086     // from the sret argument into it.
11087     SmallVector<EVT, 1> ValueVTs;
11088     ComputeValueVTs(*TLI, DAG.getDataLayout(),
11089                     PointerType::get(F.getContext(),
11090                                      DAG.getDataLayout().getAllocaAddrSpace()),
11091                     ValueVTs);
11092     MVT VT = ValueVTs[0].getSimpleVT();
11093     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
11094     std::optional<ISD::NodeType> AssertOp;
11095     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
11096                                         nullptr, F.getCallingConv(), AssertOp);
11097 
11098     MachineFunction& MF = SDB->DAG.getMachineFunction();
11099     MachineRegisterInfo& RegInfo = MF.getRegInfo();
11100     Register SRetReg =
11101         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
11102     FuncInfo->DemoteRegister = SRetReg;
11103     NewRoot =
11104         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
11105     DAG.setRoot(NewRoot);
11106 
11107     // i indexes lowered arguments.  Bump it past the hidden sret argument.
11108     ++i;
11109   }
11110 
11111   SmallVector<SDValue, 4> Chains;
11112   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
11113   for (const Argument &Arg : F.args()) {
11114     SmallVector<SDValue, 4> ArgValues;
11115     SmallVector<EVT, 4> ValueVTs;
11116     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
11117     unsigned NumValues = ValueVTs.size();
11118     if (NumValues == 0)
11119       continue;
11120 
11121     bool ArgHasUses = !Arg.use_empty();
11122 
11123     // Elide the copying store if the target loaded this argument from a
11124     // suitable fixed stack object.
11125     if (Ins[i].Flags.isCopyElisionCandidate()) {
11126       unsigned NumParts = 0;
11127       for (EVT VT : ValueVTs)
11128         NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(),
11129                                                        F.getCallingConv(), VT);
11130 
11131       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
11132                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
11133                              ArrayRef(&InVals[i], NumParts), ArgHasUses);
11134     }
11135 
11136     // If this argument is unused then remember its value. It is used to generate
11137     // debugging information.
11138     bool isSwiftErrorArg =
11139         TLI->supportSwiftError() &&
11140         Arg.hasAttribute(Attribute::SwiftError);
11141     if (!ArgHasUses && !isSwiftErrorArg) {
11142       SDB->setUnusedArgValue(&Arg, InVals[i]);
11143 
11144       // Also remember any frame index for use in FastISel.
11145       if (FrameIndexSDNode *FI =
11146           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
11147         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11148     }
11149 
11150     for (unsigned Val = 0; Val != NumValues; ++Val) {
11151       EVT VT = ValueVTs[Val];
11152       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
11153                                                       F.getCallingConv(), VT);
11154       unsigned NumParts = TLI->getNumRegistersForCallingConv(
11155           *CurDAG->getContext(), F.getCallingConv(), VT);
11156 
11157       // Even an apparent 'unused' swifterror argument needs to be returned. So
11158       // we do generate a copy for it that can be used on return from the
11159       // function.
11160       if (ArgHasUses || isSwiftErrorArg) {
11161         std::optional<ISD::NodeType> AssertOp;
11162         if (Arg.hasAttribute(Attribute::SExt))
11163           AssertOp = ISD::AssertSext;
11164         else if (Arg.hasAttribute(Attribute::ZExt))
11165           AssertOp = ISD::AssertZext;
11166 
11167         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
11168                                              PartVT, VT, nullptr,
11169                                              F.getCallingConv(), AssertOp));
11170       }
11171 
11172       i += NumParts;
11173     }
11174 
11175     // We don't need to do anything else for unused arguments.
11176     if (ArgValues.empty())
11177       continue;
11178 
11179     // Note down frame index.
11180     if (FrameIndexSDNode *FI =
11181         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
11182       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11183 
11184     SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues),
11185                                      SDB->getCurSDLoc());
11186 
11187     SDB->setValue(&Arg, Res);
11188     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
11189       // We want to associate the argument with the frame index, among
11190       // involved operands, that correspond to the lowest address. The
11191       // getCopyFromParts function, called earlier, is swapping the order of
11192       // the operands to BUILD_PAIR depending on endianness. The result of
11193       // that swapping is that the least significant bits of the argument will
11194       // be in the first operand of the BUILD_PAIR node, and the most
11195       // significant bits will be in the second operand.
11196       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
11197       if (LoadSDNode *LNode =
11198           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
11199         if (FrameIndexSDNode *FI =
11200             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
11201           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11202     }
11203 
11204     // Analyses past this point are naive and don't expect an assertion.
11205     if (Res.getOpcode() == ISD::AssertZext)
11206       Res = Res.getOperand(0);
11207 
11208     // Update the SwiftErrorVRegDefMap.
11209     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
11210       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11211       if (Register::isVirtualRegister(Reg))
11212         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
11213                                    Reg);
11214     }
11215 
11216     // If this argument is live outside of the entry block, insert a copy from
11217     // wherever we got it to the vreg that other BB's will reference it as.
11218     if (Res.getOpcode() == ISD::CopyFromReg) {
11219       // If we can, though, try to skip creating an unnecessary vreg.
11220       // FIXME: This isn't very clean... it would be nice to make this more
11221       // general.
11222       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11223       if (Register::isVirtualRegister(Reg)) {
11224         FuncInfo->ValueMap[&Arg] = Reg;
11225         continue;
11226       }
11227     }
11228     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
11229       FuncInfo->InitializeRegForValue(&Arg);
11230       SDB->CopyToExportRegsIfNeeded(&Arg);
11231     }
11232   }
11233 
11234   if (!Chains.empty()) {
11235     Chains.push_back(NewRoot);
11236     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
11237   }
11238 
11239   DAG.setRoot(NewRoot);
11240 
11241   assert(i == InVals.size() && "Argument register count mismatch!");
11242 
11243   // If any argument copy elisions occurred and we have debug info, update the
11244   // stale frame indices used in the dbg.declare variable info table.
11245   if (!ArgCopyElisionFrameIndexMap.empty()) {
11246     for (MachineFunction::VariableDbgInfo &VI :
11247          MF->getInStackSlotVariableDbgInfo()) {
11248       auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot());
11249       if (I != ArgCopyElisionFrameIndexMap.end())
11250         VI.updateStackSlot(I->second);
11251     }
11252   }
11253 
11254   // Finally, if the target has anything special to do, allow it to do so.
11255   emitFunctionEntryCode();
11256 }
11257 
11258 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
11259 /// ensure constants are generated when needed.  Remember the virtual registers
11260 /// that need to be added to the Machine PHI nodes as input.  We cannot just
11261 /// directly add them, because expansion might result in multiple MBB's for one
11262 /// BB.  As such, the start of the BB might correspond to a different MBB than
11263 /// the end.
11264 void
11265 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
11266   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11267 
11268   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
11269 
11270   // Check PHI nodes in successors that expect a value to be available from this
11271   // block.
11272   for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
11273     if (!isa<PHINode>(SuccBB->begin())) continue;
11274     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
11275 
11276     // If this terminator has multiple identical successors (common for
11277     // switches), only handle each succ once.
11278     if (!SuccsHandled.insert(SuccMBB).second)
11279       continue;
11280 
11281     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
11282 
11283     // At this point we know that there is a 1-1 correspondence between LLVM PHI
11284     // nodes and Machine PHI nodes, but the incoming operands have not been
11285     // emitted yet.
11286     for (const PHINode &PN : SuccBB->phis()) {
11287       // Ignore dead phi's.
11288       if (PN.use_empty())
11289         continue;
11290 
11291       // Skip empty types
11292       if (PN.getType()->isEmptyTy())
11293         continue;
11294 
11295       unsigned Reg;
11296       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
11297 
11298       if (const auto *C = dyn_cast<Constant>(PHIOp)) {
11299         unsigned &RegOut = ConstantsOut[C];
11300         if (RegOut == 0) {
11301           RegOut = FuncInfo.CreateRegs(C);
11302           // We need to zero/sign extend ConstantInt phi operands to match
11303           // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
11304           ISD::NodeType ExtendType = ISD::ANY_EXTEND;
11305           if (auto *CI = dyn_cast<ConstantInt>(C))
11306             ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
11307                                                     : ISD::ZERO_EXTEND;
11308           CopyValueToVirtualRegister(C, RegOut, ExtendType);
11309         }
11310         Reg = RegOut;
11311       } else {
11312         DenseMap<const Value *, Register>::iterator I =
11313           FuncInfo.ValueMap.find(PHIOp);
11314         if (I != FuncInfo.ValueMap.end())
11315           Reg = I->second;
11316         else {
11317           assert(isa<AllocaInst>(PHIOp) &&
11318                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
11319                  "Didn't codegen value into a register!??");
11320           Reg = FuncInfo.CreateRegs(PHIOp);
11321           CopyValueToVirtualRegister(PHIOp, Reg);
11322         }
11323       }
11324 
11325       // Remember that this register needs to added to the machine PHI node as
11326       // the input for this MBB.
11327       SmallVector<EVT, 4> ValueVTs;
11328       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
11329       for (EVT VT : ValueVTs) {
11330         const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
11331         for (unsigned i = 0; i != NumRegisters; ++i)
11332           FuncInfo.PHINodesToUpdate.push_back(
11333               std::make_pair(&*MBBI++, Reg + i));
11334         Reg += NumRegisters;
11335       }
11336     }
11337   }
11338 
11339   ConstantsOut.clear();
11340 }
11341 
11342 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
11343   MachineFunction::iterator I(MBB);
11344   if (++I == FuncInfo.MF->end())
11345     return nullptr;
11346   return &*I;
11347 }
11348 
11349 /// During lowering new call nodes can be created (such as memset, etc.).
11350 /// Those will become new roots of the current DAG, but complications arise
11351 /// when they are tail calls. In such cases, the call lowering will update
11352 /// the root, but the builder still needs to know that a tail call has been
11353 /// lowered in order to avoid generating an additional return.
11354 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
11355   // If the node is null, we do have a tail call.
11356   if (MaybeTC.getNode() != nullptr)
11357     DAG.setRoot(MaybeTC);
11358   else
11359     HasTailCall = true;
11360 }
11361 
11362 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
11363                                         MachineBasicBlock *SwitchMBB,
11364                                         MachineBasicBlock *DefaultMBB) {
11365   MachineFunction *CurMF = FuncInfo.MF;
11366   MachineBasicBlock *NextMBB = nullptr;
11367   MachineFunction::iterator BBI(W.MBB);
11368   if (++BBI != FuncInfo.MF->end())
11369     NextMBB = &*BBI;
11370 
11371   unsigned Size = W.LastCluster - W.FirstCluster + 1;
11372 
11373   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11374 
11375   if (Size == 2 && W.MBB == SwitchMBB) {
11376     // If any two of the cases has the same destination, and if one value
11377     // is the same as the other, but has one bit unset that the other has set,
11378     // use bit manipulation to do two compares at once.  For example:
11379     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
11380     // TODO: This could be extended to merge any 2 cases in switches with 3
11381     // cases.
11382     // TODO: Handle cases where W.CaseBB != SwitchBB.
11383     CaseCluster &Small = *W.FirstCluster;
11384     CaseCluster &Big = *W.LastCluster;
11385 
11386     if (Small.Low == Small.High && Big.Low == Big.High &&
11387         Small.MBB == Big.MBB) {
11388       const APInt &SmallValue = Small.Low->getValue();
11389       const APInt &BigValue = Big.Low->getValue();
11390 
11391       // Check that there is only one bit different.
11392       APInt CommonBit = BigValue ^ SmallValue;
11393       if (CommonBit.isPowerOf2()) {
11394         SDValue CondLHS = getValue(Cond);
11395         EVT VT = CondLHS.getValueType();
11396         SDLoc DL = getCurSDLoc();
11397 
11398         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
11399                                  DAG.getConstant(CommonBit, DL, VT));
11400         SDValue Cond = DAG.getSetCC(
11401             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
11402             ISD::SETEQ);
11403 
11404         // Update successor info.
11405         // Both Small and Big will jump to Small.BB, so we sum up the
11406         // probabilities.
11407         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
11408         if (BPI)
11409           addSuccessorWithProb(
11410               SwitchMBB, DefaultMBB,
11411               // The default destination is the first successor in IR.
11412               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
11413         else
11414           addSuccessorWithProb(SwitchMBB, DefaultMBB);
11415 
11416         // Insert the true branch.
11417         SDValue BrCond =
11418             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
11419                         DAG.getBasicBlock(Small.MBB));
11420         // Insert the false branch.
11421         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
11422                              DAG.getBasicBlock(DefaultMBB));
11423 
11424         DAG.setRoot(BrCond);
11425         return;
11426       }
11427     }
11428   }
11429 
11430   if (TM.getOptLevel() != CodeGenOptLevel::None) {
11431     // Here, we order cases by probability so the most likely case will be
11432     // checked first. However, two clusters can have the same probability in
11433     // which case their relative ordering is non-deterministic. So we use Low
11434     // as a tie-breaker as clusters are guaranteed to never overlap.
11435     llvm::sort(W.FirstCluster, W.LastCluster + 1,
11436                [](const CaseCluster &a, const CaseCluster &b) {
11437       return a.Prob != b.Prob ?
11438              a.Prob > b.Prob :
11439              a.Low->getValue().slt(b.Low->getValue());
11440     });
11441 
11442     // Rearrange the case blocks so that the last one falls through if possible
11443     // without changing the order of probabilities.
11444     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
11445       --I;
11446       if (I->Prob > W.LastCluster->Prob)
11447         break;
11448       if (I->Kind == CC_Range && I->MBB == NextMBB) {
11449         std::swap(*I, *W.LastCluster);
11450         break;
11451       }
11452     }
11453   }
11454 
11455   // Compute total probability.
11456   BranchProbability DefaultProb = W.DefaultProb;
11457   BranchProbability UnhandledProbs = DefaultProb;
11458   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
11459     UnhandledProbs += I->Prob;
11460 
11461   MachineBasicBlock *CurMBB = W.MBB;
11462   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
11463     bool FallthroughUnreachable = false;
11464     MachineBasicBlock *Fallthrough;
11465     if (I == W.LastCluster) {
11466       // For the last cluster, fall through to the default destination.
11467       Fallthrough = DefaultMBB;
11468       FallthroughUnreachable = isa<UnreachableInst>(
11469           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
11470     } else {
11471       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
11472       CurMF->insert(BBI, Fallthrough);
11473       // Put Cond in a virtual register to make it available from the new blocks.
11474       ExportFromCurrentBlock(Cond);
11475     }
11476     UnhandledProbs -= I->Prob;
11477 
11478     switch (I->Kind) {
11479       case CC_JumpTable: {
11480         // FIXME: Optimize away range check based on pivot comparisons.
11481         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
11482         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
11483 
11484         // The jump block hasn't been inserted yet; insert it here.
11485         MachineBasicBlock *JumpMBB = JT->MBB;
11486         CurMF->insert(BBI, JumpMBB);
11487 
11488         auto JumpProb = I->Prob;
11489         auto FallthroughProb = UnhandledProbs;
11490 
11491         // If the default statement is a target of the jump table, we evenly
11492         // distribute the default probability to successors of CurMBB. Also
11493         // update the probability on the edge from JumpMBB to Fallthrough.
11494         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
11495                                               SE = JumpMBB->succ_end();
11496              SI != SE; ++SI) {
11497           if (*SI == DefaultMBB) {
11498             JumpProb += DefaultProb / 2;
11499             FallthroughProb -= DefaultProb / 2;
11500             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
11501             JumpMBB->normalizeSuccProbs();
11502             break;
11503           }
11504         }
11505 
11506         // If the default clause is unreachable, propagate that knowledge into
11507         // JTH->FallthroughUnreachable which will use it to suppress the range
11508         // check.
11509         //
11510         // However, don't do this if we're doing branch target enforcement,
11511         // because a table branch _without_ a range check can be a tempting JOP
11512         // gadget - out-of-bounds inputs that are impossible in correct
11513         // execution become possible again if an attacker can influence the
11514         // control flow. So if an attacker doesn't already have a BTI bypass
11515         // available, we don't want them to be able to get one out of this
11516         // table branch.
11517         if (FallthroughUnreachable) {
11518           Function &CurFunc = CurMF->getFunction();
11519           bool HasBranchTargetEnforcement = false;
11520           if (CurFunc.hasFnAttribute("branch-target-enforcement")) {
11521             HasBranchTargetEnforcement =
11522                 CurFunc.getFnAttribute("branch-target-enforcement")
11523                     .getValueAsBool();
11524           } else {
11525             HasBranchTargetEnforcement =
11526                 CurMF->getMMI().getModule()->getModuleFlag(
11527                     "branch-target-enforcement");
11528           }
11529           if (!HasBranchTargetEnforcement)
11530             JTH->FallthroughUnreachable = true;
11531         }
11532 
11533         if (!JTH->FallthroughUnreachable)
11534           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
11535         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
11536         CurMBB->normalizeSuccProbs();
11537 
11538         // The jump table header will be inserted in our current block, do the
11539         // range check, and fall through to our fallthrough block.
11540         JTH->HeaderBB = CurMBB;
11541         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
11542 
11543         // If we're in the right place, emit the jump table header right now.
11544         if (CurMBB == SwitchMBB) {
11545           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
11546           JTH->Emitted = true;
11547         }
11548         break;
11549       }
11550       case CC_BitTests: {
11551         // FIXME: Optimize away range check based on pivot comparisons.
11552         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
11553 
11554         // The bit test blocks haven't been inserted yet; insert them here.
11555         for (BitTestCase &BTC : BTB->Cases)
11556           CurMF->insert(BBI, BTC.ThisBB);
11557 
11558         // Fill in fields of the BitTestBlock.
11559         BTB->Parent = CurMBB;
11560         BTB->Default = Fallthrough;
11561 
11562         BTB->DefaultProb = UnhandledProbs;
11563         // If the cases in bit test don't form a contiguous range, we evenly
11564         // distribute the probability on the edge to Fallthrough to two
11565         // successors of CurMBB.
11566         if (!BTB->ContiguousRange) {
11567           BTB->Prob += DefaultProb / 2;
11568           BTB->DefaultProb -= DefaultProb / 2;
11569         }
11570 
11571         if (FallthroughUnreachable)
11572           BTB->FallthroughUnreachable = true;
11573 
11574         // If we're in the right place, emit the bit test header right now.
11575         if (CurMBB == SwitchMBB) {
11576           visitBitTestHeader(*BTB, SwitchMBB);
11577           BTB->Emitted = true;
11578         }
11579         break;
11580       }
11581       case CC_Range: {
11582         const Value *RHS, *LHS, *MHS;
11583         ISD::CondCode CC;
11584         if (I->Low == I->High) {
11585           // Check Cond == I->Low.
11586           CC = ISD::SETEQ;
11587           LHS = Cond;
11588           RHS=I->Low;
11589           MHS = nullptr;
11590         } else {
11591           // Check I->Low <= Cond <= I->High.
11592           CC = ISD::SETLE;
11593           LHS = I->Low;
11594           MHS = Cond;
11595           RHS = I->High;
11596         }
11597 
11598         // If Fallthrough is unreachable, fold away the comparison.
11599         if (FallthroughUnreachable)
11600           CC = ISD::SETTRUE;
11601 
11602         // The false probability is the sum of all unhandled cases.
11603         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
11604                      getCurSDLoc(), I->Prob, UnhandledProbs);
11605 
11606         if (CurMBB == SwitchMBB)
11607           visitSwitchCase(CB, SwitchMBB);
11608         else
11609           SL->SwitchCases.push_back(CB);
11610 
11611         break;
11612       }
11613     }
11614     CurMBB = Fallthrough;
11615   }
11616 }
11617 
11618 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
11619                                               CaseClusterIt First,
11620                                               CaseClusterIt Last) {
11621   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
11622     if (X.Prob != CC.Prob)
11623       return X.Prob > CC.Prob;
11624 
11625     // Ties are broken by comparing the case value.
11626     return X.Low->getValue().slt(CC.Low->getValue());
11627   });
11628 }
11629 
11630 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
11631                                         const SwitchWorkListItem &W,
11632                                         Value *Cond,
11633                                         MachineBasicBlock *SwitchMBB) {
11634   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
11635          "Clusters not sorted?");
11636 
11637   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
11638 
11639   // Balance the tree based on branch probabilities to create a near-optimal (in
11640   // terms of search time given key frequency) binary search tree. See e.g. Kurt
11641   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
11642   CaseClusterIt LastLeft = W.FirstCluster;
11643   CaseClusterIt FirstRight = W.LastCluster;
11644   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
11645   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
11646 
11647   // Move LastLeft and FirstRight towards each other from opposite directions to
11648   // find a partitioning of the clusters which balances the probability on both
11649   // sides. If LeftProb and RightProb are equal, alternate which side is
11650   // taken to ensure 0-probability nodes are distributed evenly.
11651   unsigned I = 0;
11652   while (LastLeft + 1 < FirstRight) {
11653     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
11654       LeftProb += (++LastLeft)->Prob;
11655     else
11656       RightProb += (--FirstRight)->Prob;
11657     I++;
11658   }
11659 
11660   while (true) {
11661     // Our binary search tree differs from a typical BST in that ours can have up
11662     // to three values in each leaf. The pivot selection above doesn't take that
11663     // into account, which means the tree might require more nodes and be less
11664     // efficient. We compensate for this here.
11665 
11666     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
11667     unsigned NumRight = W.LastCluster - FirstRight + 1;
11668 
11669     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
11670       // If one side has less than 3 clusters, and the other has more than 3,
11671       // consider taking a cluster from the other side.
11672 
11673       if (NumLeft < NumRight) {
11674         // Consider moving the first cluster on the right to the left side.
11675         CaseCluster &CC = *FirstRight;
11676         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
11677         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
11678         if (LeftSideRank <= RightSideRank) {
11679           // Moving the cluster to the left does not demote it.
11680           ++LastLeft;
11681           ++FirstRight;
11682           continue;
11683         }
11684       } else {
11685         assert(NumRight < NumLeft);
11686         // Consider moving the last element on the left to the right side.
11687         CaseCluster &CC = *LastLeft;
11688         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
11689         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
11690         if (RightSideRank <= LeftSideRank) {
11691           // Moving the cluster to the right does not demot it.
11692           --LastLeft;
11693           --FirstRight;
11694           continue;
11695         }
11696       }
11697     }
11698     break;
11699   }
11700 
11701   assert(LastLeft + 1 == FirstRight);
11702   assert(LastLeft >= W.FirstCluster);
11703   assert(FirstRight <= W.LastCluster);
11704 
11705   // Use the first element on the right as pivot since we will make less-than
11706   // comparisons against it.
11707   CaseClusterIt PivotCluster = FirstRight;
11708   assert(PivotCluster > W.FirstCluster);
11709   assert(PivotCluster <= W.LastCluster);
11710 
11711   CaseClusterIt FirstLeft = W.FirstCluster;
11712   CaseClusterIt LastRight = W.LastCluster;
11713 
11714   const ConstantInt *Pivot = PivotCluster->Low;
11715 
11716   // New blocks will be inserted immediately after the current one.
11717   MachineFunction::iterator BBI(W.MBB);
11718   ++BBI;
11719 
11720   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
11721   // we can branch to its destination directly if it's squeezed exactly in
11722   // between the known lower bound and Pivot - 1.
11723   MachineBasicBlock *LeftMBB;
11724   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
11725       FirstLeft->Low == W.GE &&
11726       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
11727     LeftMBB = FirstLeft->MBB;
11728   } else {
11729     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11730     FuncInfo.MF->insert(BBI, LeftMBB);
11731     WorkList.push_back(
11732         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
11733     // Put Cond in a virtual register to make it available from the new blocks.
11734     ExportFromCurrentBlock(Cond);
11735   }
11736 
11737   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
11738   // single cluster, RHS.Low == Pivot, and we can branch to its destination
11739   // directly if RHS.High equals the current upper bound.
11740   MachineBasicBlock *RightMBB;
11741   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
11742       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
11743     RightMBB = FirstRight->MBB;
11744   } else {
11745     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11746     FuncInfo.MF->insert(BBI, RightMBB);
11747     WorkList.push_back(
11748         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
11749     // Put Cond in a virtual register to make it available from the new blocks.
11750     ExportFromCurrentBlock(Cond);
11751   }
11752 
11753   // Create the CaseBlock record that will be used to lower the branch.
11754   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
11755                getCurSDLoc(), LeftProb, RightProb);
11756 
11757   if (W.MBB == SwitchMBB)
11758     visitSwitchCase(CB, SwitchMBB);
11759   else
11760     SL->SwitchCases.push_back(CB);
11761 }
11762 
11763 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
11764 // from the swith statement.
11765 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
11766                                             BranchProbability PeeledCaseProb) {
11767   if (PeeledCaseProb == BranchProbability::getOne())
11768     return BranchProbability::getZero();
11769   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
11770 
11771   uint32_t Numerator = CaseProb.getNumerator();
11772   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
11773   return BranchProbability(Numerator, std::max(Numerator, Denominator));
11774 }
11775 
11776 // Try to peel the top probability case if it exceeds the threshold.
11777 // Return current MachineBasicBlock for the switch statement if the peeling
11778 // does not occur.
11779 // If the peeling is performed, return the newly created MachineBasicBlock
11780 // for the peeled switch statement. Also update Clusters to remove the peeled
11781 // case. PeeledCaseProb is the BranchProbability for the peeled case.
11782 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
11783     const SwitchInst &SI, CaseClusterVector &Clusters,
11784     BranchProbability &PeeledCaseProb) {
11785   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11786   // Don't perform if there is only one cluster or optimizing for size.
11787   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
11788       TM.getOptLevel() == CodeGenOptLevel::None ||
11789       SwitchMBB->getParent()->getFunction().hasMinSize())
11790     return SwitchMBB;
11791 
11792   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
11793   unsigned PeeledCaseIndex = 0;
11794   bool SwitchPeeled = false;
11795   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
11796     CaseCluster &CC = Clusters[Index];
11797     if (CC.Prob < TopCaseProb)
11798       continue;
11799     TopCaseProb = CC.Prob;
11800     PeeledCaseIndex = Index;
11801     SwitchPeeled = true;
11802   }
11803   if (!SwitchPeeled)
11804     return SwitchMBB;
11805 
11806   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
11807                     << TopCaseProb << "\n");
11808 
11809   // Record the MBB for the peeled switch statement.
11810   MachineFunction::iterator BBI(SwitchMBB);
11811   ++BBI;
11812   MachineBasicBlock *PeeledSwitchMBB =
11813       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
11814   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
11815 
11816   ExportFromCurrentBlock(SI.getCondition());
11817   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
11818   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
11819                           nullptr,   nullptr,      TopCaseProb.getCompl()};
11820   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
11821 
11822   Clusters.erase(PeeledCaseIt);
11823   for (CaseCluster &CC : Clusters) {
11824     LLVM_DEBUG(
11825         dbgs() << "Scale the probablity for one cluster, before scaling: "
11826                << CC.Prob << "\n");
11827     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
11828     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
11829   }
11830   PeeledCaseProb = TopCaseProb;
11831   return PeeledSwitchMBB;
11832 }
11833 
11834 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
11835   // Extract cases from the switch.
11836   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11837   CaseClusterVector Clusters;
11838   Clusters.reserve(SI.getNumCases());
11839   for (auto I : SI.cases()) {
11840     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
11841     const ConstantInt *CaseVal = I.getCaseValue();
11842     BranchProbability Prob =
11843         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
11844             : BranchProbability(1, SI.getNumCases() + 1);
11845     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
11846   }
11847 
11848   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
11849 
11850   // Cluster adjacent cases with the same destination. We do this at all
11851   // optimization levels because it's cheap to do and will make codegen faster
11852   // if there are many clusters.
11853   sortAndRangeify(Clusters);
11854 
11855   // The branch probablity of the peeled case.
11856   BranchProbability PeeledCaseProb = BranchProbability::getZero();
11857   MachineBasicBlock *PeeledSwitchMBB =
11858       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
11859 
11860   // If there is only the default destination, jump there directly.
11861   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11862   if (Clusters.empty()) {
11863     assert(PeeledSwitchMBB == SwitchMBB);
11864     SwitchMBB->addSuccessor(DefaultMBB);
11865     if (DefaultMBB != NextBlock(SwitchMBB)) {
11866       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
11867                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
11868     }
11869     return;
11870   }
11871 
11872   SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(),
11873                      DAG.getBFI());
11874   SL->findBitTestClusters(Clusters, &SI);
11875 
11876   LLVM_DEBUG({
11877     dbgs() << "Case clusters: ";
11878     for (const CaseCluster &C : Clusters) {
11879       if (C.Kind == CC_JumpTable)
11880         dbgs() << "JT:";
11881       if (C.Kind == CC_BitTests)
11882         dbgs() << "BT:";
11883 
11884       C.Low->getValue().print(dbgs(), true);
11885       if (C.Low != C.High) {
11886         dbgs() << '-';
11887         C.High->getValue().print(dbgs(), true);
11888       }
11889       dbgs() << ' ';
11890     }
11891     dbgs() << '\n';
11892   });
11893 
11894   assert(!Clusters.empty());
11895   SwitchWorkList WorkList;
11896   CaseClusterIt First = Clusters.begin();
11897   CaseClusterIt Last = Clusters.end() - 1;
11898   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
11899   // Scale the branchprobability for DefaultMBB if the peel occurs and
11900   // DefaultMBB is not replaced.
11901   if (PeeledCaseProb != BranchProbability::getZero() &&
11902       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
11903     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
11904   WorkList.push_back(
11905       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
11906 
11907   while (!WorkList.empty()) {
11908     SwitchWorkListItem W = WorkList.pop_back_val();
11909     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
11910 
11911     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None &&
11912         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
11913       // For optimized builds, lower large range as a balanced binary tree.
11914       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
11915       continue;
11916     }
11917 
11918     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
11919   }
11920 }
11921 
11922 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
11923   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11924   auto DL = getCurSDLoc();
11925   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11926   setValue(&I, DAG.getStepVector(DL, ResultVT));
11927 }
11928 
11929 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
11930   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11931   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11932 
11933   SDLoc DL = getCurSDLoc();
11934   SDValue V = getValue(I.getOperand(0));
11935   assert(VT == V.getValueType() && "Malformed vector.reverse!");
11936 
11937   if (VT.isScalableVector()) {
11938     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
11939     return;
11940   }
11941 
11942   // Use VECTOR_SHUFFLE for the fixed-length vector
11943   // to maintain existing behavior.
11944   SmallVector<int, 8> Mask;
11945   unsigned NumElts = VT.getVectorMinNumElements();
11946   for (unsigned i = 0; i != NumElts; ++i)
11947     Mask.push_back(NumElts - 1 - i);
11948 
11949   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
11950 }
11951 
11952 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) {
11953   auto DL = getCurSDLoc();
11954   SDValue InVec = getValue(I.getOperand(0));
11955   EVT OutVT =
11956       InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
11957 
11958   unsigned OutNumElts = OutVT.getVectorMinNumElements();
11959 
11960   // ISD Node needs the input vectors split into two equal parts
11961   SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
11962                            DAG.getVectorIdxConstant(0, DL));
11963   SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
11964                            DAG.getVectorIdxConstant(OutNumElts, DL));
11965 
11966   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
11967   // legalisation and combines.
11968   if (OutVT.isFixedLengthVector()) {
11969     SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
11970                                         createStrideMask(0, 2, OutNumElts));
11971     SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
11972                                        createStrideMask(1, 2, OutNumElts));
11973     SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc());
11974     setValue(&I, Res);
11975     return;
11976   }
11977 
11978   SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL,
11979                             DAG.getVTList(OutVT, OutVT), Lo, Hi);
11980   setValue(&I, Res);
11981 }
11982 
11983 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) {
11984   auto DL = getCurSDLoc();
11985   EVT InVT = getValue(I.getOperand(0)).getValueType();
11986   SDValue InVec0 = getValue(I.getOperand(0));
11987   SDValue InVec1 = getValue(I.getOperand(1));
11988   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11989   EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11990 
11991   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
11992   // legalisation and combines.
11993   if (OutVT.isFixedLengthVector()) {
11994     unsigned NumElts = InVT.getVectorMinNumElements();
11995     SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1);
11996     setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT),
11997                                       createInterleaveMask(NumElts, 2)));
11998     return;
11999   }
12000 
12001   SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL,
12002                             DAG.getVTList(InVT, InVT), InVec0, InVec1);
12003   Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0),
12004                     Res.getValue(1));
12005   setValue(&I, Res);
12006 }
12007 
12008 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
12009   SmallVector<EVT, 4> ValueVTs;
12010   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
12011                   ValueVTs);
12012   unsigned NumValues = ValueVTs.size();
12013   if (NumValues == 0) return;
12014 
12015   SmallVector<SDValue, 4> Values(NumValues);
12016   SDValue Op = getValue(I.getOperand(0));
12017 
12018   for (unsigned i = 0; i != NumValues; ++i)
12019     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
12020                             SDValue(Op.getNode(), Op.getResNo() + i));
12021 
12022   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12023                            DAG.getVTList(ValueVTs), Values));
12024 }
12025 
12026 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
12027   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12028   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12029 
12030   SDLoc DL = getCurSDLoc();
12031   SDValue V1 = getValue(I.getOperand(0));
12032   SDValue V2 = getValue(I.getOperand(1));
12033   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
12034 
12035   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
12036   if (VT.isScalableVector()) {
12037     MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
12038     setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
12039                              DAG.getConstant(Imm, DL, IdxVT)));
12040     return;
12041   }
12042 
12043   unsigned NumElts = VT.getVectorNumElements();
12044 
12045   uint64_t Idx = (NumElts + Imm) % NumElts;
12046 
12047   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
12048   SmallVector<int, 8> Mask;
12049   for (unsigned i = 0; i < NumElts; ++i)
12050     Mask.push_back(Idx + i);
12051   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
12052 }
12053 
12054 // Consider the following MIR after SelectionDAG, which produces output in
12055 // phyregs in the first case or virtregs in the second case.
12056 //
12057 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx
12058 // %5:gr32 = COPY $ebx
12059 // %6:gr32 = COPY $edx
12060 // %1:gr32 = COPY %6:gr32
12061 // %0:gr32 = COPY %5:gr32
12062 //
12063 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32
12064 // %1:gr32 = COPY %6:gr32
12065 // %0:gr32 = COPY %5:gr32
12066 //
12067 // Given %0, we'd like to return $ebx in the first case and %5 in the second.
12068 // Given %1, we'd like to return $edx in the first case and %6 in the second.
12069 //
12070 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap
12071 // to a single virtreg (such as %0). The remaining outputs monotonically
12072 // increase in virtreg number from there. If a callbr has no outputs, then it
12073 // should not have a corresponding callbr landingpad; in fact, the callbr
12074 // landingpad would not even be able to refer to such a callbr.
12075 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) {
12076   MachineInstr *MI = MRI.def_begin(Reg)->getParent();
12077   // There is definitely at least one copy.
12078   assert(MI->getOpcode() == TargetOpcode::COPY &&
12079          "start of copy chain MUST be COPY");
12080   Reg = MI->getOperand(1).getReg();
12081   MI = MRI.def_begin(Reg)->getParent();
12082   // There may be an optional second copy.
12083   if (MI->getOpcode() == TargetOpcode::COPY) {
12084     assert(Reg.isVirtual() && "expected COPY of virtual register");
12085     Reg = MI->getOperand(1).getReg();
12086     assert(Reg.isPhysical() && "expected COPY of physical register");
12087     MI = MRI.def_begin(Reg)->getParent();
12088   }
12089   // The start of the chain must be an INLINEASM_BR.
12090   assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR &&
12091          "end of copy chain MUST be INLINEASM_BR");
12092   return Reg;
12093 }
12094 
12095 // We must do this walk rather than the simpler
12096 //   setValue(&I, getCopyFromRegs(CBR, CBR->getType()));
12097 // otherwise we will end up with copies of virtregs only valid along direct
12098 // edges.
12099 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) {
12100   SmallVector<EVT, 8> ResultVTs;
12101   SmallVector<SDValue, 8> ResultValues;
12102   const auto *CBR =
12103       cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator());
12104 
12105   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12106   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
12107   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
12108 
12109   unsigned InitialDef = FuncInfo.ValueMap[CBR];
12110   SDValue Chain = DAG.getRoot();
12111 
12112   // Re-parse the asm constraints string.
12113   TargetLowering::AsmOperandInfoVector TargetConstraints =
12114       TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR);
12115   for (auto &T : TargetConstraints) {
12116     SDISelAsmOperandInfo OpInfo(T);
12117     if (OpInfo.Type != InlineAsm::isOutput)
12118       continue;
12119 
12120     // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the
12121     // individual constraint.
12122     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
12123 
12124     switch (OpInfo.ConstraintType) {
12125     case TargetLowering::C_Register:
12126     case TargetLowering::C_RegisterClass: {
12127       // Fill in OpInfo.AssignedRegs.Regs.
12128       getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo);
12129 
12130       // getRegistersForValue may produce 1 to many registers based on whether
12131       // the OpInfo.ConstraintVT is legal on the target or not.
12132       for (size_t i = 0, e = OpInfo.AssignedRegs.Regs.size(); i != e; ++i) {
12133         Register OriginalDef = FollowCopyChain(MRI, InitialDef++);
12134         if (Register::isPhysicalRegister(OriginalDef))
12135           FuncInfo.MBB->addLiveIn(OriginalDef);
12136         // Update the assigned registers to use the original defs.
12137         OpInfo.AssignedRegs.Regs[i] = OriginalDef;
12138       }
12139 
12140       SDValue V = OpInfo.AssignedRegs.getCopyFromRegs(
12141           DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR);
12142       ResultValues.push_back(V);
12143       ResultVTs.push_back(OpInfo.ConstraintVT);
12144       break;
12145     }
12146     case TargetLowering::C_Other: {
12147       SDValue Flag;
12148       SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
12149                                                   OpInfo, DAG);
12150       ++InitialDef;
12151       ResultValues.push_back(V);
12152       ResultVTs.push_back(OpInfo.ConstraintVT);
12153       break;
12154     }
12155     default:
12156       break;
12157     }
12158   }
12159   SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12160                           DAG.getVTList(ResultVTs), ResultValues);
12161   setValue(&I, V);
12162 }
12163